diff options
Diffstat (limited to 'lldb/packages')
653 files changed, 24003 insertions, 13716 deletions
diff --git a/lldb/packages/Python/lldbsuite/__init__.py b/lldb/packages/Python/lldbsuite/__init__.py index aa6874e78bc..4b59e4119b2 100644 --- a/lldb/packages/Python/lldbsuite/__init__.py +++ b/lldb/packages/Python/lldbsuite/__init__.py @@ -4,6 +4,7 @@ import inspect import os import sys + def find_lldb_root(): lldb_root = os.path.dirname(inspect.getfile(inspect.currentframe())) while True: diff --git a/lldb/packages/Python/lldbsuite/support/encoded_file.py b/lldb/packages/Python/lldbsuite/support/encoded_file.py index 7581564f7e3..2c2fef383f7 100644 --- a/lldb/packages/Python/lldbsuite/support/encoded_file.py +++ b/lldb/packages/Python/lldbsuite/support/encoded_file.py @@ -14,6 +14,7 @@ import io # Third party modules import six + def _encoded_read(old_read, encoding): def impl(size): result = old_read(size) @@ -24,6 +25,7 @@ def _encoded_read(old_read, encoding): return result return impl + def _encoded_write(old_write, encoding): def impl(s): # If we were asked to write a `str` (in Py2) or a `bytes` (in Py3) decode it @@ -38,9 +40,24 @@ Create a Text I/O file object that can be written to with either unicode strings under Python 2 and Python 3, and automatically encodes and decodes as necessary to return the native string type for the current Python version ''' -def open(file, encoding, mode='r', buffering=-1, errors=None, newline=None, closefd=True): - wrapped_file = io.open(file, mode=mode, buffering=buffering, encoding=encoding, - errors=errors, newline=newline, closefd=closefd) + + +def open( + file, + encoding, + mode='r', + buffering=-1, + errors=None, + newline=None, + closefd=True): + wrapped_file = io.open( + file, + mode=mode, + buffering=buffering, + encoding=encoding, + errors=errors, + newline=newline, + closefd=closefd) new_read = _encoded_read(getattr(wrapped_file, 'read'), encoding) new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding) setattr(wrapped_file, 'read', new_read) diff --git a/lldb/packages/Python/lldbsuite/support/fs.py b/lldb/packages/Python/lldbsuite/support/fs.py index 9a56808369d..30388596ea1 100644 --- a/lldb/packages/Python/lldbsuite/support/fs.py +++ b/lldb/packages/Python/lldbsuite/support/fs.py @@ -31,6 +31,7 @@ def _find_file_in_paths(paths, exe_basename): return os.path.normcase(trial_exe_path) return None + def find_executable(executable): """Finds the specified executable in the PATH or known good locations.""" @@ -59,6 +60,6 @@ def find_executable(executable): if not result or len(result) < 1: raise os.OSError( - "failed to find exe='%s' in paths='%s'" % (executable, paths_to_check)) + "failed to find exe='%s' in paths='%s'" % + (executable, paths_to_check)) return result - diff --git a/lldb/packages/Python/lldbsuite/support/funcutils.py b/lldb/packages/Python/lldbsuite/support/funcutils.py index 53dd1fb370b..2fa10097d43 100644 --- a/lldb/packages/Python/lldbsuite/support/funcutils.py +++ b/lldb/packages/Python/lldbsuite/support/funcutils.py @@ -8,9 +8,17 @@ import inspect # LLDB modules + def requires_self(func): func_argc = len(inspect.getargspec(func).args) - if func_argc == 0 or (getattr(func,'im_self', None) is not None) or (hasattr(func, '__self__')): + if func_argc == 0 or ( + getattr( + func, + 'im_self', + None) is not None) or ( + hasattr( + func, + '__self__')): return False else: return True diff --git a/lldb/packages/Python/lldbsuite/support/gmodules.py b/lldb/packages/Python/lldbsuite/support/gmodules.py index 4f2fd9643b1..5d66bd14896 100644 --- a/lldb/packages/Python/lldbsuite/support/gmodules.py +++ b/lldb/packages/Python/lldbsuite/support/gmodules.py @@ -22,9 +22,8 @@ def is_compiler_clang_with_gmodules(compiler_path): else: # Check the compiler help for the -gmodules option. clang_help = os.popen("%s --help" % compiler_path).read() - return GMODULES_HELP_REGEX.search(clang_help, re.DOTALL) is not None + return GMODULES_HELP_REGEX.search( + clang_help, re.DOTALL) is not None GMODULES_SUPPORT_MAP[compiler_path] = _gmodules_supported_internal() return GMODULES_SUPPORT_MAP[compiler_path] - - diff --git a/lldb/packages/Python/lldbsuite/support/optional_with.py b/lldb/packages/Python/lldbsuite/support/optional_with.py index 41342288bc6..f91b3c6fdeb 100644 --- a/lldb/packages/Python/lldbsuite/support/optional_with.py +++ b/lldb/packages/Python/lldbsuite/support/optional_with.py @@ -2,6 +2,7 @@ # Provides a with-style resource handler for optionally-None resources # ==================================================================== + class optional_with(object): # pylint: disable=too-few-public-methods # This is a wrapper - it is not meant to provide any extra methods. @@ -39,6 +40,7 @@ class optional_with(object): forget the try/finally using optional_with(), since the with syntax can be used. """ + def __init__(self, wrapped_object): self.wrapped_object = wrapped_object diff --git a/lldb/packages/Python/lldbsuite/support/seven.py b/lldb/packages/Python/lldbsuite/support/seven.py index 56ddd8db3f6..e04f48308b7 100644 --- a/lldb/packages/Python/lldbsuite/support/seven.py +++ b/lldb/packages/Python/lldbsuite/support/seven.py @@ -10,11 +10,16 @@ else: def get_command_status_output(command): try: import subprocess - return (0, subprocess.check_output(command, shell=True, universal_newlines=True)) + return ( + 0, + subprocess.check_output( + command, + shell=True, + universal_newlines=True)) except subprocess.CalledProcessError as e: return (e.returncode, e.output) def get_command_output(command): return get_command_status_output(command)[1] - cmp_ = lambda x, y: (x > y) - (x < y)
\ No newline at end of file + cmp_ = lambda x, y: (x > y) - (x < y) diff --git a/lldb/packages/Python/lldbsuite/support/sockutil.py b/lldb/packages/Python/lldbsuite/support/sockutil.py index b3d81d14884..789deed8017 100644 --- a/lldb/packages/Python/lldbsuite/support/sockutil.py +++ b/lldb/packages/Python/lldbsuite/support/sockutil.py @@ -14,6 +14,7 @@ import socket # LLDB modules import use_lldb_suite + def recvall(sock, size): bytes = io.BytesIO() while size > 0: diff --git a/lldb/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py b/lldb/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py index 2b6ac1818de..c038c0726c2 100644 --- a/lldb/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py +++ b/lldb/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py @@ -5,13 +5,13 @@ Verify the default cache line size for android targets from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DefaultCacheLineSizeTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,15 +24,23 @@ class DefaultCacheLineSizeTestCase(TestBase): self.assertTrue(target and target.IsValid(), "Target is valid") breakpoint = target.BreakpointCreateByName("main") - self.assertTrue(breakpoint and breakpoint.IsValid(), "Breakpoint is valid") + self.assertTrue( + breakpoint and breakpoint.IsValid(), + "Breakpoint is valid") # Run the program. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) # check the setting value - self.expect("settings show target.process.memory-cache-line-size", patterns=[" = 2048"]) + self.expect( + "settings show target.process.memory-cache-line-size", + patterns=[" = 2048"]) # Run to completion. process.Continue() diff --git a/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py b/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py index 0ed2df3ceab..0b202a092f2 100644 --- a/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py +++ b/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py @@ -6,12 +6,13 @@ should compile and link with the LLDB framework.""" from __future__ import print_function - -import os, re +import os +import re from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SBDirCheckerCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,7 +31,8 @@ class SBDirCheckerCase(TestBase): if not (self.platformIsDarwin() and self.getArchitecture() == "x86_64"): self.skipTest("This test is only for LLDB.framework built 64-bit") if self.getArchitecture() == "i386": - self.skipTest("LLDB is 64-bit and cannot be linked to 32-bit test program.") + self.skipTest( + "LLDB is 64-bit and cannot be linked to 32-bit test program.") # Generate main.cpp, build it, and execute. self.generate_main_cpp() @@ -43,7 +45,8 @@ class SBDirCheckerCase(TestBase): with open(temp, 'r') as f: content = f.read() - public_api_dir = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API") + public_api_dir = os.path.join( + os.environ["LLDB_SRC"], "include", "lldb", "API") # Look under the include/lldb/API directory and add #include statements # for all the SB API headers. @@ -51,10 +54,11 @@ class SBDirCheckerCase(TestBase): # For different platforms, the include statement can vary. if self.platformIsDarwin(): include_stmt = "'#include <%s>' % os.path.join('LLDB', header)" - if self.getPlatform() == "freebsd" or self.getPlatform() == "linux" or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile': + if self.getPlatform() == "freebsd" or self.getPlatform( + ) == "linux" or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile': include_stmt = "'#include <%s>' % os.path.join(public_api_dir, header)" - list = [eval(include_stmt) for header in public_headers if (header.startswith("SB") and - header.endswith(".h"))] + list = [eval(include_stmt) for header in public_headers if ( + header.startswith("SB") and header.endswith(".h"))] includes = '\n'.join(list) new_content = content.replace('%include_SB_APIs%', includes) src = os.path.join(os.getcwd(), self.source) @@ -69,21 +73,27 @@ class SBDirCheckerCase(TestBase): exe = os.path.join(os.getcwd(), exe_name) self.runCmd("file %s" % exe, CURRENT_EXECUTABLE_SET) - self.line_to_break = line_number(self.source, '// Set breakpoint here.') + self.line_to_break = line_number( + self.source, '// Set breakpoint here.') - env_cmd = "settings set target.env-vars %s=%s" %(self.dylibPath, self.getLLDBLibraryEnvVal()) + env_cmd = "settings set target.env-vars %s=%s" % ( + self.dylibPath, self.getLLDBLibraryEnvVal()) if self.TraceOn(): print("Set environment to: ", env_cmd) self.runCmd(env_cmd) - self.addTearDownHook(lambda: self.dbg.HandleCommand("settings remove target.env-vars %s" % self.dylibPath)) + self.addTearDownHook( + lambda: self.dbg.HandleCommand( + "settings remove target.env-vars %s" % + self.dylibPath)) - lldbutil.run_break_set_by_file_and_line (self, self.source, self.line_to_break, num_expected_locations = -1) + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line_to_break, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) self.runCmd('frame variable') diff --git a/lldb/packages/Python/lldbsuite/test/api/listeners/TestListener.py b/lldb/packages/Python/lldbsuite/test/api/listeners/TestListener.py index bd8c204e78c..65232f01410 100644 --- a/lldb/packages/Python/lldbsuite/test/api/listeners/TestListener.py +++ b/lldb/packages/Python/lldbsuite/test/api/listeners/TestListener.py @@ -15,6 +15,7 @@ from lldbsuite.test import lldbutil import six + class ListenToModuleLoadedEvents (TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,14 +25,17 @@ class ListenToModuleLoadedEvents (TestBase): TestBase.setUp(self) self.build() - def test_receiving_breakpoint_added (self): + def test_receiving_breakpoint_added(self): """Test that we get breakpoint added events, waiting on event classes on the debugger""" my_listener = lldb.SBListener("test_listener") - - my_listener.StartListeningForEventClass(self.dbg, lldb.SBTarget.GetBroadcasterClassName(), lldb.SBTarget.eBroadcastBitBreakpointChanged) - exe = os.path.join (os.getcwd(), "a.out") + my_listener.StartListeningForEventClass( + self.dbg, + lldb.SBTarget.GetBroadcasterClassName(), + lldb.SBTarget.eBroadcastBitBreakpointChanged) + + exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) @@ -39,17 +43,29 @@ class ListenToModuleLoadedEvents (TestBase): event = lldb.SBEvent() my_listener.WaitForEvent(1, event) - + self.assertTrue(event.IsValid(), "Got a valid event.") - self.assertTrue(lldb.SBBreakpoint.EventIsBreakpointEvent(event), "It is a breakpoint event.") - self.assertTrue(lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent(event) == lldb.eBreakpointEventTypeAdded, "It is a breakpoint added event.") - self.assertTrue(bkpt == lldb.SBBreakpoint.GetBreakpointFromEvent(event), "It is our breakpoint.") + self.assertTrue( + lldb.SBBreakpoint.EventIsBreakpointEvent(event), + "It is a breakpoint event.") + self.assertTrue(lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent( + event) == lldb.eBreakpointEventTypeAdded, "It is a breakpoint added event.") + self.assertTrue( + bkpt == lldb.SBBreakpoint.GetBreakpointFromEvent(event), + "It is our breakpoint.") # Now make sure if we stop listening for events we don't get them: - my_listener.StopListeningForEventClass(self.dbg, lldb.SBTarget.GetBroadcasterClassName(), lldb.SBTarget.eBroadcastBitBreakpointChanged) - my_listener.StopListeningForEvents(target.GetBroadcaster(), lldb.SBTarget.eBroadcastBitBreakpointChanged) + my_listener.StopListeningForEventClass( + self.dbg, + lldb.SBTarget.GetBroadcasterClassName(), + lldb.SBTarget.eBroadcastBitBreakpointChanged) + my_listener.StopListeningForEvents( + target.GetBroadcaster(), + lldb.SBTarget.eBroadcastBitBreakpointChanged) bkpt2 = target.BreakpointCreateByName("main") my_listener.WaitForEvent(1, event) - self.assertTrue(not event.IsValid(), "We don't get events we aren't listening to.") + self.assertTrue( + not event.IsValid(), + "We don't get events we aren't listening to.") diff --git a/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py b/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py index ca2b986ce74..ca8a69c8d89 100644 --- a/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py +++ b/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py @@ -3,8 +3,8 @@ from __future__ import print_function - -import os, re +import os +import re import subprocess import lldb @@ -12,16 +12,24 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestMultipleSimultaneousDebuggers(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIfNoSBHeaders @expectedFlakeyDarwin() - @expectedFailureAll(archs="i[3-6]86", bugnumber="multi-process-driver.cpp creates an x64 target") - @expectedFailureAll(oslist=["windows", "linux", "freebsd"], bugnumber="llvm.org/pr20282") + @expectedFailureAll( + archs="i[3-6]86", + bugnumber="multi-process-driver.cpp creates an x64 target") + @expectedFailureAll( + oslist=[ + "windows", + "linux", + "freebsd"], + bugnumber="llvm.org/pr20282") def test_multiple_debuggers(self): - env = {self.dylibPath : self.getLLDBLibraryEnvVal()} + env = {self.dylibPath: self.getLLDBLibraryEnvVal()} self.driver_exe = os.path.join(os.getcwd(), "multi-process-driver") self.buildDriver('multi-process-driver.cpp', self.driver_exe) @@ -41,4 +49,5 @@ class TestMultipleSimultaneousDebuggers(TestBase): check_call([self.driver_exe, self.inferior_exe], env=env) else: with open(os.devnull, 'w') as fnull: - check_call([self.driver_exe, self.inferior_exe], env=env, stdout=fnull, stderr=fnull) + check_call([self.driver_exe, self.inferior_exe], + env=env, stdout=fnull, stderr=fnull) diff --git a/lldb/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py b/lldb/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py index 7959bb73de0..970c25107f6 100644 --- a/lldb/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py +++ b/lldb/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py @@ -5,19 +5,22 @@ from __future__ import print_function # __package__ = "lldbsuite.test" -import os, re +import os +import re from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil import subprocess + class SBBreakpointCallbackCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIfRemote @skipIfNoSBHeaders - @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538) + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows def test_breakpoint_callback(self): """Test the that SBBreakpoint callback is invoked when a breakpoint is hit. """ self.build_and_test('driver.cpp test_breakpoint_callback.cpp', @@ -25,40 +28,52 @@ class SBBreakpointCallbackCase(TestBase): @skipIfRemote @skipIfNoSBHeaders - @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538) + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows @expectedFlakeyFreeBSD def test_sb_api_listener_event_description(self): """ Test the description of an SBListener breakpoint event is valid.""" - self.build_and_test('driver.cpp listener_test.cpp test_listener_event_description.cpp', - 'test_listener_event_description') + self.build_and_test( + 'driver.cpp listener_test.cpp test_listener_event_description.cpp', + 'test_listener_event_description') pass @skipIfRemote @skipIfNoSBHeaders - @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538) + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows @expectedFlakeyFreeBSD - @expectedFailureAll("llvm.org/pr23139", oslist=["linux"], compiler="gcc", compiler_version=[">=","4.9"], archs=["x86_64"]) + @expectedFailureAll( + "llvm.org/pr23139", + oslist=["linux"], + compiler="gcc", + compiler_version=[ + ">=", + "4.9"], + archs=["x86_64"]) def test_sb_api_listener_event_process_state(self): """ Test that a registered SBListener receives events when a process changes state. """ - self.build_and_test('driver.cpp listener_test.cpp test_listener_event_process_state.cpp', - 'test_listener_event_process_state') + self.build_and_test( + 'driver.cpp listener_test.cpp test_listener_event_process_state.cpp', + 'test_listener_event_process_state') pass - @skipIfRemote @skipIfNoSBHeaders - @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538) + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows @expectedFlakeyFreeBSD @expectedFailureAll(oslist=["linux"]) def test_sb_api_listener_resume(self): """ Test that a process can be resumed from a non-main thread. """ - self.build_and_test('driver.cpp listener_test.cpp test_listener_resume.cpp', - 'test_listener_resume') + self.build_and_test( + 'driver.cpp listener_test.cpp test_listener_resume.cpp', + 'test_listener_resume') pass - def build_and_test(self, sources, test_name, args = None): + def build_and_test(self, sources, test_name, args=None): """ Build LLDB test from sources, and run expecting 0 exit code """ # These tests link against host lldb API. @@ -66,7 +81,8 @@ class SBBreakpointCallbackCase(TestBase): # because remote is disabled, we can assume that the os is the same # still need to check architecture if self.getLldbArchitecture() != self.getArchitecture(): - self.skipTest("This test is only run if the target arch is the same as the lldb binary arch") + self.skipTest( + "This test is only run if the target arch is the same as the lldb binary arch") self.inferior = 'inferior_program' self.buildProgram('inferior.cpp', self.inferior) @@ -79,7 +95,7 @@ class SBBreakpointCallbackCase(TestBase): self.signBinary(test_exe) exe = [test_exe, self.inferior] - env = {self.dylibPath : self.getLLDBLibraryEnvVal()} + env = {self.dylibPath: self.getLLDBLibraryEnvVal()} if self.TraceOn(): print("Running test %s" % " ".join(exe)) check_call(exe, env=env) diff --git a/lldb/packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py b/lldb/packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py index d502b6dfca8..4ddda525537 100644 --- a/lldb/packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py +++ b/lldb/packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py @@ -5,52 +5,53 @@ Test some ARM instruction emulation. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ARMEmulationTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) @no_debug_info_test - def test_thumb_emulations (self): - current_dir = os.getcwd(); - test_dir = os.path.join (current_dir, "new-test-files") - files = os.listdir (test_dir) + def test_thumb_emulations(self): + current_dir = os.getcwd() + test_dir = os.path.join(current_dir, "new-test-files") + files = os.listdir(test_dir) thumb_files = list() for f in files: if '-thumb.dat' in f: - thumb_files.append (f) - + thumb_files.append(f) + for f in thumb_files: - test_file = os.path.join (test_dir, f) - self.run_a_single_test (test_file) + test_file = os.path.join(test_dir, f) + self.run_a_single_test(test_file) @no_debug_info_test - def test_arm_emulations (self): - current_dir = os.getcwd(); - test_dir = os.path.join (current_dir, "new-test-files") - files = os.listdir (test_dir) + def test_arm_emulations(self): + current_dir = os.getcwd() + test_dir = os.path.join(current_dir, "new-test-files") + files = os.listdir(test_dir) arm_files = list() for f in files: if '-arm.dat' in f: - arm_files.append (f) - + arm_files.append(f) + for f in arm_files: - test_file = os.path.join (test_dir, f) - self.run_a_single_test (test_file) - - def run_a_single_test (self, filename): - insn = lldb.SBInstruction (); - stream = lldb.SBStream (); - success = insn.TestEmulation (stream, filename); - output = stream.GetData(); + test_file = os.path.join(test_dir, f) + self.run_a_single_test(test_file) + + def run_a_single_test(self, filename): + insn = lldb.SBInstruction() + stream = lldb.SBStream() + success = insn.TestEmulation(stream, filename) + output = stream.GetData() if self.TraceOn(): print('\nRunning test ' + os.path.basename(filename)) print(output) - self.assertTrue (success, 'Emulation test succeeded.') + self.assertTrue(success, 'Emulation test succeeded.') diff --git a/lldb/packages/Python/lldbsuite/test/attic/tester.py b/lldb/packages/Python/lldbsuite/test/attic/tester.py index 5c1a2370ced..2e783512369 100644 --- a/lldb/packages/Python/lldbsuite/test/attic/tester.py +++ b/lldb/packages/Python/lldbsuite/test/attic/tester.py @@ -3,112 +3,146 @@ from __future__ import print_function -import math, os.path, re, sys, time, unittest +import math +import os.path +import re +import sys +import time +import unittest + def setupSysPath(): - testPath = sys.path[0] - rem = re.match("(^.*/)test$", testPath) - if not rem: - print("This script expects to reside in .../test.") - sys.exit(-1) - lldbBasePath = rem.group(1) - lldbDebugPythonPath = "build/Debug/LLDB.framework/Resources/Python" - lldbReleasePythonPath = "build/Release/LLDB.framework/Resources/Python" - lldbPythonPath = None - if os.path.isfile(lldbDebugPythonPath + "/lldb.py"): - lldbPythonPath = lldbDebugPythonPath - if os.path.isfile(lldbReleasePythonPath + "/lldb.py"): - lldbPythonPath = lldbReleasePythonPath - if not lldbPythonPath: - print("This script requires lldb.py to be in either " + lldbDebugPythonPath, end='') - print("or" + lldbReleasePythonPath) - sys.exit(-1) - sys.path.append(lldbPythonPath) + testPath = sys.path[0] + rem = re.match("(^.*/)test$", testPath) + if not rem: + print("This script expects to reside in .../test.") + sys.exit(-1) + lldbBasePath = rem.group(1) + lldbDebugPythonPath = "build/Debug/LLDB.framework/Resources/Python" + lldbReleasePythonPath = "build/Release/LLDB.framework/Resources/Python" + lldbPythonPath = None + if os.path.isfile(lldbDebugPythonPath + "/lldb.py"): + lldbPythonPath = lldbDebugPythonPath + if os.path.isfile(lldbReleasePythonPath + "/lldb.py"): + lldbPythonPath = lldbReleasePythonPath + if not lldbPythonPath: + print( + "This script requires lldb.py to be in either " + + lldbDebugPythonPath, + end='') + print("or" + lldbReleasePythonPath) + sys.exit(-1) + sys.path.append(lldbPythonPath) + def prettyTime(t): - if t == 0.0: - return "0s" - if t < 0.000001: - return ("%.3f" % (t * 1000000000.0)) + "ns" - if t < 0.001: - return ("%.3f" % (t * 1000000.0)) + "µs" - if t < 1: - return ("%.3f" % (t * 1000.0)) + "ms" - return str(t) + "s" + if t == 0.0: + return "0s" + if t < 0.000001: + return ("%.3f" % (t * 1000000000.0)) + "ns" + if t < 0.001: + return ("%.3f" % (t * 1000000.0)) + "µs" + if t < 1: + return ("%.3f" % (t * 1000.0)) + "ms" + return str(t) + "s" + class ExecutionTimes: - @classmethod - def executionTimes(cls): - if cls.m_executionTimes == None: - cls.m_executionTimes = ExecutionTimes() - for i in range(100): - cls.m_executionTimes.start() - cls.m_executionTimes.end("null") - return cls.m_executionTimes - def __init__(self): - self.m_times = dict() - def start(self): - self.m_start = time.time() - def end(self, component): - e = time.time() - if component not in self.m_times: - self.m_times[component] = list() - self.m_times[component].append(e - self.m_start) - def dumpStats(self): - for key in list(self.m_times.keys()): - if len(self.m_times[key]): - sampleMin = float('inf') - sampleMax = float('-inf') - sampleSum = 0.0 - sampleCount = 0.0 - for time in self.m_times[key]: - if time > sampleMax: - sampleMax = time - if time < sampleMin: - sampleMin = time - sampleSum += time - sampleCount += 1.0 - sampleMean = sampleSum / sampleCount - sampleVariance = 0 - for time in self.m_times[key]: - sampleVariance += (time - sampleMean) ** 2 - sampleVariance /= sampleCount - sampleStandardDeviation = math.sqrt(sampleVariance) - print(key + ": [" + prettyTime(sampleMin) + ", " + prettyTime(sampleMax) + "] ", end='') - print("µ " + prettyTime(sampleMean) + ", σ " + prettyTime(sampleStandardDeviation)) - m_executionTimes = None + + @classmethod + def executionTimes(cls): + if cls.m_executionTimes is None: + cls.m_executionTimes = ExecutionTimes() + for i in range(100): + cls.m_executionTimes.start() + cls.m_executionTimes.end("null") + return cls.m_executionTimes + + def __init__(self): + self.m_times = dict() + + def start(self): + self.m_start = time.time() + + def end(self, component): + e = time.time() + if component not in self.m_times: + self.m_times[component] = list() + self.m_times[component].append(e - self.m_start) + + def dumpStats(self): + for key in list(self.m_times.keys()): + if len(self.m_times[key]): + sampleMin = float('inf') + sampleMax = float('-inf') + sampleSum = 0.0 + sampleCount = 0.0 + for time in self.m_times[key]: + if time > sampleMax: + sampleMax = time + if time < sampleMin: + sampleMin = time + sampleSum += time + sampleCount += 1.0 + sampleMean = sampleSum / sampleCount + sampleVariance = 0 + for time in self.m_times[key]: + sampleVariance += (time - sampleMean) ** 2 + sampleVariance /= sampleCount + sampleStandardDeviation = math.sqrt(sampleVariance) + print( + key + + ": [" + + prettyTime(sampleMin) + + ", " + + prettyTime(sampleMax) + + "] ", + end='') + print( + "µ " + + prettyTime(sampleMean) + + ", σ " + + prettyTime(sampleStandardDeviation)) + m_executionTimes = None setupSysPath() import lldb + class LLDBTestCase(unittest.TestCase): - def setUp(self): - debugger = lldb.SBDebugger.Create() - debugger.SetAsync(True) - self.m_commandInterpreter = debugger.GetCommandInterpreter() - if not self.m_commandInterpreter: - print("Couldn't get the command interpreter") - sys.exit(-1) - def runCommand(self, command, component): - res = lldb.SBCommandReturnObject() - ExecutionTimes.executionTimes().start() - self.m_commandInterpreter.HandleCommand(command, res, False) - ExecutionTimes.executionTimes().end(component) - if res.Succeeded(): - return res.GetOutput() - else: - self.fail("Command " + command + " returned an error") - return None - def getCategories(self): - return [] + + def setUp(self): + debugger = lldb.SBDebugger.Create() + debugger.SetAsync(True) + self.m_commandInterpreter = debugger.GetCommandInterpreter() + if not self.m_commandInterpreter: + print("Couldn't get the command interpreter") + sys.exit(-1) + + def runCommand(self, command, component): + res = lldb.SBCommandReturnObject() + ExecutionTimes.executionTimes().start() + self.m_commandInterpreter.HandleCommand(command, res, False) + ExecutionTimes.executionTimes().end(component) + if res.Succeeded(): + return res.GetOutput() + else: + self.fail("Command " + command + " returned an error") + return None + + def getCategories(self): + return [] + class SanityCheckTestCase(LLDBTestCase): - def runTest(self): - ret = self.runCommand("show arch", "show-arch") - #print(ret) - def getCategories(self): - return [] + + def runTest(self): + ret = self.runCommand("show arch", "show-arch") + # print(ret) + + def getCategories(self): + return [] suite = unittest.TestLoader().loadTestsFromTestCase(SanityCheckTestCase) unittest.TextTestRunner(verbosity=2).run(suite) diff --git a/lldb/packages/Python/lldbsuite/test/bench.py b/lldb/packages/Python/lldbsuite/test/bench.py index ce9c2e75d71..5a0fec7534a 100644 --- a/lldb/packages/Python/lldbsuite/test/bench.py +++ b/lldb/packages/Python/lldbsuite/test/bench.py @@ -17,14 +17,16 @@ See also bench-history. from __future__ import print_function from __future__ import absolute_import -import os, sys +import os +import sys import re from optparse import OptionParser # dotest.py invocation with no '-e exe-path' uses lldb as the inferior program, # unless there is a mentioning of custom executable program. benches = [ - # Measure startup delays creating a target, setting a breakpoint, and run to breakpoint stop. + # Measure startup delays creating a target, setting a breakpoint, and run + # to breakpoint stop. './dotest.py -v +b %E %X -n -p TestStartupDelays.py', # Measure 'frame variable' response after stopping at a breakpoint. @@ -40,6 +42,7 @@ benches = [ './dotest.py -v +b -n %E -p TestDoAttachThenDisassembly.py' ] + def main(): """Read the items from 'benches' and run the command line one by one.""" parser = OptionParser(usage="""\ @@ -57,14 +60,14 @@ Run the standard benchmarks defined in the list named 'benches'.\ # Parses the options, if any. opts, args = parser.parse_args() - + print("Starting bench runner....") for item in benches: command = item.replace('%E', '-e "%s"' % opts.exe if opts.exe else '') - command = command.replace('%X', - '-x "%s"' % opts.break_spec if opts.break_spec else '') + command = command.replace('%X', '-x "%s"' % + opts.break_spec if opts.break_spec else '') print("Running %s" % (command)) os.system(command) diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py b/lldb/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py index f7c274522f9..74336693bcb 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestBenchmarkContinue(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -31,14 +32,16 @@ class TestBenchmarkContinue(BenchBase): """Benchmark different ways to continue a process""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "// break here")) + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "// break here")) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,22 +50,24 @@ class TestBenchmarkContinue(BenchBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + runCmd_sw = Stopwatch() lldbutil_sw = Stopwatch() - for i in range(0,15): + for i in range(0, 15): runCmd_sw.start() self.runCmd("continue") runCmd_sw.stop() - - for i in range(0,15): + + for i in range(0, 15): lldbutil_sw.start() lldbutil.continue_to_breakpoint(self.process(), bkpt) lldbutil_sw.stop() - - print("runCmd: %s\nlldbutil: %s" % (runCmd_sw,lldbutil_sw)) + + print("runCmd: %s\nlldbutil: %s" % (runCmd_sw, lldbutil_sw)) diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py b/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py index 8a0c044147a..8bce4815894 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py @@ -3,18 +3,20 @@ from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + def is_exe(fpath): """Returns true if fpath is an executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + class DisassembleDriverMainLoop(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -42,7 +44,9 @@ class DisassembleDriverMainLoop(BenchBase): @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_run_lldb_then_gdb(self): """Test disassembly on a large function with lldb vs. gdb.""" print() @@ -54,11 +58,13 @@ class DisassembleDriverMainLoop(BenchBase): print("lldb benchmark:", self.stopwatch) self.run_gdb_disassembly(self.exe, self.function, self.count) print("gdb benchmark:", self.stopwatch) - print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg)) + print("lldb_avg/gdb_avg: %f" % (self.lldb_avg / self.gdb_avg)) @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_run_gdb_then_lldb(self): """Test disassembly on a large function with lldb vs. gdb.""" print() @@ -70,7 +76,7 @@ class DisassembleDriverMainLoop(BenchBase): print("gdb benchmark:", self.stopwatch) self.run_lldb_disassembly(self.exe, self.function, self.count) print("lldb benchmark:", self.stopwatch) - print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg)) + print("lldb_avg/gdb_avg: %f" % (self.lldb_avg / self.gdb_avg)) def run_lldb_disassembly(self, exe, function, count): import pexpect @@ -79,7 +85,9 @@ class DisassembleDriverMainLoop(BenchBase): prompt = self.child_prompt # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py b/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py index f8e3d94b657..36f23572648 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py @@ -5,13 +5,14 @@ inferior and traverses the stack for thread0 to arrive at frame with function from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * from lldbsuite.test.lldbtest import * + class AttachThenDisassemblyBench(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -32,10 +33,11 @@ class AttachThenDisassemblyBench(BenchBase): def run_lldb_attach_then_disassembly(self, exe, count): target = self.dbg.CreateTarget(exe) - # Spawn a new process and don't display the stdout if not in TraceOn() mode. + # Spawn a new process and don't display the stdout if not in TraceOn() + # mode. import subprocess - popen = subprocess.Popen([exe, self.lldbOption], - stdout = open(os.devnull, 'w') if not self.TraceOn() else None) + popen = subprocess.Popen([exe, self.lldbOption], stdout=open( + os.devnull, 'w') if not self.TraceOn() else None) if self.TraceOn(): print("pid of spawned process: %d" % popen.pid) @@ -51,7 +53,7 @@ class AttachThenDisassemblyBench(BenchBase): i = 0 found = False for f in thread0: - #print("frame#%d %s" % (i, f.GetFunctionName())) + # print("frame#%d %s" % (i, f.GetFunctionName())) if "MainLoop" in f.GetFunctionName(): found = True thread0.SetSelectedFrame(i) @@ -59,7 +61,7 @@ class AttachThenDisassemblyBench(BenchBase): print("Found frame#%d for function 'MainLoop'" % i) break i += 1 - + # Reset the stopwatch now. self.stopwatch.reset() for i in range(count): diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py b/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py index 618aac7eafc..fd91bb441d9 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py @@ -3,8 +3,8 @@ from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * @@ -12,6 +12,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import configuration from lldbsuite.test import lldbutil + class XCode41Vs42GDBDisassembly(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -28,31 +29,53 @@ class XCode41Vs42GDBDisassembly(BenchBase): @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_run_41_then_42(self): """Test disassembly on a large function with 4.1 vs. 4.2's gdb.""" print() - self.run_gdb_disassembly(self.gdb_41_exe, self.exe, self.function, self.count) + self.run_gdb_disassembly( + self.gdb_41_exe, + self.exe, + self.function, + self.count) print("4.1 gdb benchmark:", self.stopwatch) self.gdb_41_avg = self.stopwatch.avg() - self.run_gdb_disassembly(self.gdb_42_exe, self.exe, self.function, self.count) + self.run_gdb_disassembly( + self.gdb_42_exe, + self.exe, + self.function, + self.count) print("4.2 gdb benchmark:", self.stopwatch) self.gdb_42_avg = self.stopwatch.avg() - print("gdb_42_avg/gdb_41_avg: %f" % (self.gdb_42_avg/self.gdb_41_avg)) + print("gdb_42_avg/gdb_41_avg: %f" % + (self.gdb_42_avg / self.gdb_41_avg)) @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_run_42_then_41(self): """Test disassembly on a large function with 4.1 vs. 4.2's gdb.""" print() - self.run_gdb_disassembly(self.gdb_42_exe, self.exe, self.function, self.count) + self.run_gdb_disassembly( + self.gdb_42_exe, + self.exe, + self.function, + self.count) print("4.2 gdb benchmark:", self.stopwatch) self.gdb_42_avg = self.stopwatch.avg() - self.run_gdb_disassembly(self.gdb_41_exe, self.exe, self.function, self.count) + self.run_gdb_disassembly( + self.gdb_41_exe, + self.exe, + self.function, + self.count) print("4.1 gdb benchmark:", self.stopwatch) self.gdb_41_avg = self.stopwatch.avg() - print("gdb_42_avg/gdb_41_avg: %f" % (self.gdb_42_avg/self.gdb_41_avg)) + print("gdb_42_avg/gdb_41_avg: %f" % + (self.gdb_42_avg / self.gdb_41_avg)) def run_gdb_disassembly(self, gdb_exe_path, exe, function, count): import pexpect diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py b/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py index 68d2bd9793e..a9899d93bf0 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py @@ -3,8 +3,8 @@ from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * @@ -12,6 +12,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import configuration from lldbsuite.test import lldbutil + class ExpressionEvaluationCase(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -19,11 +20,14 @@ class ExpressionEvaluationCase(BenchBase): def setUp(self): BenchBase.setUp(self) self.source = 'main.cpp' - self.line_to_break = line_number(self.source, '// Set breakpoint here.') + self.line_to_break = line_number( + self.source, '// Set breakpoint here.') self.count = 25 @benchmarks_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_expr_cmd(self): """Test lldb's expression commands and collect statistics.""" self.build() @@ -45,7 +49,9 @@ class ExpressionEvaluationCase(BenchBase): self.stopwatch.reset() for i in range(count): # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. @@ -53,7 +59,9 @@ class ExpressionEvaluationCase(BenchBase): child.logfile_read = sys.stdout child.expect_exact(prompt) - child.sendline('breakpoint set -f %s -l %d' % (self.source, self.line_to_break)) + child.sendline( + 'breakpoint set -f %s -l %d' % + (self.source, self.line_to_break)) child.expect_exact(prompt) child.sendline('run') child.expect_exact(prompt) diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py b/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py index 2ad409e53b0..a223d2cf1fa 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py @@ -3,8 +3,8 @@ from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test.lldbbench import BenchBase from lldbsuite.test.decorators import * @@ -12,6 +12,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import configuration from lldbsuite.test import lldbutil + class RepeatedExprsCase(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -19,13 +20,16 @@ class RepeatedExprsCase(BenchBase): def setUp(self): BenchBase.setUp(self) self.source = 'main.cpp' - self.line_to_break = line_number(self.source, '// Set breakpoint here.') + self.line_to_break = line_number( + self.source, '// Set breakpoint here.') self.lldb_avg = None self.gdb_avg = None self.count = 100 @benchmarks_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_compare_lldb_to_gdb(self): """Test repeated expressions with lldb vs. gdb.""" self.build() @@ -36,7 +40,7 @@ class RepeatedExprsCase(BenchBase): print("lldb benchmark:", self.stopwatch) self.run_gdb_repeated_exprs(self.exe_name, self.count) print("gdb benchmark:", self.stopwatch) - print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg)) + print("lldb_avg/gdb_avg: %f" % (self.lldb_avg / self.gdb_avg)) def run_lldb_repeated_exprs(self, exe_name, count): import pexpect @@ -47,7 +51,9 @@ class RepeatedExprsCase(BenchBase): prompt = self.child_prompt # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. @@ -55,7 +61,9 @@ class RepeatedExprsCase(BenchBase): child.logfile_read = sys.stdout child.expect_exact(prompt) - child.sendline('breakpoint set -f %s -l %d' % (self.source, self.line_to_break)) + child.sendline( + 'breakpoint set -f %s -l %d' % + (self.source, self.line_to_break)) child.expect_exact(prompt) child.sendline('run') child.expect_exact(prompt) @@ -71,7 +79,7 @@ class RepeatedExprsCase(BenchBase): child.sendline(expr_cmd2) child.expect_exact(prompt) child.sendline('process continue') - child.expect_exact(prompt) + child.expect_exact(prompt) child.sendline('quit') try: @@ -117,7 +125,7 @@ class RepeatedExprsCase(BenchBase): child.sendline(expr_cmd2) child.expect_exact(prompt) child.sendline('continue') - child.expect_exact(prompt) + child.expect_exact(prompt) child.sendline('quit') child.expect_exact('The program is running. Exit anyway?') diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py b/lldb/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py index 9f583529737..3ed23e61540 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py @@ -3,14 +3,15 @@ from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test import configuration from lldbsuite.test import lldbtest_config from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * + class FrameVariableResponseBench(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -23,7 +24,9 @@ class FrameVariableResponseBench(BenchBase): @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_startup_delay(self): """Test response time for the 'frame variable' command.""" print() @@ -40,7 +43,9 @@ class FrameVariableResponseBench(BenchBase): self.stopwatch.reset() for i in range(count): # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. @@ -52,9 +57,9 @@ class FrameVariableResponseBench(BenchBase): child.expect_exact(prompt) # Run the target and expect it to be stopped due to breakpoint. - child.sendline('run') # Aka 'process launch'. + child.sendline('run') # Aka 'process launch'. child.expect_exact(prompt) - + with self.stopwatch: # Measure the 'frame variable' response time. child.sendline('frame variable') diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py b/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py index 12e23e95694..659382e7311 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestBenchmarkLibcxxList(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -31,14 +32,16 @@ class TestBenchmarkLibcxxList(BenchBase): """Benchmark the std::list data formatter (libc++)""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "break here")) + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "break here")) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,15 +50,17 @@ class TestBenchmarkLibcxxList(BenchBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + sw = Stopwatch() - + sw.start() self.expect('frame variable -A list', substrs=['[300]', '300']) sw.stop() - + print("time to print: %s" % (sw)) diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py b/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py index 4466cd083ca..343f93d95c4 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbbench import * from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestBenchmarkLibcxxMap(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -31,14 +32,16 @@ class TestBenchmarkLibcxxMap(BenchBase): """Benchmark the std::map data formatter (libc++)""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "break here")) + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "break here")) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,15 +50,17 @@ class TestBenchmarkLibcxxMap(BenchBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + sw = Stopwatch() - + sw.start() self.expect('frame variable -A map', substrs=['[300]', '300']) sw.stop() - + print("time to print: %s" % (sw)) diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py b/lldb/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py index 9d2356ab54f..baacdc81e23 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py @@ -3,14 +3,15 @@ from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test import configuration from lldbsuite.test import lldbtest_config from lldbsuite.test.decorators import * from lldbsuite.test.lldbbench import * + class StartupDelaysBench(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -28,14 +29,22 @@ class StartupDelaysBench(BenchBase): @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_startup_delay(self): """Test start up delays creating a target, setting a breakpoint, and run to breakpoint stop.""" print() self.run_startup_delays_bench(self.exe, self.break_spec, self.count) - print("lldb startup delay (create fresh target) benchmark:", self.stopwatch) - print("lldb startup delay (set first breakpoint) benchmark:", self.stopwatch2) - print("lldb startup delay (run to breakpoint) benchmark:", self.stopwatch3) + print( + "lldb startup delay (create fresh target) benchmark:", + self.stopwatch) + print( + "lldb startup delay (set first breakpoint) benchmark:", + self.stopwatch2) + print( + "lldb startup delay (run to breakpoint) benchmark:", + self.stopwatch3) def run_startup_delays_bench(self, exe, break_spec, count): import pexpect @@ -48,7 +57,9 @@ class StartupDelaysBench(BenchBase): self.stopwatch2.reset() for i in range(count): # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption)) + self.child = pexpect.spawn( + '%s %s' % + (lldbtest_config.lldbExec, self.lldbOption)) child = self.child # Turn on logging for what the child sends back. @@ -57,7 +68,7 @@ class StartupDelaysBench(BenchBase): with self.stopwatch: # Create a fresh target. - child.sendline('file %s' % exe) # Aka 'target create'. + child.sendline('file %s' % exe) # Aka 'target create'. child.expect_exact(prompt) with self.stopwatch2: diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py b/lldb/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py index 3ab760d4abe..2a2a8ef000a 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py @@ -2,7 +2,8 @@ from __future__ import print_function -import os, sys +import os +import sys import lldb from lldbsuite.test import configuration from lldbsuite.test import lldbtest_config @@ -11,6 +12,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SteppingSpeedBench(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -26,7 +28,9 @@ class SteppingSpeedBench(BenchBase): @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_run_lldb_steppings(self): """Test lldb steppings on a large executable.""" print() @@ -40,7 +44,9 @@ class SteppingSpeedBench(BenchBase): prompt = self.child_prompt # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. @@ -58,7 +64,7 @@ class SteppingSpeedBench(BenchBase): for i in range(count): with self.stopwatch: # Disassemble the function. - child.sendline('next') # Aka 'thread step-over'. + child.sendline('next') # Aka 'thread step-over'. child.expect_exact(prompt) child.sendline('quit') diff --git a/lldb/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py b/lldb/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py index 3106c4511f5..ab2b2004fc5 100644 --- a/lldb/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py +++ b/lldb/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py @@ -3,8 +3,8 @@ from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test.lldbbench import * from lldbsuite.test.decorators import * @@ -12,6 +12,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import configuration from lldbsuite.test import lldbutil + class CompileRunToBreakpointBench(BenchBase): mydir = TestBase.compute_mydir(__file__) @@ -27,7 +28,9 @@ class CompileRunToBreakpointBench(BenchBase): @benchmarks_test @no_debug_info_test - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_run_lldb_then_gdb(self): """Benchmark turnaround time with lldb vs. gdb.""" print() @@ -35,15 +38,18 @@ class CompileRunToBreakpointBench(BenchBase): print("lldb turnaround benchmark:", self.stopwatch) self.run_gdb_turnaround(self.exe, self.function, self.count) print("gdb turnaround benchmark:", self.stopwatch) - print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg)) + print("lldb_avg/gdb_avg: %f" % (self.lldb_avg / self.gdb_avg)) def run_lldb_turnaround(self, exe, function, count): import pexpect + def run_one_round(): prompt = self.child_prompt # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. @@ -62,7 +68,8 @@ class CompileRunToBreakpointBench(BenchBase): self.stopwatch.reset() for i in range(count + 1): - # Ignore the first invoke lldb and run to the breakpoint turnaround time. + # Ignore the first invoke lldb and run to the breakpoint turnaround + # time. if i == 0: run_one_round() else: @@ -80,6 +87,7 @@ class CompileRunToBreakpointBench(BenchBase): def run_gdb_turnaround(self, exe, function, count): import pexpect + def run_one_round(): prompt = self.child_prompt @@ -102,8 +110,9 @@ class CompileRunToBreakpointBench(BenchBase): # Reset the stopwatch now. self.stopwatch.reset() - for i in range(count+1): - # Ignore the first invoke lldb and run to the breakpoint turnaround time. + for i in range(count + 1): + # Ignore the first invoke lldb and run to the breakpoint turnaround + # time. if i == 0: run_one_round() else: diff --git a/lldb/packages/Python/lldbsuite/test/concurrent_base.py b/lldb/packages/Python/lldbsuite/test/concurrent_base.py index bf51eb87369..4a7ae0b9c27 100644 --- a/lldb/packages/Python/lldbsuite/test/concurrent_base.py +++ b/lldb/packages/Python/lldbsuite/test/concurrent_base.py @@ -13,14 +13,15 @@ verified to match the expected number of events. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ConcurrentEventsBase(TestBase): # Concurrency is the primary test factor here, not debug info variants. @@ -49,18 +50,24 @@ class ConcurrentEventsBase(TestBase): if reason == lldb.eStopReasonBreakpoint: bpid = x.GetStopReasonDataAtIndex(0) bp = self.inferior_target.FindBreakpointByID(bpid) - reason_str = "%s hit %d times" % (lldbutil.get_description(bp), bp.GetHitCount()) + reason_str = "%s hit %d times" % ( + lldbutil.get_description(bp), bp.GetHitCount()) elif reason == lldb.eStopReasonWatchpoint: watchid = x.GetStopReasonDataAtIndex(0) watch = self.inferior_target.FindWatchpointByID(watchid) - reason_str = "%s hit %d times" % (lldbutil.get_description(watch), watch.GetHitCount()) + reason_str = "%s hit %d times" % ( + lldbutil.get_description(watch), watch.GetHitCount()) elif reason == lldb.eStopReasonSignal: signals = self.inferior_process.GetUnixSignals() - signal_name = signals.GetSignalAsCString(x.GetStopReasonDataAtIndex(0)) + signal_name = signals.GetSignalAsCString( + x.GetStopReasonDataAtIndex(0)) reason_str = "signal %s" % signal_name - location = "\t".join([lldbutil.get_description(x.GetFrameAtIndex(i)) for i in range(x.GetNumFrames())]) - ret.append("thread %d %s due to %s at\n\t%s" % (id, status, reason_str, location)) + location = "\t".join([lldbutil.get_description( + x.GetFrameAtIndex(i)) for i in range(x.GetNumFrames())]) + ret.append( + "thread %d %s due to %s at\n\t%s" % + (id, status, reason_str, location)) return ret def add_breakpoint(self, line, descriptions): @@ -68,35 +75,39 @@ class ConcurrentEventsBase(TestBase): returns the LLDB SBBreakpoint object. """ - bpno = lldbutil.run_break_set_by_file_and_line(self, self.filename, line, num_expected_locations=-1) + bpno = lldbutil.run_break_set_by_file_and_line( + self, self.filename, line, num_expected_locations=-1) bp = self.inferior_target.FindBreakpointByID(bpno) - descriptions.append(": file = 'main.cpp', line = %d" % self.finish_breakpoint_line) + descriptions.append( + ": file = 'main.cpp', line = %d" % + self.finish_breakpoint_line) return bp def inferior_done(self): - """ Returns true if the inferior is done executing all the event threads (and is stopped at self.finish_breakpoint, + """ Returns true if the inferior is done executing all the event threads (and is stopped at self.finish_breakpoint, or has terminated execution. """ return self.finish_breakpoint.GetHitCount() > 0 or \ - self.crash_count > 0 or \ - self.inferior_process.GetState() == lldb.eStateExited + self.crash_count > 0 or \ + self.inferior_process.GetState() == lldb.eStateExited def count_signaled_threads(self): count = 0 for thread in self.inferior_process: - if thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex(0) == self.inferior_process.GetUnixSignals().GetSignalNumberFromName('SIGUSR1'): + if thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex( + 0) == self.inferior_process.GetUnixSignals().GetSignalNumberFromName('SIGUSR1'): count += 1 return count def do_thread_actions(self, - num_breakpoint_threads = 0, - num_signal_threads = 0, - num_watchpoint_threads = 0, - num_crash_threads = 0, - num_delay_breakpoint_threads = 0, - num_delay_signal_threads = 0, - num_delay_watchpoint_threads = 0, - num_delay_crash_threads = 0): + num_breakpoint_threads=0, + num_signal_threads=0, + num_watchpoint_threads=0, + num_crash_threads=0, + num_delay_breakpoint_threads=0, + num_delay_signal_threads=0, + num_delay_watchpoint_threads=0, + num_delay_crash_threads=0): """ Sets a breakpoint in the main thread where test parameters (numbers of threads) can be adjusted, runs the inferior to that point, and modifies the locals that control the event thread counts. Also sets a breakpoint in breakpoint_func (the function executed by each 'breakpoint' thread) and a watchpoint on a global modified in @@ -112,105 +123,166 @@ class ConcurrentEventsBase(TestBase): expected_bps = [] # Initialize all the breakpoints (main thread/aux thread) - self.setup_breakpoint = self.add_breakpoint(self.setup_breakpoint_line, expected_bps) - self.finish_breakpoint = self.add_breakpoint(self.finish_breakpoint_line, expected_bps) + self.setup_breakpoint = self.add_breakpoint( + self.setup_breakpoint_line, expected_bps) + self.finish_breakpoint = self.add_breakpoint( + self.finish_breakpoint_line, expected_bps) # Set the thread breakpoint if num_breakpoint_threads + num_delay_breakpoint_threads > 0: - self.thread_breakpoint = self.add_breakpoint(self.thread_breakpoint_line, expected_bps) + self.thread_breakpoint = self.add_breakpoint( + self.thread_breakpoint_line, expected_bps) # Verify breakpoints - self.expect("breakpoint list -f", "Breakpoint locations shown correctly", substrs = expected_bps) + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=expected_bps) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Check we are at line self.setup_breakpoint self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) + substrs=["stop reason = breakpoint 1."]) # Initialize the (single) watchpoint on the global variable (g_watchme) if num_watchpoint_threads + num_delay_watchpoint_threads > 0: self.runCmd("watchpoint set variable g_watchme") for w in self.inferior_target.watchpoint_iter(): self.thread_watchpoint = w - self.assertTrue("g_watchme" in str(self.thread_watchpoint), "Watchpoint location not shown correctly") + self.assertTrue( + "g_watchme" in str( + self.thread_watchpoint), + "Watchpoint location not shown correctly") # Get the process self.inferior_process = self.inferior_target.GetProcess() # We should be stopped at the setup site where we can set the number of # threads doing each action (break/crash/signal/watch) - self.assertEqual(self.inferior_process.GetNumThreads(), 1, 'Expected to stop before any additional threads are spawned.') + self.assertEqual( + self.inferior_process.GetNumThreads(), + 1, + 'Expected to stop before any additional threads are spawned.') self.runCmd("expr num_breakpoint_threads=%d" % num_breakpoint_threads) self.runCmd("expr num_crash_threads=%d" % num_crash_threads) self.runCmd("expr num_signal_threads=%d" % num_signal_threads) self.runCmd("expr num_watchpoint_threads=%d" % num_watchpoint_threads) - self.runCmd("expr num_delay_breakpoint_threads=%d" % num_delay_breakpoint_threads) - self.runCmd("expr num_delay_crash_threads=%d" % num_delay_crash_threads) - self.runCmd("expr num_delay_signal_threads=%d" % num_delay_signal_threads) - self.runCmd("expr num_delay_watchpoint_threads=%d" % num_delay_watchpoint_threads) + self.runCmd( + "expr num_delay_breakpoint_threads=%d" % + num_delay_breakpoint_threads) + self.runCmd( + "expr num_delay_crash_threads=%d" % + num_delay_crash_threads) + self.runCmd( + "expr num_delay_signal_threads=%d" % + num_delay_signal_threads) + self.runCmd( + "expr num_delay_watchpoint_threads=%d" % + num_delay_watchpoint_threads) # Continue the inferior so threads are spawned self.runCmd("continue") # Make sure we see all the threads. The inferior program's threads all synchronize with a pseudo-barrier; that is, - # the inferior program ensures all threads are started and running before any thread triggers its 'event'. + # the inferior program ensures all threads are started and running + # before any thread triggers its 'event'. num_threads = self.inferior_process.GetNumThreads() expected_num_threads = num_breakpoint_threads + num_delay_breakpoint_threads \ - + num_signal_threads + num_delay_signal_threads \ - + num_watchpoint_threads + num_delay_watchpoint_threads \ - + num_crash_threads + num_delay_crash_threads + 1 - self.assertEqual(num_threads, expected_num_threads, - 'Expected to see %d threads, but seeing %d. Details:\n%s' % (expected_num_threads, - num_threads, - "\n\t".join(self.describe_threads()))) + + num_signal_threads + num_delay_signal_threads \ + + num_watchpoint_threads + num_delay_watchpoint_threads \ + + num_crash_threads + num_delay_crash_threads + 1 + self.assertEqual( + num_threads, + expected_num_threads, + 'Expected to see %d threads, but seeing %d. Details:\n%s' % + (expected_num_threads, + num_threads, + "\n\t".join( + self.describe_threads()))) self.signal_count = self.count_signaled_threads() - self.crash_count = len(lldbutil.get_crashed_threads(self, self.inferior_process)) + self.crash_count = len( + lldbutil.get_crashed_threads( + self, self.inferior_process)) # Run to completion (or crash) - while not self.inferior_done(): + while not self.inferior_done(): if self.TraceOn(): self.runCmd("thread backtrace all") self.runCmd("continue") self.signal_count += self.count_signaled_threads() - self.crash_count += len(lldbutil.get_crashed_threads(self, self.inferior_process)) + self.crash_count += len( + lldbutil.get_crashed_threads( + self, self.inferior_process)) if num_crash_threads > 0 or num_delay_crash_threads > 0: # Expecting a crash - self.assertTrue(self.crash_count > 0, - "Expecting at least one thread to crash. Details: %s" % "\t\n".join(self.describe_threads())) + self.assertTrue( + self.crash_count > 0, + "Expecting at least one thread to crash. Details: %s" % + "\t\n".join( + self.describe_threads())) # Ensure the zombie process is reaped self.runCmd("process kill") elif num_crash_threads == 0 and num_delay_crash_threads == 0: - # There should be a single active thread (the main one) which hit the breakpoint after joining - self.assertEqual(1, self.finish_breakpoint.GetHitCount(), "Expected main thread (finish) breakpoint to be hit once") + # There should be a single active thread (the main one) which hit + # the breakpoint after joining + self.assertEqual( + 1, + self.finish_breakpoint.GetHitCount(), + "Expected main thread (finish) breakpoint to be hit once") num_threads = self.inferior_process.GetNumThreads() - self.assertEqual(1, num_threads, "Expecting 1 thread but seeing %d. Details:%s" % (num_threads, - "\n\t".join(self.describe_threads()))) + self.assertEqual( + 1, + num_threads, + "Expecting 1 thread but seeing %d. Details:%s" % + (num_threads, + "\n\t".join( + self.describe_threads()))) self.runCmd("continue") # The inferior process should have exited without crashing - self.assertEqual(0, self.crash_count, "Unexpected thread(s) in crashed state") - self.assertEqual(self.inferior_process.GetState(), lldb.eStateExited, PROCESS_EXITED) + self.assertEqual( + 0, + self.crash_count, + "Unexpected thread(s) in crashed state") + self.assertEqual( + self.inferior_process.GetState(), + lldb.eStateExited, + PROCESS_EXITED) # Verify the number of actions took place matches expected numbers expected_breakpoint_threads = num_delay_breakpoint_threads + num_breakpoint_threads - breakpoint_hit_count = self.thread_breakpoint.GetHitCount() if expected_breakpoint_threads > 0 else 0 - self.assertEqual(expected_breakpoint_threads, breakpoint_hit_count, - "Expected %d breakpoint hits, but got %d" % (expected_breakpoint_threads, breakpoint_hit_count)) + breakpoint_hit_count = self.thread_breakpoint.GetHitCount( + ) if expected_breakpoint_threads > 0 else 0 + self.assertEqual( + expected_breakpoint_threads, + breakpoint_hit_count, + "Expected %d breakpoint hits, but got %d" % + (expected_breakpoint_threads, + breakpoint_hit_count)) expected_signal_threads = num_delay_signal_threads + num_signal_threads - self.assertEqual(expected_signal_threads, self.signal_count, - "Expected %d stops due to signal delivery, but got %d" % (expected_signal_threads, self.signal_count)) + self.assertEqual( + expected_signal_threads, + self.signal_count, + "Expected %d stops due to signal delivery, but got %d" % + (expected_signal_threads, + self.signal_count)) expected_watchpoint_threads = num_delay_watchpoint_threads + num_watchpoint_threads - watchpoint_hit_count = self.thread_watchpoint.GetHitCount() if expected_watchpoint_threads > 0 else 0 - self.assertEqual(expected_watchpoint_threads, watchpoint_hit_count, - "Expected %d watchpoint hits, got %d" % (expected_watchpoint_threads, watchpoint_hit_count)) + watchpoint_hit_count = self.thread_watchpoint.GetHitCount( + ) if expected_watchpoint_threads > 0 else 0 + self.assertEqual( + expected_watchpoint_threads, + watchpoint_hit_count, + "Expected %d watchpoint hits, got %d" % + (expected_watchpoint_threads, + watchpoint_hit_count)) diff --git a/lldb/packages/Python/lldbsuite/test/configuration.py b/lldb/packages/Python/lldbsuite/test/configuration.py index d797b17c164..ff061782d47 100644 --- a/lldb/packages/Python/lldbsuite/test/configuration.py +++ b/lldb/packages/Python/lldbsuite/test/configuration.py @@ -23,26 +23,31 @@ import unittest2 # LLDB Modules import lldbsuite + def __setCrashInfoHook_Mac(text): from . import crashinfo crashinfo.setCrashReporterDescription(text) + def setupCrashInfoHook(): if platform.system() == "Darwin": from . import lock test_dir = os.environ['LLDB_TEST'] if not test_dir or not os.path.exists(test_dir): return - dylib_lock = os.path.join(test_dir,"crashinfo.lock") - dylib_src = os.path.join(test_dir,"crashinfo.c") - dylib_dst = os.path.join(test_dir,"crashinfo.so") + dylib_lock = os.path.join(test_dir, "crashinfo.lock") + dylib_src = os.path.join(test_dir, "crashinfo.c") + dylib_dst = os.path.join(test_dir, "crashinfo.so") try: compile_lock = lock.Lock(dylib_lock) compile_lock.acquire() - if not os.path.isfile(dylib_dst) or os.path.getmtime(dylib_dst) < os.path.getmtime(dylib_src): + if not os.path.isfile(dylib_dst) or os.path.getmtime( + dylib_dst) < os.path.getmtime(dylib_src): # we need to compile - cmd = "SDKROOT= xcrun clang %s -o %s -framework Python -Xlinker -dylib -iframework /System/Library/Frameworks/ -Xlinker -F /System/Library/Frameworks/" % (dylib_src,dylib_dst) - if subprocess.call(cmd,shell=True) != 0 or not os.path.isfile(dylib_dst): + cmd = "SDKROOT= xcrun clang %s -o %s -framework Python -Xlinker -dylib -iframework /System/Library/Frameworks/ -Xlinker -F /System/Library/Frameworks/" % ( + dylib_src, dylib_dst) + if subprocess.call( + cmd, shell=True) != 0 or not os.path.isfile(dylib_dst): raise Exception('command failed: "{}"'.format(cmd)) finally: compile_lock.release() @@ -92,7 +97,8 @@ skip_long_running_test = True # prints machine-readable output similar to what clang tests produce. parsable = False -# The regular expression pattern to match against eligible filenames as our test cases. +# The regular expression pattern to match against eligible filenames as +# our test cases. regexp = None # By default, recorded session info for errored/failed test are dumped into its @@ -121,7 +127,7 @@ verbose = 0 # By default, search from the script directory. # We can't use sys.path[0] to determine the script directory # because it doesn't work under a debugger -testdirs = [ os.path.dirname(os.path.realpath(__file__)) ] +testdirs = [os.path.dirname(os.path.realpath(__file__))] # Separator string. separator = '-' * 70 @@ -152,15 +158,18 @@ test_result = None rerun_all_issues = False rerun_max_file_threhold = 0 -# The names of all tests. Used to assert we don't have two tests with the same base name. +# The names of all tests. Used to assert we don't have two tests with the +# same base name. all_tests = set() # safe default -setCrashInfoHook = lambda x : None +setCrashInfoHook = lambda x: None + def shouldSkipBecauseOfCategories(test_categories): if useCategories: - if len(test_categories) == 0 or len(categoriesList & set(test_categories)) == 0: + if len(test_categories) == 0 or len( + categoriesList & set(test_categories)) == 0: return True for category in skipCategories: diff --git a/lldb/packages/Python/lldbsuite/test/darwin_log.py b/lldb/packages/Python/lldbsuite/test/darwin_log.py index d603880391b..c613ea46782 100644 --- a/lldb/packages/Python/lldbsuite/test/darwin_log.py +++ b/lldb/packages/Python/lldbsuite/test/darwin_log.py @@ -46,9 +46,9 @@ class DarwinLogTestBase(lldbtest.TestBase): # or greater. version = platform.mac_ver()[0].split('.') if ((int(version[0]) == 10) and (int(version[1]) < 12) or - (int(version[0]) < 10)): - self.skipTest("DarwinLog tests currently require macOS 10.12+") - return + (int(version[0]) < 10)): + self.skipTest("DarwinLog tests currently require macOS 10.12+") + return self.child = None self.child_prompt = '(lldb) ' @@ -73,8 +73,9 @@ class DarwinLogTestBase(lldbtest.TestBase): if self.enable_process_monitor_logging: if platform.system() == 'Darwin': - self.runCmd("settings set target.process.extra-startup-command " - "QSetLogging:bitmask=LOG_DARWIN_LOG;") + self.runCmd( + "settings set target.process.extra-startup-command " + "QSetLogging:bitmask=LOG_DARWIN_LOG;") self.expect_prompt() # Run the enable command if we have one. @@ -98,7 +99,8 @@ class DarwinLogTestBase(lldbtest.TestBase): # Prevent mirroring of NSLog/os_log content to stderr. We want log # messages to come exclusively through our log channel. - self.runCmd("settings set target.env-vars IDE_DISABLED_OS_ACTIVITY_DT_MODE=1") + self.runCmd( + "settings set target.env-vars IDE_DISABLED_OS_ACTIVITY_DT_MODE=1") self.expect_prompt() # Run any darwin-log settings commands now, before we enable logging. @@ -176,7 +178,7 @@ class DarwinLogTestBase(lldbtest.TestBase): expect_regexes = ( [re.compile(r"source-log-([^-]+)-(\S+)"), re.compile(r"exited with status") - ]) + ]) self.expect(expect_regexes) @@ -193,8 +195,11 @@ class DarwinLogEventBasedTestBase(lldbtest.TestBase): NO_DEBUG_INFO_TESTCASE = True class EventListenerThread(threading.Thread): + def __init__(self, listener, process, trace_on, max_entry_count): - super(DarwinLogEventBasedTestBase.EventListenerThread, self).__init__() + super( + DarwinLogEventBasedTestBase.EventListenerThread, + self).__init__() self.process = process self.listener = listener self.trace_on = trace_on @@ -301,9 +306,9 @@ class DarwinLogEventBasedTestBase(lldbtest.TestBase): # or greater. version = platform.mac_ver()[0].split('.') if ((int(version[0]) == 10) and (int(version[1]) < 12) or - (int(version[0]) < 10)): - self.skipTest("DarwinLog tests currently require macOS 10.12+") - return + (int(version[0]) < 10)): + self.skipTest("DarwinLog tests currently require macOS 10.12+") + return # Source filename. self.source = 'main.c' @@ -406,8 +411,8 @@ class DarwinLogEventBasedTestBase(lldbtest.TestBase): listener = lldb.SBListener("SBStructuredData listener") self.assertIsNotNone(listener) - rc = broadcaster.AddListener(listener, - lldb.SBProcess.eBroadcastBitStructuredData) + rc = broadcaster.AddListener( + listener, lldb.SBProcess.eBroadcastBitStructuredData) self.assertTrue(rc, "Successfully add listener to process broadcaster") # Start the listening thread to retrieve the events. diff --git a/lldb/packages/Python/lldbsuite/test/decorators.py b/lldb/packages/Python/lldbsuite/test/decorators.py index 6613b25109e..4d78f16f9ae 100644 --- a/lldb/packages/Python/lldbsuite/test/decorators.py +++ b/lldb/packages/Python/lldbsuite/test/decorators.py @@ -24,24 +24,33 @@ from lldbsuite.support import funcutils from lldbsuite.test import lldbplatform from lldbsuite.test import lldbplatformutil + class DecorateMode: Skip, Xfail = range(2) - + # You can use no_match to reverse the test of the conditional that is used to match keyword # arguments in the skip / xfail decorators. If oslist=["windows", "linux"] skips windows -# and linux, oslist=no_match(["windows", "linux"]) skips *unless* windows or linux. +# and linux, oslist=no_match(["windows", "linux"]) skips *unless* windows +# or linux. class no_match: + def __init__(self, item): self.item = item + def _check_expected_version(comparison, expected, actual): - def fn_leq(x,y): return x <= y - def fn_less(x,y): return x < y - def fn_geq(x,y): return x >= y - def fn_greater(x,y): return x > y - def fn_eq(x,y): return x == y - def fn_neq(x,y): return x != y + def fn_leq(x, y): return x <= y + + def fn_less(x, y): return x < y + + def fn_geq(x, y): return x >= y + + def fn_greater(x, y): return x > y + + def fn_eq(x, y): return x == y + + def fn_neq(x, y): return x != y op_lookup = { "==": fn_eq, @@ -52,11 +61,14 @@ def _check_expected_version(comparison, expected, actual): "<": fn_less, ">=": fn_geq, "<=": fn_leq - } + } expected_str = '.'.join([str(x) for x in expected]) actual_str = '.'.join([str(x) for x in actual]) - return op_lookup[comparison](LooseVersion(actual_str), LooseVersion(expected_str)) + return op_lookup[comparison]( + LooseVersion(actual_str), + LooseVersion(expected_str)) + def _match_decorator_property(expected, actual): if actual is None or expected is None: @@ -64,17 +76,21 @@ def _match_decorator_property(expected, actual): if isinstance(expected, no_match): return not _match_decorator_property(expected.item, actual) - elif isinstance(expected, (re._pattern_type,)+six.string_types): + elif isinstance(expected, (re._pattern_type,) + six.string_types): return re.search(expected, actual) is not None elif hasattr(expected, "__iter__"): - return any([x is not None and _match_decorator_property(x, actual) for x in expected]) + return any([x is not None and _match_decorator_property(x, actual) + for x in expected]) else: return expected == actual + def expectedFailure(expected_fn, bugnumber=None): def expectedFailure_impl(func): if isinstance(func, type) and issubclass(func, unittest2.TestCase): - raise Exception("Decorator can only be used to decorate a test method") + raise Exception( + "Decorator can only be used to decorate a test method") + @wraps(func) def wrapper(*args, **kwargs): self = args[0] @@ -102,10 +118,12 @@ def expectedFailure(expected_fn, bugnumber=None): else: return expectedFailure_impl + def skipTestIfFn(expected_fn, bugnumber=None): def skipTestIfFn_impl(func): if isinstance(func, type) and issubclass(func, unittest2.TestCase): - raise Exception("@skipTestIfFn can only be used to decorate a test method") + raise Exception( + "@skipTestIfFn can only be used to decorate a test method") @wraps(func) def wrapper(*args, **kwargs): @@ -116,7 +134,7 @@ def skipTestIfFn(expected_fn, bugnumber=None): reason = expected_fn() if reason is not None: - self.skipTest(reason) + self.skipTest(reason) else: func(*args, **kwargs) return wrapper @@ -124,30 +142,50 @@ def skipTestIfFn(expected_fn, bugnumber=None): # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows) # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])). When called # the first way, the first argument will be the actual function because decorators are - # weird like that. So this is basically a check that says "how was the decorator used" + # weird like that. So this is basically a check that says "how was the + # decorator used" if six.callable(bugnumber): return skipTestIfFn_impl(bugnumber) else: return skipTestIfFn_impl + def _decorateTest(mode, - bugnumber=None, oslist=None, hostoslist=None, - compiler=None, compiler_version=None, - archs=None, triple=None, - debug_info=None, - swig_version=None, py_version=None, - remote=None): + bugnumber=None, oslist=None, hostoslist=None, + compiler=None, compiler_version=None, + archs=None, triple=None, + debug_info=None, + swig_version=None, py_version=None, + remote=None): def fn(self): - skip_for_os = _match_decorator_property(lldbplatform.translate(oslist), self.getPlatform()) - skip_for_hostos = _match_decorator_property(lldbplatform.translate(hostoslist), lldbplatformutil.getHostPlatform()) - skip_for_compiler = _match_decorator_property(compiler, self.getCompiler()) and self.expectedCompilerVersion(compiler_version) - skip_for_arch = _match_decorator_property(archs, self.getArchitecture()) - skip_for_debug_info = _match_decorator_property(debug_info, self.debug_info) - skip_for_triple = _match_decorator_property(triple, lldb.DBG.GetSelectedPlatform().GetTriple()) - skip_for_remote = _match_decorator_property(remote, lldb.remote_platform is not None) - - skip_for_swig_version = (swig_version is None) or (not hasattr(lldb, 'swig_version')) or (_check_expected_version(swig_version[0], swig_version[1], lldb.swig_version)) - skip_for_py_version = (py_version is None) or _check_expected_version(py_version[0], py_version[1], sys.version_info) + skip_for_os = _match_decorator_property( + lldbplatform.translate(oslist), self.getPlatform()) + skip_for_hostos = _match_decorator_property( + lldbplatform.translate(hostoslist), + lldbplatformutil.getHostPlatform()) + skip_for_compiler = _match_decorator_property( + compiler, self.getCompiler()) and self.expectedCompilerVersion(compiler_version) + skip_for_arch = _match_decorator_property( + archs, self.getArchitecture()) + skip_for_debug_info = _match_decorator_property( + debug_info, self.debug_info) + skip_for_triple = _match_decorator_property( + triple, lldb.DBG.GetSelectedPlatform().GetTriple()) + skip_for_remote = _match_decorator_property( + remote, lldb.remote_platform is not None) + + skip_for_swig_version = ( + swig_version is None) or ( + not hasattr( + lldb, + 'swig_version')) or ( + _check_expected_version( + swig_version[0], + swig_version[1], + lldb.swig_version)) + skip_for_py_version = ( + py_version is None) or _check_expected_version( + py_version[0], py_version[1], sys.version_info) # For the test to be skipped, all specified (e.g. not None) parameters must be True. # An unspecified parameter means "any", so those are marked skip by default. And we skip @@ -169,10 +207,13 @@ def _decorateTest(mode, reasons.append(this_condition[2]) reason_str = None if final_skip_result: - mode_str = {DecorateMode.Skip : "skipping", DecorateMode.Xfail : "xfailing"}[mode] + mode_str = { + DecorateMode.Skip: "skipping", + DecorateMode.Xfail: "xfailing"}[mode] if len(reasons) > 0: reason_str = ",".join(reasons) - reason_str = "{} due to the following parameter(s): {}".format(mode_str, reason_str) + reason_str = "{} due to the following parameter(s): {}".format( + mode_str, reason_str) else: reason_str = "{} unconditionally" if bugnumber is not None and not six.callable(bugnumber): @@ -192,6 +233,8 @@ def _decorateTest(mode, # @expectedFailureAll, xfail for all platform/compiler/arch, # @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture # @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386 + + def expectedFailureAll(bugnumber=None, oslist=None, hostoslist=None, compiler=None, compiler_version=None, @@ -200,13 +243,13 @@ def expectedFailureAll(bugnumber=None, swig_version=None, py_version=None, remote=None): return _decorateTest(DecorateMode.Xfail, - bugnumber=bugnumber, - oslist=oslist, hostoslist=hostoslist, - compiler=compiler, compiler_version=compiler_version, - archs=archs, triple=triple, - debug_info=debug_info, - swig_version=swig_version, py_version=py_version, - remote=remote) + bugnumber=bugnumber, + oslist=oslist, hostoslist=hostoslist, + compiler=compiler, compiler_version=compiler_version, + archs=archs, triple=triple, + debug_info=debug_info, + swig_version=swig_version, py_version=py_version, + remote=remote) # provide a function to skip on defined oslist, compiler version, and archs @@ -223,26 +266,31 @@ def skipIf(bugnumber=None, swig_version=None, py_version=None, remote=None): return _decorateTest(DecorateMode.Skip, - bugnumber=bugnumber, - oslist=oslist, hostoslist=hostoslist, - compiler=compiler, compiler_version=compiler_version, - archs=archs, triple=triple, - debug_info=debug_info, - swig_version=swig_version, py_version=py_version, - remote=remote) + bugnumber=bugnumber, + oslist=oslist, hostoslist=hostoslist, + compiler=compiler, compiler_version=compiler_version, + archs=archs, triple=triple, + debug_info=debug_info, + swig_version=swig_version, py_version=py_version, + remote=remote) + def _skip_for_android(reason, api_levels, archs): def impl(obj): - result = lldbplatformutil.match_android_device(obj.getArchitecture(), valid_archs=archs, valid_api_levels=api_levels) + result = lldbplatformutil.match_android_device( + obj.getArchitecture(), valid_archs=archs, valid_api_levels=api_levels) return reason if result else None return impl + def add_test_categories(cat): """Add test categories to a TestCase method""" cat = test_categories.validate(cat, True) + def impl(func): if isinstance(func, type) and issubclass(func, unittest2.TestCase): - raise Exception("@add_test_categories can only be used to decorate a test method") + raise Exception( + "@add_test_categories can only be used to decorate a test method") if hasattr(func, "categories"): cat.extend(func.categories) func.categories = cat @@ -250,6 +298,7 @@ def add_test_categories(cat): return impl + def benchmarks_test(func): """Decorate the item as a benchmarks test.""" def should_skip_benchmarks_test(): @@ -260,11 +309,14 @@ def benchmarks_test(func): result.__benchmarks_test__ = True return result + def no_debug_info_test(func): """Decorate the item as a test what don't use any debug info. If this annotation is specified then the test runner won't generate a separate test for each debug info format. """ if isinstance(func, type) and issubclass(func, unittest2.TestCase): - raise Exception("@no_debug_info_test can only be used to decorate a test method") + raise Exception( + "@no_debug_info_test can only be used to decorate a test method") + @wraps(func) def wrapper(self, *args, **kwargs): return func(self, *args, **kwargs) @@ -273,30 +325,51 @@ def no_debug_info_test(func): wrapper.__no_debug_info_test__ = True return wrapper + def debugserver_test(func): """Decorate the item as a debugserver test.""" def should_skip_debugserver_test(): return "debugserver tests" if configuration.dont_do_debugserver_test else None return skipTestIfFn(should_skip_debugserver_test)(func) + def llgs_test(func): """Decorate the item as a lldb-server test.""" def should_skip_llgs_tests(): return "llgs tests" if configuration.dont_do_llgs_test else None return skipTestIfFn(should_skip_llgs_tests)(func) + def not_remote_testsuite_ready(func): """Decorate the item as a test which is not ready yet for remote testsuite.""" def is_remote(): return "Not ready for remote testsuite" if lldb.remote_platform else None return skipTestIfFn(is_remote)(func) -def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None, archs=None): - return expectedFailureAll(oslist=oslist, bugnumber=bugnumber, compiler=compilers, archs=archs, debug_info=debug_info) + +def expectedFailureOS( + oslist, + bugnumber=None, + compilers=None, + debug_info=None, + archs=None): + return expectedFailureAll( + oslist=oslist, + bugnumber=bugnumber, + compiler=compilers, + archs=archs, + debug_info=debug_info) + def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None): - # For legacy reasons, we support both "darwin" and "macosx" as OS X triples. - return expectedFailureOS(lldbplatform.darwin_all, bugnumber, compilers, debug_info=debug_info) + # For legacy reasons, we support both "darwin" and "macosx" as OS X + # triples. + return expectedFailureOS( + lldbplatform.darwin_all, + bugnumber, + compilers, + debug_info=debug_info) + def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None): """ Mark a test as xfail for Android. @@ -308,10 +381,17 @@ def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None): arch - A sequence of architecture names specifying the architectures for which a test is expected to fail. None means all architectures. """ - return expectedFailure(_skip_for_android("xfailing on android", api_levels, archs), bugnumber) + return expectedFailure( + _skip_for_android( + "xfailing on android", + api_levels, + archs), + bugnumber) # Flakey tests get two chances to run. If they fail the first time round, the result formatter # makes sure it is run one more time. + + def expectedFlakey(expected_fn, bugnumber=None): def expectedFailure_impl(func): @wraps(func) @@ -335,52 +415,76 @@ def expectedFlakey(expected_fn, bugnumber=None): else: return expectedFailure_impl + def expectedFlakeyDwarf(bugnumber=None): def fn(self): return self.debug_info == "dwarf" return expectedFlakey(fn, bugnumber) + def expectedFlakeyDsym(bugnumber=None): def fn(self): return self.debug_info == "dwarf" return expectedFlakey(fn, bugnumber) + def expectedFlakeyOS(oslist, bugnumber=None, compilers=None): def fn(self): return (self.getPlatform() in oslist and self.expectedCompiler(compilers)) return expectedFlakey(fn, bugnumber) + def expectedFlakeyDarwin(bugnumber=None, compilers=None): - # For legacy reasons, we support both "darwin" and "macosx" as OS X triples. - return expectedFlakeyOS(lldbplatformutil.getDarwinOSTriples(), bugnumber, compilers) + # For legacy reasons, we support both "darwin" and "macosx" as OS X + # triples. + return expectedFlakeyOS( + lldbplatformutil.getDarwinOSTriples(), + bugnumber, + compilers) + def expectedFlakeyFreeBSD(bugnumber=None, compilers=None): return expectedFlakeyOS(['freebsd'], bugnumber, compilers) + def expectedFlakeyLinux(bugnumber=None, compilers=None): return expectedFlakeyOS(['linux'], bugnumber, compilers) + def expectedFlakeyNetBSD(bugnumber=None, compilers=None): return expectedFlakeyOS(['netbsd'], bugnumber, compilers) + def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None): if compiler_version is None: - compiler_version=['=', None] + compiler_version = ['=', None] + def fn(self): return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version) return expectedFlakey(fn, bugnumber) # @expectedFlakeyClang('bugnumber', ['<=', '3.4']) + + def expectedFlakeyClang(bugnumber=None, compiler_version=None): return expectedFlakeyCompiler('clang', compiler_version, bugnumber) # @expectedFlakeyGcc('bugnumber', ['<=', '3.4']) + + def expectedFlakeyGcc(bugnumber=None, compiler_version=None): return expectedFlakeyCompiler('gcc', compiler_version, bugnumber) + def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None): - return expectedFlakey(_skip_for_android("flakey on android", api_levels, archs), bugnumber) + return expectedFlakey( + _skip_for_android( + "flakey on android", + api_levels, + archs), + bugnumber) + def skipIfRemote(func): """Decorate the item to skip tests if testing remotely.""" @@ -388,61 +492,86 @@ def skipIfRemote(func): return "skip on remote platform" if lldb.remote_platform else None return skipTestIfFn(is_remote)(func) + def skipIfRemoteDueToDeadlock(func): """Decorate the item to skip tests if testing remotely due to the test deadlocking.""" def is_remote(): return "skip on remote platform (deadlocks)" if lldb.remote_platform else None return skipTestIfFn(is_remote)(func) + def skipIfNoSBHeaders(func): """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers.""" def are_sb_headers_missing(): if lldbplatformutil.getHostPlatform() == 'darwin': - header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h') + header = os.path.join( + os.environ["LLDB_LIB_DIR"], + 'LLDB.framework', + 'Versions', + 'Current', + 'Headers', + 'LLDB.h') else: - header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h") + header = os.path.join( + os.environ["LLDB_SRC"], + "include", + "lldb", + "API", + "LLDB.h") if not os.path.exists(header): return "skip because LLDB.h header not found" return None return skipTestIfFn(are_sb_headers_missing)(func) + def skipIfiOSSimulator(func): """Decorate the item to skip tests that should be skipped on the iOS Simulator.""" def is_ios_simulator(): return "skip on the iOS Simulator" if configuration.lldb_platform_name == 'ios-simulator' else None return skipTestIfFn(is_ios_simulator)(func) + def skipIfFreeBSD(func): """Decorate the item to skip tests that should be skipped on FreeBSD.""" return skipIfPlatform(["freebsd"])(func) + def skipIfNetBSD(func): """Decorate the item to skip tests that should be skipped on NetBSD.""" return skipIfPlatform(["netbsd"])(func) + def skipIfDarwin(func): """Decorate the item to skip tests that should be skipped on Darwin.""" - return skipIfPlatform(lldbplatform.translate(lldbplatform.darwin_all))(func) + return skipIfPlatform( + lldbplatform.translate( + lldbplatform.darwin_all))(func) + def skipIfLinux(func): """Decorate the item to skip tests that should be skipped on Linux.""" return skipIfPlatform(["linux"])(func) + def skipIfWindows(func): """Decorate the item to skip tests that should be skipped on Windows.""" return skipIfPlatform(["windows"])(func) + def skipUnlessWindows(func): """Decorate the item to skip tests that should be skipped on any non-Windows platform.""" return skipUnlessPlatform(["windows"])(func) + def skipUnlessDarwin(func): """Decorate the item to skip tests that should be skipped on any non Darwin platform.""" return skipUnlessPlatform(lldbplatformutil.getDarwinOSTriples())(func) + def skipUnlessGoInstalled(func): """Decorate the item to skip tests when no Go compiler is available.""" + def is_go_missing(self): compiler = self.getGoCompilerVersion() if not compiler: @@ -450,7 +579,8 @@ def skipUnlessGoInstalled(func): match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler) if not match_version: # Couldn't determine version. - return "skipping because go version could not be parsed out of {}".format(compiler) + return "skipping because go version could not be parsed out of {}".format( + compiler) else: min_strict_version = StrictVersion("1.4.0") compiler_strict_version = StrictVersion(match_version.group(1)) @@ -460,20 +590,26 @@ def skipUnlessGoInstalled(func): return None return skipTestIfFn(is_go_missing)(func) + def skipIfHostIncompatibleWithRemote(func): """Decorate the item to skip tests if binaries built on this host are incompatible.""" + def is_host_incompatible_with_remote(self): host_arch = self.getLldbArchitecture() host_platform = lldbplatformutil.getHostPlatform() target_arch = self.getArchitecture() target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform() - if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch: - return "skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch) + if not (target_arch == 'x86_64' and host_arch == + 'i386') and host_arch != target_arch: + return "skipping because target %s is not compatible with host architecture %s" % ( + target_arch, host_arch) elif target_platform != host_platform: - return "skipping because target is %s but host is %s" % (target_platform, host_platform) + return "skipping because target is %s but host is %s" % ( + target_platform, host_platform) return None return skipTestIfFn(is_host_incompatible_with_remote)(func) + def skipIfPlatform(oslist): """Decorate the item to skip tests if running on one of the listed platforms.""" # This decorator cannot be ported to `skipIf` yet because it is used on entire @@ -481,6 +617,7 @@ def skipIfPlatform(oslist): return unittest2.skipIf(lldbplatformutil.getPlatform() in oslist, "skip on %s" % (", ".join(oslist))) + def skipUnlessPlatform(oslist): """Decorate the item to skip tests unless running on one of the listed platforms.""" # This decorator cannot be ported to `skipIf` yet because it is used on entire @@ -488,6 +625,7 @@ def skipUnlessPlatform(oslist): return unittest2.skipUnless(lldbplatformutil.getPlatform() in oslist, "requires one of %s" % (", ".join(oslist))) + def skipIfTargetAndroid(api_levels=None, archs=None): """Decorator to skip tests when the target is Android. @@ -497,17 +635,33 @@ def skipIfTargetAndroid(api_levels=None, archs=None): arch - A sequence of architecture names specifying the architectures for which a test is skipped. None means all architectures. """ - return skipTestIfFn(_skip_for_android("skipping for android", api_levels, archs)) + return skipTestIfFn( + _skip_for_android( + "skipping for android", + api_levels, + archs)) + def skipUnlessCompilerRt(func): """Decorate the item to skip tests if testing remotely.""" def is_compiler_rt_missing(): - compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "llvm","projects","compiler-rt") - return "compiler-rt not found" if not os.path.exists(compilerRtPath) else None + compilerRtPath = os.path.join( + os.path.dirname(__file__), + "..", + "..", + "..", + "..", + "llvm", + "projects", + "compiler-rt") + return "compiler-rt not found" if not os.path.exists( + compilerRtPath) else None return skipTestIfFn(is_compiler_rt_missing)(func) + def skipUnlessThreadSanitizer(func): """Decorate the item to skip test unless Clang -fsanitize=thread is supported.""" + def is_compiler_clang_with_thread_sanitizer(self): compiler_path = self.getCompiler() compiler = os.path.basename(compiler_path) @@ -515,10 +669,10 @@ def skipUnlessThreadSanitizer(func): return "Test requires clang as compiler" f = tempfile.NamedTemporaryFile() cmd = "echo 'int main() {}' | %s -x c -o %s -" % (compiler_path, f.name) - if os.popen(cmd).close() != None: + if os.popen(cmd).close() is not None: return None # The compiler cannot compile at all, let's *not* skip the test cmd = "echo 'int main() {}' | %s -fsanitize=thread -x c -o %s -" % (compiler_path, f.name) - if os.popen(cmd).close() != None: + if os.popen(cmd).close() is not None: return "Compiler cannot compile with -fsanitize=thread" return None return skipTestIfFn(is_compiler_clang_with_thread_sanitizer)(func) diff --git a/lldb/packages/Python/lldbsuite/test/dosep.py b/lldb/packages/Python/lldbsuite/test/dosep.py index f218774ccc0..6352fa83dfc 100644 --- a/lldb/packages/Python/lldbsuite/test/dosep.py +++ b/lldb/packages/Python/lldbsuite/test/dosep.py @@ -104,6 +104,7 @@ def setup_global_variables( global GET_WORKER_INDEX GET_WORKER_INDEX = get_worker_index_use_pid + def report_test_failure(name, command, output, timeout): global output_lock with output_lock: @@ -152,14 +153,15 @@ def parse_test_results(output): result, re.MULTILINE) error_count = re.search("^RESULT:.*([0-9]+) errors", result, re.MULTILINE) - unexpected_success_count = re.search("^RESULT:.*([0-9]+) unexpected successes", - result, re.MULTILINE) + unexpected_success_count = re.search( + "^RESULT:.*([0-9]+) unexpected successes", result, re.MULTILINE) if pass_count is not None: passes = passes + int(pass_count.group(1)) if fail_count is not None: failures = failures + int(fail_count.group(1)) if unexpected_success_count is not None: - unexpected_successes = unexpected_successes + int(unexpected_success_count.group(1)) + unexpected_successes = unexpected_successes + \ + int(unexpected_success_count.group(1)) if error_count is not None: failures = failures + int(error_count.group(1)) return passes, failures, unexpected_successes @@ -167,6 +169,7 @@ def parse_test_results(output): class DoTestProcessDriver(process_control.ProcessDriver): """Drives the dotest.py inferior process and handles bookkeeping.""" + def __init__(self, output_file, output_file_lock, pid_events, file_name, soft_terminate_timeout): super(DoTestProcessDriver, self).__init__( @@ -210,7 +213,11 @@ class DoTestProcessDriver(process_control.ProcessDriver): # only stderr does. report_test_pass(self.file_name, output[1]) else: - report_test_failure(self.file_name, command, output[1], was_timeout) + report_test_failure( + self.file_name, + command, + output[1], + was_timeout) # Save off the results for the caller. self.results = ( @@ -635,8 +642,13 @@ def initialize_global_vars_common(num_threads, test_work_items): test_counter = multiprocessing.Value('i', 0) test_name_len = multiprocessing.Value('i', 0) if not (RESULTS_FORMATTER and RESULTS_FORMATTER.is_using_terminal()): - print("Testing: %d test suites, %d thread%s" % ( - total_tests, num_threads, (num_threads > 1) * "s"), file=sys.stderr) + print( + "Testing: %d test suites, %d thread%s" % + (total_tests, + num_threads, + (num_threads > 1) * + "s"), + file=sys.stderr) update_progress() @@ -671,7 +683,6 @@ def initialize_global_vars_threading(num_threads, test_work_items): index_map[thread_id] = len(index_map) return index_map[thread_id] - global GET_WORKER_INDEX GET_WORKER_INDEX = get_worker_index_threading @@ -1079,6 +1090,7 @@ def inprocess_exec_test_runner(test_work_items): return test_results + def walk_and_invoke(test_files, dotest_argv, num_workers, test_runner_func): """Invokes the test runner on each test file specified by test_files. @@ -1278,7 +1290,7 @@ def _remove_option( removal_count = 2 else: removal_count = 1 - del args[index:index+removal_count] + del args[index:index + removal_count] return True except ValueError: # Thanks to argparse not handling options with known arguments @@ -1516,7 +1528,8 @@ def main(num_threads, test_subdir, test_runner_name, results_formatter): if test_subdir and len(test_subdir) > 0: test_subdir = os.path.join(test_directory, test_subdir) if not os.path.isdir(test_subdir): - print('specified test subdirectory {} is not a valid directory\n'.format(test_subdir)) + print( + 'specified test subdirectory {} is not a valid directory\n'.format(test_subdir)) else: test_subdir = test_directory @@ -1662,7 +1675,9 @@ def main(num_threads, test_subdir, test_runner_name, results_formatter): unexpected_successes.sort() print("\nUnexpected Successes (%d)" % len(unexpected_successes)) for u in unexpected_successes: - print("UNEXPECTED SUCCESS: LLDB (suite) :: %s (%s)" % (u, system_info)) + print( + "UNEXPECTED SUCCESS: LLDB (suite) :: %s (%s)" % + (u, system_info)) sys.exit(exit_code) diff --git a/lldb/packages/Python/lldbsuite/test/dotest.py b/lldb/packages/Python/lldbsuite/test/dotest.py index 702e57e9987..7075f2a812f 100644 --- a/lldb/packages/Python/lldbsuite/test/dotest.py +++ b/lldb/packages/Python/lldbsuite/test/dotest.py @@ -46,10 +46,12 @@ from . import test_result from lldbsuite.test_event.event_builder import EventBuilder from ..support import seven + def is_exe(fpath): """Returns true if fpath is an executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + def which(program): """Returns the full path to a program; None otherwise.""" fpath, fname = os.path.split(program) @@ -63,24 +65,28 @@ def which(program): return exe_file return None + class _WritelnDecorator(object): """Used to decorate file-like objects with a handy 'writeln' method""" - def __init__(self,stream): + + def __init__(self, stream): self.stream = stream def __getattr__(self, attr): if attr in ('stream', '__getstate__'): raise AttributeError(attr) - return getattr(self.stream,attr) + return getattr(self.stream, attr) def writeln(self, arg=None): if arg: self.write(arg) - self.write('\n') # text-mode streams translate to \r\n if needed + self.write('\n') # text-mode streams translate to \r\n if needed # # Global variables: # + + def usage(parser): parser.print_help() if configuration.verbose > 0: @@ -195,6 +201,7 @@ o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the """) sys.exit(0) + def parseOptionsAndInitTestdirs(): """Initialize the list of directories containing our unittest scripts. @@ -213,9 +220,10 @@ def parseOptionsAndInitTestdirs(): for env_var in args.unset_env_varnames: if env_var in os.environ: # From Python Doc: When unsetenv() is supported, deletion of items in os.environ - # is automatically translated into a corresponding call to unsetenv(). + # is automatically translated into a corresponding call to + # unsetenv(). del os.environ[env_var] - #os.unsetenv(env_var) + # os.unsetenv(env_var) if args.set_env_vars: for env_var in args.set_env_vars: @@ -235,9 +243,13 @@ def parseOptionsAndInitTestdirs(): if args.compilers: configuration.compilers = args.compilers else: - # Use a compiler appropriate appropriate for the Apple SDK if one was specified + # Use a compiler appropriate appropriate for the Apple SDK if one was + # specified if platform_system == 'Darwin' and args.apple_sdk: - configuration.compilers = [seven.get_command_output('xcrun -sdk "%s" -find clang 2> /dev/null' % (args.apple_sdk))] + configuration.compilers = [ + seven.get_command_output( + 'xcrun -sdk "%s" -find clang 2> /dev/null' % + (args.apple_sdk))] else: # 'clang' on ubuntu 14.04 is 3.4 so we try clang-3.5 first candidateCompilers = ['clang-3.5', 'clang', 'gcc'] @@ -254,33 +266,43 @@ def parseOptionsAndInitTestdirs(): # Set SDKROOT if we are using an Apple SDK if platform_system == 'Darwin' and args.apple_sdk: - os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk "%s" --show-sdk-path 2> /dev/null' % (args.apple_sdk)) + os.environ['SDKROOT'] = seven.get_command_output( + 'xcrun --sdk "%s" --show-sdk-path 2> /dev/null' % + (args.apple_sdk)) if args.archs: configuration.archs = args.archs for arch in configuration.archs: - if arch.startswith('arm') and platform_system == 'Darwin' and not args.apple_sdk: - os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk iphoneos.internal --show-sdk-path 2> /dev/null') + if arch.startswith( + 'arm') and platform_system == 'Darwin' and not args.apple_sdk: + os.environ['SDKROOT'] = seven.get_command_output( + 'xcrun --sdk iphoneos.internal --show-sdk-path 2> /dev/null') if not os.path.exists(os.environ['SDKROOT']): - os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk iphoneos --show-sdk-path 2> /dev/null') + os.environ['SDKROOT'] = seven.get_command_output( + 'xcrun --sdk iphoneos --show-sdk-path 2> /dev/null') else: configuration.archs = [platform_machine] if args.categoriesList: - configuration.categoriesList = set(test_categories.validate(args.categoriesList, False)) + configuration.categoriesList = set( + test_categories.validate( + args.categoriesList, False)) configuration.useCategories = True else: configuration.categoriesList = [] if args.skipCategories: - configuration.skipCategories = test_categories.validate(args.skipCategories, False) + configuration.skipCategories = test_categories.validate( + args.skipCategories, False) if args.E: cflags_extras = args.E os.environ['CFLAGS_EXTRAS'] = cflags_extras if args.d: - sys.stdout.write("Suspending the process %d to wait for debugger to attach...\n" % os.getpid()) + sys.stdout.write( + "Suspending the process %d to wait for debugger to attach...\n" % + os.getpid()) sys.stdout.flush() os.kill(os.getpid(), signal.SIGSTOP) @@ -334,10 +356,11 @@ def parseOptionsAndInitTestdirs(): configuration.count = args.sharp if sys.platform.startswith('win32'): - os.environ['LLDB_DISABLE_CRASH_DIALOG'] = str(args.disable_crash_dialog) + os.environ['LLDB_DISABLE_CRASH_DIALOG'] = str( + args.disable_crash_dialog) os.environ['LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE'] = str(True) - if do_help == True: + if do_help: usage(parser) if args.no_multiprocess: @@ -415,12 +438,14 @@ def parseOptionsAndInitTestdirs(): # Gather all the dirs passed on the command line. if len(args.args) > 0: - configuration.testdirs = list(map(lambda x: os.path.realpath(os.path.abspath(x)), args.args)) + configuration.testdirs = list( + map(lambda x: os.path.realpath(os.path.abspath(x)), args.args)) # Shut off multiprocessing mode when test directories are specified. configuration.no_multiprocess_test_runner = True #print("testdirs:", testdirs) + def getXcodeOutputPaths(lldbRootDirectory): result = [] @@ -428,11 +453,16 @@ def getXcodeOutputPaths(lldbRootDirectory): xcode3_build_dir = ['build'] xcode4_build_dir = ['build', 'lldb', 'Build', 'Products'] - configurations = [['Debug'], ['DebugClang'], ['Release'], ['BuildAndIntegration']] + configurations = [ + ['Debug'], + ['DebugClang'], + ['Release'], + ['BuildAndIntegration']] xcode_build_dirs = [xcode3_build_dir, xcode4_build_dir] for configuration in configurations: for xcode_build_dir in xcode_build_dirs: - outputPath = os.path.join(lldbRootDirectory, *(xcode_build_dir+configuration) ) + outputPath = os.path.join( + lldbRootDirectory, *(xcode_build_dir + configuration)) result.append(outputPath) return result @@ -499,17 +529,24 @@ def getOutputPaths(lldbRootDirectory): # cmake builds? look for build or build/host folder next to llvm directory # lldb is located in llvm/tools/lldb so we need to go up three levels - llvmParentDir = os.path.abspath(os.path.join(lldbRootDirectory, os.pardir, os.pardir, os.pardir)) + llvmParentDir = os.path.abspath( + os.path.join( + lldbRootDirectory, + os.pardir, + os.pardir, + os.pardir)) result.append(os.path.join(llvmParentDir, 'build', 'bin')) result.append(os.path.join(llvmParentDir, 'build', 'host', 'bin')) - # some cmake developers keep their build directory beside their lldb directory + # some cmake developers keep their build directory beside their lldb + # directory lldbParentDir = os.path.abspath(os.path.join(lldbRootDirectory, os.pardir)) result.append(os.path.join(lldbParentDir, 'build', 'bin')) result.append(os.path.join(lldbParentDir, 'build', 'host', 'bin')) return result + def setupSysPath(): """ Add LLDB.framework/Resources/Python to the search paths for modules. @@ -535,12 +572,15 @@ def setupSysPath(): toolsLLDBMIPath = os.path.join(scriptPath, 'tools', 'lldb-mi') toolsLLDBServerPath = os.path.join(scriptPath, 'tools', 'lldb-server') - # Insert script dir, plugin dir, lldb-mi dir and lldb-server dir to the sys.path. + # Insert script dir, plugin dir, lldb-mi dir and lldb-server dir to the + # sys.path. sys.path.insert(0, pluginPath) - sys.path.insert(0, toolsLLDBMIPath) # Adding test/tools/lldb-mi to the path makes it easy - # to "import lldbmi_testcase" from the MI tests - sys.path.insert(0, toolsLLDBServerPath) # Adding test/tools/lldb-server to the path makes it easy - # to "import lldbgdbserverutils" from the lldb-server tests + # Adding test/tools/lldb-mi to the path makes it easy + sys.path.insert(0, toolsLLDBMIPath) + # to "import lldbmi_testcase" from the MI tests + # Adding test/tools/lldb-server to the path makes it easy + sys.path.insert(0, toolsLLDBServerPath) + # to "import lldbgdbserverutils" from the lldb-server tests # This is the root of the lldb git/svn checkout # When this changes over to a package instead of a standalone script, this @@ -572,16 +612,22 @@ def setupSysPath(): lldbtest_config.lldbExec = which('lldb') if lldbtest_config.lldbExec and not is_exe(lldbtest_config.lldbExec): - print("'{}' is not a path to a valid executable".format(lldbtest_config.lldbExec)) + print( + "'{}' is not a path to a valid executable".format( + lldbtest_config.lldbExec)) lldbtest_config.lldbExec = None if not lldbtest_config.lldbExec: print("The 'lldb' executable cannot be located. Some of the tests may not be run as a result.") sys.exit(-1) - lldbLibDir = os.path.dirname(lldbtest_config.lldbExec) # confusingly, this is the "bin" directory + # confusingly, this is the "bin" directory + lldbLibDir = os.path.dirname(lldbtest_config.lldbExec) os.environ["LLDB_LIB_DIR"] = lldbLibDir - lldbImpLibDir = os.path.join(lldbLibDir, '..', 'lib') if sys.platform.startswith('win32') else lldbLibDir + lldbImpLibDir = os.path.join( + lldbLibDir, + '..', + 'lib') if sys.platform.startswith('win32') else lldbLibDir os.environ["LLDB_IMPLIB_DIR"] = lldbImpLibDir print("LLDB library dir:", os.environ["LLDB_LIB_DIR"]) print("LLDB import library dir:", os.environ["LLDB_IMPLIB_DIR"]) @@ -594,27 +640,32 @@ def setupSysPath(): lldbMiExec = lldbtest_config.lldbExec + "-mi" if not lldbMiExec: if not configuration.shouldSkipBecauseOfCategories(["lldb-mi"]): - print("The 'lldb-mi' executable cannot be located. The lldb-mi tests can not be run as a result.") + print( + "The 'lldb-mi' executable cannot be located. The lldb-mi tests can not be run as a result.") configuration.skipCategories.append("lldb-mi") else: os.environ["LLDBMI_EXEC"] = lldbMiExec - lldbPythonDir = None # The directory that contains 'lldb/__init__.py' + lldbPythonDir = None # The directory that contains 'lldb/__init__.py' if configuration.lldbFrameworkPath: - candidatePath = os.path.join(configuration.lldbFrameworkPath, 'Resources', 'Python') + candidatePath = os.path.join( + configuration.lldbFrameworkPath, 'Resources', 'Python') if os.path.isfile(os.path.join(candidatePath, 'lldb/__init__.py')): lldbPythonDir = candidatePath if not lldbPythonDir: - print('Resources/Python/lldb/__init__.py was not found in ' + configuration.lldbFrameworkPath) + print( + 'Resources/Python/lldb/__init__.py was not found in ' + + configuration.lldbFrameworkPath) sys.exit(-1) else: # If our lldb supports the -P option, use it to find the python path: init_in_python_dir = os.path.join('lldb', '__init__.py') - lldb_dash_p_result = subprocess.check_output([lldbtest_config.lldbExec, "-P"], stderr=subprocess.STDOUT, universal_newlines=True) + lldb_dash_p_result = subprocess.check_output( + [lldbtest_config.lldbExec, "-P"], stderr=subprocess.STDOUT, universal_newlines=True) - if lldb_dash_p_result and not lldb_dash_p_result.startswith(("<", "lldb: invalid option:")) \ - and not lldb_dash_p_result.startswith("Traceback"): + if lldb_dash_p_result and not lldb_dash_p_result.startswith( + ("<", "lldb: invalid option:")) and not lldb_dash_p_result.startswith("Traceback"): lines = lldb_dash_p_result.splitlines() # Workaround for readline vs libedit issue on FreeBSD. If stdout @@ -625,55 +676,73 @@ def setupSysPath(): # because cpython commit f0ab6f9f0603 added a #ifndef __APPLE__ # around the call. See http://bugs.python.org/issue19884 for more # information. For now we just discard the warning output. - if len(lines) >= 1 and lines[0].startswith("bind: Invalid command"): + if len(lines) >= 1 and lines[0].startswith( + "bind: Invalid command"): lines.pop(0) # Taking the last line because lldb outputs # 'Cannot read termcap database;\nusing dumb terminal settings.\n' # before the path - if len(lines) >= 1 and os.path.isfile(os.path.join(lines[-1], init_in_python_dir)): + if len(lines) >= 1 and os.path.isfile( + os.path.join(lines[-1], init_in_python_dir)): lldbPythonDir = lines[-1] if "freebsd" in sys.platform or "linux" in sys.platform: - os.environ['LLDB_LIB_DIR'] = os.path.join(lldbPythonDir, '..', '..') - + os.environ['LLDB_LIB_DIR'] = os.path.join( + lldbPythonDir, '..', '..') + if not lldbPythonDir: if platform.system() == "Darwin": python_resource_dir = ['LLDB.framework', 'Resources', 'Python'] outputPaths = getXcodeOutputPaths(lldbRootDirectory) for outputPath in outputPaths: - candidatePath = os.path.join(outputPath, *python_resource_dir) - if os.path.isfile(os.path.join(candidatePath, init_in_python_dir)): + candidatePath = os.path.join( + outputPath, *python_resource_dir) + if os.path.isfile( + os.path.join( + candidatePath, + init_in_python_dir)): lldbPythonDir = candidatePath break if not lldbPythonDir: print("lldb.py is not found, some tests may fail.") else: - print("Unable to load lldb extension module. Possible reasons for this include:") + print( + "Unable to load lldb extension module. Possible reasons for this include:") print(" 1) LLDB was built with LLDB_DISABLE_PYTHON=1") - print(" 2) PYTHONPATH and PYTHONHOME are not set correctly. PYTHONHOME should refer to") - print(" the version of Python that LLDB built and linked against, and PYTHONPATH") - print(" should contain the Lib directory for the same python distro, as well as the") + print( + " 2) PYTHONPATH and PYTHONHOME are not set correctly. PYTHONHOME should refer to") + print( + " the version of Python that LLDB built and linked against, and PYTHONPATH") + print( + " should contain the Lib directory for the same python distro, as well as the") print(" location of LLDB\'s site-packages folder.") - print(" 3) A different version of Python than that which was built against is exported in") + print( + " 3) A different version of Python than that which was built against is exported in") print(" the system\'s PATH environment variable, causing conflicts.") - print(" 4) The executable '%s' could not be found. Please check " % lldbtest_config.lldbExec) + print( + " 4) The executable '%s' could not be found. Please check " % + lldbtest_config.lldbExec) print(" that it exists and is executable.") if lldbPythonDir: lldbPythonDir = os.path.normpath(lldbPythonDir) - # Some of the code that uses this path assumes it hasn't resolved the Versions... link. - # If the path we've constructed looks like that, then we'll strip out the Versions/A part. - (before, frameWithVersion, after) = lldbPythonDir.rpartition("LLDB.framework/Versions/A") - if frameWithVersion != "" : + # Some of the code that uses this path assumes it hasn't resolved the Versions... link. + # If the path we've constructed looks like that, then we'll strip out + # the Versions/A part. + (before, frameWithVersion, after) = lldbPythonDir.rpartition( + "LLDB.framework/Versions/A") + if frameWithVersion != "": lldbPythonDir = before + "LLDB.framework" + after lldbPythonDir = os.path.abspath(lldbPythonDir) # If tests need to find LLDB_FRAMEWORK, now they can do it - os.environ["LLDB_FRAMEWORK"] = os.path.dirname(os.path.dirname(lldbPythonDir)) + os.environ["LLDB_FRAMEWORK"] = os.path.dirname( + os.path.dirname(lldbPythonDir)) - # This is to locate the lldb.py module. Insert it right after sys.path[0]. + # This is to locate the lldb.py module. Insert it right after + # sys.path[0]. sys.path[1:1] = [lldbPythonDir] @@ -713,7 +782,8 @@ def visit_file(dir, name): if filtered: # print("adding filter spec %s to module %s" % (filterspec, module)) configuration.suite.addTests( - unittest2.defaultTestLoader.loadTestsFromName(filterspec, module)) + unittest2.defaultTestLoader.loadTestsFromName( + filterspec, module)) continue # Forgo this module if the (base, filterspec) combo is invalid @@ -724,7 +794,8 @@ def visit_file(dir, name): # Add the entire file's worth of tests since we're not filtered. # Also the fail-over case when the filterspec branch # (base, filterspec) combo doesn't make sense. - configuration.suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base)) + configuration.suite.addTests( + unittest2.defaultTestLoader.loadTestsFromName(base)) def visit(prefix, dir, names): @@ -774,10 +845,14 @@ def disabledynamics(): import lldb ci = lldb.DBG.GetCommandInterpreter() res = lldb.SBCommandReturnObject() - ci.HandleCommand("setting set target.prefer-dynamic-value no-dynamic-values", res, False) + ci.HandleCommand( + "setting set target.prefer-dynamic-value no-dynamic-values", + res, + False) if not res.Succeeded(): raise Exception('disabling dynamic type support failed') + def lldbLoggings(): import lldb """Check and do lldb loggings if necessary.""" @@ -793,7 +868,10 @@ def lldbLoggings(): else: lldb_log_option = "event process expr state api" ci.HandleCommand( - "log enable -n -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option, + "log enable -n -f " + + os.environ["LLDB_LOG"] + + " lldb " + + lldb_log_option, res) if not res.Succeeded(): raise Exception('log enable failed (check LLDB_LOG env variable)') @@ -805,11 +883,15 @@ def lldbLoggings(): else: lldb_log_option = "event process expr state api" ci.HandleCommand( - "log enable -n -f " + os.environ["LLDB_LINUX_LOG"] + " linux " + lldb_log_option, + "log enable -n -f " + + os.environ["LLDB_LINUX_LOG"] + + " linux " + + lldb_log_option, res) if not res.Succeeded(): - raise Exception('log enable failed (check LLDB_LINUX_LOG env variable)') - + raise Exception( + 'log enable failed (check LLDB_LINUX_LOG env variable)') + # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined. # Use ${GDB_REMOTE_LOG} to specify the log file. if ("GDB_REMOTE_LOG" in os.environ): @@ -822,7 +904,9 @@ def lldbLoggings(): + gdb_remote_log_option, res) if not res.Succeeded(): - raise Exception('log enable failed (check GDB_REMOTE_LOG env variable)') + raise Exception( + 'log enable failed (check GDB_REMOTE_LOG env variable)') + def getMyCommandLine(): return ' '.join(sys.argv) @@ -833,18 +917,24 @@ def getMyCommandLine(): # # # ======================================== # + def checkDsymForUUIDIsNotOn(): cmd = ["defaults", "read", "com.apple.DebugSymbols"] - pipe = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) + pipe = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) cmd_output = pipe.stdout.read() if cmd_output and "DBGFileMappedPaths = " in cmd_output: print("%s =>" % ' '.join(cmd)) print(cmd_output) - print("Disable automatic lookup and caching of dSYMs before running the test suite!") + print( + "Disable automatic lookup and caching of dSYMs before running the test suite!") print("Exiting...") sys.exit(0) -def exitTestSuite(exitCode = None): + +def exitTestSuite(exitCode=None): import lldb lldb.SBDebugger.Terminate() if exitCode: @@ -856,7 +946,9 @@ def isMultiprocessTestRunner(): # the inferior (as specified by the multiprocess test # runner) OR we've been told to skip using the multiprocess # test runner - return not (configuration.is_inferior_test_runner or configuration.no_multiprocess_test_runner) + return not ( + configuration.is_inferior_test_runner or configuration.no_multiprocess_test_runner) + def getVersionForSDK(sdk): sdk = str.lower(sdk) @@ -867,19 +959,24 @@ def getVersionForSDK(sdk): ver = basename.replace(sdk, '') return ver + def getPathForSDK(sdk): sdk = str.lower(sdk) full_path = seven.get_command_output('xcrun -sdk %s --show-sdk-path' % sdk) - if os.path.exists(full_path): return full_path + if os.path.exists(full_path): + return full_path return None + def setDefaultTripleForPlatform(): if configuration.lldb_platform_name == 'ios-simulator': - triple_str = 'x86_64-apple-ios%s' % (getVersionForSDK('iphonesimulator')) + triple_str = 'x86_64-apple-ios%s' % ( + getVersionForSDK('iphonesimulator')) os.environ['TRIPLE'] = triple_str - return {'TRIPLE':triple_str} + return {'TRIPLE': triple_str} return {} + def run_suite(): # On MacOS X, check to make sure that domain for com.apple.DebugSymbols defaults # does not exist before proceeding to running the test suite. @@ -900,8 +997,11 @@ def run_suite(): # multiprocess test runner here. if isMultiprocessTestRunner(): from . import dosep - dosep.main(configuration.num_threads, configuration.multiprocess_test_subdir, - configuration.test_runner_name, configuration.results_formatter_object) + dosep.main( + configuration.num_threads, + configuration.multiprocess_test_subdir, + configuration.test_runner_name, + configuration.results_formatter_object) raise Exception("should never get here") elif configuration.is_inferior_test_runner: # Shut off Ctrl-C processing in inferiors. The parallel @@ -924,20 +1024,29 @@ def run_suite(): lldb.DBG = lldb.SBDebugger.Create() if configuration.lldb_platform_name: - print("Setting up remote platform '%s'" % (configuration.lldb_platform_name)) - lldb.remote_platform = lldb.SBPlatform(configuration.lldb_platform_name) + print("Setting up remote platform '%s'" % + (configuration.lldb_platform_name)) + lldb.remote_platform = lldb.SBPlatform( + configuration.lldb_platform_name) if not lldb.remote_platform.IsValid(): - print("error: unable to create the LLDB platform named '%s'." % (configuration.lldb_platform_name)) + print( + "error: unable to create the LLDB platform named '%s'." % + (configuration.lldb_platform_name)) exitTestSuite(1) if configuration.lldb_platform_url: - # We must connect to a remote platform if a LLDB platform URL was specified - print("Connecting to remote platform '%s' at '%s'..." % (configuration.lldb_platform_name, configuration.lldb_platform_url)) - platform_connect_options = lldb.SBPlatformConnectOptions(configuration.lldb_platform_url) + # We must connect to a remote platform if a LLDB platform URL was + # specified + print( + "Connecting to remote platform '%s' at '%s'..." % + (configuration.lldb_platform_name, configuration.lldb_platform_url)) + platform_connect_options = lldb.SBPlatformConnectOptions( + configuration.lldb_platform_url) err = lldb.remote_platform.ConnectRemote(platform_connect_options) if err.Success(): print("Connected.") else: - print("error: failed to connect to remote platform using URL '%s': %s" % (configuration.lldb_platform_url, err)) + print("error: failed to connect to remote platform using URL '%s': %s" % ( + configuration.lldb_platform_url, err)) exitTestSuite(1) else: configuration.lldb_platform_url = None @@ -948,11 +1057,13 @@ def run_suite(): if first: print("Environment variables setup for platform support:") first = False - print("%s = %s" % (key,platform_changes[key])) + print("%s = %s" % (key, platform_changes[key])) if configuration.lldb_platform_working_dir: - print("Setting remote platform working directory to '%s'..." % (configuration.lldb_platform_working_dir)) - lldb.remote_platform.SetWorkingDirectory(configuration.lldb_platform_working_dir) + print("Setting remote platform working directory to '%s'..." % + (configuration.lldb_platform_working_dir)) + lldb.remote_platform.SetWorkingDirectory( + configuration.lldb_platform_working_dir) lldb.DBG.SetSelectedPlatform(lldb.remote_platform) else: lldb.remote_platform = None @@ -998,10 +1109,13 @@ def run_suite(): timestamp_started = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S") if not configuration.sdir_name: configuration.sdir_name = timestamp_started - os.environ["LLDB_SESSION_DIRNAME"] = os.path.join(os.getcwd(), configuration.sdir_name) + os.environ["LLDB_SESSION_DIRNAME"] = os.path.join( + os.getcwd(), configuration.sdir_name) - sys.stderr.write("\nSession logs for test failures/errors/unexpected successes" - " will go into directory '%s'\n" % configuration.sdir_name) + sys.stderr.write( + "\nSession logs for test failures/errors/unexpected successes" + " will go into directory '%s'\n" % + configuration.sdir_name) sys.stderr.write("Command invoked: %s\n" % getMyCommandLine()) if not os.path.isdir(configuration.sdir_name): @@ -1024,14 +1138,16 @@ def run_suite(): # # Add some intervention here to sanity check that the compilers requested are sane. - # If found not to be an executable program, the invalid one is dropped from the list. + # If found not to be an executable program, the invalid one is dropped + # from the list. for i in range(len(configuration.compilers)): c = configuration.compilers[i] if which(c): continue else: if sys.platform.startswith("darwin"): - pipe = subprocess.Popen(['xcrun', '-find', c], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) + pipe = subprocess.Popen( + ['xcrun', '-find', c], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_output = pipe.stdout.read() if cmd_output: if "not found" in cmd_output: @@ -1039,7 +1155,9 @@ def run_suite(): configuration.compilers.remove(i) else: configuration.compilers[i] = cmd_output.split('\n')[0] - print("'xcrun -find %s' returning %s" % (c, configuration.compilers[i])) + print( + "'xcrun -find %s' returning %s" % + (c, configuration.compilers[i])) if not configuration.parsable: print("compilers=%s" % str(configuration.compilers)) @@ -1048,10 +1166,14 @@ def run_suite(): print("No eligible compiler found, exiting.") exitTestSuite(1) - if isinstance(configuration.compilers, list) and len(configuration.compilers) >= 1: + if isinstance( + configuration.compilers, + list) and len( + configuration.compilers) >= 1: iterCompilers = True - # If we iterate on archs or compilers, there is a chance we want to split stderr/stdout. + # If we iterate on archs or compilers, there is a chance we want to split + # stderr/stdout. if iterArchs or iterCompilers: old_stderr = sys.stderr old_stdout = sys.stdout @@ -1067,7 +1189,8 @@ def run_suite(): for ic in range(len(configuration.compilers) if iterCompilers else 1): if iterCompilers: os.environ["CC"] = configuration.compilers[ic] - configString = "%s compiler=%s" % (archConfig, configuration.compilers[ic]) + configString = "%s compiler=%s" % ( + archConfig, configuration.compilers[ic]) else: configString = archConfig @@ -1090,9 +1213,10 @@ def run_suite(): # First, write out the number of collected test cases. if not configuration.parsable: sys.stderr.write(configuration.separator + "\n") - sys.stderr.write("Collected %d test%s\n\n" - % (configuration.suite.countTestCases(), - configuration.suite.countTestCases() != 1 and "s" or "")) + sys.stderr.write( + "Collected %d test%s\n\n" % + (configuration.suite.countTestCases(), + configuration.suite.countTestCases() != 1 and "s" or "")) if configuration.parsable: v = 0 @@ -1101,30 +1225,39 @@ def run_suite(): # Invoke the test runner. if configuration.count == 1: - result = unittest2.TextTestRunner(stream=sys.stderr, - verbosity=v, - resultclass=test_result.LLDBTestResult).run(configuration.suite) + result = unittest2.TextTestRunner( + stream=sys.stderr, + verbosity=v, + resultclass=test_result.LLDBTestResult).run( + configuration.suite) else: # We are invoking the same test suite more than once. In this case, # mark __ignore_singleton__ flag as True so the signleton pattern is # not enforced. test_result.LLDBTestResult.__ignore_singleton__ = True for i in range(configuration.count): - - result = unittest2.TextTestRunner(stream=sys.stderr, - verbosity=v, - resultclass=test_result.LLDBTestResult).run(configuration.suite) + + result = unittest2.TextTestRunner( + stream=sys.stderr, + verbosity=v, + resultclass=test_result.LLDBTestResult).run( + configuration.suite) configuration.failed = configuration.failed or not result.wasSuccessful() if configuration.sdir_has_content and not configuration.parsable: - sys.stderr.write("Session logs for test failures/errors/unexpected successes" - " can be found in directory '%s'\n" % configuration.sdir_name) + sys.stderr.write( + "Session logs for test failures/errors/unexpected successes" + " can be found in directory '%s'\n" % + configuration.sdir_name) - if configuration.useCategories and len(configuration.failuresPerCategory) > 0: + if configuration.useCategories and len( + configuration.failuresPerCategory) > 0: sys.stderr.write("Failures per category:\n") for category in configuration.failuresPerCategory: - sys.stderr.write("%s - %d\n" % (category, configuration.failuresPerCategory[category])) + sys.stderr.write( + "%s - %d\n" % + (category, configuration.failuresPerCategory[category])) # Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined. # This should not be necessary now. @@ -1136,5 +1269,7 @@ def run_suite(): exitTestSuite(configuration.failed) if __name__ == "__main__": - print(__file__ + " is for use as a module only. It should not be run as a standalone script.") + print( + __file__ + + " is for use as a module only. It should not be run as a standalone script.") sys.exit(-1) diff --git a/lldb/packages/Python/lldbsuite/test/dotest_args.py b/lldb/packages/Python/lldbsuite/test/dotest_args.py index 8bbc29c98f0..67fe9091f12 100644 --- a/lldb/packages/Python/lldbsuite/test/dotest_args.py +++ b/lldb/packages/Python/lldbsuite/test/dotest_args.py @@ -13,9 +13,11 @@ import textwrap # LLDB modules from . import configuration + class ArgParseNamespace(object): pass + def parse_args(parser, argv): """ Returns an argument object. LLDB_TEST_ARGUMENTS environment variable can be used to pass additional arguments. @@ -23,8 +25,11 @@ def parse_args(parser, argv): args = ArgParseNamespace() if ('LLDB_TEST_ARGUMENTS' in os.environ): - print("Arguments passed through environment: '%s'" % os.environ['LLDB_TEST_ARGUMENTS']) - args = parser.parse_args([sys.argv[0]].__add__(os.environ['LLDB_TEST_ARGUMENTS'].split()),namespace=args) + print( + "Arguments passed through environment: '%s'" % + os.environ['LLDB_TEST_ARGUMENTS']) + args = parser.parse_args([sys.argv[0]].__add__( + os.environ['LLDB_TEST_ARGUMENTS'].split()), namespace=args) return parser.parse_args(args=argv, namespace=args) @@ -39,59 +44,152 @@ def default_thread_count(): def create_parser(): - parser = argparse.ArgumentParser(description='description', prefix_chars='+-', add_help=False) + parser = argparse.ArgumentParser( + description='description', + prefix_chars='+-', + add_help=False) group = None - # Helper function for boolean options (group will point to the current group when executing X) - X = lambda optstr, helpstr, **kwargs: group.add_argument(optstr, help=helpstr, action='store_true', **kwargs) + # Helper function for boolean options (group will point to the current + # group when executing X) + X = lambda optstr, helpstr, **kwargs: group.add_argument( + optstr, help=helpstr, action='store_true', **kwargs) group = parser.add_argument_group('Help') - group.add_argument('-h', '--help', dest='h', action='store_true', help="Print this help message and exit. Add '-v' for more detailed help.") + group.add_argument( + '-h', + '--help', + dest='h', + action='store_true', + help="Print this help message and exit. Add '-v' for more detailed help.") # C and Python toolchain options group = parser.add_argument_group('Toolchain options') - group.add_argument('-A', '--arch', metavar='arch', action='append', dest='archs', help=textwrap.dedent('''Specify the architecture(s) to test. This option can be specified more than once''')) - group.add_argument('-C', '--compiler', metavar='compiler', dest='compilers', action='append', help=textwrap.dedent('''Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.''')) + group.add_argument( + '-A', + '--arch', + metavar='arch', + action='append', + dest='archs', + help=textwrap.dedent('''Specify the architecture(s) to test. This option can be specified more than once''')) + group.add_argument('-C', '--compiler', metavar='compiler', dest='compilers', action='append', help=textwrap.dedent( + '''Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.''')) if sys.platform == 'darwin': - group.add_argument('--apple-sdk', metavar='apple_sdk', dest='apple_sdk', help=textwrap.dedent('''Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.''')) + group.add_argument('--apple-sdk', metavar='apple_sdk', dest='apple_sdk', help=textwrap.dedent( + '''Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.''')) # FIXME? This won't work for different extra flags according to each arch. - group.add_argument('-E', metavar='extra-flags', help=textwrap.dedent('''Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged + group.add_argument( + '-E', + metavar='extra-flags', + help=textwrap.dedent('''Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures''')) # Test filtering options group = parser.add_argument_group('Test filtering options') - group.add_argument('-f', metavar='filterspec', action='append', help='Specify a filter, which consists of the test class name, a dot, followed by the test method, to only admit such test into the test suite') # FIXME: Example? + group.add_argument( + '-f', + metavar='filterspec', + action='append', + help='Specify a filter, which consists of the test class name, a dot, followed by the test method, to only admit such test into the test suite') # FIXME: Example? X('-l', "Don't skip long running tests") - group.add_argument('-p', metavar='pattern', help='Specify a regexp filename pattern for inclusion in the test suite') - group.add_argument('-G', '--category', metavar='category', action='append', dest='categoriesList', help=textwrap.dedent('''Specify categories of test cases of interest. Can be specified more than once.''')) - group.add_argument('--skip-category', metavar='category', action='append', dest='skipCategories', help=textwrap.dedent('''Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.''')) + group.add_argument( + '-p', + metavar='pattern', + help='Specify a regexp filename pattern for inclusion in the test suite') + group.add_argument( + '-G', + '--category', + metavar='category', + action='append', + dest='categoriesList', + help=textwrap.dedent('''Specify categories of test cases of interest. Can be specified more than once.''')) + group.add_argument( + '--skip-category', + metavar='category', + action='append', + dest='skipCategories', + help=textwrap.dedent('''Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.''')) # Configuration options group = parser.add_argument_group('Configuration options') - group.add_argument('--framework', metavar='framework-path', help='The path to LLDB.framework') - group.add_argument('--executable', metavar='executable-path', help='The path to the lldb executable') - group.add_argument('-s', metavar='name', help='Specify the name of the dir created to store the session files of tests with errored or failed status. If not specified, the test driver uses the timestamp as the session dir name') - group.add_argument('-S', '--session-file-format', default=configuration.session_file_format, metavar='format', help='Specify session file name format. See configuration.py for a description.') - group.add_argument('-y', type=int, metavar='count', help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.") - group.add_argument('-#', type=int, metavar='sharp', dest='sharp', help='Repeat the test suite for a specified number of times') - group.add_argument('--channel', metavar='channel', dest='channels', action='append', help=textwrap.dedent("Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used")) - group.add_argument('--log-success', dest='log_success', action='store_true', help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)") + group.add_argument( + '--framework', + metavar='framework-path', + help='The path to LLDB.framework') + group.add_argument( + '--executable', + metavar='executable-path', + help='The path to the lldb executable') + group.add_argument( + '-s', + metavar='name', + help='Specify the name of the dir created to store the session files of tests with errored or failed status. If not specified, the test driver uses the timestamp as the session dir name') + group.add_argument( + '-S', + '--session-file-format', + default=configuration.session_file_format, + metavar='format', + help='Specify session file name format. See configuration.py for a description.') + group.add_argument( + '-y', + type=int, + metavar='count', + help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.") + group.add_argument( + '-#', + type=int, + metavar='sharp', + dest='sharp', + help='Repeat the test suite for a specified number of times') + group.add_argument('--channel', metavar='channel', dest='channels', action='append', help=textwrap.dedent( + "Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used")) + group.add_argument( + '--log-success', + dest='log_success', + action='store_true', + help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)") # Configuration options group = parser.add_argument_group('Remote platform options') - group.add_argument('--platform-name', dest='lldb_platform_name', metavar='platform-name', help='The name of a remote platform to use') - group.add_argument('--platform-url', dest='lldb_platform_url', metavar='platform-url', help='A LLDB platform URL to use when connecting to a remote platform to run the test suite') - group.add_argument('--platform-working-dir', dest='lldb_platform_working_dir', metavar='platform-working-dir', help='The directory to use on the remote platform.') + group.add_argument( + '--platform-name', + dest='lldb_platform_name', + metavar='platform-name', + help='The name of a remote platform to use') + group.add_argument( + '--platform-url', + dest='lldb_platform_url', + metavar='platform-url', + help='A LLDB platform URL to use when connecting to a remote platform to run the test suite') + group.add_argument( + '--platform-working-dir', + dest='lldb_platform_working_dir', + metavar='platform-working-dir', + help='The directory to use on the remote platform.') # Test-suite behaviour group = parser.add_argument_group('Runtime behaviour options') X('-d', 'Suspend the process after launch to wait indefinitely for a debugger to attach') X('-q', "Don't print extra output from this script.") X('-t', 'Turn on tracing of lldb command and other detailed test executions') - group.add_argument('-u', dest='unset_env_varnames', metavar='variable', action='append', help='Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble') - group.add_argument('--env', dest='set_env_vars', metavar='variable', action='append', help='Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES') + group.add_argument( + '-u', + dest='unset_env_varnames', + metavar='variable', + action='append', + help='Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble') + group.add_argument( + '--env', + dest='set_env_vars', + metavar='variable', + action='append', + help='Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES') X('-v', 'Do verbose mode of unittest framework (print out each test case invocation)') - group.add_argument('--enable-crash-dialog', dest='disable_crash_dialog', action='store_false', help='(Windows only) When LLDB crashes, display the Windows crash dialog.') + group.add_argument( + '--enable-crash-dialog', + dest='disable_crash_dialog', + action='store_false', + help='(Windows only) When LLDB crashes, display the Windows crash dialog.') group.set_defaults(disable_crash_dialog=True) group = parser.add_argument_group('Parallel execution options') @@ -185,6 +283,10 @@ def create_parser(): del X group = parser.add_argument_group('Test directories') - group.add_argument('args', metavar='test-dir', nargs='*', help='Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.') + group.add_argument( + 'args', + metavar='test-dir', + nargs='*', + help='Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.') return parser diff --git a/lldb/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py b/lldb/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py index 6713a5a764e..8699b31f992 100644 --- a/lldb/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py +++ b/lldb/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py @@ -5,13 +5,14 @@ Test that the lldb driver's batch mode works correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DriverBatchModeTest (TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,21 +24,23 @@ class DriverBatchModeTest (TestBase): self.source = 'main.c' self.victim = None - def expect_string (self, string): + def expect_string(self, string): import pexpect """This expects for "string", with timeout & EOF being test fails.""" try: self.child.expect_exact(string) except pexpect.EOF: - self.fail ("Got EOF waiting for '%s'"%(string)) + self.fail("Got EOF waiting for '%s'" % (string)) except pexpect.TIMEOUT: - self.fail ("Timed out waiting for '%s'"%(string)) + self.fail("Timed out waiting for '%s'" % (string)) - @skipIfRemote # test not remote-ready llvm.org/pr24813 + @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - def test_batch_mode_run_crash (self): + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_batch_mode_run_crash(self): """Test that the lldb driver's batch mode works correctly.""" self.build() self.setTearDownCleanup() @@ -48,33 +51,36 @@ class DriverBatchModeTest (TestBase): # Pass CRASH so the process will crash and stop in batch mode. run_commands = ' -b -o "break set -n main" -o "run" -o "continue" -k "frame var touch_me_not"' - self.child = pexpect.spawn('%s %s %s %s -- CRASH' % (lldbtest_config.lldbExec, self.lldbOption, run_commands, exe)) + self.child = pexpect.spawn( + '%s %s %s %s -- CRASH' % + (lldbtest_config.lldbExec, self.lldbOption, run_commands, exe)) child = self.child # Turn on logging for what the child sends back. if self.TraceOn(): child.logfile_read = sys.stdout # We should see the "run": - self.expect_string ("run") + self.expect_string("run") # We should have hit the breakpoint & continued: - self.expect_string ("continue") + self.expect_string("continue") # The App should have crashed: self.expect_string("About to crash") # The -k option should have printed the frame variable once: - self.expect_string ('(char *) touch_me_not') + self.expect_string('(char *) touch_me_not') # Then we should have a live prompt: - self.expect_string (prompt) + self.expect_string(prompt) self.child.sendline("frame variable touch_me_not") - self.expect_string ('(char *) touch_me_not') - - self.deletePexpectChild() + self.expect_string('(char *) touch_me_not') + self.deletePexpectChild() - @skipIfRemote # test not remote-ready llvm.org/pr24813 + @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - def test_batch_mode_run_exit (self): + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_batch_mode_run_exit(self): """Test that the lldb driver's batch mode works correctly.""" self.build() self.setTearDownCleanup() @@ -85,66 +91,78 @@ class DriverBatchModeTest (TestBase): # Now do it again, and make sure if we don't crash, we quit: run_commands = ' -b -o "break set -n main" -o "run" -o "continue" ' - self.child = pexpect.spawn('%s %s %s %s -- NOCRASH' % (lldbtest_config.lldbExec, self.lldbOption, run_commands, exe)) + self.child = pexpect.spawn( + '%s %s %s %s -- NOCRASH' % + (lldbtest_config.lldbExec, self.lldbOption, run_commands, exe)) child = self.child # Turn on logging for what the child sends back. if self.TraceOn(): child.logfile_read = sys.stdout # We should see the "run": - self.expect_string ("run") + self.expect_string("run") # We should have hit the breakpoint & continued: - self.expect_string ("continue") + self.expect_string("continue") # The App should have not have crashed: self.expect_string("Got there on time and it did not crash.") # Then we should have a live prompt: - self.expect_string ("exited") + self.expect_string("exited") index = self.child.expect([pexpect.EOF, pexpect.TIMEOUT]) - self.assertTrue(index == 0, "lldb didn't close on successful batch completion.") + self.assertTrue( + index == 0, + "lldb didn't close on successful batch completion.") def closeVictim(self): - if self.victim != None: + if self.victim is not None: self.victim.close() self.victim = None - @skipIfRemote # test not remote-ready llvm.org/pr24813 + @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - def test_batch_mode_attach_exit (self): + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_batch_mode_attach_exit(self): """Test that the lldb driver's batch mode works correctly.""" self.build() self.setTearDownCleanup() - + import pexpect exe = os.path.join(os.getcwd(), "a.out") prompt = "(lldb) " # Finally, start up the process by hand, attach to it, and wait for its completion. - # Attach is funny, since it looks like it stops with a signal on most Unixen so + # Attach is funny, since it looks like it stops with a signal on most Unixen so # care must be taken not to treat that as a reason to exit batch mode. - + # Start up the process by hand and wait for it to get to the wait loop. - self.victim = pexpect.spawn('%s WAIT' %(exe)) - if self.victim == None: + self.victim = pexpect.spawn('%s WAIT' % (exe)) + if self.victim is None: self.fail("Could not spawn ", exe, ".") - self.addTearDownHook (self.closeVictim) + self.addTearDownHook(self.closeVictim) if self.TraceOn(): self.victim.logfile_read = sys.stdout self.victim.expect("PID: ([0-9]+) END") - if self.victim.match == None: + if self.victim.match is None: self.fail("Couldn't get the target PID.") victim_pid = int(self.victim.match.group(1)) - + self.victim.expect("Waiting") - run_commands = ' -b -o "process attach -p %d" -o "breakpoint set --file %s -p \'Stop here to unset keep_waiting\' -N keep_waiting" -o "continue" -o "break delete keep_waiting" -o "expr keep_waiting = 0" -o "continue" ' % (victim_pid, self.source) - self.child = pexpect.spawn('%s %s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, run_commands, exe)) + run_commands = ' -b -o "process attach -p %d" -o "breakpoint set --file %s -p \'Stop here to unset keep_waiting\' -N keep_waiting" -o "continue" -o "break delete keep_waiting" -o "expr keep_waiting = 0" -o "continue" ' % ( + victim_pid, self.source) + self.child = pexpect.spawn( + '%s %s %s %s' % + (lldbtest_config.lldbExec, + self.lldbOption, + run_commands, + exe)) child = self.child # Turn on logging for what the child sends back. @@ -152,19 +170,19 @@ class DriverBatchModeTest (TestBase): child.logfile_read = sys.stdout # We should see the "run": - self.expect_string ("attach") + self.expect_string("attach") self.expect_string(prompt + "continue") self.expect_string(prompt + "continue") # Then we should see the process exit: - self.expect_string ("Process %d exited with status"%(victim_pid)) - + self.expect_string("Process %d exited with status" % (victim_pid)) + victim_index = self.victim.expect([pexpect.EOF, pexpect.TIMEOUT]) self.assertTrue(victim_index == 0, "Victim didn't really exit.") index = self.child.expect([pexpect.EOF, pexpect.TIMEOUT]) - self.assertTrue(index == 0, "lldb didn't close on successful batch completion.") - - + self.assertTrue( + index == 0, + "lldb didn't close on successful batch completion.") diff --git a/lldb/packages/Python/lldbsuite/test/example/TestSequenceFunctions.py b/lldb/packages/Python/lldbsuite/test/example/TestSequenceFunctions.py index a0852930064..8c5fedf58ab 100644 --- a/lldb/packages/Python/lldbsuite/test/example/TestSequenceFunctions.py +++ b/lldb/packages/Python/lldbsuite/test/example/TestSequenceFunctions.py @@ -4,14 +4,15 @@ import random import unittest import traceback + class SequenceFunctionsTestCase(unittest.TestCase): def setUp(self): - #traceback.print_stack() + # traceback.print_stack() self.seq = list(range(10)) def tearDown(self): - #traceback.print_stack() + # traceback.print_stack() pass def test_shuffle(self): diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/anonymous-struct/TestCallUserAnonTypedef.py b/lldb/packages/Python/lldbsuite/test/expression_command/anonymous-struct/TestCallUserAnonTypedef.py index e1a53305a0d..2d4504f7ba4 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/anonymous-struct/TestCallUserAnonTypedef.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/anonymous-struct/TestCallUserAnonTypedef.py @@ -24,7 +24,10 @@ class TestExprLookupAnonStructTypedef(TestBase): self.line = line_number('main.cpp', '// lldb testsuite break') @expectedFailureAll(oslist=["windows"]) - @expectedFailureAll(oslist=['linux'], archs=['arm'], bugnumber="llvm.org/pr27868") + @expectedFailureAll( + oslist=['linux'], + archs=['arm'], + bugnumber="llvm.org/pr27868") def test(self): """Test typedeffed untagged struct arguments for function call expressions""" self.build() diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py b/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py index 61702ee8803..6645692f93e 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py @@ -5,12 +5,12 @@ Test calling std::String member functions. from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommandCallFunctionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,26 +19,33 @@ class ExprCommandCallFunctionTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.cpp', - '// Please test these expressions while stopped at this line:') - - @expectedFailureAll(compiler="icc", bugnumber="llvm.org/pr14437, fails with ICC 13.1") - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr17807 Fails on FreeBSD buildbot') + self.line = line_number( + 'main.cpp', + '// Please test these expressions while stopped at this line:') + + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr14437, fails with ICC 13.1") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber='llvm.org/pr17807 Fails on FreeBSD buildbot') @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") def test_with(self): """Test calling std::String member function.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - # Some versions of GCC encode two locations for the 'return' statement in main.cpp - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + # Some versions of GCC encode two locations for the 'return' statement + # in main.cpp + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.expect("print str", - substrs = ['Hello world']) + substrs=['Hello world']) # Calling this function now succeeds, but we follow the typedef return type through to # const char *, and thus don't invoke the Summary formatter. self.expect("print str.c_str()", - substrs = ['Hello world']) + substrs=['Hello world']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py b/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py index 066d94bd19d..a48a38aaf92 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py @@ -5,12 +5,12 @@ Test calling a function, stopping in the call, continue and gather the result on from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommandCallStopContinueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,28 +19,40 @@ class ExprCommandCallStopContinueTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.cpp', - '// Please test these expressions while stopped at this line:') - self.func_line = line_number ('main.cpp', '{5, "five"}') + self.line = line_number( + 'main.cpp', + '// Please test these expressions while stopped at this line:') + self.func_line = line_number('main.cpp', '{5, "five"}') @expectedFlakeyDarwin("llvm.org/pr20274") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test(self): """Test gathering result from interrupted function call.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - # Some versions of GCC encode two locations for the 'return' statement in main.cpp - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + # Some versions of GCC encode two locations for the 'return' statement + # in main.cpp + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.func_line, num_expected_locations=-1, loc_exact=True) - + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.func_line, + num_expected_locations=-1, + loc_exact=True) + self.expect("expr -i false -- returnsFive()", error=True, - substrs = ['Execution was interrupted, reason: breakpoint']) + substrs=['Execution was interrupted, reason: breakpoint']) self.runCmd("continue", "Continue completed") - self.expect ("thread list", - substrs = ['stop reason = User Expression thread plan', - r'Completed expression: (Five) $0 = (number = 5, name = "five")']) + self.expect( + "thread list", + substrs=[ + 'stop reason = User Expression thread plan', + r'Completed expression: (Five) $0 = (number = 5, name = "five")']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py b/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py index c0727a84fc0..fda81ae8c36 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py @@ -10,12 +10,12 @@ Note: from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommandCallUserDefinedFunction(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,30 +24,39 @@ class ExprCommandCallUserDefinedFunction(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.cpp', - '// Please test these expressions while stopped at this line:') + self.line = line_number( + 'main.cpp', + '// Please test these expressions while stopped at this line:') + @expectedFlakeyDsym("llvm.org/pr20274") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test(self): """Test return values of user defined function calls.""" self.build() # Set breakpoint in main and run exe self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # Test recursive function call. - self.expect("expr fib(5)", substrs = ['$0 = 5']) + self.expect("expr fib(5)", substrs=['$0 = 5']) # Test function with more than one paramter - self.expect("expr add(4,8)", substrs = ['$1 = 12']) + self.expect("expr add(4,8)", substrs=['$1 = 12']) # Test nesting function calls in function paramters - self.expect("expr add(add(5,2),add(3,4))", substrs = ['$2 = 14']) - self.expect("expr add(add(5,2),fib(5))", substrs = ['$3 = 12']) + self.expect("expr add(add(5,2),add(3,4))", substrs=['$2 = 14']) + self.expect("expr add(add(5,2),fib(5))", substrs=['$3 = 12']) # Test function with pointer paramter - self.expect("exp stringCompare((const char*) \"Hello world\")", substrs = ['$4 = true']) - self.expect("exp stringCompare((const char*) \"Hellworld\")", substrs = ['$5 = false']) + self.expect( + "exp stringCompare((const char*) \"Hello world\")", + substrs=['$4 = true']) + self.expect( + "exp stringCompare((const char*) \"Hellworld\")", + substrs=['$5 = false']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py b/lldb/packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py index 6b754a76878..bef4be1eb5f 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py @@ -5,12 +5,12 @@ Test calling a function that hits a signal set to auto-restart, make sure the ca from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommandThatRestartsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,24 +20,30 @@ class ExprCommandThatRestartsTestCase(TestBase): TestBase.setUp(self) self.main_source = "lotta-signals.c" - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) - @skipIfFreeBSD # llvm.org/pr19246: intermittent failure - @skipIfDarwin # llvm.org/pr19246: intermittent failure - @skipIfWindows # Test relies on signals, unsupported on Windows + @skipIfFreeBSD # llvm.org/pr19246: intermittent failure + @skipIfDarwin # llvm.org/pr19246: intermittent failure + @skipIfWindows # Test relies on signals, unsupported on Windows def test(self): """Test calling function that hits a signal and restarts.""" self.build() self.call_function() - def check_after_call (self, num_sigchld): + def check_after_call(self, num_sigchld): after_call = self.sigchld_no.GetValueAsSigned(-1) - self.assertTrue (after_call - self.start_sigchld_no == num_sigchld, "Really got %d SIGCHLD signals through the call."%(num_sigchld)) + self.assertTrue( + after_call - + self.start_sigchld_no == num_sigchld, + "Really got %d SIGCHLD signals through the call." % + (num_sigchld)) self.start_sigchld_no = after_call # Check that we are back where we were before: frame = self.thread.GetFrameAtIndex(0) - self.assertTrue (self.orig_frame_pc == frame.GetPC(), "Restored the zeroth frame correctly") + self.assertTrue( + self.orig_frame_pc == frame.GetPC(), + "Restored the zeroth frame correctly") def call_function(self): exe_name = "a.out" @@ -46,95 +52,133 @@ class ExprCommandThatRestartsTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) empty = lldb.SBFileSpec() - breakpoint = target.BreakpointCreateBySourceRegex('Stop here in main.',self.main_source_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + 'Stop here in main.', self.main_source_spec) self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be at our breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1) self.thread = threads[0] - + # Make sure the SIGCHLD behavior is pass/no-stop/no-notify: return_obj = lldb.SBCommandReturnObject() - self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 0 -p 1 -n 0", return_obj) - self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, no-stop") + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 0 -p 1 -n 0", return_obj) + self.assertTrue(return_obj.Succeeded(), "Set SIGCHLD to pass, no-stop") # The sigchld_no variable should be 0 at this point. self.sigchld_no = target.FindFirstGlobalVariable("sigchld_no") - self.assertTrue (self.sigchld_no.IsValid(), "Got a value for sigchld_no") + self.assertTrue( + self.sigchld_no.IsValid(), + "Got a value for sigchld_no") - self.start_sigchld_no = self.sigchld_no.GetValueAsSigned (-1) - self.assertTrue (self.start_sigchld_no != -1, "Got an actual value for sigchld_no") + self.start_sigchld_no = self.sigchld_no.GetValueAsSigned(-1) + self.assertTrue( + self.start_sigchld_no != -1, + "Got an actual value for sigchld_no") options = lldb.SBExpressionOptions() - # processing 30 signals takes a while, increase the expression timeout a bit - options.SetTimeoutInMicroSeconds(3000000) # 3s + # processing 30 signals takes a while, increase the expression timeout + # a bit + options.SetTimeoutInMicroSeconds(3000000) # 3s options.SetUnwindOnError(True) frame = self.thread.GetFrameAtIndex(0) - # Store away the PC to check that the functions unwind to the right place after calls + # Store away the PC to check that the functions unwind to the right + # place after calls self.orig_frame_pc = frame.GetPC() num_sigchld = 30 - value = frame.EvaluateExpression ("call_me (%d)"%(num_sigchld), options) - self.assertTrue (value.IsValid()) - self.assertTrue (value.GetError().Success() == True) - self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld) + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) self.check_after_call(num_sigchld) # Okay, now try with a breakpoint in the called code in the case where # we are ignoring breakpoint hits. - handler_bkpt = target.BreakpointCreateBySourceRegex("Got sigchld %d.", self.main_source_spec) - self.assertTrue (handler_bkpt.GetNumLocations() > 0) + handler_bkpt = target.BreakpointCreateBySourceRegex( + "Got sigchld %d.", self.main_source_spec) + self.assertTrue(handler_bkpt.GetNumLocations() > 0) options.SetIgnoreBreakpoints(True) options.SetUnwindOnError(True) - value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options) + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) - self.assertTrue (value.IsValid() and value.GetError().Success() == True) - self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld) + self.assertTrue(value.IsValid() and value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) self.check_after_call(num_sigchld) - # Now set the signal to print but not stop and make sure that calling still works: - self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 0 -p 1 -n 1", return_obj) - self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, no-stop, notify") + # Now set the signal to print but not stop and make sure that calling + # still works: + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 0 -p 1 -n 1", return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Set SIGCHLD to pass, no-stop, notify") - value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options) + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) - self.assertTrue (value.IsValid() and value.GetError().Success() == True) - self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld) + self.assertTrue(value.IsValid() and value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) self.check_after_call(num_sigchld) - # Now set this unwind on error to false, and make sure that we still complete the call: + # Now set this unwind on error to false, and make sure that we still + # complete the call: options.SetUnwindOnError(False) - value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options) + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) - self.assertTrue (value.IsValid() and value.GetError().Success() == True) - self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld) + self.assertTrue(value.IsValid() and value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) self.check_after_call(num_sigchld) # Okay, now set UnwindOnError to true, and then make the signal behavior to stop # and see that now we do stop at the signal point: - - self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 1 -p 1 -n 1", return_obj) - self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, stop, notify") - - value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options) - self.assertTrue (value.IsValid() and value.GetError().Success() == False) - - # Set signal handling back to no-stop, and continue and we should end up back in out starting frame: - self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 0 -p 1 -n 1", return_obj) - self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, no-stop, notify") + + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 1 -p 1 -n 1", return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Set SIGCHLD to pass, stop, notify") + + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) + + # Set signal handling back to no-stop, and continue and we should end + # up back in out starting frame: + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 0 -p 1 -n 1", return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Set SIGCHLD to pass, no-stop, notify") error = process.Continue() - self.assertTrue (error.Success(), "Continuing after stopping for signal succeeds.") - + self.assertTrue( + error.Success(), + "Continuing after stopping for signal succeeds.") + frame = self.thread.GetFrameAtIndex(0) - self.assertTrue (frame.GetPC() == self.orig_frame_pc, "Continuing returned to the place we started.") + self.assertTrue( + frame.GetPC() == self.orig_frame_pc, + "Continuing returned to the place we started.") diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py b/lldb/packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py index a6eb1bddc00..e5162609dfa 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py @@ -5,12 +5,12 @@ Test calling a function that throws an ObjC exception, make sure that it doesn't from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommandWithThrowTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,7 +20,7 @@ class ExprCommandWithThrowTestCase(TestBase): TestBase.setUp(self) self.main_source = "call-throws.m" - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) @skipUnlessDarwin def test(self): @@ -28,12 +28,13 @@ class ExprCommandWithThrowTestCase(TestBase): self.build() self.call_function() - def check_after_call (self): + def check_after_call(self): # Check that we are back where we were before: frame = self.thread.GetFrameAtIndex(0) - self.assertTrue (self.orig_frame_pc == frame.GetPC(), "Restored the zeroth frame correctly") + self.assertTrue( + self.orig_frame_pc == frame.GetPC(), + "Restored the zeroth frame correctly") - def call_function(self): """Test calling function that throws.""" exe_name = "a.out" @@ -42,72 +43,82 @@ class ExprCommandWithThrowTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateBySourceRegex('I am about to throw.',self.main_source_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + 'I am about to throw.', self.main_source_spec) self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be at our breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1) self.thread = threads[0] - + options = lldb.SBExpressionOptions() options.SetUnwindOnError(True) frame = self.thread.GetFrameAtIndex(0) - # Store away the PC to check that the functions unwind to the right place after calls + # Store away the PC to check that the functions unwind to the right + # place after calls self.orig_frame_pc = frame.GetPC() - value = frame.EvaluateExpression ("[my_class callMeIThrow]", options) - self.assertTrue (value.IsValid()) - self.assertTrue (value.GetError().Success() == False) + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success() == False) self.check_after_call() # Okay, now try with a breakpoint in the called code in the case where # we are ignoring breakpoint hits. - handler_bkpt = target.BreakpointCreateBySourceRegex("I felt like it", self.main_source_spec) - self.assertTrue (handler_bkpt.GetNumLocations() > 0) + handler_bkpt = target.BreakpointCreateBySourceRegex( + "I felt like it", self.main_source_spec) + self.assertTrue(handler_bkpt.GetNumLocations() > 0) options.SetIgnoreBreakpoints(True) options.SetUnwindOnError(True) - value = frame.EvaluateExpression ("[my_class callMeIThrow]", options) + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) - self.assertTrue (value.IsValid() and value.GetError().Success() == False) + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) self.check_after_call() - # Now set the ObjC language breakpoint and make sure that doesn't interfere with the call: - exception_bkpt = target.BreakpointCreateForException (lldb.eLanguageTypeObjC, False, True) + # Now set the ObjC language breakpoint and make sure that doesn't + # interfere with the call: + exception_bkpt = target.BreakpointCreateForException( + lldb.eLanguageTypeObjC, False, True) self.assertTrue(exception_bkpt.GetNumLocations() > 0) options.SetIgnoreBreakpoints(True) options.SetUnwindOnError(True) - value = frame.EvaluateExpression ("[my_class callMeIThrow]", options) + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) - self.assertTrue (value.IsValid() and value.GetError().Success() == False) + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) self.check_after_call() - # Now turn off exception trapping, and call a function that catches the exceptions, - # and make sure the function actually completes, and we get the right value: + # and make sure the function actually completes, and we get the right + # value: options.SetTrapExceptions(False) - value = frame.EvaluateExpression ("[my_class iCatchMyself]", options) - self.assertTrue (value.IsValid()) - self.assertTrue (value.GetError().Success() == True) - self.assertTrue (value.GetValueAsUnsigned() == 57) + value = frame.EvaluateExpression("[my_class iCatchMyself]", options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned() == 57) self.check_after_call() options.SetTrapExceptions(True) - # Now set this unwind on error to false, and make sure that we stop where the exception was thrown + # Now set this unwind on error to false, and make sure that we stop + # where the exception was thrown options.SetUnwindOnError(False) - value = frame.EvaluateExpression ("[my_class callMeIThrow]", options) - + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) - self.assertTrue (value.IsValid() and value.GetError().Success() == False) + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) self.check_after_call() diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py b/lldb/packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py index 66fa69cdfff..308732b6c8e 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py @@ -1,12 +1,12 @@ from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCharTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -16,24 +16,27 @@ class ExprCharTestCase(TestBase): TestBase.setUp(self) self.main_source = "main.cpp" - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) self.exe = os.path.join(os.getcwd(), "a.out") def do_test(self, dictionary=None): """These basic expression commands should work as expected.""" - self.build(dictionary = dictionary) + self.build(dictionary=dictionary) target = self.dbg.CreateTarget(self.exe) self.assertTrue(target) - breakpoint = target.BreakpointCreateBySourceRegex('// Break here', self.main_source_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + '// Break here', self.main_source_spec) self.assertTrue(breakpoint) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process) - threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) self.assertEqual(len(threads), 1) frame = threads[0].GetFrameAtIndex(0) @@ -57,13 +60,22 @@ class ExprCharTestCase(TestBase): def test_default_char(self): self.do_test() - @expectedFailureAll(archs=["arm", "aarch64", "s390x"], bugnumber="llvm.org/pr23069") + @expectedFailureAll( + archs=[ + "arm", + "aarch64", + "s390x"], + bugnumber="llvm.org/pr23069") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") def test_signed_char(self): self.do_test(dictionary={'CFLAGS_EXTRAS': '-fsigned-char'}) - @expectedFailureAll(archs=["i[3-6]86", "x86_64"], bugnumber="llvm.org/pr23069") + @expectedFailureAll( + archs=[ + "i[3-6]86", + "x86_64"], + bugnumber="llvm.org/pr23069") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") - @expectedFailureAll(triple = 'mips*', bugnumber="llvm.org/pr23069") + @expectedFailureAll(triple='mips*', bugnumber="llvm.org/pr23069") def test_unsigned_char(self): self.do_test(dictionary={'CFLAGS_EXTRAS': '-funsigned-char'}) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py b/lldb/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py index a715ee31e5f..dcfb648ada5 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py @@ -3,7 +3,6 @@ from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * @@ -15,7 +14,9 @@ class ExprSyscallTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765, getpid() does not exist on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21765, getpid() does not exist on Windows") def test_setpgid(self): self.build() self.expr_syscall() @@ -32,16 +33,16 @@ class ExprSyscallTestCase(TestBase): # launch the inferior and don't wait for it to stop self.dbg.SetAsync(True) error = lldb.SBError() - process = target.Launch (listener, - None, # argv - None, # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working directory - 0, # launch flags - False, # Stop at entry - error) # error + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) @@ -54,7 +55,10 @@ class ExprSyscallTestCase(TestBase): pass # now the process should be running (blocked in the syscall) - self.assertEqual(process.GetState(), lldb.eStateRunning, "Process is running") + self.assertEqual( + process.GetState(), + lldb.eStateRunning, + "Process is running") # send the process a signal process.SendAsyncInterrupt() @@ -62,13 +66,18 @@ class ExprSyscallTestCase(TestBase): pass # as a result the process should stop - # in all likelihood we have stopped in the middle of the sleep() syscall - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) + # in all likelihood we have stopped in the middle of the sleep() + # syscall + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) thread = process.GetSelectedThread() # try evaluating a couple of expressions in this state - self.expect("expr release_flag = 1", substrs = [" = 1"]) - self.expect("print (int)getpid()", substrs = [str(process.GetProcessID())]) + self.expect("expr release_flag = 1", substrs=[" = 1"]) + self.expect("print (int)getpid()", + substrs=[str(process.GetProcessID())]) # and run the process to completion process.Continue() diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/fixits/TestFixIts.py b/lldb/packages/Python/lldbsuite/test/expression_command/fixits/TestFixIts.py index 7e11f2b201f..a472a014cee 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/fixits/TestFixIts.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/fixits/TestFixIts.py @@ -5,12 +5,12 @@ Test calling an expression with errors that a FixIt can fix. from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommandWithFixits(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,7 +20,7 @@ class ExprCommandWithFixits(TestBase): TestBase.setUp(self) self.main_source = "main.cpp" - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) @skipUnlessDarwin def test(self): @@ -36,20 +36,23 @@ class ExprCommandWithFixits(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateBySourceRegex('Stop here to evaluate expressions',self.main_source_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + 'Stop here to evaluate expressions', self.main_source_spec) self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be at our breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1) self.thread = threads[0] - + options = lldb.SBExpressionOptions() options.SetAutoApplyFixIts(True) @@ -60,7 +63,7 @@ class ExprCommandWithFixits(TestBase): self.assertTrue(value.IsValid()) self.assertTrue(value.GetError().Success()) self.assertTrue(value.GetValueAsUnsigned() == 10) - + # Try with two errors: two_error_expression = "my_pointer.second->a" value = frame.EvaluateExpression(two_error_expression, options) @@ -74,8 +77,9 @@ class ExprCommandWithFixits(TestBase): self.assertTrue(value.IsValid()) self.assertTrue(value.GetError().Fail()) error_string = value.GetError().GetCString() - self.assertTrue(error_string.find("fixed expression suggested:") != -1, "Fix was suggested") - self.assertTrue(error_string.find("my_pointer->second.a") != -1, "Fix was right") - - - + self.assertTrue( + error_string.find("fixed expression suggested:") != -1, + "Fix was suggested") + self.assertTrue( + error_string.find("my_pointer->second.a") != -1, + "Fix was right") diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py b/lldb/packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py index 4a99dc47901..c4126a32968 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py @@ -5,12 +5,12 @@ Test using LLDB data formatters with frozen objects coming from the expression p from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprFormattersTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,11 +22,13 @@ class ExprFormattersTestCase(TestBase): self.line = line_number('main.cpp', '// Stop here') - @skipIfFreeBSD # llvm.org/pr24691 skipping to avoid crashing the test runner - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr19011 Newer Clang omits C1 complete object constructor') + @skipIfFreeBSD # llvm.org/pr24691 skipping to avoid crashing the test runner + @expectedFailureAll( + oslist=['freebsd'], + bugnumber='llvm.org/pr19011 Newer Clang omits C1 complete object constructor') @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") - @skipIfTargetAndroid() # skipping to avoid crashing the test runner - @expectedFailureAndroid('llvm.org/pr24691') # we hit an assertion in clang + @skipIfTargetAndroid() # skipping to avoid crashing the test runner + @expectedFailureAndroid('llvm.org/pr24691') # we hit an assertion in clang def test(self): """Test expr + formatters for good interoperability.""" self.build() @@ -36,64 +38,117 @@ class ExprFormattersTestCase(TestBase): def cleanup(): self.runCmd('type summary clear', check=False) self.runCmd('type synthetic clear', check=False) - + # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) """Test expr + formatters for good interoperability.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("command script import formatters.py") self.runCmd("command script import foosynth.py") - + if self.TraceOn(): self.runCmd("frame variable foo1 --show-types") self.runCmd("frame variable foo1.b --show-types") self.runCmd("frame variable foo1.b.b_ref --show-types") - self.expect("expression --show-types -- *(new foo(47))", - substrs = ['(int) a = 47', '(bar) b = {', '(int) i = 94', '(baz) b = {', '(int) k = 99']) + self.expect( + "expression --show-types -- *(new foo(47))", + substrs=[ + '(int) a = 47', + '(bar) b = {', + '(int) i = 94', + '(baz) b = {', + '(int) k = 99']) self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") self.expect("expression new int(12)", - substrs = ['(int *) $', ' = 0x']) + substrs=['(int *) $', ' = 0x']) - self.runCmd("type summary add -s \"${var%pointer} -> ${*var%decimal}\" \"int *\"") + self.runCmd( + "type summary add -s \"${var%pointer} -> ${*var%decimal}\" \"int *\"") self.expect("expression new int(12)", - substrs = ['(int *) $', '= 0x', ' -> 12']) + substrs=['(int *) $', '= 0x', ' -> 12']) self.expect("expression foo1.a_ptr", - substrs = ['(int *) $', '= 0x', ' -> 13']) - - self.expect("expression foo1", - substrs = ['(foo) $', ' a = 12', 'a_ptr = ', ' -> 13','i = 24','i_ptr = ', ' -> 25']) - - self.expect("expression --ptr-depth=1 -- new foo(47)", - substrs = ['(foo *) $', 'a = 47','a_ptr = ', ' -> 48','i = 94','i_ptr = ', ' -> 95']) - - self.expect("expression foo2", - substrs = ['(foo) $', 'a = 121','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 243']) + substrs=['(int *) $', '= 0x', ' -> 13']) + + self.expect( + "expression foo1", + substrs=[ + '(foo) $', + ' a = 12', + 'a_ptr = ', + ' -> 13', + 'i = 24', + 'i_ptr = ', + ' -> 25']) + + self.expect( + "expression --ptr-depth=1 -- new foo(47)", + substrs=[ + '(foo *) $', + 'a = 47', + 'a_ptr = ', + ' -> 48', + 'i = 94', + 'i_ptr = ', + ' -> 95']) + + self.expect( + "expression foo2", + substrs=[ + '(foo) $', + 'a = 121', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 243']) object_name = self.res.GetOutput() object_name = object_name[7:] object_name = object_name[0:object_name.find(' =')] - self.expect("frame variable foo2", - substrs = ['(foo)', 'foo2', 'a = 121','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 243']) - - self.expect("expression $" + object_name, - substrs = ['(foo) $', 'a = 121','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 243', 'h = 245','k = 247']) + self.expect( + "frame variable foo2", + substrs=[ + '(foo)', + 'foo2', + 'a = 121', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 243']) + + self.expect( + "expression $" + + object_name, + substrs=[ + '(foo) $', + 'a = 121', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 243', + 'h = 245', + 'k = 247']) self.runCmd("type summary delete foo") - self.runCmd("type synthetic add --python-class foosynth.FooSyntheticProvider foo") + self.runCmd( + "type synthetic add --python-class foosynth.FooSyntheticProvider foo") self.expect("expression --show-types -- $" + object_name, - substrs = ['(foo) $', ' = {', '(int) *i_ptr = 243']) + substrs=['(foo) $', ' = {', '(int) *i_ptr = 243']) self.runCmd("n") self.runCmd("n") @@ -101,31 +156,61 @@ class ExprFormattersTestCase(TestBase): self.runCmd("type synthetic delete foo") self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") - self.expect("expression foo2", - substrs = ['(foo) $', 'a = 7777','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 8888']) + self.expect( + "expression foo2", + substrs=[ + '(foo) $', + 'a = 7777', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 8888']) self.expect("expression $" + object_name + '.a', - substrs = ['7777']) + substrs=['7777']) self.expect("expression *$" + object_name + '.b.i_ptr', - substrs = ['8888']) - - self.expect("expression $" + object_name, - substrs = ['(foo) $', 'a = 121', 'a_ptr = ', ' -> 122', 'i = 242', 'i_ptr = ', ' -> 8888', 'h = 245','k = 247']) + substrs=['8888']) + + self.expect( + "expression $" + + object_name, + substrs=[ + '(foo) $', + 'a = 121', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 8888', + 'h = 245', + 'k = 247']) self.runCmd("type summary delete foo") - self.runCmd("type synthetic add --python-class foosynth.FooSyntheticProvider foo") + self.runCmd( + "type synthetic add --python-class foosynth.FooSyntheticProvider foo") self.expect("expression --show-types -- $" + object_name, - substrs = ['(foo) $', ' = {', '(int) *i_ptr = 8888']) + substrs=['(foo) $', ' = {', '(int) *i_ptr = 8888']) self.runCmd("n") self.runCmd("type synthetic delete foo") self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") - self.expect("expression $" + object_name, - substrs = ['(foo) $', 'a = 121','a_ptr = ', ' -> 122','i = 242', 'i_ptr = ', ' -> 8888','k = 247']) + self.expect( + "expression $" + + object_name, + substrs=[ + '(foo) $', + 'a = 121', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 8888', + 'k = 247']) process = self.dbg.GetSelectedTarget().GetProcess() thread = process.GetThreadAtIndex(0) @@ -136,32 +221,78 @@ class ExprFormattersTestCase(TestBase): a_data = frozen.GetPointeeData() error = lldb.SBError() - self.assertTrue(a_data.GetUnsignedInt32(error, 0) == 122, '*a_ptr = 122') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 0) == 122, + '*a_ptr = 122') - self.runCmd("n");self.runCmd("n");self.runCmd("n"); + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") self.expect("frame variable numbers", - substrs = ['1','2','3','4','5']) + substrs=['1', '2', '3', '4', '5']) self.expect("expression numbers", - substrs = ['1','2','3','4','5']) + substrs=['1', '2', '3', '4', '5']) frozen = frame.EvaluateExpression("&numbers") a_data = frozen.GetPointeeData(0, 1) - self.assertTrue(a_data.GetUnsignedInt32(error, 0) == 1, 'numbers[0] == 1') - self.assertTrue(a_data.GetUnsignedInt32(error, 4) == 2, 'numbers[1] == 2') - self.assertTrue(a_data.GetUnsignedInt32(error, 8) == 3, 'numbers[2] == 3') - self.assertTrue(a_data.GetUnsignedInt32(error, 12) == 4, 'numbers[3] == 4') - self.assertTrue(a_data.GetUnsignedInt32(error, 16) == 5, 'numbers[4] == 5') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 0) == 1, + 'numbers[0] == 1') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 4) == 2, + 'numbers[1] == 2') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 8) == 3, + 'numbers[2] == 3') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 12) == 4, + 'numbers[3] == 4') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 16) == 5, + 'numbers[4] == 5') frozen = frame.EvaluateExpression("numbers") a_data = frozen.GetData() - self.assertTrue(a_data.GetUnsignedInt32(error, 0) == 1, 'numbers[0] == 1') - self.assertTrue(a_data.GetUnsignedInt32(error, 4) == 2, 'numbers[1] == 2') - self.assertTrue(a_data.GetUnsignedInt32(error, 8) == 3, 'numbers[2] == 3') - self.assertTrue(a_data.GetUnsignedInt32(error, 12) == 4, 'numbers[3] == 4') - self.assertTrue(a_data.GetUnsignedInt32(error, 16) == 5, 'numbers[4] == 5') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 0) == 1, + 'numbers[0] == 1') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 4) == 2, + 'numbers[1] == 2') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 8) == 3, + 'numbers[2] == 3') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 12) == 4, + 'numbers[3] == 4') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 16) == 5, + 'numbers[4] == 5') diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py b/lldb/packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py index 91c4d4a84c6..7b1284d2a76 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py @@ -1,29 +1,33 @@ import lldb + class FooSyntheticProvider: - def __init__(self,valobj,dict): - self.valobj = valobj; - self.update(); - - def update(self): - self.adjust_for_architecture() - - def num_children(self): - return 1; - - def get_child_at_index(self,index): - if index != 0: - return None; - return self.i_ptr.Dereference(); - - def get_child_index(self,name): - if name == "*i_ptr": - return 0; - return None; - - def adjust_for_architecture(self): - self.lp64 = (self.valobj.GetTarget().GetProcess().GetAddressByteSize() == 8) - self.is_little = (self.valobj.GetTarget().GetProcess().GetByteOrder() == lldb.eByteOrderLittle) - self.pointer_size = self.valobj.GetTarget().GetProcess().GetAddressByteSize() - self.bar = self.valobj.GetChildMemberWithName('b'); - self.i_ptr = self.bar.GetChildMemberWithName('i_ptr');
\ No newline at end of file + + def __init__(self, valobj, dict): + self.valobj = valobj + self.update() + + def update(self): + self.adjust_for_architecture() + + def num_children(self): + return 1 + + def get_child_at_index(self, index): + if index != 0: + return None + return self.i_ptr.Dereference() + + def get_child_index(self, name): + if name == "*i_ptr": + return 0 + return None + + def adjust_for_architecture(self): + self.lp64 = ( + self.valobj.GetTarget().GetProcess().GetAddressByteSize() == 8) + self.is_little = (self.valobj.GetTarget().GetProcess( + ).GetByteOrder() == lldb.eByteOrderLittle) + self.pointer_size = self.valobj.GetTarget().GetProcess().GetAddressByteSize() + self.bar = self.valobj.GetChildMemberWithName('b') + self.i_ptr = self.bar.GetChildMemberWithName('i_ptr') diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/formatters/formatters.py b/lldb/packages/Python/lldbsuite/test/expression_command/formatters/formatters.py index ce922a8f911..dae84988af9 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/formatters/formatters.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/formatters/formatters.py @@ -1,17 +1,17 @@ -def foo_SummaryProvider (valobj,dict): - a = valobj.GetChildMemberWithName('a'); - a_ptr = valobj.GetChildMemberWithName('a_ptr'); - bar = valobj.GetChildMemberWithName('b'); - i = bar.GetChildMemberWithName('i'); - i_ptr = bar.GetChildMemberWithName('i_ptr'); - b_ref = bar.GetChildMemberWithName('b_ref'); - b_ref_ptr = b_ref.AddressOf() - b_ref = b_ref_ptr.Dereference() - h = b_ref.GetChildMemberWithName('h'); - k = b_ref.GetChildMemberWithName('k'); - return 'a = ' + str(a.GetValueAsUnsigned(0)) + ', a_ptr = ' + \ - str(a_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(a_ptr.Dereference().GetValueAsUnsigned(0)) + \ - ', i = ' + str(i.GetValueAsUnsigned(0)) + \ - ', i_ptr = ' + str(i_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(i_ptr.Dereference().GetValueAsUnsigned(0)) + \ - ', b_ref = ' + str(b_ref.GetValueAsUnsigned(0)) + \ - ', h = ' + str(h.GetValueAsUnsigned(0)) + ' , k = ' + str(k.GetValueAsUnsigned(0))
\ No newline at end of file +def foo_SummaryProvider(valobj, dict): + a = valobj.GetChildMemberWithName('a') + a_ptr = valobj.GetChildMemberWithName('a_ptr') + bar = valobj.GetChildMemberWithName('b') + i = bar.GetChildMemberWithName('i') + i_ptr = bar.GetChildMemberWithName('i_ptr') + b_ref = bar.GetChildMemberWithName('b_ref') + b_ref_ptr = b_ref.AddressOf() + b_ref = b_ref_ptr.Dereference() + h = b_ref.GetChildMemberWithName('h') + k = b_ref.GetChildMemberWithName('k') + return 'a = ' + str(a.GetValueAsUnsigned(0)) + ', a_ptr = ' + \ + str(a_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(a_ptr.Dereference().GetValueAsUnsigned(0)) + \ + ', i = ' + str(i.GetValueAsUnsigned(0)) + \ + ', i_ptr = ' + str(i_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(i_ptr.Dereference().GetValueAsUnsigned(0)) + \ + ', b_ref = ' + str(b_ref.GetValueAsUnsigned(0)) + \ + ', h = ' + str(h.GetValueAsUnsigned(0)) + ' , k = ' + str(k.GetValueAsUnsigned(0)) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py b/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py index c4f17670322..894d0bfaa86 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py @@ -2,38 +2,41 @@ Test PHI nodes work in the IR interpreter. """ -import os, os.path +import os +import os.path import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class IRInterpreterPHINodesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def test_phi_node_support(self): """Test support for PHI nodes in the IR interpreter.""" - + self.build() exe = os.path.join(os.getcwd(), 'a.out') self.runCmd('file ' + exe, CURRENT_EXECUTABLE_SET) - + # Break on the first assignment to i line = line_number('main.cpp', 'i = 5') - lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', line, num_expected_locations=1, loc_exact=True) - + lldbutil.run_break_set_by_file_and_line( + self, 'main.cpp', line, num_expected_locations=1, loc_exact=True) + self.runCmd('run', RUN_SUCCEEDED) - + # The stop reason of the thread should be breakpoint self.expect('thread list', STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) - + substrs=['stopped', 'stop reason = breakpoint']) + self.runCmd('s') - + # The logical 'or' causes a PHI node to be generated. Execute without JIT # to test that the interpreter can handle this self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['true']) - + self.runCmd('s') self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['false']) self.runCmd('s') diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter/TestIRInterpreter.py b/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter/TestIRInterpreter.py index 2a21d047371..5c5110b6994 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter/TestIRInterpreter.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/ir-interpreter/TestIRInterpreter.py @@ -6,12 +6,14 @@ from __future__ import print_function import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class IRInterpreterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,7 +27,8 @@ class IRInterpreterTestCase(TestBase): # Disable confirmation prompt to avoid infinite wait self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def build_and_run(self): """Test the IR interpreter""" @@ -33,13 +36,20 @@ class IRInterpreterTestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=False) self.runCmd("run", RUN_SUCCEEDED) @add_test_categories(['pyapi']) - @expectedFailureAll(oslist=['windows'], bugnumber="http://llvm.org/pr21765") # getpid() is POSIX, among other problems, see bug - @expectedFailureAll(oslist=['linux'], archs=['arm'], bugnumber="llvm.org/pr27868") + # getpid() is POSIX, among other problems, see bug + @expectedFailureAll( + oslist=['windows'], + bugnumber="http://llvm.org/pr21765") + @expectedFailureAll( + oslist=['linux'], + archs=['arm'], + bugnumber="llvm.org/pr27868") def test_ir_interpreter(self): self.build_and_run() @@ -62,11 +72,16 @@ class IRInterpreterTestCase(TestBase): self.frame().EvaluateExpression(expression, options) for expression in expressions: - interp_expression = expression - jit_expression = "(int)getpid(); " + expression - - interp_result = self.frame().EvaluateExpression(interp_expression, options).GetValueAsSigned() - jit_result = self.frame().EvaluateExpression(jit_expression, options).GetValueAsSigned() - - self.assertEqual(interp_result, jit_result, "While evaluating " + expression) - + interp_expression = expression + jit_expression = "(int)getpid(); " + expression + + interp_result = self.frame().EvaluateExpression( + interp_expression, options).GetValueAsSigned() + jit_result = self.frame().EvaluateExpression( + jit_expression, options).GetValueAsSigned() + + self.assertEqual( + interp_result, + jit_result, + "While evaluating " + + expression) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py b/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py index 2d0b23b4e5b..afb497e04b5 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py @@ -7,13 +7,14 @@ expected in a SyntheticChildrenProvider from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class Issue11581TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,54 +26,61 @@ class Issue11581TestCase(TestBase): def cleanup(): self.runCmd('type synthetic clear', check=False) - # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) """valobj.AddressOf() should return correct values.""" self.build() - + exe = os.path.join(os.getcwd(), "a.out") - + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateBySourceRegex('Set breakpoint here.',lldb.SBFileSpec ("main.cpp", False)) - - process = target.LaunchSimple (None, None, self.get_process_working_directory()) - self.assertTrue (process, "Created a process.") - self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.") + breakpoint = target.BreakpointCreateBySourceRegex( + 'Set breakpoint here.', lldb.SBFileSpec("main.cpp", False)) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Created a process.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped it too.") - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] self.runCmd("command script import --allow-reload s11588.py") - self.runCmd("type synthetic add --python-class s11588.Issue11581SyntheticProvider StgClosure") + self.runCmd( + "type synthetic add --python-class s11588.Issue11581SyntheticProvider StgClosure") self.expect("expr --show-types -- *((StgClosure*)(r14-1))", - substrs = ["(StgClosure) $", - "(StgClosure *) &$","0x", - "addr = ", - "load_address = "]) + substrs=["(StgClosure) $", + "(StgClosure *) &$", "0x", + "addr = ", + "load_address = "]) # register r14 is an x86_64 extension let's skip this part of the test # if we are on a different architecture if self.getArchitecture() == 'x86_64': - target = lldb.debugger.GetSelectedTarget() - process = target.GetProcess() - frame = process.GetSelectedThread().GetSelectedFrame() - pointer = frame.FindVariable("r14") - addr = pointer.GetValueAsUnsigned(0) - self.assertTrue(addr != 0, "could not read pointer to StgClosure") - addr = addr - 1 - self.runCmd("register write r14 %d" % addr) - self.expect("register read r14", - substrs = ["0x",hex(addr)[2:].rstrip("L")]) # Remove trailing 'L' if it exists - self.expect("expr --show-types -- *(StgClosure*)$r14", - substrs = ["(StgClosure) $", - "(StgClosure *) &$","0x", - "addr = ", - "load_address = ", - hex(addr)[2:].rstrip("L"), - str(addr)]) + target = lldb.debugger.GetSelectedTarget() + process = target.GetProcess() + frame = process.GetSelectedThread().GetSelectedFrame() + pointer = frame.FindVariable("r14") + addr = pointer.GetValueAsUnsigned(0) + self.assertTrue(addr != 0, "could not read pointer to StgClosure") + addr = addr - 1 + self.runCmd("register write r14 %d" % addr) + self.expect( + "register read r14", substrs=[ + "0x", hex(addr)[ + 2:].rstrip("L")]) # Remove trailing 'L' if it exists + self.expect("expr --show-types -- *(StgClosure*)$r14", + substrs=["(StgClosure) $", + "(StgClosure *) &$", "0x", + "addr = ", + "load_address = ", + hex(addr)[2:].rstrip("L"), + str(addr)]) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py b/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py index 01bb09a1b0d..51c20423ed3 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py @@ -1,26 +1,28 @@ class Issue11581SyntheticProvider(object): - def __init__(self, valobj, dict): - self.valobj = valobj - self.addrOf = valobj.AddressOf() - self.addr = valobj.GetAddress() - self.load_address = valobj.GetLoadAddress() - def num_children(self): - return 3; + def __init__(self, valobj, dict): + self.valobj = valobj + self.addrOf = valobj.AddressOf() + self.addr = valobj.GetAddress() + self.load_address = valobj.GetLoadAddress() - def get_child_at_index(self, index): - if index == 0: - return self.addrOf - if index == 1: - return self.valobj.CreateValueFromExpression("addr", str(self.addr)) - if index == 2: - return self.valobj.CreateValueFromExpression("load_address", str(self.load_address)) + def num_children(self): + return 3 - def get_child_index(self, name): - if name == "addrOf": - return 0 - if name == "addr": - return 1 - if name == "load_address": - return 2 + def get_child_at_index(self, index): + if index == 0: + return self.addrOf + if index == 1: + return self.valobj.CreateValueFromExpression( + "addr", str(self.addr)) + if index == 2: + return self.valobj.CreateValueFromExpression( + "load_address", str(self.load_address)) + def get_child_index(self, name): + if name == "addrOf": + return 0 + if name == "addr": + return 1 + if name == "load_address": + return 2 diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py b/lldb/packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py index 939d2e45d7d..70b862bf486 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py @@ -6,13 +6,21 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestMacros(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(compiler="clang", bugnumber="clang does not emit .debug_macro[.dwo] sections.") - @expectedFailureAll(debug_info="dwo", bugnumber="GCC produces multiple .debug_macro.dwo sections and the spec is unclear as to what it means") - @expectedFailureAll(hostoslist=["windows"], compiler="gcc", triple='.*-android') + @expectedFailureAll( + compiler="clang", + bugnumber="clang does not emit .debug_macro[.dwo] sections.") + @expectedFailureAll( + debug_info="dwo", + bugnumber="GCC produces multiple .debug_macro.dwo sections and the spec is unclear as to what it means") + @expectedFailureAll( + hostoslist=["windows"], + compiler="gcc", + triple='.*-android') def test_expr_with_macros(self): self.build() @@ -25,7 +33,7 @@ class TestMacros(TestBase): # Get the path of the executable cwd = os.getcwd() exe_file = "a.out" - exe_path = os.path.join(cwd, exe_file) + exe_path = os.path.join(cwd, exe_file) # Load the executable target = self.dbg.CreateTarget(exe_path) @@ -33,51 +41,78 @@ class TestMacros(TestBase): # Set breakpoints bp1 = target.BreakpointCreateBySourceRegex("Break here", src_file_spec) - self.assertTrue(bp1.IsValid() and bp1.GetNumLocations() >= 1, VALID_BREAKPOINT) + self.assertTrue( + bp1.IsValid() and bp1.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) # Get frame for current thread frame = thread.GetSelectedFrame() result = frame.EvaluateExpression("MACRO_1") - self.assertTrue(result.IsValid() and result.GetValue() == "100", "MACRO_1 = 100") + self.assertTrue( + result.IsValid() and result.GetValue() == "100", + "MACRO_1 = 100") result = frame.EvaluateExpression("MACRO_2") - self.assertTrue(result.IsValid() and result.GetValue() == "200", "MACRO_2 = 200") + self.assertTrue( + result.IsValid() and result.GetValue() == "200", + "MACRO_2 = 200") result = frame.EvaluateExpression("ONE") - self.assertTrue(result.IsValid() and result.GetValue() == "1", "ONE = 1") + self.assertTrue( + result.IsValid() and result.GetValue() == "1", + "ONE = 1") result = frame.EvaluateExpression("TWO") - self.assertTrue(result.IsValid() and result.GetValue() == "2", "TWO = 2") + self.assertTrue( + result.IsValid() and result.GetValue() == "2", + "TWO = 2") result = frame.EvaluateExpression("THREE") - self.assertTrue(result.IsValid() and result.GetValue() == "3", "THREE = 3") + self.assertTrue( + result.IsValid() and result.GetValue() == "3", + "THREE = 3") result = frame.EvaluateExpression("FOUR") - self.assertTrue(result.IsValid() and result.GetValue() == "4", "FOUR = 4") + self.assertTrue( + result.IsValid() and result.GetValue() == "4", + "FOUR = 4") result = frame.EvaluateExpression("HUNDRED") - self.assertTrue(result.IsValid() and result.GetValue() == "100", "HUNDRED = 100") + self.assertTrue( + result.IsValid() and result.GetValue() == "100", + "HUNDRED = 100") result = frame.EvaluateExpression("THOUSAND") - self.assertTrue(result.IsValid() and result.GetValue() == "1000", "THOUSAND = 1000") + self.assertTrue( + result.IsValid() and result.GetValue() == "1000", + "THOUSAND = 1000") result = frame.EvaluateExpression("MILLION") - self.assertTrue(result.IsValid() and result.GetValue() == "1000000", "MILLION = 1000000") + self.assertTrue(result.IsValid() and result.GetValue() + == "1000000", "MILLION = 1000000") result = frame.EvaluateExpression("MAX(ONE, TWO)") - self.assertTrue(result.IsValid() and result.GetValue() == "2", "MAX(ONE, TWO) = 2") + self.assertTrue( + result.IsValid() and result.GetValue() == "2", + "MAX(ONE, TWO) = 2") result = frame.EvaluateExpression("MAX(THREE, TWO)") - self.assertTrue(result.IsValid() and result.GetValue() == "3", "MAX(THREE, TWO) = 3") + self.assertTrue( + result.IsValid() and result.GetValue() == "3", + "MAX(THREE, TWO) = 3") # Get the thread of the process thread.StepOver() @@ -86,10 +121,14 @@ class TestMacros(TestBase): frame = thread.GetSelectedFrame() result = frame.EvaluateExpression("MACRO_2") - self.assertTrue(result.GetError().Fail(), "Printing MACRO_2 fails in the mail file") + self.assertTrue( + result.GetError().Fail(), + "Printing MACRO_2 fails in the mail file") result = frame.EvaluateExpression("FOUR") - self.assertTrue(result.GetError().Fail(), "Printing FOUR fails in the main file") + self.assertTrue( + result.GetError().Fail(), + "Printing FOUR fails in the main file") thread.StepInto() @@ -97,14 +136,20 @@ class TestMacros(TestBase): frame = thread.GetSelectedFrame() result = frame.EvaluateExpression("ONE") - self.assertTrue(result.IsValid() and result.GetValue() == "1", "ONE = 1") + self.assertTrue( + result.IsValid() and result.GetValue() == "1", + "ONE = 1") result = frame.EvaluateExpression("MAX(ONE, TWO)") - self.assertTrue(result.IsValid() and result.GetValue() == "2", "MAX(ONE, TWO) = 2") + self.assertTrue( + result.IsValid() and result.GetValue() == "2", + "MAX(ONE, TWO) = 2") # This time, MACRO_1 and MACRO_2 are not visible. result = frame.EvaluateExpression("MACRO_1") - self.assertTrue(result.GetError().Fail(), "Printing MACRO_1 fails in the header file") + self.assertTrue(result.GetError().Fail(), + "Printing MACRO_1 fails in the header file") result = frame.EvaluateExpression("MACRO_2") - self.assertTrue(result.GetError().Fail(), "Printing MACRO_2 fails in the header file") + self.assertTrue(result.GetError().Fail(), + "Printing MACRO_2 fails in the header file") diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/multiline/TestMultilineExpressions.py b/lldb/packages/Python/lldbsuite/test/expression_command/multiline/TestMultilineExpressions.py index 0691a866743..b1b5cbe677c 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/multiline/TestMultilineExpressions.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/multiline/TestMultilineExpressions.py @@ -8,6 +8,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MultilineExpressionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +20,9 @@ class MultilineExpressionsTestCase(TestBase): self.line = line_number('main.c', 'break') @skipIfRemote - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_with_run_commands(self): """Test that multiline expressions work correctly""" self.build() @@ -28,7 +31,9 @@ class MultilineExpressionsTestCase(TestBase): prompt = "(lldb) " # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. if self.TraceOn(): @@ -54,4 +59,4 @@ class MultilineExpressionsTestCase(TestBase): child.sendline('') child.expect_exact(prompt) self.expect(child.before, exe=False, - patterns = ['= 5']) + patterns=['= 5']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py b/lldb/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py index 00c34820eef..0d1a17352a3 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py @@ -10,12 +10,13 @@ o test_expr_options: from __future__ import print_function - -import os, time +import os +import time import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * + class ExprOptionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,7 +26,7 @@ class ExprOptionsTestCase(TestBase): TestBase.setUp(self) self.main_source = "main.cpp" - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) self.line = line_number('main.cpp', '// breakpoint_in_main') self.exe = os.path.join(os.getcwd(), "a.out") @@ -41,14 +42,17 @@ class ExprOptionsTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Set breakpoints inside main. - breakpoint = target.BreakpointCreateBySourceRegex('// breakpoint_in_main', self.main_source_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + '// breakpoint_in_main', self.main_source_spec) self.assertTrue(breakpoint) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) self.assertEqual(len(threads), 1) frame = threads[0].GetFrameAtIndex(0) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py b/lldb/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py index d3ce10d8f2a..7eadfcd4c47 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py @@ -5,12 +5,12 @@ Test that we can p *objcObject from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PersistObjCPointeeType(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +19,7 @@ class PersistObjCPointeeType(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.cpp. - self.line = line_number('main.m','// break here') + self.line = line_number('main.m', '// break here') @skipUnlessDarwin @expectedFailureAll( @@ -37,15 +37,16 @@ class PersistObjCPointeeType(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - + self.expect("p *self", substrs=['_sc_name = nil', - '_sc_name2 = nil', - '_sc_name3 = nil', - '_sc_name4 = nil', - '_sc_name5 = nil', - '_sc_name6 = nil', - '_sc_name7 = nil', - '_sc_name8 = nil']) + '_sc_name2 = nil', + '_sc_name3 = nil', + '_sc_name4 = nil', + '_sc_name5 = nil', + '_sc_name6 = nil', + '_sc_name7 = nil', + '_sc_name8 = nil']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py index 9d7359fb2d4..118b9f32c4b 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py @@ -5,11 +5,11 @@ Test that we can have persistent pointer variables from __future__ import print_function - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * + class PersistentPtrUpdateTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,18 +24,18 @@ class PersistentPtrUpdateTestCase(TestBase): def cleanup(): pass - + # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - + self.runCmd('break set -p here') self.runCmd("run", RUN_SUCCEEDED) - + self.runCmd("expr void* $foo = 0") - + self.runCmd("continue") - - self.expect("expr $foo", substrs=['$foo','0x0']) + + self.expect("expr $foo", substrs=['$foo', '0x0']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py index 9099ae1806e..12452a96377 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py @@ -5,13 +5,14 @@ Test that nested persistent types work. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NestedPersistentTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,15 +30,16 @@ class NestedPersistentTypesTestCase(TestBase): self.runCmd("expression struct $foo { int a; int b; };") - self.runCmd("expression struct $bar { struct $foo start; struct $foo end; };") + self.runCmd( + "expression struct $bar { struct $foo start; struct $foo end; };") self.runCmd("expression struct $bar $my_bar = {{ 2, 3 }, { 4, 5 }};") self.expect("expression $my_bar", - substrs = ['a = 2', 'b = 3', 'a = 4', 'b = 5']) + substrs=['a = 2', 'b = 3', 'a = 4', 'b = 5']) self.expect("expression $my_bar.start.b", - substrs = ['(int)', '3']) + substrs=['(int)', '3']) self.expect("expression $my_bar.end.b", - substrs = ['(int)', '5']) + substrs=['(int)', '5']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py index 59e0f0b84f6..3d4df307d1b 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py @@ -5,13 +5,14 @@ Test that lldb persistent types works correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PersistenttypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,31 +30,57 @@ class PersistenttypesTestCase(TestBase): self.runCmd("expression struct $foo { int a; int b; };") - self.expect("expression struct $foo $my_foo; $my_foo.a = 2; $my_foo.b = 3;", - startstr = "(int) $0 = 3") + self.expect( + "expression struct $foo $my_foo; $my_foo.a = 2; $my_foo.b = 3;", + startstr="(int) $0 = 3") self.expect("expression $my_foo", - substrs = ['a = 2', 'b = 3']) + substrs=['a = 2', 'b = 3']) self.runCmd("expression typedef int $bar") self.expect("expression $bar i = 5; i", - startstr = "($bar) $1 = 5") + startstr="($bar) $1 = 5") - self.runCmd("expression struct $foobar { char a; char b; char c; char d; };") + self.runCmd( + "expression struct $foobar { char a; char b; char c; char d; };") self.runCmd("next") - self.expect("memory read foo -t $foobar", - substrs = ['($foobar) 0x', ' = ', "a = 'H'","b = 'e'","c = 'l'","d = 'l'"]) # persistent types are OK to use for memory read - - self.expect("memory read foo -t foobar", - substrs = ['($foobar) 0x', ' = ', "a = 'H'","b = 'e'","c = 'l'","d = 'l'"],matching=False,error=True) # the type name is $foobar, make sure we settle for nothing less + self.expect( + "memory read foo -t $foobar", + substrs=[ + '($foobar) 0x', + ' = ', + "a = 'H'", + "b = 'e'", + "c = 'l'", + "d = 'l'"]) # persistent types are OK to use for memory read + + self.expect( + "memory read foo -t foobar", + substrs=[ + '($foobar) 0x', + ' = ', + "a = 'H'", + "b = 'e'", + "c = 'l'", + "d = 'l'"], + matching=False, + error=True) # the type name is $foobar, make sure we settle for nothing less self.expect("expression struct { int a; int b; } x = { 2, 3 }; x", - substrs = ['a = 2', 'b = 3']) - - self.expect("expression struct { int x; int y; int z; } object; object.y = 1; object.z = 3; object.x = 2; object", - substrs = ['x = 2', 'y = 1', 'z = 3']) - - self.expect("expression struct A { int x; int y; }; struct { struct A a; int z; } object; object.a.y = 1; object.z = 3; object.a.x = 2; object", - substrs = ['x = 2', 'y = 1', 'z = 3']) + substrs=['a = 2', 'b = 3']) + + self.expect( + "expression struct { int x; int y; int z; } object; object.y = 1; object.z = 3; object.x = 2; object", + substrs=[ + 'x = 2', + 'y = 1', + 'z = 3']) + + self.expect( + "expression struct A { int x; int y; }; struct { struct A a; int z; } object; object.a.y = 1; object.z = 3; object.a.x = 2; object", + substrs=[ + 'x = 2', + 'y = 1', + 'z = 3']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py index e148fcd8959..b6f027964ba 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py @@ -5,11 +5,12 @@ Test that lldb persistent variables works correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * + class PersistentVariablesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,28 +28,28 @@ class PersistentVariablesTestCase(TestBase): self.runCmd("expression int $i = i") self.expect("expression $i == i", - startstr = "(bool) $0 = true") + startstr="(bool) $0 = true") self.expect("expression $i + 1", - startstr = "(int) $1 = 6") + startstr="(int) $1 = 6") self.expect("expression $i + 3", - startstr = "(int) $2 = 8") + startstr="(int) $2 = 8") self.expect("expression $2 + $1", - startstr = "(int) $3 = 14") + startstr="(int) $3 = 14") self.expect("expression $3", - startstr = "(int) $3 = 14") + startstr="(int) $3 = 14") self.expect("expression $2", - startstr = "(int) $2 = 8") + startstr="(int) $2 = 8") self.expect("expression (int)-2", - startstr = "(int) $4 = -2") + startstr="(int) $4 = -2") self.expect("expression $4 > (int)31", - startstr = "(bool) $5 = false") + startstr="(bool) $5 = false") self.expect("expression (long)$4", - startstr = "(long) $6 = -2") + startstr="(long) $6 = -2") diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py b/lldb/packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py index da87bcee9cf..13f8f58564e 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py @@ -5,12 +5,12 @@ Test that the po command acts correctly. from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PoVerbosityTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,37 +26,38 @@ class PoVerbosityTestCase(TestBase): def test(self): """Test that the po command acts correctly.""" self.build() - + # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): self.runCmd('type summary clear', check=False) self.runCmd('type synthetic clear', check=False) - + # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) """Test expr + formatters for good interoperability.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - + self.expect("expr -O -v -- foo", - substrs = ['(id) $',' = 0x', '1 = 2','2 = 3;']) + substrs=['(id) $', ' = 0x', '1 = 2', '2 = 3;']) self.expect("expr -O -vfull -- foo", - substrs = ['(id) $',' = 0x', '1 = 2','2 = 3;']) - self.expect("expr -O -- foo",matching=False, - substrs = ['(id) $']) + substrs=['(id) $', ' = 0x', '1 = 2', '2 = 3;']) + self.expect("expr -O -- foo", matching=False, + substrs=['(id) $']) - self.expect("expr -O -- 22",matching=False, - substrs = ['(int) $']) + self.expect("expr -O -- 22", matching=False, + substrs=['(int) $']) self.expect("expr -O -- 22", - substrs = ['22']) + substrs=['22']) self.expect("expr -O -vfull -- 22", - substrs = ['(int) $', ' = 22']) + substrs=['(int) $', ' = 22']) self.expect("expr -O -v -- 22", - substrs = ['(int) $', ' = 22']) + substrs=['(int) $', ' = 22']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py b/lldb/packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py index 302b14b7360..ca43585616e 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py @@ -5,11 +5,12 @@ Test the robustness of lldb expression parser. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * + class Radar8638051TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,15 +26,15 @@ class Radar8638051TestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.expect("expression val", - startstr = "(int) $0 = 1") + startstr="(int) $0 = 1") # (int) $0 = 1 self.expect("expression *(&val)", - startstr = "(int) $1 = 1") + startstr="(int) $1 = 1") # (int) $1 = 1 # rdar://problem/8638051 # lldb expression command: Could this crash be avoided self.expect("expression &val", - startstr = "(int *) $2 = ") + startstr="(int *) $2 = ") # (int *) $2 = 0x.... diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py b/lldb/packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py index e0b219dbe2b..c4d899cfc1e 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py @@ -5,13 +5,14 @@ The evaluating printf(...) after break stop and then up a stack frame. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class Radar9531204TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,7 +25,8 @@ class Radar9531204TestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_symbol (self, 'foo', sym_exact=True, num_expected_locations=1) + lldbutil.run_break_set_by_symbol( + self, 'foo', sym_exact=True, num_expected_locations=1) self.runCmd("run", RUN_SUCCEEDED) @@ -35,7 +37,7 @@ class Radar9531204TestCase(TestBase): # rdar://problem/9531204 # "Error dematerializing struct" error when evaluating expressions "up" on the stack - self.runCmd('up') # frame select -r 1 + self.runCmd('up') # frame select -r 1 self.runCmd("frame variable") diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py b/lldb/packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py index a1505b08c50..a6c0c050c46 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py @@ -5,13 +5,14 @@ Test example snippets from the lldb 'help expression' output. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class Radar9673644TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,13 +31,18 @@ class Radar9673644TestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # rdar://problem/9673664 lldb expression evaluation problem self.expect('expr char c[] = "foo"; c[0]', - substrs = ["'f'"]) + substrs=["'f'"]) # runCmd: expr char c[] = "foo"; c[0] # output: (char) $0 = 'f' diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs.py b/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs.py index 8c9a9a5a27e..1cd11a8c275 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs.py @@ -14,15 +14,16 @@ o test_expr_commands_can_handle_quotes: from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BasicExprCommandsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -31,13 +32,14 @@ class BasicExprCommandsTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.cpp', - '// Please test many expressions while stopped at this line:') + self.line = line_number( + 'main.cpp', + '// Please test many expressions while stopped at this line:') # Disable confirmation prompt to avoid infinite wait self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) - + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def build_and_run(self): """These basic expression commands should work as expected.""" @@ -45,56 +47,58 @@ class BasicExprCommandsTestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) self.runCmd("run", RUN_SUCCEEDED) - @unittest2.expectedFailure("llvm.org/pr17135 <rdar://problem/14874559> APFloat::toString does not identify the correct (i.e. least) precision.") + @unittest2.expectedFailure( + "llvm.org/pr17135 <rdar://problem/14874559> APFloat::toString does not identify the correct (i.e. least) precision.") def test_floating_point_expr_commands(self): self.build_and_run() self.expect("expression 2.234f", - patterns = ["\(float\) \$.* = 2\.234"]) + patterns=["\(float\) \$.* = 2\.234"]) # (float) $2 = 2.234 def test_many_expr_commands(self): self.build_and_run() self.expect("expression 2", - patterns = ["\(int\) \$.* = 2"]) + patterns=["\(int\) \$.* = 2"]) # (int) $0 = 1 self.expect("expression 2ull", - patterns = ["\(unsigned long long\) \$.* = 2"]) + patterns=["\(unsigned long long\) \$.* = 2"]) # (unsigned long long) $1 = 2 self.expect("expression 0.5f", - patterns = ["\(float\) \$.* = 0\.5"]) + patterns=["\(float\) \$.* = 0\.5"]) # (float) $2 = 0.5 self.expect("expression 2.234", - patterns = ["\(double\) \$.* = 2\.234"]) + patterns=["\(double\) \$.* = 2\.234"]) # (double) $3 = 2.234 self.expect("expression 2+3", - patterns = ["\(int\) \$.* = 5"]) + patterns=["\(int\) \$.* = 5"]) # (int) $4 = 5 self.expect("expression argc", - patterns = ["\(int\) \$.* = 1"]) + patterns=["\(int\) \$.* = 1"]) # (int) $5 = 1 self.expect("expression argc + 22", - patterns = ["\(int\) \$.* = 23"]) + patterns=["\(int\) \$.* = 23"]) # (int) $6 = 23 self.expect("expression argv", - patterns = ["\(const char \*\*\) \$.* = 0x"]) + patterns=["\(const char \*\*\) \$.* = 0x"]) # (const char *) $7 = ... self.expect("expression argv[0]", - substrs = ["(const char *)", - "a.out"]) + substrs=["(const char *)", + "a.out"]) # (const char *) $8 = 0x... "/Volumes/data/lldb/svn/trunk/test/expression_command/test/a.out" @add_test_categories(['pyapi']) @@ -115,12 +119,13 @@ class BasicExprCommandsTestCase(TestBase): # Verify the breakpoint just created. self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False, - substrs = ['main.cpp', - str(self.line)]) + substrs=['main.cpp', + str(self.line)]) # Launch the process, and do not stop at the entry point. # Pass 'X Y Z' as the args, which makes argc == 4. - process = target.LaunchSimple (['X', 'Y', 'Z'], None, self.get_process_working_directory()) + process = target.LaunchSimple( + ['X', 'Y', 'Z'], None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") @@ -130,16 +135,18 @@ class BasicExprCommandsTestCase(TestBase): "instead the actual state is: '%s'" % lldbutil.state_type_to_str(process.GetState())) - thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, breakpoint) - self.assertIsNotNone(thread, "Expected one thread to be stopped at the breakpoint") + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + self.assertIsNotNone( + thread, "Expected one thread to be stopped at the breakpoint") # The filename of frame #0 should be 'main.cpp' and function is main. self.expect(lldbutil.get_filenames(thread)[0], "Break correctly at main.cpp", exe=False, - startstr = "main.cpp") + startstr="main.cpp") self.expect(lldbutil.get_function_names(thread)[0], "Break correctly at main()", exe=False, - startstr = "main") + startstr="main") # We should be stopped on the breakpoint with a hit count of 1. self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE) @@ -151,49 +158,51 @@ class BasicExprCommandsTestCase(TestBase): val = frame.EvaluateExpression("2.234") self.expect(val.GetValue(), "2.345 evaluated correctly", exe=False, - startstr = "2.234") + startstr="2.234") self.expect(val.GetTypeName(), "2.345 evaluated correctly", exe=False, - startstr = "double") + startstr="double") self.DebugSBValue(val) val = frame.EvaluateExpression("argc") self.expect(val.GetValue(), "Argc evaluated correctly", exe=False, - startstr = "4") + startstr="4") self.DebugSBValue(val) val = frame.EvaluateExpression("*argv[1]") self.expect(val.GetValue(), "Argv[1] evaluated correctly", exe=False, - startstr = "'X'") + startstr="'X'") self.DebugSBValue(val) val = frame.EvaluateExpression("*argv[2]") self.expect(val.GetValue(), "Argv[2] evaluated correctly", exe=False, - startstr = "'Y'") + startstr="'Y'") self.DebugSBValue(val) val = frame.EvaluateExpression("*argv[3]") self.expect(val.GetValue(), "Argv[3] evaluated correctly", exe=False, - startstr = "'Z'") + startstr="'Z'") self.DebugSBValue(val) - callee_break = target.BreakpointCreateByName ("a_function_to_call", None) + callee_break = target.BreakpointCreateByName( + "a_function_to_call", None) self.assertTrue(callee_break.GetNumLocations() > 0) # Make sure ignoring breakpoints works from the command line: self.expect("expression -i true -- a_function_to_call()", - substrs = ['(int) $', ' 1']) - self.assertTrue (callee_break.GetHitCount() == 1) + substrs=['(int) $', ' 1']) + self.assertTrue(callee_break.GetHitCount() == 1) # Now try ignoring breakpoints using the SB API's: options = lldb.SBExpressionOptions() options.SetIgnoreBreakpoints(True) value = frame.EvaluateExpression('a_function_to_call()', options) - self.assertTrue (value.IsValid()) - self.assertTrue (value.GetValueAsSigned(0) == 2) - self.assertTrue (callee_break.GetHitCount() == 2) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetValueAsSigned(0) == 2) + self.assertTrue(callee_break.GetHitCount() == 2) # rdar://problem/8686536 - # CommandInterpreter::HandleCommand is stripping \'s from input for WantsRawCommand commands + # CommandInterpreter::HandleCommand is stripping \'s from input for + # WantsRawCommand commands @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") def test_expr_commands_can_handle_quotes(self): """Throw some expression commands with quotes at lldb.""" @@ -201,44 +210,46 @@ class BasicExprCommandsTestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line, num_expected_locations=1,loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) self.runCmd("run", RUN_SUCCEEDED) # runCmd: expression 'a' # output: (char) $0 = 'a' self.expect("expression 'a'", - substrs = ['(char) $', - "'a'"]) + substrs=['(char) $', + "'a'"]) # runCmd: expression (int) printf ("\n\n\tHello there!\n") # output: (int) $1 = 16 self.expect(r'''expression (int) printf ("\n\n\tHello there!\n")''', - substrs = ['(int) $', - '16']) + substrs=['(int) $', + '16']) # runCmd: expression (int) printf("\t\x68\n") # output: (int) $2 = 3 self.expect(r'''expression (int) printf("\t\x68\n")''', - substrs = ['(int) $', - '3']) + substrs=['(int) $', + '3']) # runCmd: expression (int) printf("\"\n") # output: (int) $3 = 2 self.expect(r'''expression (int) printf("\"\n")''', - substrs = ['(int) $', - '2']) + substrs=['(int) $', + '2']) # runCmd: expression (int) printf("'\n") # output: (int) $4 = 2 self.expect(r'''expression (int) printf("'\n")''', - substrs = ['(int) $', - '2']) + substrs=['(int) $', + '2']) # runCmd: command alias print_hi expression (int) printf ("\n\tHi!\n") - # output: - self.runCmd(r'''command alias print_hi expression (int) printf ("\n\tHi!\n")''') + # output: + self.runCmd( + r'''command alias print_hi expression (int) printf ("\n\tHi!\n")''') # This fails currently. self.expect('print_hi', - substrs = ['(int) $', - '6']) + substrs=['(int) $', + '6']) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py b/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py index 523ee51a9f1..35ac151a390 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py @@ -5,13 +5,13 @@ Test some more expression commands. from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommands2TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,42 +20,46 @@ class ExprCommands2TestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.c. - self.line = line_number('main.cpp', - '// Please test many expressions while stopped at this line:') + self.line = line_number( + 'main.cpp', + '// Please test many expressions while stopped at this line:') - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_more_expr_commands(self): """Test some more expression commands.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line, num_expected_locations=1,loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) self.runCmd("run", RUN_SUCCEEDED) # Does static casting work? self.expect("expression (int*)argv", - startstr = "(int *) $0 = 0x") + startstr="(int *) $0 = 0x") # (int *) $0 = 0x00007fff5fbff258 # Do anonymous symbols work? self.expect("expression ((char**)environ)[0]", - startstr = "(char *) $1 = 0x") + startstr="(char *) $1 = 0x") # (char *) $1 = 0x00007fff5fbff298 "Apple_PubSub_Socket_Render=/tmp/launch-7AEsUD/Render" # Do return values containing the contents of expression locals work? self.expect("expression int i = 5; i", - startstr = "(int) $2 = 5") + startstr="(int) $2 = 5") # (int) $2 = 5 self.expect("expression $2 + 1", - startstr = "(int) $3 = 6") + startstr="(int) $3 = 6") # (int) $3 = 6 # Do return values containing the results of static expressions work? self.expect("expression 20 + 3", - startstr = "(int) $4 = 23") + startstr="(int) $4 = 23") # (int) $4 = 5 self.expect("expression $4 + 1", - startstr = "(int) $5 = 24") + startstr="(int) $5 = 24") # (int) $5 = 6 diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py b/lldb/packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py index 82614319f2a..29c03b1d7ef 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py @@ -5,12 +5,12 @@ Test calling a function that waits a while, and make sure the timeout option to from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprCommandWithTimeoutsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,11 +20,14 @@ class ExprCommandWithTimeoutsTestCase(TestBase): TestBase.setUp(self) self.main_source = "wait-a-while.cpp" - self.main_source_spec = lldb.SBFileSpec (self.main_source) - + self.main_source_spec = lldb.SBFileSpec(self.main_source) @expectedFlakeyFreeBSD("llvm.org/pr19605") - @expectedFailureAll(oslist=["windows", "macosx"], bugnumber="llvm.org/pr21765") + @expectedFailureAll( + oslist=[ + "windows", + "macosx"], + bugnumber="llvm.org/pr21765") def test(self): """Test calling std::String member function.""" self.build() @@ -35,58 +38,65 @@ class ExprCommandWithTimeoutsTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateBySourceRegex('stop here in main.',self.main_source_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + 'stop here in main.', self.main_source_spec) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.step_out_of_malloc. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1) thread = threads[0] - + # First set the timeout too short, and make sure we fail. options = lldb.SBExpressionOptions() options.SetTimeoutInMicroSeconds(10) options.SetUnwindOnError(True) frame = thread.GetFrameAtIndex(0) - + value = frame.EvaluateExpression("wait_a_while(1000000)", options) - self.assertTrue (value.IsValid()) - self.assertFalse (value.GetError().Success()) + self.assertTrue(value.IsValid()) + self.assertFalse(value.GetError().Success()) - # Now do the same thing with the command line command, and make sure it works too. + # Now do the same thing with the command line command, and make sure it + # works too. interp = self.dbg.GetCommandInterpreter() result = lldb.SBCommandReturnObject() - return_value = interp.HandleCommand("expr -t 100 -u true -- wait_a_while(1000000)", result) - self.assertTrue (return_value == lldb.eReturnStatusFailed) + return_value = interp.HandleCommand( + "expr -t 100 -u true -- wait_a_while(1000000)", result) + self.assertTrue(return_value == lldb.eReturnStatusFailed) # Okay, now do it again with long enough time outs: options.SetTimeoutInMicroSeconds(1000000) - value = frame.EvaluateExpression ("wait_a_while (1000)", options) + value = frame.EvaluateExpression("wait_a_while (1000)", options) self.assertTrue(value.IsValid()) - self.assertTrue (value.GetError().Success() == True) - - # Now do the same thingwith the command line command, and make sure it works too. + self.assertTrue(value.GetError().Success()) + + # Now do the same thingwith the command line command, and make sure it + # works too. interp = self.dbg.GetCommandInterpreter() result = lldb.SBCommandReturnObject() - return_value = interp.HandleCommand ("expr -t 1000000 -u true -- wait_a_while(1000)", result) + return_value = interp.HandleCommand( + "expr -t 1000000 -u true -- wait_a_while(1000)", result) self.assertTrue(return_value == lldb.eReturnStatusSuccessFinishResult) - - # Finally set the one thread timeout and make sure that doesn't change things much: + # Finally set the one thread timeout and make sure that doesn't change + # things much: options.SetTimeoutInMicroSeconds(1000000) options.SetOneThreadTimeoutInMicroSeconds(500000) - value = frame.EvaluateExpression ("wait_a_while (1000)", options) + value = frame.EvaluateExpression("wait_a_while (1000)", options) self.assertTrue(value.IsValid()) - self.assertTrue (value.GetError().Success() == True) + self.assertTrue(value.GetError().Success()) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/top-level/TestTopLevelExprs.py b/lldb/packages/Python/lldbsuite/test/expression_command/top-level/TestTopLevelExprs.py index 9a17624cb8e..137c4039887 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/top-level/TestTopLevelExprs.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/top-level/TestTopLevelExprs.py @@ -5,15 +5,16 @@ Test top-level expressions. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TopLevelExpressionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,8 +30,8 @@ class TopLevelExpressionsTestCase(TestBase): # Disable confirmation prompt to avoid infinite wait self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) - + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def build_and_run(self): """Test top-level expressions.""" @@ -38,23 +39,43 @@ class TopLevelExpressionsTestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) self.runCmd("run", RUN_SUCCEEDED) def run_dummy(self): self.runCmd("file dummy", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "dummy.cpp", self.dummy_line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "dummy.cpp", + self.dummy_line, + num_expected_locations=1, + loc_exact=False) self.runCmd("run", RUN_SUCCEEDED) @add_test_categories(['pyapi']) @expectedFailureAndroid(api_levels=[21, 22], bugnumber="llvm.org/pr27787") - @expectedFailureAll(oslist=["linux"], archs=["arm", "aarch64"], bugnumber="llvm.org/pr27787") - @expectedFailureAll(bugnumber="llvm.org/pr28353", oslist=["linux"], archs=["i386", "x86_64"], compiler="gcc", compiler_version=["<", "4.9"]) - @skipIf(debug_info="gmodules") # not relevant - @skipIf(oslist=["windows"]) # Error in record layout on Windows + @expectedFailureAll( + oslist=["linux"], + archs=[ + "arm", + "aarch64"], + bugnumber="llvm.org/pr27787") + @expectedFailureAll( + bugnumber="llvm.org/pr28353", + oslist=["linux"], + archs=[ + "i386", + "x86_64"], + compiler="gcc", + compiler_version=[ + "<", + "4.9"]) + @skipIf(debug_info="gmodules") # not relevant + @skipIf(oslist=["windows"]) # Error in record layout on Windows def test_top_level_expressions(self): self.build_and_run() @@ -86,4 +107,6 @@ class TopLevelExpressionsTestCase(TestBase): resultFromTopLevel = self.frame().EvaluateExpression("doTest()") self.assertTrue(resultFromTopLevel.IsValid()) - self.assertEqual(resultFromCode, resultFromTopLevel.GetValueAsUnsigned()) + self.assertEqual( + resultFromCode, + resultFromTopLevel.GetValueAsUnsigned()) diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py b/lldb/packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py index 2b37faad807..1ce75144017 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py @@ -7,12 +7,12 @@ The expression parser's type search only looks in the current compilation unit f from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCTypeQueryTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,8 +21,8 @@ class ObjCTypeQueryTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.m. - self.line = line_number('main.m', - "// Set breakpoint here, then do 'expr (NSArray*)array_token'.") + self.line = line_number( + 'main.m', "// Set breakpoint here, then do 'expr (NSArray*)array_token'.") @skipUnlessDarwin def test(self): @@ -30,11 +30,12 @@ class ObjCTypeQueryTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # Now do a NSArry type query from the 'main.m' compile uint. self.expect("expression (NSArray*)array_token", - substrs = ['(NSArray *) $0 = 0x']) + substrs=['(NSArray *) $0 = 0x']) # (NSArray *) $0 = 0x00007fff70118398 diff --git a/lldb/packages/Python/lldbsuite/test/expression_command/unwind_expression/TestUnwindExpression.py b/lldb/packages/Python/lldbsuite/test/expression_command/unwind_expression/TestUnwindExpression.py index 6e9af641d03..09917ab3162 100644 --- a/lldb/packages/Python/lldbsuite/test/expression_command/unwind_expression/TestUnwindExpression.py +++ b/lldb/packages/Python/lldbsuite/test/expression_command/unwind_expression/TestUnwindExpression.py @@ -5,15 +5,16 @@ Test stopping at a breakpoint in an expression, and unwinding from there. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class UnwindFromExpressionTest(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,7 +24,6 @@ class UnwindFromExpressionTest(TestBase): TestBase.setUp(self) @add_test_categories(['pyapi']) - def test_unwind_expression(self): """Test unwinding from an expression.""" self.build() @@ -35,11 +35,13 @@ class UnwindFromExpressionTest(TestBase): # Create the breakpoint. main_spec = lldb.SBFileSpec("main.cpp", False) - breakpoint = target.BreakpointCreateBySourceRegex("// Set a breakpoint here to get started", main_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + "// Set a breakpoint here to get started", main_spec) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") @@ -49,17 +51,20 @@ class UnwindFromExpressionTest(TestBase): "instead the actual state is: '%s'" % lldbutil.state_type_to_str(process.GetState())) - thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, breakpoint) - self.assertIsNotNone(thread, "Expected one thread to be stopped at the breakpoint") + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + self.assertIsNotNone( + thread, "Expected one thread to be stopped at the breakpoint") # # Use Python API to evaluate expressions while stopped in a stack frame. # main_frame = thread.GetFrameAtIndex(0) - # Next set a breakpoint in this function, set up Expression options to stop on + # Next set a breakpoint in this function, set up Expression options to stop on # breakpoint hits, and call the function. - fun_bkpt = target.BreakpointCreateBySourceRegex("// Stop inside the function here.", main_spec) + fun_bkpt = target.BreakpointCreateBySourceRegex( + "// Stop inside the function here.", main_spec) self.assertTrue(fun_bkpt, VALID_BREAKPOINT) options = lldb.SBExpressionOptions() options.SetIgnoreBreakpoints(False) @@ -67,17 +72,26 @@ class UnwindFromExpressionTest(TestBase): val = main_frame.EvaluateExpression("a_function_to_call()", options) - self.assertTrue(val.GetError().Fail(), "We did not complete the execution.") + self.assertTrue( + val.GetError().Fail(), + "We did not complete the execution.") error_str = val.GetError().GetCString() - self.assertTrue("Execution was interrupted, reason: breakpoint" in error_str, "And the reason was right.") - - thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, fun_bkpt) - self.assertTrue(thread.IsValid(), "We are indeed stopped at our breakpoint") - - # Now unwind the expression, and make sure we got back to where we started. + self.assertTrue( + "Execution was interrupted, reason: breakpoint" in error_str, + "And the reason was right.") + + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, fun_bkpt) + self.assertTrue( + thread.IsValid(), + "We are indeed stopped at our breakpoint") + + # Now unwind the expression, and make sure we got back to where we + # started. error = thread.UnwindInnermostExpression() self.assertTrue(error.Success(), "We succeeded in unwinding") - - cur_frame = thread.GetFrameAtIndex(0) - self.assertTrue(cur_frame.IsEqual(main_frame), "We got back to the main frame.") + cur_frame = thread.GetFrameAtIndex(0) + self.assertTrue( + cur_frame.IsEqual(main_frame), + "We got back to the main frame.") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py b/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py index 6423ecf27ae..b3095c758f9 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py @@ -5,19 +5,20 @@ Test some lldb command abbreviations and aliases for proper resolution. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class AbbreviationsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @no_debug_info_test - def test_command_abbreviations_and_aliases (self): + def test_command_abbreviations_and_aliases(self): command_interpreter = self.dbg.GetCommandInterpreter() self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER) result = lldb.SBCommandReturnObject() @@ -47,9 +48,12 @@ class AbbreviationsTestCase(TestBase): self.assertTrue(result.GetError().startswith("Ambiguous command")) # Make sure an unabbreviated command is not mangled. - command_interpreter.ResolveCommand("breakpoint set --name main --line 123", result) + command_interpreter.ResolveCommand( + "breakpoint set --name main --line 123", result) self.assertTrue(result.Succeeded()) - self.assertEqual("breakpoint set --name main --line 123", result.GetOutput()) + self.assertEqual( + "breakpoint set --name main --line 123", + result.GetOutput()) # Create some aliases. self.runCmd("com a alias com al") @@ -69,33 +73,40 @@ class AbbreviationsTestCase(TestBase): self.runCmd("alias pltty process launch -s -o %1 -e %1") command_interpreter.ResolveCommand("pltty /dev/tty0", result) self.assertTrue(result.Succeeded()) - self.assertEqual("process launch -s -o /dev/tty0 -e /dev/tty0", result.GetOutput()) + self.assertEqual( + "process launch -s -o /dev/tty0 -e /dev/tty0", + result.GetOutput()) self.runCmd("alias xyzzy breakpoint set -n %1 -l %2") command_interpreter.ResolveCommand("xyzzy main 123", result) self.assertTrue(result.Succeeded()) - self.assertEqual("breakpoint set -n main -l 123", result.GetOutput().strip()) + self.assertEqual( + "breakpoint set -n main -l 123", + result.GetOutput().strip()) # And again, without enough parameters. command_interpreter.ResolveCommand("xyzzy main", result) self.assertFalse(result.Succeeded()) # Check a command that wants the raw input. - command_interpreter.ResolveCommand(r'''sc print("\n\n\tHello!\n")''', result) + command_interpreter.ResolveCommand( + r'''sc print("\n\n\tHello!\n")''', result) self.assertTrue(result.Succeeded()) - self.assertEqual(r'''script print("\n\n\tHello!\n")''', result.GetOutput()) + self.assertEqual( + r'''script print("\n\n\tHello!\n")''', + result.GetOutput()) # Prompt changing stuff should be tested, but this doesn't seem like the # right test to do it in. It has nothing to do with aliases or abbreviations. #self.runCmd("com sou ./change_prompt.lldb") - #self.expect("settings show prompt", + # self.expect("settings show prompt", # startstr = 'prompt (string) = "[with-three-trailing-spaces] "') #self.runCmd("settings clear prompt") - #self.expect("settings show prompt", + # self.expect("settings show prompt", # startstr = 'prompt (string) = "(lldb) "') #self.runCmd("se se prompt 'Sycamore> '") - #self.expect("se sh prompt", + # self.expect("se sh prompt", # startstr = 'prompt (string) = "Sycamore> "') #self.runCmd("se cl prompt") - #self.expect("set sh prompt", + # self.expect("set sh prompt", # startstr = 'prompt (string) = "(lldb) "') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py b/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py index fa6f3f30689..519b93efebe 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py @@ -6,19 +6,20 @@ many commands remain available even after we add/delete commands in the future. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CommonShortSpellingsTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) @no_debug_info_test - def test_abbrevs2 (self): + def test_abbrevs2(self): command_interpreter = self.dbg.GetCommandInterpreter() self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER) result = lldb.SBCommandReturnObject() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/apropos_with_process/TestAproposWithProcess.py b/lldb/packages/Python/lldbsuite/test/functionalities/apropos_with_process/TestAproposWithProcess.py index 66ed3ff7329..aecbab1b363 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/apropos_with_process/TestAproposWithProcess.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/apropos_with_process/TestAproposWithProcess.py @@ -5,13 +5,14 @@ Test that apropos env doesn't crash trying to touch the process plugin commmand from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class AproposWithProcessTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,16 +30,17 @@ class AproposWithProcessTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main() aftre the variables are assigned values. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) self.runCmd('apropos env') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py b/lldb/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py index b419ad97a69..f825eaa86e8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BSDArchivesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -18,10 +19,18 @@ class BSDArchivesTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number in a(int) to break at. - self.line = line_number('a.c', '// Set file and line breakpoint inside a().') + self.line = line_number( + 'a.c', '// Set file and line breakpoint inside a().') - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24527. Makefile.rules doesn't know how to build static libs on Windows") - @expectedFailureAll(oslist=["linux"], archs=["arm", "aarch64"], bugnumber="llvm.org/pr27795") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24527. Makefile.rules doesn't know how to build static libs on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=[ + "arm", + "aarch64"], + bugnumber="llvm.org/pr27795") def test(self): """Break inside a() and b() defined within libfoo.a.""" self.build() @@ -30,30 +39,32 @@ class BSDArchivesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside a() by file and line first. - lldbutil.run_break_set_by_file_and_line (self, "a.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "a.c", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Break at a(int) first. self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(int) arg = 1']) + substrs=['(int) arg = 1']) self.expect("frame variable __a_global", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(int) __a_global = 1']) + substrs=['(int) __a_global = 1']) # Set breakpoint for b() next. - lldbutil.run_break_set_by_symbol (self, "b", num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, "b", num_expected_locations=1, sym_exact=True) # Continue the program, we should break at b(int) next. self.runCmd("continue") self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(int) arg = 2']) + substrs=['(int) arg = 2']) self.expect("frame variable __b_global", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(int) __b_global = 2']) + substrs=['(int) __b_global = 2']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py b/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py index 6416bccc483..29e75f86308 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py @@ -5,25 +5,28 @@ Test that ASan memory history provider returns correct stack traces from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbplatform from lldbsuite.test import lldbutil + class AsanTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt - def test (self): - self.build () - self.asan_tests () + def test(self): + self.build() + self.asan_tests() def setUp(self): # Call super's setUp(). @@ -33,68 +36,99 @@ class AsanTestCase(TestBase): self.line_free = line_number('main.c', '// free line') self.line_breakpoint = line_number('main.c', '// break line') - def asan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def asan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("breakpoint set -f main.c -l %d" % self.line_breakpoint) # "memory history" command should not work without a process self.expect("memory history 0", - error = True, - substrs = ["invalid process"]) + error=True, + substrs=["invalid process"]) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") # the stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # test that the ASan dylib is present - self.expect("image lookup -n __asan_describe_address", "__asan_describe_address should be present", - substrs = ['1 match found']) + self.expect( + "image lookup -n __asan_describe_address", + "__asan_describe_address should be present", + substrs=['1 match found']) # test the 'memory history' command - self.expect("memory history 'pointer'", - substrs = [ - 'Memory allocated by Thread', 'a.out`f1', 'main.c:%d' % self.line_malloc, - 'Memory deallocated by Thread', 'a.out`f2', 'main.c:%d' % self.line_free]) + self.expect( + "memory history 'pointer'", + substrs=[ + 'Memory allocated by Thread', + 'a.out`f1', + 'main.c:%d' % + self.line_malloc, + 'Memory deallocated by Thread', + 'a.out`f2', + 'main.c:%d' % + self.line_free]) # do the same using SB API process = self.dbg.GetSelectedTarget().process val = process.GetSelectedThread().GetSelectedFrame().EvaluateExpression("pointer") addr = val.GetValueAsUnsigned() - threads = process.GetHistoryThreads(addr); + threads = process.GetHistoryThreads(addr) self.assertEqual(threads.GetSize(), 2) - + history_thread = threads.GetThreadAtIndex(0) self.assertTrue(history_thread.num_frames >= 2) - self.assertEqual(history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), "main.c") - self.assertEqual(history_thread.frames[1].GetLineEntry().GetLine(), self.line_free) - + self.assertEqual(history_thread.frames[1].GetLineEntry( + ).GetFileSpec().GetFilename(), "main.c") + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), + self.line_free) + history_thread = threads.GetThreadAtIndex(1) self.assertTrue(history_thread.num_frames >= 2) - self.assertEqual(history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), "main.c") - self.assertEqual(history_thread.frames[1].GetLineEntry().GetLine(), self.line_malloc) - - # let's free the container (SBThreadCollection) and see if the SBThreads still live + self.assertEqual(history_thread.frames[1].GetLineEntry( + ).GetFileSpec().GetFilename(), "main.c") + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), + self.line_malloc) + + # let's free the container (SBThreadCollection) and see if the + # SBThreads still live threads = None self.assertTrue(history_thread.num_frames >= 2) - self.assertEqual(history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), "main.c") - self.assertEqual(history_thread.frames[1].GetLineEntry().GetLine(), self.line_malloc) - + self.assertEqual(history_thread.frames[1].GetLineEntry( + ).GetFileSpec().GetFilename(), "main.c") + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), + self.line_malloc) + # ASan will break when a report occurs and we'll try the API then self.runCmd("continue") - self.expect("thread list", "Process should be stopped due to ASan report", - substrs = ['stopped', 'stop reason = Use of deallocated memory detected']) - - # make sure the 'memory history' command still works even when we're generating a report now - self.expect("memory history 'another_pointer'", - substrs = [ - 'Memory allocated by Thread', 'a.out`f1', 'main.c:%d' % self.line_malloc2]) + self.expect( + "thread list", + "Process should be stopped due to ASan report", + substrs=[ + 'stopped', + 'stop reason = Use of deallocated memory detected']) + + # make sure the 'memory history' command still works even when we're + # generating a report now + self.expect( + "memory history 'another_pointer'", + substrs=[ + 'Memory allocated by Thread', + 'a.out`f1', + 'main.c:%d' % + self.line_malloc2]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py b/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py index b02732ddedd..b89572dc4ef 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py @@ -5,25 +5,28 @@ Test the AddressSanitizer runtime support for report breakpoint and data extract from __future__ import print_function - -import os, time +import os +import time import json import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class AsanTestReportDataCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt def test(self): - self.build () - self.asan_tests () + self.build() + self.asan_tests() def setUp(self): # Call super's setUp(). @@ -34,26 +37,43 @@ class AsanTestReportDataCase(TestBase): self.line_breakpoint = line_number('main.c', '// break line') self.line_crash = line_number('main.c', '// BOOM line') - def asan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def asan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") - self.expect("thread list", "Process should be stopped due to ASan report", - substrs = ['stopped', 'stop reason = Use of deallocated memory detected']) + self.expect( + "thread list", + "Process should be stopped due to ASan report", + substrs=[ + 'stopped', + 'stop reason = Use of deallocated memory detected']) - self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation) + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) self.expect("bt", "The backtrace should show the crashing line", - substrs = ['main.c:%d' % self.line_crash]) - - self.expect("thread info -s", "The extended stop info should contain the ASan provided fields", - substrs = ["access_size", "access_type", "address", "pc", "description", "heap-use-after-free"]) + substrs=['main.c:%d' % self.line_crash]) + + self.expect( + "thread info -s", + "The extended stop info should contain the ASan provided fields", + substrs=[ + "access_size", + "access_type", + "address", + "pc", + "description", + "heap-use-after-free"]) output_lines = self.res.GetOutput().split('\n') json_line = '\n'.join(output_lines[2:]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py b/lldb/packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py index 54463c56827..b348e72606a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py @@ -5,8 +5,8 @@ Test process attach/resume. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -14,6 +14,7 @@ from lldbsuite.test import lldbutil exe_name = "AttachResume" # Must match Makefile + class AttachResumeTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -41,35 +42,53 @@ class AttachResumeTestCase(TestBase): process = self.dbg.GetSelectedTarget().GetProcess() self.runCmd("c") - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) self.runCmd("process interrupt") - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateStopped]) # be sure to continue/interrupt/continue (r204504) self.runCmd("c") - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) self.runCmd("process interrupt") - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateStopped]) # Second interrupt should have no effect. - self.expect("process interrupt", patterns=["Process is not running"], error=True) + self.expect( + "process interrupt", + patterns=["Process is not running"], + error=True) # check that this breakpoint is auto-cleared on detach (r204752) - self.runCmd("br set -f main.cpp -l %u" % (line_number('main.cpp', '// Set breakpoint here'))) + self.runCmd("br set -f main.cpp -l %u" % + (line_number('main.cpp', '// Set breakpoint here'))) self.runCmd("c") - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning, lldb.eStateStopped]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning, lldb.eStateStopped]) self.expect('br list', 'Breakpoint not hit', - substrs = ['hit count = 1']) + substrs=['hit count = 1']) # Make sure the breakpoint is not hit again. - self.expect("expr debugger_flag = false", substrs=[" = false"]); + self.expect("expr debugger_flag = false", substrs=[" = false"]) self.runCmd("c") - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) # make sure to detach while in running state (r204759) self.runCmd("detach") - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateDetached]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateDetached]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py b/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py index e31eac48ad7..867b6053a57 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py @@ -5,7 +5,6 @@ Test whether a process started by lldb has no extra file descriptors open. from __future__ import print_function - import os import lldb from lldbsuite.test import lldbutil @@ -28,55 +27,79 @@ class AvoidsFdLeakTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376") - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") - @skipIfWindows # The check for descriptor leakage needs to be implemented differently here. - @skipIfTargetAndroid() # Android have some other file descriptors open by the shell - def test_fd_leak_basic (self): + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") + # The check for descriptor leakage needs to be implemented differently + # here. + @skipIfWindows + @skipIfTargetAndroid() # Android have some other file descriptors open by the shell + def test_fd_leak_basic(self): self.do_test([]) @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376") - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") - @skipIfWindows # The check for descriptor leakage needs to be implemented differently here. - @skipIfTargetAndroid() # Android have some other file descriptors open by the shell - def test_fd_leak_log (self): + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") + # The check for descriptor leakage needs to be implemented differently + # here. + @skipIfWindows + @skipIfTargetAndroid() # Android have some other file descriptors open by the shell + def test_fd_leak_log(self): self.do_test(["log enable -f '/dev/null' lldb commands"]) - def do_test (self, commands): + def do_test(self, commands): self.build() - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") for c in commands: self.runCmd(c) target = self.dbg.CreateTarget(exe) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - self.assertTrue(process.GetState() == lldb.eStateExited, "Process should have exited.") - self.assertTrue(process.GetExitStatus() == 0, - "Process returned non-zero status. Were incorrect file descriptors passed?") + self.assertTrue( + process.GetState() == lldb.eStateExited, + "Process should have exited.") + self.assertTrue( + process.GetExitStatus() == 0, + "Process returned non-zero status. Were incorrect file descriptors passed?") @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376") - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") - @skipIfWindows # The check for descriptor leakage needs to be implemented differently here. - @skipIfTargetAndroid() # Android have some other file descriptors open by the shell - def test_fd_leak_multitarget (self): + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") + # The check for descriptor leakage needs to be implemented differently + # here. + @skipIfWindows + @skipIfTargetAndroid() # Android have some other file descriptors open by the shell + def test_fd_leak_multitarget(self): self.build() - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) - breakpoint = target.BreakpointCreateBySourceRegex ('Set breakpoint here', lldb.SBFileSpec ("main.c", False)) + breakpoint = target.BreakpointCreateBySourceRegex( + 'Set breakpoint here', lldb.SBFileSpec("main.c", False)) self.assertTrue(breakpoint, VALID_BREAKPOINT) - process1 = target.LaunchSimple (None, None, self.get_process_working_directory()) + process1 = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process1, PROCESS_IS_VALID) - self.assertTrue(process1.GetState() == lldb.eStateStopped, "Process should have been stopped.") + self.assertTrue( + process1.GetState() == lldb.eStateStopped, + "Process should have been stopped.") target2 = self.dbg.CreateTarget(exe) - process2 = target2.LaunchSimple (None, None, self.get_process_working_directory()) + process2 = target2.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process2, PROCESS_IS_VALID) - self.assertTrue(process2.GetState() == lldb.eStateExited, "Process should have exited.") - self.assertTrue(process2.GetExitStatus() == 0, - "Process returned non-zero status. Were incorrect file descriptors passed?") + self.assertTrue( + process2.GetState() == lldb.eStateExited, + "Process should have exited.") + self.assertTrue( + process2.GetExitStatus() == 0, + "Process returned non-zero status. Were incorrect file descriptors passed?") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py b/lldb/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py index 851e4d376b3..528e52565b5 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py @@ -5,13 +5,14 @@ Test that backticks without a target should work (not infinite looping). from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BackticksWithNoTargetTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,4 +21,4 @@ class BackticksWithNoTargetTestCase(TestBase): def test_backticks_no_target(self): """A simple test of backticks without a target.""" self.expect("print `1+2-3`", - substrs = [' = 0']) + substrs=[' = 0']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py index 9442a076e2a..a48d5645e5f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py @@ -5,18 +5,19 @@ Test address breakpoints set with shared library of SBAddress work correctly. from __future__ import print_function - -import os, time +import os +import time import re import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * + class AddressBreakpointTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def test_address_breakpoints (self): + def test_address_breakpoints(self): """Test address breakpoints set with shared library of SBAddress work correctly.""" self.build() self.address_breakpoints() @@ -34,7 +35,8 @@ class AddressBreakpointTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. - breakpoint = target.BreakpointCreateBySourceRegex("Set a breakpoint here", lldb.SBFileSpec("main.c")) + breakpoint = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", lldb.SBFileSpec("main.c")) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) @@ -48,7 +50,7 @@ class AddressBreakpointTestCase(TestBase): # Next get the address from the location, and create an address breakpoint using # that address: - + address = location.GetAddress() target.BreakpointDelete(breakpoint.GetID()) @@ -61,16 +63,18 @@ class AddressBreakpointTestCase(TestBase): flags = launch_info.GetLaunchFlags() flags &= ~lldb.eLaunchFlagDisableASLR launch_info.SetLaunchFlags(flags) - + error = lldb.SBError() - process = target.Launch (launch_info, error) + process = target.Launch(launch_info, error) self.assertTrue(process, PROCESS_IS_VALID) # Did we hit our breakpoint? - from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint - threads = get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue(len(threads) == 1, "There should be a thread stopped at our breakpoint") + from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") # The hit count for the breakpoint should be 1. self.assertTrue(breakpoint.GetHitCount() == 1) @@ -82,10 +86,12 @@ class AddressBreakpointTestCase(TestBase): launch_info.SetLaunchFlags(flags) process = target.Launch(launch_info, error) - self.assertTrue (process, PROCESS_IS_VALID) + self.assertTrue(process, PROCESS_IS_VALID) - thread = get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue(len(threads) == 1, "There should be a thread stopped at our breakpoint") + thread = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") # The hit count for the breakpoint should now be 2. self.assertTrue(breakpoint.GetHitCount() == 2) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py index 73b3ef5eae2..7876e3b3d90 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py @@ -5,18 +5,19 @@ Test that breakpoints set on a bad address say they are bad. from __future__ import print_function - -import os, time +import os +import time import re import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * + class BadAddressBreakpointTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def test_bad_address_breakpoints (self): + def test_bad_address_breakpoints(self): """Test that breakpoints set on a bad address say they are bad.""" self.build() self.address_breakpoints() @@ -34,7 +35,8 @@ class BadAddressBreakpointTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. - breakpoint = target.BreakpointCreateBySourceRegex("Set a breakpoint here", lldb.SBFileSpec("main.c")) + breakpoint = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", lldb.SBFileSpec("main.c")) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) @@ -47,16 +49,18 @@ class BadAddressBreakpointTestCase(TestBase): VALID_BREAKPOINT_LOCATION) launch_info = lldb.SBLaunchInfo(None) - + error = lldb.SBError() - process = target.Launch (launch_info, error) + process = target.Launch(launch_info, error) self.assertTrue(process, PROCESS_IS_VALID) # Did we hit our breakpoint? - from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint - threads = get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue(len(threads) == 1, "There should be a thread stopped at our breakpoint") + from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") # The hit count for the breakpoint should be 1. self.assertTrue(breakpoint.GetHitCount() == 1) @@ -72,6 +76,5 @@ class BadAddressBreakpointTestCase(TestBase): for bp_loc in bkpt: self.assertTrue(bp_loc.IsResolved() == False) else: - self.fail("Could not find an illegal address at which to set a bad breakpoint.") - - + self.fail( + "Could not find an illegal address at which to set a bad breakpoint.") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_case_sensitivity/TestBreakpointCaseSensitivity.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_case_sensitivity/TestBreakpointCaseSensitivity.py index aa4ee14ffc5..bd5ae0e541d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_case_sensitivity/TestBreakpointCaseSensitivity.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_case_sensitivity/TestBreakpointCaseSensitivity.py @@ -9,6 +9,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * from lldbsuite.test import lldbplatform, lldbplatformutil + class BreakpointCaseSensitivityTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) BREAKPOINT_TEXT = 'Set a breakpoint here' @@ -24,8 +25,9 @@ class BreakpointCaseSensitivityTestCase(TestBase): self.build() self.case_sensitivity_breakpoint(True) - @skipIf(oslist=['windows']) # Skip for windows platforms - @expectedFailureAll() # Failing for unknown reason on non-Windows platforms. + @skipIf(oslist=['windows']) # Skip for windows platforms + # Failing for unknown reason on non-Windows platforms. + @expectedFailureAll() def test_breakpoint_doesnt_match_file_with_different_case(self): """Set breakpoint on file, shouldn't match files with different case on POSIX systems""" self.build() @@ -33,19 +35,19 @@ class BreakpointCaseSensitivityTestCase(TestBase): def case_sensitivity_breakpoint(self, case_insensitive): """Set breakpoint on file, should match files with different case if case_insensitive is True""" - + # use different case to check CreateTarget exe = 'a.out' if case_insensitive: exe = exe.upper() - + exe = os.path.join(os.getcwd(), exe) # Create a target by the debugger. self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - cwd = self.get_process_working_directory(); - + cwd = self.get_process_working_directory() + # try both BreakpointCreateByLocation and BreakpointCreateBySourceRegex for regex in [False, True]: # should always hit @@ -68,47 +70,54 @@ class BreakpointCaseSensitivityTestCase(TestBase): def check_breakpoint(self, file, source_regex, should_hit): """ Check breakpoint hit at given file set by given method - + file: File where insert the breakpoint - + source_regex: True for testing using BreakpointCreateBySourceRegex, False for BreakpointCreateByLocation - + should_hit: True if the breakpoint should hit, False otherwise """ - - desc = ' file %s set by %s' % (file, 'regex' if source_regex else 'location') + + desc = ' file %s set by %s' % ( + file, 'regex' if source_regex else 'location') if source_regex: - breakpoint = self.target.BreakpointCreateBySourceRegex(self.BREAKPOINT_TEXT, - lldb.SBFileSpec(file)) - else: - breakpoint = self.target.BreakpointCreateByLocation(file, self.line) - + breakpoint = self.target.BreakpointCreateBySourceRegex( + self.BREAKPOINT_TEXT, lldb.SBFileSpec(file)) + else: + breakpoint = self.target.BreakpointCreateByLocation( + file, self.line) + self.assertEqual(breakpoint and breakpoint.GetNumLocations() == 1, - should_hit, - VALID_BREAKPOINT + desc) + should_hit, + VALID_BREAKPOINT + desc) # Get the breakpoint location from breakpoint after we verified that, # indeed, it has one location. location = breakpoint.GetLocationAtIndex(0) self.assertEqual(location and location.IsEnabled(), - should_hit, - VALID_BREAKPOINT_LOCATION + desc) - - process = self.target.LaunchSimple(None, None, self.get_process_working_directory()) + should_hit, + VALID_BREAKPOINT_LOCATION + desc) + + process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID + desc) if should_hit: # Did we hit our breakpoint? - from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint - threads = get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertEqual(len(threads), 1, "There should be a thread stopped at breakpoint" + desc) + from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertEqual( + len(threads), + 1, + "There should be a thread stopped at breakpoint" + + desc) # The hit count for the breakpoint should be 1. self.assertEqual(breakpoint.GetHitCount(), 1) - + else: # check the breakpoint was not hit self.assertEqual(lldb.eStateExited, process.GetState()) @@ -116,6 +125,6 @@ class BreakpointCaseSensitivityTestCase(TestBase): # let process finish process.Continue() - + # cleanup self.target.BreakpointDelete(breakpoint.GetID()) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py index 78d14b7d770..bfc1cdf3a79 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py @@ -5,13 +5,14 @@ Test lldb breakpoint command add/list/delete. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BreakpointCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,7 +28,7 @@ class BreakpointCommandTestCase(TestBase): """Test a sequence of breakpoint command add, list, and delete.""" self.build() self.breakpoint_command_sequence() - self.breakpoint_command_script_parameters () + self.breakpoint_command_script_parameters() def setUp(self): # Call super's setUp(). @@ -36,7 +37,8 @@ class BreakpointCommandTestCase(TestBase): self.line = line_number('main.c', '// Set break point at this line.') # disable "There is a running process, kill it and restart?" prompt self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def breakpoint_command_sequence(self): """Test a sequence of breakpoint command add, list, and delete.""" @@ -45,45 +47,64 @@ class BreakpointCommandTestCase(TestBase): # Add three breakpoints on the same line. The first time we don't specify the file, # since the default file is the one containing main: - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) - # Breakpoint 4 - set at the same location as breakpoint 1 to test setting breakpoint commands on two breakpoints at a time - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + # Breakpoint 4 - set at the same location as breakpoint 1 to test + # setting breakpoint commands on two breakpoints at a time + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1, loc_exact=True) # Now add callbacks for the breakpoints just created. - self.runCmd("breakpoint command add -s command -o 'frame variable --show-types --scope' 1 4") - self.runCmd("breakpoint command add -s python -o 'here = open(\"output.txt\", \"w\"); here.write(\"lldb\\n\"); here.close()' 2") - self.runCmd("breakpoint command add --python-function bktptcmd.function 3") + self.runCmd( + "breakpoint command add -s command -o 'frame variable --show-types --scope' 1 4") + self.runCmd( + "breakpoint command add -s python -o 'here = open(\"output.txt\", \"w\"); here.write(\"lldb\\n\"); here.close()' 2") + self.runCmd( + "breakpoint command add --python-function bktptcmd.function 3") # Check that the breakpoint commands are correctly set. # The breakpoint list now only contains breakpoint 1. - self.expect("breakpoint list", "Breakpoints 1 & 2 created", - substrs = ["2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line], - patterns = ["1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % self.line] ) - - self.expect("breakpoint list -f", "Breakpoints 1 & 2 created", - substrs = ["2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line], - patterns = ["1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % self.line, - "1.1: .+at main.c:%d, .+unresolved, hit count = 0" % self.line, - "2.1: .+at main.c:%d, .+unresolved, hit count = 0" % self.line]) + self.expect( + "breakpoint list", "Breakpoints 1 & 2 created", substrs=[ + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line], patterns=[ + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % + self.line]) + + self.expect( + "breakpoint list -f", + "Breakpoints 1 & 2 created", + substrs=[ + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line], + patterns=[ + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % + self.line, + "1.1: .+at main.c:%d, .+unresolved, hit count = 0" % + self.line, + "2.1: .+at main.c:%d, .+unresolved, hit count = 0" % + self.line]) self.expect("breakpoint command list 1", "Breakpoint 1 command ok", - substrs = ["Breakpoint commands:", - "frame variable --show-types --scope"]) + substrs=["Breakpoint commands:", + "frame variable --show-types --scope"]) self.expect("breakpoint command list 2", "Breakpoint 2 command ok", - substrs = ["Breakpoint commands:", - "here = open", - "here.write", - "here.close()"]) + substrs=["Breakpoint commands:", + "here = open", + "here.write", + "here.close()"]) self.expect("breakpoint command list 3", "Breakpoint 3 command ok", - substrs = ["Breakpoint commands:", - "bktptcmd.function(frame, bp_loc, internal_dict)"]) + substrs=["Breakpoint commands:", + "bktptcmd.function(frame, bp_loc, internal_dict)"]) self.expect("breakpoint command list 4", "Breakpoint 4 command ok", - substrs = ["Breakpoint commands:", - "frame variable --show-types --scope"]) + substrs=["Breakpoint commands:", + "frame variable --show-types --scope"]) self.runCmd("breakpoint delete 4") @@ -93,43 +114,68 @@ class BreakpointCommandTestCase(TestBase): # and then specify only one file. The first time we should get two locations, # the second time only one: - lldbutil.run_break_set_by_regexp (self, r"._MyFunction", num_expected_locations=2) - - lldbutil.run_break_set_by_regexp (self, r"._MyFunction", extra_options="-f a.c", num_expected_locations=1) - - lldbutil.run_break_set_by_regexp (self, r"._MyFunction", extra_options="-f a.c -f b.c", num_expected_locations=2) + lldbutil.run_break_set_by_regexp( + self, r"._MyFunction", num_expected_locations=2) + + lldbutil.run_break_set_by_regexp( + self, + r"._MyFunction", + extra_options="-f a.c", + num_expected_locations=1) + + lldbutil.run_break_set_by_regexp( + self, + r"._MyFunction", + extra_options="-f a.c -f b.c", + num_expected_locations=2) # Now try a source regex breakpoint: - lldbutil.run_break_set_by_source_regexp (self, r"is about to return [12]0", extra_options="-f a.c -f b.c", num_expected_locations=2) - - lldbutil.run_break_set_by_source_regexp (self, r"is about to return [12]0", extra_options="-f a.c", num_expected_locations=1) - + lldbutil.run_break_set_by_source_regexp( + self, + r"is about to return [12]0", + extra_options="-f a.c -f b.c", + num_expected_locations=2) + + lldbutil.run_break_set_by_source_regexp( + self, + r"is about to return [12]0", + extra_options="-f a.c", + num_expected_locations=1) + # Run the program. Remove 'output.txt' if it exists. self.RemoveTempFile("output.txt") self.RemoveTempFile("output2.txt") self.runCmd("run", RUN_SUCCEEDED) - # Check that the file 'output.txt' exists and contains the string "lldb". + # Check that the file 'output.txt' exists and contains the string + # "lldb". # The 'output.txt' file should now exist. - self.assertTrue(os.path.isfile("output.txt"), - "'output.txt' exists due to breakpoint command for breakpoint 2.") - self.assertTrue(os.path.isfile("output2.txt"), - "'output2.txt' exists due to breakpoint command for breakpoint 3.") + self.assertTrue( + os.path.isfile("output.txt"), + "'output.txt' exists due to breakpoint command for breakpoint 2.") + self.assertTrue( + os.path.isfile("output2.txt"), + "'output2.txt' exists due to breakpoint command for breakpoint 3.") # Read the output file produced by running the program. with open('output.txt', 'r') as f: output = f.read() - self.expect(output, "File 'output.txt' and the content matches", exe=False, - startstr = "lldb") + self.expect( + output, + "File 'output.txt' and the content matches", + exe=False, + startstr="lldb") with open('output2.txt', 'r') as f: output = f.read() - self.expect(output, "File 'output2.txt' and the content matches", exe=False, - startstr = "lldb") - + self.expect( + output, + "File 'output2.txt' and the content matches", + exe=False, + startstr="lldb") # Finish the program. self.runCmd("process continue") @@ -140,21 +186,31 @@ class BreakpointCommandTestCase(TestBase): # Remove breakpoint 2. self.runCmd("breakpoint delete 2") - self.expect("breakpoint command list 1", - startstr = "Breakpoint 1 does not have an associated command.") - self.expect("breakpoint command list 2", error=True, - startstr = "error: '2' is not a currently valid breakpoint ID.") + self.expect( + "breakpoint command list 1", + startstr="Breakpoint 1 does not have an associated command.") + self.expect( + "breakpoint command list 2", + error=True, + startstr="error: '2' is not a currently valid breakpoint ID.") # The breakpoint list now only contains breakpoint 1. - self.expect("breakpoint list -f", "Breakpoint 1 exists", - patterns = ["1: file = '.*main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % - self.line, - "hit count = 1"]) + self.expect( + "breakpoint list -f", + "Breakpoint 1 exists", + patterns=[ + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % + self.line, + "hit count = 1"]) # Not breakpoint 2. - self.expect("breakpoint list -f", "No more breakpoint 2", matching=False, - substrs = ["2: file = 'main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % - self.line]) + self.expect( + "breakpoint list -f", + "No more breakpoint 2", + matching=False, + substrs=[ + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % + self.line]) # Run the program again, with breakpoint 1 remaining. self.runCmd("run", RUN_SUCCEEDED) @@ -163,20 +219,21 @@ class BreakpointCommandTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 2. self.expect("breakpoint list -f", BREAKPOINT_HIT_TWICE, - substrs = ['resolved, hit count = 2']) + substrs=['resolved, hit count = 2']) - def breakpoint_command_script_parameters (self): + def breakpoint_command_script_parameters(self): """Test that the frame and breakpoint location are being properly passed to the script breakpoint command function.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) # Now add callbacks for the breakpoints just created. self.runCmd("breakpoint command add -s python -o 'here = open(\"output-2.txt\", \"w\"); here.write(str(frame) + \"\\n\"); here.write(str(bp_loc) + \"\\n\"); here.close()' 1") @@ -184,24 +241,30 @@ class BreakpointCommandTestCase(TestBase): # Remove 'output-2.txt' if it already exists. if (os.path.exists('output-2.txt')): - os.remove ('output-2.txt') + os.remove('output-2.txt') - # Run program, hit breakpoint, and hopefully write out new version of 'output-2.txt' - self.runCmd ("run", RUN_SUCCEEDED) + # Run program, hit breakpoint, and hopefully write out new version of + # 'output-2.txt' + self.runCmd("run", RUN_SUCCEEDED) - # Check that the file 'output.txt' exists and contains the string "lldb". + # Check that the file 'output.txt' exists and contains the string + # "lldb". # The 'output-2.txt' file should now exist. - self.assertTrue(os.path.isfile("output-2.txt"), - "'output-2.txt' exists due to breakpoint command for breakpoint 1.") + self.assertTrue( + os.path.isfile("output-2.txt"), + "'output-2.txt' exists due to breakpoint command for breakpoint 1.") # Read the output file produced by running the program. with open('output-2.txt', 'r') as f: output = f.read() - self.expect (output, "File 'output-2.txt' and the content matches", exe=False, - startstr = "frame #0:", - patterns = ["1.* where = .*main .* resolved, hit count = 1" ]) + self.expect( + output, + "File 'output-2.txt' and the content matches", + exe=False, + startstr="frame #0:", + patterns=["1.* where = .*main .* resolved, hit count = 1"]) # Now remove 'output-2.txt' - os.remove ('output-2.txt') + os.remove('output-2.txt') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py index 4f8ab9e115d..01af8369aaf 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py @@ -5,7 +5,6 @@ Test that you can set breakpoint commands successfully with the Python API's: from __future__ import print_function - import os import re import sys @@ -14,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PythonBreakpointCommandSettingTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,36 +23,42 @@ class PythonBreakpointCommandSettingTestCase(TestBase): def test_step_out_python(self): """Test stepping out using avoid-no-debug with dsyms.""" self.build() - self.do_set_python_command_from_python () + self.do_set_python_command_from_python() - def setUp (self): + def setUp(self): TestBase.setUp(self) self.main_source = "main.c" self.main_source_spec = lldb.SBFileSpec(self.main_source) - - def do_set_python_command_from_python (self): + def do_set_python_command_from_python(self): exe = os.path.join(os.getcwd(), "a.out") error = lldb.SBError() self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - body_bkpt = self.target.BreakpointCreateBySourceRegex("Set break point at this line.", self.main_source_spec) + body_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) self.assertTrue(body_bkpt, VALID_BREAKPOINT) - func_bkpt = self.target.BreakpointCreateBySourceRegex("Set break point at this line.", self.main_source_spec) + func_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) self.assertTrue(func_bkpt, VALID_BREAKPOINT) - # Also test that setting a source regex breakpoint with an empty file spec list sets it on all files: - no_files_bkpt = self.target.BreakpointCreateBySourceRegex("Set a breakpoint here", lldb.SBFileSpecList(), lldb.SBFileSpecList()) + # Also test that setting a source regex breakpoint with an empty file + # spec list sets it on all files: + no_files_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", lldb.SBFileSpecList(), lldb.SBFileSpecList()) self.assertTrue(no_files_bkpt, VALID_BREAKPOINT) num_locations = no_files_bkpt.GetNumLocations() - self.assertTrue(num_locations >= 2, "Got at least two breakpoint locations") + self.assertTrue( + num_locations >= 2, + "Got at least two breakpoint locations") got_one_in_A = False got_one_in_B = False for idx in range(0, num_locations): - comp_unit = no_files_bkpt.GetLocationAtIndex(idx).GetAddress().GetSymbolContext(lldb.eSymbolContextCompUnit).GetCompileUnit().GetFileSpec() + comp_unit = no_files_bkpt.GetLocationAtIndex(idx).GetAddress().GetSymbolContext( + lldb.eSymbolContextCompUnit).GetCompileUnit().GetFileSpec() print("Got comp unit: ", comp_unit.GetFilename()) if comp_unit.GetFilename() == "a.c": got_one_in_A = True @@ -69,28 +75,36 @@ class PythonBreakpointCommandSettingTestCase(TestBase): import TestBreakpointCommandsFromPython\n\ TestBreakpointCommandsFromPython.PythonBreakpointCommandSettingTestCase.my_var = 20\n\ print('Hit breakpoint')") - self.assertTrue (error.Success(), "Failed to set the script callback body: %s."%(error.GetCString())) + self.assertTrue( + error.Success(), + "Failed to set the script callback body: %s." % + (error.GetCString())) - self.dbg.HandleCommand("command script import --allow-reload ./bktptcmd.py") + self.dbg.HandleCommand( + "command script import --allow-reload ./bktptcmd.py") func_bkpt.SetScriptCallbackFunction("bktptcmd.function") - # We will use the function that touches a text file, so remove it first: + # We will use the function that touches a text file, so remove it + # first: self.RemoveTempFile("output2.txt") # Now launch the process, and do not stop at entry point. - self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process, PROCESS_IS_VALID) # Now finish, and make sure the return value is correct. - threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, body_bkpt) + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, body_bkpt) self.assertTrue(len(threads) == 1, "Stopped at inner breakpoint.") self.thread = threads[0] - + self.assertTrue(PythonBreakpointCommandSettingTestCase.my_var == 20) # Check for the function version as well, which produced this file: # Remember to clean up after ourselves... - self.assertTrue(os.path.isfile("output2.txt"), - "'output2.txt' exists due to breakpoint command for breakpoint function.") + self.assertTrue( + os.path.isfile("output2.txt"), + "'output2.txt' exists due to breakpoint command for breakpoint function.") self.RemoveTempFile("output2.txt") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py index 1ea71cbde45..baf237bf076 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py @@ -5,12 +5,13 @@ Test _regexp-break command which uses regular expression matching to dispatch to from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class RegexpBreakCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,27 +26,47 @@ class RegexpBreakCommandTestCase(TestBase): TestBase.setUp(self) # Find the line number to break inside main(). self.source = 'main.c' - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') def regexp_break_command(self): """Test the super consie "b" command, which is analias for _regexp-break.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - break_results = lldbutil.run_break_set_command (self, "b %d" % self.line) - lldbutil.check_breakpoint_result (self, break_results, file_name='main.c', line_number=self.line, num_locations=1) + break_results = lldbutil.run_break_set_command( + self, "b %d" % + self.line) + lldbutil.check_breakpoint_result( + self, + break_results, + file_name='main.c', + line_number=self.line, + num_locations=1) - break_results = lldbutil.run_break_set_command (self, "b %s:%d" % (self.source, self.line)) - lldbutil.check_breakpoint_result (self, break_results, file_name='main.c', line_number=self.line, num_locations=1) + break_results = lldbutil.run_break_set_command( + self, "b %s:%d" % (self.source, self.line)) + lldbutil.check_breakpoint_result( + self, + break_results, + file_name='main.c', + line_number=self.line, + num_locations=1) # Check breakpoint with full file path. full_path = os.path.join(os.getcwd(), self.source) - break_results = lldbutil.run_break_set_command (self, "b %s:%d" % (full_path, self.line)) - lldbutil.check_breakpoint_result (self, break_results, file_name='main.c', line_number=self.line, num_locations=1) + break_results = lldbutil.run_break_set_command( + self, "b %s:%d" % (full_path, self.line)) + lldbutil.check_breakpoint_result( + self, + break_results, + file_name='main.c', + line_number=self.line, + num_locations=1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py index 4bbb0327eac..cf1fc2cf02c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py @@ -1,6 +1,7 @@ from __future__ import print_function + def function(frame, bp_loc, dict): - there = open("output2.txt", "w"); - print("lldb", file=there) - there.close() + there = open("output2.txt", "w") + print("lldb", file=there) + there.close() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py index 8d2732fd3c2..3fd9b13c711 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py @@ -5,38 +5,43 @@ Test breakpoint conditions with 'breakpoint modify -c <expr> id'. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BreakpointConditionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + @skipIfWindows def test_breakpoint_condition_and_run_command(self): """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'.""" self.build() self.breakpoint_conditions() - @skipIfWindows # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + @skipIfWindows def test_breakpoint_condition_inline_and_run_command(self): """Exercise breakpoint condition inline with 'breakpoint set'.""" self.build() self.breakpoint_conditions(inline=True) - @skipIfWindows # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + @skipIfWindows @add_test_categories(['pyapi']) def test_breakpoint_condition_and_python_api(self): """Use Python APIs to set breakpoint conditions.""" self.build() self.breakpoint_conditions_python() - @skipIfWindows # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + # Requires EE to support COFF on Windows (http://llvm.org/pr22232) + @skipIfWindows @add_test_categories(['pyapi']) def test_breakpoint_invalid_condition_and_python_api(self): """Use Python APIs to set breakpoint conditions.""" @@ -47,8 +52,10 @@ class BreakpointConditionsTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line1 = line_number('main.c', '// Find the line number of function "c" here.') - self.line2 = line_number('main.c', "// Find the line number of c's parent call here.") + self.line1 = line_number( + 'main.c', '// Find the line number of function "c" here.') + self.line2 = line_number( + 'main.c', "// Find the line number of c's parent call here.") def breakpoint_conditions(self, inline=False): """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'.""" @@ -57,10 +64,16 @@ class BreakpointConditionsTestCase(TestBase): if inline: # Create a breakpoint by function name 'c' and set the condition. - lldbutil.run_break_set_by_symbol (self, "c", extra_options="-c 'val == 3'", num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + "c", + extra_options="-c 'val == 3'", + num_expected_locations=1, + sym_exact=True) else: # Create a breakpoint by function name 'c'. - lldbutil.run_break_set_by_symbol (self, "c", num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, "c", num_expected_locations=1, sym_exact=True) # And set a condition on the breakpoint to stop on when 'val == 3'. self.runCmd("breakpoint modify -c 'val == 3' 1") @@ -70,42 +83,50 @@ class BreakpointConditionsTestCase(TestBase): # The process should be stopped at this point. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* stopped']) + patterns=['Process .* stopped']) # 'frame variable --show-types val' should return 3 due to breakpoint condition. - self.expect("frame variable --show-types val", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int) val = 3') + self.expect( + "frame variable --show-types val", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) val = 3') # Also check the hit count, which should be 3, by design. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = ["resolved = 1", - "Condition: val == 3", - "hit count = 1"]) + substrs=["resolved = 1", + "Condition: val == 3", + "hit count = 1"]) # The frame #0 should correspond to main.c:36, the executable statement - # in function name 'c'. And the parent frame should point to main.c:24. + # in function name 'c'. And the parent frame should point to + # main.c:24. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_CONDITION, - #substrs = ["stop reason = breakpoint"], - patterns = ["frame #0.*main.c:%d" % self.line1, - "frame #1.*main.c:%d" % self.line2]) + #substrs = ["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #1.*main.c:%d" % self.line2]) # Test that "breakpoint modify -c ''" clears the condition for the last # created breakpoint, so that when the breakpoint hits, val == 1. self.runCmd("process kill") self.runCmd("breakpoint modify -c ''") - self.expect("breakpoint list -f", BREAKPOINT_STATE_CORRECT, matching=False, - substrs = ["Condition:"]) + self.expect( + "breakpoint list -f", + BREAKPOINT_STATE_CORRECT, + matching=False, + substrs=["Condition:"]) # Now run the program again. self.runCmd("run", RUN_SUCCEEDED) # The process should be stopped at this point. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* stopped']) + patterns=['Process .* stopped']) # 'frame variable --show-types val' should return 1 since it is the first breakpoint hit. - self.expect("frame variable --show-types val", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int) val = 1') + self.expect( + "frame variable --show-types val", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) val = 1') self.runCmd("process kill") @@ -124,7 +145,8 @@ class BreakpointConditionsTestCase(TestBase): breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) - # We didn't associate a thread index with the breakpoint, so it should be invalid. + # We didn't associate a thread index with the breakpoint, so it should + # be invalid. self.assertTrue(breakpoint.GetThreadIndex() == lldb.UINT32_MAX, "The thread index should be invalid") # The thread name should be invalid, too. @@ -133,7 +155,8 @@ class BreakpointConditionsTestCase(TestBase): # Let's set the thread index for this breakpoint and verify that it is, # indeed, being set correctly. - breakpoint.SetThreadIndex(1) # There's only one thread for the process. + # There's only one thread for the process. + breakpoint.SetThreadIndex(1) self.assertTrue(breakpoint.GetThreadIndex() == 1, "The thread index has been set correctly") @@ -147,16 +170,19 @@ class BreakpointConditionsTestCase(TestBase): # Set the condition on the breakpoint location. location.SetCondition('val == 3') self.expect(location.GetCondition(), exe=False, - startstr = 'val == 3') + startstr='val == 3') # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1 and the break condition should hold. from lldbsuite.test.lldbutil import get_stopped_thread thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) var = frame0.FindValue('val', lldb.eValueTypeVariableArgument) self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and @@ -168,7 +194,8 @@ class BreakpointConditionsTestCase(TestBase): # Test that the condition expression didn't create a result variable: options = lldb.SBExpressionOptions() value = frame0.EvaluateExpression("$0", options) - self.assertTrue(value.GetError().Fail(), "Conditions should not make result variables.") + self.assertTrue(value.GetError().Fail(), + "Conditions should not make result variables.") process.Continue() def breakpoint_invalid_conditions_python(self): @@ -189,21 +216,22 @@ class BreakpointConditionsTestCase(TestBase): # Set the condition on the breakpoint. breakpoint.SetCondition('no_such_variable == not_this_one_either') self.expect(breakpoint.GetCondition(), exe=False, - startstr = 'no_such_variable == not_this_one_either') + startstr='no_such_variable == not_this_one_either') # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1 and the break condition should hold. from lldbsuite.test.lldbutil import get_stopped_thread thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) var = frame0.FindValue('val', lldb.eValueTypeVariableArgument) self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1) # The hit count for the breakpoint should be 1. self.assertTrue(breakpoint.GetHitCount() == 1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py index b7edf2a6e4d..621bd4a55f0 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py @@ -5,47 +5,56 @@ Test lldb breakpoint ids. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class BreakpointIDTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def test (self): + def test(self): self.build() - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") self.expect("file " + exe, - patterns = [ "Current executable set to .*a.out" ]) - - - bpno = lldbutil.run_break_set_by_symbol (self, 'product', num_expected_locations=-1, sym_exact=False) - self.assertTrue (bpno == 1, "First breakpoint number is 1.") - - bpno = lldbutil.run_break_set_by_symbol (self, 'sum', num_expected_locations=-1, sym_exact=False) - self.assertTrue (bpno == 2, "Second breakpoint number is 2.") - - bpno = lldbutil.run_break_set_by_symbol (self, 'junk', num_expected_locations=0, sym_exact=False) - self.assertTrue (bpno == 3, "Third breakpoint number is 3.") - - self.expect ("breakpoint disable 1.1 - 2.2 ", - COMMAND_FAILED_AS_EXPECTED, error = True, - startstr = "error: Invalid range: Ranges that specify particular breakpoint locations must be within the same major breakpoint; you specified two different major breakpoints, 1 and 2.") - - self.expect ("breakpoint disable 2 - 2.2", - COMMAND_FAILED_AS_EXPECTED, error = True, - startstr = "error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") - - self.expect ("breakpoint disable 2.1 - 2", - COMMAND_FAILED_AS_EXPECTED, error = True, - startstr = "error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") - - self.expect ("breakpoint disable 2.1 - 2.2", - startstr = "2 breakpoints disabled.") - - self.expect ("breakpoint enable 2.*", - patterns = [ ".* breakpoints enabled."] ) + patterns=["Current executable set to .*a.out"]) + + bpno = lldbutil.run_break_set_by_symbol( + self, 'product', num_expected_locations=-1, sym_exact=False) + self.assertTrue(bpno == 1, "First breakpoint number is 1.") + + bpno = lldbutil.run_break_set_by_symbol( + self, 'sum', num_expected_locations=-1, sym_exact=False) + self.assertTrue(bpno == 2, "Second breakpoint number is 2.") + + bpno = lldbutil.run_break_set_by_symbol( + self, 'junk', num_expected_locations=0, sym_exact=False) + self.assertTrue(bpno == 3, "Third breakpoint number is 3.") + + self.expect( + "breakpoint disable 1.1 - 2.2 ", + COMMAND_FAILED_AS_EXPECTED, + error=True, + startstr="error: Invalid range: Ranges that specify particular breakpoint locations must be within the same major breakpoint; you specified two different major breakpoints, 1 and 2.") + + self.expect( + "breakpoint disable 2 - 2.2", + COMMAND_FAILED_AS_EXPECTED, + error=True, + startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") + + self.expect( + "breakpoint disable 2.1 - 2", + COMMAND_FAILED_AS_EXPECTED, + error=True, + startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") + + self.expect("breakpoint disable 2.1 - 2.2", + startstr="2 breakpoints disabled.") + + self.expect("breakpoint enable 2.*", + patterns=[".* breakpoints enabled."]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py index 05ef1c6d94c..09e20bc5ac3 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py @@ -5,14 +5,15 @@ Test breakpoint ignore count features. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BreakpointIgnoreCountTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -32,11 +33,16 @@ class BreakpointIgnoreCountTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line1 = line_number('main.c', '// Find the line number of function "c" here.') - self.line2 = line_number('main.c', '// b(2) -> c(2) Find the call site of b(2).') - self.line3 = line_number('main.c', '// a(3) -> c(3) Find the call site of c(3).') - self.line4 = line_number('main.c', '// a(3) -> c(3) Find the call site of a(3).') - self.line5 = line_number('main.c', '// Find the call site of c in main.') + self.line1 = line_number( + 'main.c', '// Find the line number of function "c" here.') + self.line2 = line_number( + 'main.c', '// b(2) -> c(2) Find the call site of b(2).') + self.line3 = line_number( + 'main.c', '// a(3) -> c(3) Find the call site of c(3).') + self.line4 = line_number( + 'main.c', '// a(3) -> c(3) Find the call site of a(3).') + self.line5 = line_number( + 'main.c', '// Find the call site of c in main.') def breakpoint_ignore_count(self): """Exercise breakpoint ignore count with 'breakpoint set -i <count>'.""" @@ -44,26 +50,33 @@ class BreakpointIgnoreCountTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Create a breakpoint in main.c at line1. - lldbutil.run_break_set_by_file_and_line (self, 'main.c', self.line1, extra_options='-i 1', num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + 'main.c', + self.line1, + extra_options='-i 1', + num_expected_locations=1, + loc_exact=True) # Now run the program. self.runCmd("run", RUN_SUCCEEDED) # The process should be stopped at this point. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* stopped']) + patterns=['Process .* stopped']) - # Also check the hit count, which should be 2, due to ignore count of 1. + # Also check the hit count, which should be 2, due to ignore count of + # 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_THRICE, - substrs = ["resolved = 1", - "hit count = 2"]) + substrs=["resolved = 1", + "hit count = 2"]) # The frame #0 should correspond to main.c:37, the executable statement # in function name 'c'. And frame #2 should point to main.c:45. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, - #substrs = ["stop reason = breakpoint"], - patterns = ["frame #0.*main.c:%d" % self.line1, - "frame #2.*main.c:%d" % self.line2]) + #substrs = ["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #2.*main.c:%d" % self.line2]) # continue -i 1 is the same as setting the ignore count to 1 again, try that: # Now run the program. @@ -71,21 +84,20 @@ class BreakpointIgnoreCountTestCase(TestBase): # The process should be stopped at this point. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* stopped']) + patterns=['Process .* stopped']) - # Also check the hit count, which should be 2, due to ignore count of 1. + # Also check the hit count, which should be 2, due to ignore count of + # 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_THRICE, - substrs = ["resolved = 1", - "hit count = 4"]) + substrs=["resolved = 1", + "hit count = 4"]) # The frame #0 should correspond to main.c:37, the executable statement # in function name 'c'. And frame #2 should point to main.c:45. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, - #substrs = ["stop reason = breakpoint"], - patterns = ["frame #0.*main.c:%d" % self.line1, - "frame #1.*main.c:%d" % self.line5]) - - + #substrs = ["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #1.*main.c:%d" % self.line5]) def breakpoint_ignore_count_python(self): """Use Python APIs to set breakpoint ignore count.""" @@ -114,15 +126,18 @@ class BreakpointIgnoreCountTestCase(TestBase): "SetIgnoreCount() works correctly") # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame#0 should be on main.c:37, frame#1 should be on main.c:25, and # frame#2 should be on main.c:48. - #lldbutil.print_stacktraces(process) + # lldbutil.print_stacktraces(process) from lldbsuite.test.lldbutil import get_stopped_thread thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") frame0 = thread.GetFrameAtIndex(0) frame1 = thread.GetFrameAtIndex(1) frame2 = thread.GetFrameAtIndex(2) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py index b1e0d3deeae..255b6f7fa29 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py @@ -1,10 +1,11 @@ """ -Test specific to MIPS +Test specific to MIPS """ from __future__ import print_function -import os, time +import os +import time import re import unittest2 import lldb @@ -12,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class AvoidBreakpointInDelaySlotAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,8 +23,8 @@ class AvoidBreakpointInDelaySlotAPITestCase(TestBase): self.build() exe = os.path.join(os.getcwd(), "a.out") self.expect("file " + exe, - patterns = [ "Current executable set to .*a.out.*" ]) - + patterns=["Current executable set to .*a.out.*"]) + # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) @@ -33,7 +35,8 @@ class AvoidBreakpointInDelaySlotAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) list = target.FindFunctions('foo', lldb.eFunctionNameTypeAuto) @@ -44,7 +47,7 @@ class AvoidBreakpointInDelaySlotAPITestCase(TestBase): self.assertTrue(function) self.function(function, target) - def function (self, function, target): + def function(self, function, target): """Iterate over instructions in function and place a breakpoint on delay slot instruction""" # Get the list of all instructions in the function insts = function.GetInstructions(target) @@ -56,7 +59,7 @@ class AvoidBreakpointInDelaySlotAPITestCase(TestBase): branchinstaddress = inst.GetAddress().GetLoadAddress(target) # Get next instruction i.e delay slot instruction. - delayinst = insts.GetInstructionAtIndex(i+1) + delayinst = insts.GetInstructionAtIndex(i + 1) delayinstaddr = delayinst.GetAddress().GetLoadAddress(target) # Set breakpoint on delay slot instruction @@ -71,9 +74,10 @@ class AvoidBreakpointInDelaySlotAPITestCase(TestBase): # Get the address where breakpoint is actually set. bpaddr = location.GetLoadAddress() - - # Breakpoint address should be adjusted to the address of branch instruction. - self.assertTrue(branchinstaddress == bpaddr) + + # Breakpoint address should be adjusted to the address of + # branch instruction. + self.assertTrue(branchinstaddress == bpaddr) i += 1 else: i += 1 diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py index 94fc7bf79f6..214c110afcd 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py @@ -6,14 +6,15 @@ parser. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil import shutil import subprocess + class TestBreakpointLanguage(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,7 +24,7 @@ class TestBreakpointLanguage(TestBase): TestBase.setUp(self) # Find the line number to break inside main(). - def check_location_file (self, bp, loc, test_name): + def check_location_file(self, bp, loc, test_name): bp_loc = bp.GetLocationAtIndex(loc) addr = bp_loc.GetAddress() comp_unit = addr.GetCompileUnit() @@ -37,22 +38,40 @@ class TestBreakpointLanguage(TestBase): # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") error = lldb.SBError() - # Don't read in dependencies so we don't come across false matches that + # Don't read in dependencies so we don't come across false matches that # add unwanted breakpoint hits. self.target = self.dbg.CreateTarget(exe, None, None, False, error) self.assertTrue(self.target, VALID_TARGET) - cpp_bp = self.target.BreakpointCreateByRegex("func_from", lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(cpp_bp.GetNumLocations() == 1, "Only one C++ symbol matches") + cpp_bp = self.target.BreakpointCreateByRegex( + "func_from", + lldb.eLanguageTypeC_plus_plus, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + cpp_bp.GetNumLocations() == 1, + "Only one C++ symbol matches") self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp")) - c_bp = self.target.BreakpointCreateByRegex("func_from", lldb.eLanguageTypeC, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(c_bp.GetNumLocations() == 1, "Only one C symbol matches") + c_bp = self.target.BreakpointCreateByRegex( + "func_from", + lldb.eLanguageTypeC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + c_bp.GetNumLocations() == 1, + "Only one C symbol matches") self.assertTrue(self.check_location_file(c_bp, 0, "a.c")) - - objc_bp = self.target.BreakpointCreateByRegex("func_from", lldb.eLanguageTypeObjC, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(objc_bp.GetNumLocations() == 0, "No ObjC symbol matches") - + + objc_bp = self.target.BreakpointCreateByRegex( + "func_from", + lldb.eLanguageTypeObjC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + objc_bp.GetNumLocations() == 0, + "No ObjC symbol matches") + def test_by_name_breakpoint_language(self): """Test that the name regex breakpoint commands obey the language filter.""" @@ -60,26 +79,59 @@ class TestBreakpointLanguage(TestBase): # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") error = lldb.SBError() - # Don't read in dependencies so we don't come across false matches that + # Don't read in dependencies so we don't come across false matches that # add unwanted breakpoint hits. self.target = self.dbg.CreateTarget(exe, None, None, False, error) self.assertTrue(self.target, VALID_TARGET) - cpp_bp = self.target.BreakpointCreateByName("func_from_cpp", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(cpp_bp.GetNumLocations() == 1, "Only one C++ symbol matches") + cpp_bp = self.target.BreakpointCreateByName( + "func_from_cpp", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC_plus_plus, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + cpp_bp.GetNumLocations() == 1, + "Only one C++ symbol matches") self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp")) - no_cpp_bp = self.target.BreakpointCreateByName("func_from_c", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(no_cpp_bp.GetNumLocations() == 0, "And the C one doesn't match") - - c_bp = self.target.BreakpointCreateByName("func_from_c", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(c_bp.GetNumLocations() == 1, "Only one C symbol matches") + no_cpp_bp = self.target.BreakpointCreateByName( + "func_from_c", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC_plus_plus, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + no_cpp_bp.GetNumLocations() == 0, + "And the C one doesn't match") + + c_bp = self.target.BreakpointCreateByName( + "func_from_c", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + c_bp.GetNumLocations() == 1, + "Only one C symbol matches") self.assertTrue(self.check_location_file(c_bp, 0, "a.c")) - - no_c_bp = self.target.BreakpointCreateByName("func_from_cpp", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(no_c_bp.GetNumLocations() == 0, "And the C++ one doesn't match") - - objc_bp = self.target.BreakpointCreateByName("func_from_cpp", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeObjC, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(objc_bp.GetNumLocations() == 0, "No ObjC symbol matches") - + no_c_bp = self.target.BreakpointCreateByName( + "func_from_cpp", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + no_c_bp.GetNumLocations() == 0, + "And the C++ one doesn't match") + + objc_bp = self.target.BreakpointCreateByName( + "func_from_cpp", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeObjC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + objc_bp.GetNumLocations() == 0, + "No ObjC symbol matches") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py index 707b6502e91..fdbd622f767 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py @@ -5,13 +5,14 @@ Test breakpoint commands for a breakpoint ID with multiple locations. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BreakpointLocationsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -34,55 +35,72 @@ class BreakpointLocationsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint with 3 locations. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=3) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=3) # The breakpoint list should show 3 locations. - self.expect("breakpoint list -f", "Breakpoint locations shown correctly", - substrs = ["1: file = 'main.c', line = %d, exact_match = 0, locations = 3" % self.line], - patterns = ["where = a.out`func_inlined .+unresolved, hit count = 0", - "where = a.out`main .+\[inlined\].+unresolved, hit count = 0"]) + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=[ + "1: file = 'main.c', line = %d, exact_match = 0, locations = 3" % + self.line], + patterns=[ + "where = a.out`func_inlined .+unresolved, hit count = 0", + "where = a.out`main .+\[inlined\].+unresolved, hit count = 0"]) # The 'breakpoint disable 3.*' command should fail gracefully. self.expect("breakpoint disable 3.*", "Disabling an invalid breakpoint should fail gracefully", error=True, - startstr = "error: '3' is not a valid breakpoint ID.") + startstr="error: '3' is not a valid breakpoint ID.") # The 'breakpoint disable 1.*' command should disable all 3 locations. - self.expect("breakpoint disable 1.*", "All 3 breakpoint locatons disabled correctly", - startstr = "3 breakpoints disabled.") + self.expect( + "breakpoint disable 1.*", + "All 3 breakpoint locatons disabled correctly", + startstr="3 breakpoints disabled.") # Run the program. self.runCmd("run", RUN_SUCCEEDED) # We should not stopped on any breakpoint at all. self.expect("process status", "No stopping on any disabled breakpoint", - patterns = ["^Process [0-9]+ exited with status = 0"]) + patterns=["^Process [0-9]+ exited with status = 0"]) # The 'breakpoint enable 1.*' command should enable all 3 breakpoints. - self.expect("breakpoint enable 1.*", "All 3 breakpoint locatons enabled correctly", - startstr = "3 breakpoints enabled.") + self.expect( + "breakpoint enable 1.*", + "All 3 breakpoint locatons enabled correctly", + startstr="3 breakpoints enabled.") # The 'breakpoint disable 1.1' command should disable 1 location. - self.expect("breakpoint disable 1.1", "1 breakpoint locatons disabled correctly", - startstr = "1 breakpoints disabled.") + self.expect( + "breakpoint disable 1.1", + "1 breakpoint locatons disabled correctly", + startstr="1 breakpoints disabled.") - # Run the program againt. We should stop on the two breakpoint locations. + # Run the program againt. We should stop on the two breakpoint + # locations. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) + substrs=["stop reason = breakpoint 1."]) # Continue the program, there should be another stop. self.runCmd("process continue") # Stopped again. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) - - # At this point, 1.1 has a hit count of 0 and the other a hit count of 1". - self.expect("breakpoint list -f", "The breakpoints should report correct hit counts", - patterns = ["1\.1: .+ unresolved, hit count = 0 +Options: disabled", - "1\.2: .+ resolved, hit count = 1", - "1\.3: .+ resolved, hit count = 1"]) + substrs=["stop reason = breakpoint 1."]) + + # At this point, 1.1 has a hit count of 0 and the other a hit count of + # 1". + self.expect( + "breakpoint list -f", + "The breakpoints should report correct hit counts", + patterns=[ + "1\.1: .+ unresolved, hit count = 0 +Options: disabled", + "1\.2: .+ resolved, hit count = 1", + "1\.3: .+ resolved, hit count = 1"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py index 29afec20233..c0c2267a836 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py @@ -5,12 +5,12 @@ Test breakpoint command for different options. from __future__ import print_function - import os import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class BreakpointOptionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -32,38 +32,59 @@ class BreakpointOptionsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint with 1 locations. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, extra_options = "-K 1", num_expected_locations = 1) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, extra_options = "-K 0", num_expected_locations = 1) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + extra_options="-K 1", + num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + extra_options="-K 0", + num_expected_locations=1) # This should create a breakpoint 0 locations. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, extra_options = "-m 0", num_expected_locations = 0) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + extra_options="-m 0", + num_expected_locations=0) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 2."]) + substrs=["stop reason = breakpoint 2."]) # Check the list of breakpoint. - self.expect("breakpoint list -f", "Breakpoint locations shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.line, - "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.line, - "3: file = 'main.cpp', line = %d, exact_match = 1, locations = 0" % self.line]) + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.line, + "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.line, + "3: file = 'main.cpp', line = %d, exact_match = 1, locations = 0" % + self.line]) # Continue the program, there should be another stop. self.runCmd("process continue") # Stopped again. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) + substrs=["stop reason = breakpoint 1."]) # Continue the program, we should exit. self.runCmd("process continue") # We should exit. self.expect("process status", "Process exited successfully", - patterns = ["^Process [0-9]+ exited with status = 0"]) + patterns=["^Process [0-9]+ exited with status = 0"]) def breakpoint_options_language_test(self): """Test breakpoint command for language option.""" @@ -71,23 +92,34 @@ class BreakpointOptionsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint with 1 locations. - lldbutil.run_break_set_by_symbol (self, 'ns::func', sym_exact=False, extra_options = "-L c++", num_expected_locations=1) + lldbutil.run_break_set_by_symbol( + self, + 'ns::func', + sym_exact=False, + extra_options="-L c++", + num_expected_locations=1) # This should create a breakpoint with 0 locations. - lldbutil.run_break_set_by_symbol (self, 'ns::func', sym_exact=False, extra_options = "-L c", num_expected_locations=0) + lldbutil.run_break_set_by_symbol( + self, + 'ns::func', + sym_exact=False, + extra_options="-L c", + num_expected_locations=0) self.runCmd("settings set target.language c") - lldbutil.run_break_set_by_symbol (self, 'ns::func', sym_exact=False, num_expected_locations=0) + lldbutil.run_break_set_by_symbol( + self, 'ns::func', sym_exact=False, num_expected_locations=0) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) + substrs=["stop reason = breakpoint 1."]) # Continue the program, we should exit. self.runCmd("process continue") # We should exit. self.expect("process status", "Process exited successfully", - patterns = ["^Process [0-9]+ exited with status = 0"]) + patterns=["^Process [0-9]+ exited with status = 0"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py index 4ca93765b65..2410f2ee82b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py @@ -6,6 +6,7 @@ import os import lldb from lldbsuite.test.lldbtest import * + class BreakpointSetRestart(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -16,12 +17,13 @@ class BreakpointSetRestart(TestBase): cwd = os.getcwd() exe = os.path.join(cwd, 'a.out') - + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) self.dbg.SetAsync(True) - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) event = lldb.SBEvent() @@ -29,15 +31,22 @@ class BreakpointSetRestart(TestBase): while self.dbg.GetListener().WaitForEvent(2, event): if lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateRunning: break - - bp = target.BreakpointCreateBySourceRegex(self.BREAKPOINT_TEXT, - lldb.SBFileSpec(os.path.join(cwd, 'main.cpp'))) - self.assertTrue(bp.IsValid() and bp.GetNumLocations() == 1, VALID_BREAKPOINT) + + bp = target.BreakpointCreateBySourceRegex( + self.BREAKPOINT_TEXT, lldb.SBFileSpec( + os.path.join( + cwd, 'main.cpp'))) + self.assertTrue( + bp.IsValid() and bp.GetNumLocations() == 1, + VALID_BREAKPOINT) while self.dbg.GetListener().WaitForEvent(2, event): - if lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateStopped and lldb.SBProcess.GetRestartedFromEvent(event): + if lldb.SBProcess.GetStateFromEvent( + event) == lldb.eStateStopped and lldb.SBProcess.GetRestartedFromEvent(event): continue if lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateRunning: continue - self.fail("Setting a breakpoint generated an unexpected event: %s" % lldb.SBDebugger.StateAsCString(lldb.SBProcess.GetStateFromEvent(event))) - + self.fail( + "Setting a breakpoint generated an unexpected event: %s" % + lldb.SBDebugger.StateAsCString( + lldb.SBProcess.GetStateFromEvent(event))) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py index 4933d6d01d4..e4672fbbf1b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py @@ -4,7 +4,6 @@ Test breakpoint command with AT_comp_dir set to symbolic link. from __future__ import print_function - import os import shutil import lldb @@ -17,6 +16,7 @@ _EXE_NAME = 'CompDirSymLink' # Must match Makefile _SRC_FILE = 'main.cpp' _COMP_DIR_SYM_LINK_PROP = 'plugin.symbol-file.dwarf.comp-dir-symlink-paths' + class CompDirSymLinkTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -32,14 +32,18 @@ class CompDirSymLinkTestCase(TestBase): def test_symlink_paths_set(self): pwd_symlink = self.create_src_symlink() self.doBuild(pwd_symlink) - self.runCmd("settings set %s %s" % (_COMP_DIR_SYM_LINK_PROP, pwd_symlink)) + self.runCmd( + "settings set %s %s" % + (_COMP_DIR_SYM_LINK_PROP, pwd_symlink)) lldbutil.run_break_set_by_file_and_line(self, self.src_path, self.line) @skipIf(hostoslist=no_match(["linux"])) def test_symlink_paths_set_procselfcwd(self): pwd_symlink = '/proc/self/cwd' self.doBuild(pwd_symlink) - self.runCmd("settings set %s %s" % (_COMP_DIR_SYM_LINK_PROP, pwd_symlink)) + self.runCmd( + "settings set %s %s" % + (_COMP_DIR_SYM_LINK_PROP, pwd_symlink)) lldbutil.run_break_set_by_file_and_line(self, self.src_path, self.line) @skipIf(hostoslist=["windows"]) @@ -47,12 +51,17 @@ class CompDirSymLinkTestCase(TestBase): pwd_symlink = self.create_src_symlink() self.doBuild(pwd_symlink) self.runCmd('settings clear ' + _COMP_DIR_SYM_LINK_PROP) - self.assertRaises(AssertionError, lldbutil.run_break_set_by_file_and_line, self, self.src_path, self.line) + self.assertRaises( + AssertionError, + lldbutil.run_break_set_by_file_and_line, + self, + self.src_path, + self.line) def create_src_symlink(self): pwd_symlink = os.path.join(os.getcwd(), 'pwd_symlink') if os.path.exists(pwd_symlink): - os.unlink(pwd_symlink) + os.unlink(pwd_symlink) os.symlink(os.getcwd(), pwd_symlink) self.addTearDownHook(lambda: os.remove(pwd_symlink)) return pwd_symlink diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py index 472479391c0..312f2944102 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py @@ -5,35 +5,42 @@ Test that we handle breakpoints on consecutive instructions correctly. from __future__ import print_function - import unittest2 import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ConsecutiveBreakpointsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def prepare_test(self): self.build() - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") # Create a target by the debugger. self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - breakpoint1 = self.target.BreakpointCreateBySourceRegex("Set breakpoint here", lldb.SBFileSpec("main.cpp")) - self.assertTrue(breakpoint1 and breakpoint1.GetNumLocations() == 1, VALID_BREAKPOINT) + breakpoint1 = self.target.BreakpointCreateBySourceRegex( + "Set breakpoint here", lldb.SBFileSpec("main.cpp")) + self.assertTrue( + breakpoint1 and breakpoint1.GetNumLocations() == 1, + VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertIsNotNone(self.process, PROCESS_IS_VALID) # We should be stopped at the first breakpoint - self.thread = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, breakpoint1) - self.assertIsNotNone(self.thread, "Expected one thread to be stopped at breakpoint 1") + self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, breakpoint1) + self.assertIsNotNone( + self.thread, + "Expected one thread to be stopped at breakpoint 1") # Set breakpoint to the next instruction frame = self.thread.GetFrameAtIndex(0) @@ -42,8 +49,11 @@ class ConsecutiveBreakpointsTestCase(TestBase): instructions = self.target.ReadInstructions(address, 2) self.assertTrue(len(instructions) == 2) self.bkpt_address = instructions[1].GetAddress() - self.breakpoint2 = self.target.BreakpointCreateByAddress(self.bkpt_address.GetLoadAddress(self.target)) - self.assertTrue(self.breakpoint2 and self.breakpoint2.GetNumLocations() == 1, VALID_BREAKPOINT) + self.breakpoint2 = self.target.BreakpointCreateByAddress( + self.bkpt_address.GetLoadAddress(self.target)) + self.assertTrue( + self.breakpoint2 and self.breakpoint2.GetNumLocations() == 1, + VALID_BREAKPOINT) def finish_test(self): # Run the process until termination @@ -58,8 +68,11 @@ class ConsecutiveBreakpointsTestCase(TestBase): self.process.Continue() self.assertEquals(self.process.GetState(), lldb.eStateStopped) # We should be stopped at the second breakpoint - self.thread = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, self.breakpoint2) - self.assertIsNotNone(self.thread, "Expected one thread to be stopped at breakpoint 2") + self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, self.breakpoint2) + self.assertIsNotNone( + self.thread, + "Expected one thread to be stopped at breakpoint 2") self.finish_test() @@ -72,10 +85,15 @@ class ConsecutiveBreakpointsTestCase(TestBase): self.thread.StepInstruction(step_over) self.assertEquals(self.process.GetState(), lldb.eStateStopped) - self.assertEquals(self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress(self.target), - self.bkpt_address.GetLoadAddress(self.target)) - self.thread = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, self.breakpoint2) - self.assertIsNotNone(self.thread, "Expected one thread to be stopped at breakpoint 2") + self.assertEquals( + self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress( + self.target), self.bkpt_address.GetLoadAddress( + self.target)) + self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, self.breakpoint2) + self.assertIsNotNone( + self.thread, + "Expected one thread to be stopped at breakpoint 2") self.finish_test() @@ -84,8 +102,9 @@ class ConsecutiveBreakpointsTestCase(TestBase): """Test that single step stops, even though the second breakpoint is not valid.""" self.prepare_test() - # Choose a thread other than the current one. A non-existing thread is fine. - thread_index = self.process.GetNumThreads()+1 + # Choose a thread other than the current one. A non-existing thread is + # fine. + thread_index = self.process.GetNumThreads() + 1 self.assertFalse(self.process.GetThreadAtIndex(thread_index).IsValid()) self.breakpoint2.SetThreadIndex(thread_index) @@ -93,9 +112,13 @@ class ConsecutiveBreakpointsTestCase(TestBase): self.thread.StepInstruction(step_over) self.assertEquals(self.process.GetState(), lldb.eStateStopped) - self.assertEquals(self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress(self.target), - self.bkpt_address.GetLoadAddress(self.target)) - self.assertEquals(self.thread.GetStopReason(), lldb.eStopReasonPlanComplete, - "Stop reason should be 'plan complete'") + self.assertEquals( + self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress( + self.target), self.bkpt_address.GetLoadAddress( + self.target)) + self.assertEquals( + self.thread.GetStopReason(), + lldb.eStopReasonPlanComplete, + "Stop reason should be 'plan complete'") self.finish_test() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py index c2aa597214e..adec9fa5ddd 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py @@ -5,60 +5,64 @@ Test lldb breakpoint ids. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCPPBreakpointLocations(TestBase): mydir = TestBase.compute_mydir(__file__) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") - def test (self): - self.build () - self.breakpoint_id_tests () + def test(self): + self.build() + self.breakpoint_id_tests() def verify_breakpoint_locations(self, target, bp_dict): - + name = bp_dict['name'] names = bp_dict['loc_names'] - bp = target.BreakpointCreateByName (name) - self.assertEquals(bp.GetNumLocations(), len(names), "Make sure we find the right number of breakpoint locations") - + bp = target.BreakpointCreateByName(name) + self.assertEquals( + bp.GetNumLocations(), + len(names), + "Make sure we find the right number of breakpoint locations") + bp_loc_names = list() for bp_loc in bp: bp_loc_names.append(bp_loc.GetAddress().GetFunction().GetName()) - + for name in names: found = name in bp_loc_names if not found: print("Didn't find '%s' in: %s" % (name, bp_loc_names)) - self.assertTrue (found, "Make sure we find all required locations") - - def breakpoint_id_tests (self): - + self.assertTrue(found, "Make sure we find all required locations") + + def breakpoint_id_tests(self): + # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) bp_dicts = [ - { 'name' : 'func1', 'loc_names' : [ 'a::c::func1()', 'b::c::func1()'] }, - { 'name' : 'func2', 'loc_names' : [ 'a::c::func2()', 'c::d::func2()'] }, - { 'name' : 'func3', 'loc_names' : [ 'a::c::func3()', 'b::c::func3()', 'c::d::func3()'] }, - { 'name' : 'c::func1', 'loc_names' : [ 'a::c::func1()', 'b::c::func1()'] }, - { 'name' : 'c::func2', 'loc_names' : [ 'a::c::func2()'] }, - { 'name' : 'c::func3', 'loc_names' : [ 'a::c::func3()', 'b::c::func3()'] }, - { 'name' : 'a::c::func1', 'loc_names' : [ 'a::c::func1()'] }, - { 'name' : 'b::c::func1', 'loc_names' : [ 'b::c::func1()'] }, - { 'name' : 'c::d::func2', 'loc_names' : [ 'c::d::func2()'] }, - { 'name' : 'a::c::func1()', 'loc_names' : [ 'a::c::func1()'] }, - { 'name' : 'b::c::func1()', 'loc_names' : [ 'b::c::func1()'] }, - { 'name' : 'c::d::func2()', 'loc_names' : [ 'c::d::func2()'] }, + {'name': 'func1', 'loc_names': ['a::c::func1()', 'b::c::func1()']}, + {'name': 'func2', 'loc_names': ['a::c::func2()', 'c::d::func2()']}, + {'name': 'func3', 'loc_names': ['a::c::func3()', 'b::c::func3()', 'c::d::func3()']}, + {'name': 'c::func1', 'loc_names': ['a::c::func1()', 'b::c::func1()']}, + {'name': 'c::func2', 'loc_names': ['a::c::func2()']}, + {'name': 'c::func3', 'loc_names': ['a::c::func3()', 'b::c::func3()']}, + {'name': 'a::c::func1', 'loc_names': ['a::c::func1()']}, + {'name': 'b::c::func1', 'loc_names': ['b::c::func1()']}, + {'name': 'c::d::func2', 'loc_names': ['c::d::func2()']}, + {'name': 'a::c::func1()', 'loc_names': ['a::c::func1()']}, + {'name': 'b::c::func1()', 'loc_names': ['b::c::func1()']}, + {'name': 'c::d::func2()', 'loc_names': ['c::d::func2()']}, ] - + for bp_dict in bp_dicts: self.verify_breakpoint_locations(target, bp_dict) @@ -68,28 +72,43 @@ class TestCPPBreakpointLocations(TestBase): exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) - # Don't skip prologue, so we can check the breakpoint address more easily + # Don't skip prologue, so we can check the breakpoint address more + # easily self.runCmd("settings set target.skip-prologue false") try: names = ['~c', 'c::~c', 'c::~c()'] loc_names = {'a::c::~c()', 'b::c::~c()'} - # TODO: For windows targets we should put windows mangled names here - symbols = ['_ZN1a1cD1Ev', '_ZN1a1cD2Ev', '_ZN1b1cD1Ev', '_ZN1b1cD2Ev'] + # TODO: For windows targets we should put windows mangled names + # here + symbols = [ + '_ZN1a1cD1Ev', + '_ZN1a1cD2Ev', + '_ZN1b1cD1Ev', + '_ZN1b1cD2Ev'] for name in names: bp = target.BreakpointCreateByName(name) - bp_loc_names = { bp_loc.GetAddress().GetFunction().GetName() for bp_loc in bp } - self.assertEquals(bp_loc_names, loc_names, "Breakpoint set on the correct symbol") + bp_loc_names = {bp_loc.GetAddress().GetFunction().GetName() + for bp_loc in bp} + self.assertEquals( + bp_loc_names, + loc_names, + "Breakpoint set on the correct symbol") - bp_addresses = { bp_loc.GetLoadAddress() for bp_loc in bp } + bp_addresses = {bp_loc.GetLoadAddress() for bp_loc in bp} symbol_addresses = set() for symbol in symbols: sc_list = target.FindSymbols(symbol, lldb.eSymbolTypeCode) - self.assertEquals(sc_list.GetSize(), 1, "Found symbol " + symbol) + self.assertEquals( + sc_list.GetSize(), 1, "Found symbol " + symbol) symbol = sc_list.GetContextAtIndex(0).GetSymbol() - symbol_addresses.add(symbol.GetStartAddress().GetLoadAddress(target)) + symbol_addresses.add( + symbol.GetStartAddress().GetLoadAddress(target)) - self.assertEquals(symbol_addresses, bp_addresses, "Breakpoint set on correct address") + self.assertEquals( + symbol_addresses, + bp_addresses, + "Breakpoint set on correct address") finally: self.runCmd("settings clear target.skip-prologue") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py index 2aac3a9600d..3019e1c1c55 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py @@ -5,7 +5,6 @@ Test that you can set breakpoint and hit the C++ language exception breakpoint from __future__ import print_function - import os import re import sys @@ -14,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCPPExceptionBreakpoint (TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,26 +24,31 @@ class TestCPPExceptionBreakpoint (TestBase): def test_cpp_exception_breakpoint(self): """Test setting and hitting the C++ exception breakpoint.""" self.build() - self.do_cpp_exception_bkpt () + self.do_cpp_exception_bkpt() - def setUp (self): + def setUp(self): TestBase.setUp(self) self.main_source = "main.c" self.main_source_spec = lldb.SBFileSpec(self.main_source) - - def do_cpp_exception_bkpt (self): + def do_cpp_exception_bkpt(self): exe = os.path.join(os.getcwd(), "a.out") error = lldb.SBError() self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - exception_bkpt = self.target.BreakpointCreateForException(lldb.eLanguageTypeC_plus_plus, False, True) - self.assertTrue (exception_bkpt.IsValid(), "Created exception breakpoint.") + exception_bkpt = self.target.BreakpointCreateForException( + lldb.eLanguageTypeC_plus_plus, False, True) + self.assertTrue( + exception_bkpt.IsValid(), + "Created exception breakpoint.") - process = self.target.LaunchSimple (None, None, self.get_process_working_directory()) + process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, exception_bkpt) - self.assertTrue (len(thread_list) == 1, "One thread stopped at the exception breakpoint.") + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, exception_bkpt) + self.assertTrue(len(thread_list) == 1, + "One thread stopped at the exception breakpoint.") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/TestDebugBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/TestDebugBreak.py index de61f9e88f1..d044827e008 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/TestDebugBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/TestDebugBreak.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DebugBreakTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,19 +24,23 @@ class DebugBreakTestCase(TestBase): # Run the program. target = self.dbg.CreateTarget(exe) - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We've hit the first stop, so grab the frame. self.assertEqual(process.GetState(), lldb.eStateStopped) - stop_reason = lldb.eStopReasonException if (lldbplatformutil.getPlatform()=="windows" or lldbplatformutil.getPlatform()=="macosx") else lldb.eStopReasonSignal + stop_reason = lldb.eStopReasonException if (lldbplatformutil.getPlatform( + ) == "windows" or lldbplatformutil.getPlatform() == "macosx") else lldb.eStopReasonSignal thread = lldbutil.get_stopped_thread(process, stop_reason) - self.assertIsNotNone(thread, "Unable to find thread stopped at the __debugbreak()") + self.assertIsNotNone( + thread, "Unable to find thread stopped at the __debugbreak()") frame = thread.GetFrameAtIndex(0) # We should be in funciton 'bar'. self.assertTrue(frame.IsValid()) function_name = frame.GetFunctionName() - self.assertTrue('bar' in function_name, "Unexpected function name {}".format(function_name)) + self.assertTrue('bar' in function_name, + "Unexpected function name {}".format(function_name)) # We should be able to evaluate the parameter foo. value = frame.EvaluateExpression('*foo') @@ -45,10 +50,10 @@ class DebugBreakTestCase(TestBase): # subsequent stop. counter = 1 while counter < 20: - value = frame.EvaluateExpression('count') - self.assertEqual(value.GetValueAsSigned(), counter) - counter += 2 - process.Continue() + value = frame.EvaluateExpression('count') + self.assertEqual(value.GetValueAsSigned(), counter) + counter += 2 + process.Continue() # The inferior should exit after the last iteration. self.assertEqual(process.GetState(), lldb.eStateExited) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py index f2693e6ed59..a934ad356ac 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py @@ -5,12 +5,13 @@ Test breakpoint commands set before we have a target from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class BreakpointInDummyTarget (TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,43 +26,49 @@ class BreakpointInDummyTarget (TestBase): TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', 'Set a breakpoint on this line.') - self.line2 = line_number ('main.c', 'Set another on this line.') + self.line2 = line_number('main.c', 'Set another on this line.') def dummy_breakpoint_test(self): """Test breakpoint set before we have a target. """ # This should create a breakpoint with 3 locations. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=0) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line2, num_expected_locations=0) - + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=0) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line2, num_expected_locations=0) + # This is the function to remove breakpoints from the dummy target # to get a clean slate for the next test case. def cleanup(): self.runCmd('breakpoint delete -D -f', check=False) self.runCmd('breakpoint list', check=False) - # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # The breakpoint list should show 3 locations. - self.expect("breakpoint list -f", "Breakpoint locations shown correctly", - substrs = ["1: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line, - "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line2]) + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=[ + "1: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line, + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line2]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) + substrs=["stop reason = breakpoint 1."]) # Continue the program, there should be another stop. self.runCmd("process continue") # Stopped again. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 2."]) + substrs=["stop reason = breakpoint 2."]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py index d04178bda78..fe8f430096d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py @@ -6,12 +6,13 @@ another source file) works correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class InlinedBreakpointsTestCase(TestBase): """Bug fixed: rdar://problem/8464339""" @@ -26,32 +27,43 @@ class InlinedBreakpointsTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside basic_type.cpp. - self.line = line_number('basic_type.cpp', '// Set break point at this line.') + self.line = line_number( + 'basic_type.cpp', + '// Set break point at this line.') def inlined_breakpoints(self): """Test 'b basic_types.cpp:176' does break (where int.cpp includes basic_type.cpp).""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - # With the inline-breakpoint-strategy, our file+line breakpoint should not resolve to a location. + # With the inline-breakpoint-strategy, our file+line breakpoint should + # not resolve to a location. self.runCmd('settings set target.inline-breakpoint-strategy headers') - # Set a breakpoint and fail because it is in an inlined source implemenation file - lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", self.line, num_expected_locations=0) + # Set a breakpoint and fail because it is in an inlined source + # implemenation file + lldbutil.run_break_set_by_file_and_line( + self, "basic_type.cpp", self.line, num_expected_locations=0) - # Now enable breakpoints in implementation files and see the breakpoint set succeed + # Now enable breakpoints in implementation files and see the breakpoint + # set succeed self.runCmd('settings set target.inline-breakpoint-strategy always') # And add hooks to restore the settings during tearDown(). - self.addTearDownHook( - lambda: self.runCmd("settings set target.inline-breakpoint-strategy always")) + self.addTearDownHook(lambda: self.runCmd( + "settings set target.inline-breakpoint-strategy always")) - lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "basic_type.cpp", + self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. # And it should break at basic_type.cpp:176. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint', - 'basic_type.cpp:%d' % self.line]) + substrs=['stopped', + 'stop reason = breakpoint', + 'basic_type.cpp:%d' % self.line]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py index c48cee1bd2b..f43bbb7515c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py @@ -6,8 +6,8 @@ parser. from __future__ import print_function - -import os, time +import os +import time import shutil import subprocess import lldb @@ -15,6 +15,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class TestObjCBreakpoints(TestBase): @@ -34,20 +35,37 @@ class TestObjCBreakpoints(TestBase): self.line = line_number(self.main_source, '// Set breakpoint here') def check_category_breakpoints(self): - name_bp = self.target.BreakpointCreateByName ("myCategoryFunction") - selector_bp = self.target.BreakpointCreateByName ("myCategoryFunction", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(name_bp.GetNumLocations() == selector_bp.GetNumLocations(), 'Make sure setting a breakpoint by name "myCategoryFunction" sets a breakpoint even though it is in a category') + name_bp = self.target.BreakpointCreateByName("myCategoryFunction") + selector_bp = self.target.BreakpointCreateByName( + "myCategoryFunction", + lldb.eFunctionNameTypeSelector, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + name_bp.GetNumLocations() == selector_bp.GetNumLocations(), + 'Make sure setting a breakpoint by name "myCategoryFunction" sets a breakpoint even though it is in a category') for bp_loc in selector_bp: function_name = bp_loc.GetAddress().GetSymbol().GetName() - self.assertTrue(" myCategoryFunction]" in function_name, 'Make sure all function names have " myCategoryFunction]" in their names') - - category_bp = self.target.BreakpointCreateByName ("-[MyClass(MyCategory) myCategoryFunction]") - stripped_bp = self.target.BreakpointCreateByName ("-[MyClass myCategoryFunction]") - stripped2_bp = self.target.BreakpointCreateByName ("[MyClass myCategoryFunction]") - self.assertTrue(category_bp.GetNumLocations() == 1, "Make sure we can set a breakpoint using a full objective C function name with the category included (-[MyClass(MyCategory) myCategoryFunction])") - self.assertTrue(stripped_bp.GetNumLocations() == 1, "Make sure we can set a breakpoint using a full objective C function name without the category included (-[MyClass myCategoryFunction])") - self.assertTrue(stripped2_bp.GetNumLocations() == 1, "Make sure we can set a breakpoint using a full objective C function name without the category included ([MyClass myCategoryFunction])") - + self.assertTrue( + " myCategoryFunction]" in function_name, + 'Make sure all function names have " myCategoryFunction]" in their names') + + category_bp = self.target.BreakpointCreateByName( + "-[MyClass(MyCategory) myCategoryFunction]") + stripped_bp = self.target.BreakpointCreateByName( + "-[MyClass myCategoryFunction]") + stripped2_bp = self.target.BreakpointCreateByName( + "[MyClass myCategoryFunction]") + self.assertTrue( + category_bp.GetNumLocations() == 1, + "Make sure we can set a breakpoint using a full objective C function name with the category included (-[MyClass(MyCategory) myCategoryFunction])") + self.assertTrue( + stripped_bp.GetNumLocations() == 1, + "Make sure we can set a breakpoint using a full objective C function name without the category included (-[MyClass myCategoryFunction])") + self.assertTrue( + stripped2_bp.GetNumLocations() == 1, + "Make sure we can set a breakpoint using a full objective C function name without the category included ([MyClass myCategoryFunction])") + def check_objc_breakpoints(self, have_dsym): """Test constant string generation amd comparison by the expression parser.""" @@ -60,36 +78,55 @@ class TestObjCBreakpoints(TestBase): self.assertTrue(self.target, VALID_TARGET) #---------------------------------------------------------------------- - # Set breakpoints on all selectors whose name is "count". This should - # catch breakpoints that are both C functions _and_ anything whose + # Set breakpoints on all selectors whose name is "count". This should + # catch breakpoints that are both C functions _and_ anything whose # selector is "count" because just looking at "count" we can't tell # definitively if the name is a selector or a C function #---------------------------------------------------------------------- - name_bp = self.target.BreakpointCreateByName ("count") - selector_bp = self.target.BreakpointCreateByName ("count", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(name_bp.GetNumLocations() >= selector_bp.GetNumLocations(), 'Make sure we get at least the same amount of breakpoints if not more when setting by name "count"') - self.assertTrue(selector_bp.GetNumLocations() > 50, 'Make sure we find a lot of "count" selectors') # There are 93 on the latest MacOSX + name_bp = self.target.BreakpointCreateByName("count") + selector_bp = self.target.BreakpointCreateByName( + "count", + lldb.eFunctionNameTypeSelector, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + name_bp.GetNumLocations() >= selector_bp.GetNumLocations(), + 'Make sure we get at least the same amount of breakpoints if not more when setting by name "count"') + self.assertTrue( + selector_bp.GetNumLocations() > 50, + 'Make sure we find a lot of "count" selectors') # There are 93 on the latest MacOSX for bp_loc in selector_bp: function_name = bp_loc.GetAddress().GetSymbol().GetName() - self.assertTrue(" count]" in function_name, 'Make sure all function names have " count]" in their names') + self.assertTrue( + " count]" in function_name, + 'Make sure all function names have " count]" in their names') #---------------------------------------------------------------------- # Set breakpoints on all selectors whose name is "isEqual:". This should # catch breakpoints that are only ObjC selectors because no C function # can end with a : #---------------------------------------------------------------------- - name_bp = self.target.BreakpointCreateByName ("isEqual:") - selector_bp = self.target.BreakpointCreateByName ("isEqual:", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), lldb.SBFileSpecList()) - self.assertTrue(name_bp.GetNumLocations() == selector_bp.GetNumLocations(), 'Make sure setting a breakpoint by name "isEqual:" only sets selector breakpoints') + name_bp = self.target.BreakpointCreateByName("isEqual:") + selector_bp = self.target.BreakpointCreateByName( + "isEqual:", + lldb.eFunctionNameTypeSelector, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + name_bp.GetNumLocations() == selector_bp.GetNumLocations(), + 'Make sure setting a breakpoint by name "isEqual:" only sets selector breakpoints') for bp_loc in selector_bp: function_name = bp_loc.GetAddress().GetSymbol().GetName() - self.assertTrue(" isEqual:]" in function_name, 'Make sure all function names have " isEqual:]" in their names') - + self.assertTrue( + " isEqual:]" in function_name, + 'Make sure all function names have " isEqual:]" in their names') + self.check_category_breakpoints() - + if have_dsym: shutil.rmtree(exe + ".dSYM") - self.assertTrue(subprocess.call(['/usr/bin/strip', '-Sx', exe]) == 0, 'stripping dylib succeeded') - + self.assertTrue(subprocess.call( + ['/usr/bin/strip', '-Sx', exe]) == 0, 'stripping dylib succeeded') + # Check breakpoints again, this time using the symbol table only self.check_category_breakpoints() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py index 81cab927d21..791cc70a749 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py @@ -5,26 +5,27 @@ This test just tests the source file & function restrictions. from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestSourceRegexBreakpoints(TestBase): mydir = TestBase.compute_mydir(__file__) - def test_location (self): + def test_location(self): self.build() self.source_regex_locations() - def test_restrictions (self): - self.build () - self.source_regex_restrictions () - + def test_restrictions(self): + self.build() + self.source_regex_restrictions() - def source_regex_locations (self): + def source_regex_locations(self): """ Test that restricting source expressions to files & to functions. """ # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") @@ -39,24 +40,28 @@ class TestSourceRegexBreakpoints(TestBase): func_names.AppendString("a_func") source_regex = "Set . breakpoint here" - main_break = target.BreakpointCreateBySourceRegex (source_regex, - lldb.SBFileSpecList(), - target_files, - func_names) + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, func_names) num_locations = main_break.GetNumLocations() - self.assertTrue(num_locations == 1, "a.c in a_func should give one breakpoint, got %d."%(num_locations)) + self.assertTrue( + num_locations == 1, + "a.c in a_func should give one breakpoint, got %d." % + (num_locations)) loc = main_break.GetLocationAtIndex(0) self.assertTrue(loc.IsValid(), "Got a valid location.") address = loc.GetAddress() - self.assertTrue(address.IsValid(), "Got a valid address from the location.") - + self.assertTrue( + address.IsValid(), + "Got a valid address from the location.") + a_func_line = line_number("a.c", "Set A breakpoint here") line_entry = address.GetLineEntry() self.assertTrue(line_entry.IsValid(), "Got a valid line entry.") - self.assertTrue(line_entry.line == a_func_line, "Our line number matches the one lldbtest found.") + self.assertTrue(line_entry.line == a_func_line, + "Our line number matches the one lldbtest found.") - def source_regex_restrictions (self): + def source_regex_restrictions(self): """ Test that restricting source expressions to files & to functions. """ # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") @@ -67,34 +72,35 @@ class TestSourceRegexBreakpoints(TestBase): target_files = lldb.SBFileSpecList() target_files.Append(lldb.SBFileSpec("main.c")) source_regex = "Set . breakpoint here" - main_break = target.BreakpointCreateBySourceRegex (source_regex, - lldb.SBFileSpecList(), - target_files, - lldb.SBStringList()) + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList()) num_locations = main_break.GetNumLocations() - self.assertTrue(num_locations == 2, "main.c should have 2 matches, got %d."%(num_locations)) + self.assertTrue( + num_locations == 2, + "main.c should have 2 matches, got %d." % + (num_locations)) # Now look in both files: target_files.Append(lldb.SBFileSpec("a.c")) - main_break = target.BreakpointCreateBySourceRegex (source_regex, - lldb.SBFileSpecList(), - target_files, - lldb.SBStringList()) + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList()) - num_locations =main_break.GetNumLocations() - self.assertTrue(num_locations == 4, "main.c and a.c should have 4 matches, got %d."%(num_locations)) + num_locations = main_break.GetNumLocations() + self.assertTrue( + num_locations == 4, + "main.c and a.c should have 4 matches, got %d." % + (num_locations)) # Now restrict it to functions: func_names = lldb.SBStringList() func_names.AppendString("main_func") - main_break = target.BreakpointCreateBySourceRegex (source_regex, - lldb.SBFileSpecList(), - target_files, - func_names) - - num_locations =main_break.GetNumLocations() - self.assertTrue(num_locations == 2, "main_func in main.c and a.c should have 2 matches, got %d."%(num_locations)) - + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, func_names) + num_locations = main_break.GetNumLocations() + self.assertTrue( + num_locations == 2, + "main_func in main.c and a.c should have 2 matches, got %d." % + (num_locations)) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py index 66ba8d07622..17b7b6d395d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py @@ -5,13 +5,13 @@ Test the command history mechanism from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CommandHistoryTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,52 +19,90 @@ class CommandHistoryTestCase(TestBase): @no_debug_info_test def test_history(self): self.runCmd('command history --clear', inHistory=False) - self.runCmd('breakpoint list', check=False, inHistory=True) #0 - self.runCmd('register read', check=False, inHistory=True) #1 - self.runCmd('apropos hello', check=False, inHistory=True) #2 - self.runCmd('memory write', check=False, inHistory=True) #3 - self.runCmd('log list', check=False, inHistory=True) #4 - self.runCmd('disassemble', check=False, inHistory=True) #5 - self.runCmd('expression 1', check=False, inHistory=True) #6 - self.runCmd('type summary list -w default', check=False, inHistory=True) #7 - self.runCmd('version', check=False, inHistory=True) #8 - self.runCmd('frame select 1', check=False, inHistory=True) #9 - - self.expect ("command history -s 3 -c 3", inHistory=True, - substrs = ['3: memory write','4: log list','5: disassemble']) - - self.expect ("command history -s 3 -e 3", inHistory=True, - substrs = ['3: memory write']) - - self.expect ("command history -s 6 -e 7", inHistory=True, - substrs = ['6: expression 1','7: type summary list -w default']) - - self.expect ("command history -c 2", inHistory=True, - substrs = ['0: breakpoint list','1: register read']) - - self.expect ("command history -e 3 -c 1", inHistory=True, - substrs = ['3: memory write']) - - self.expect ("command history -e 2", inHistory=True, - substrs = ['0: breakpoint list','1: register read','2: apropos hello']) - - self.expect ("command history -s 12", inHistory=True, - substrs = ['12: command history -s 6 -e 7','13: command history -c 2','14: command history -e 3 -c 1','15: command history -e 2','16: command history -s 12']) - - self.expect ("command history -s end -c 3", inHistory=True, - substrs = ['15: command history -e 2','16: command history -s 12','17: command history -s end -c 3']) - - self.expect ("command history -s end -e 15", inHistory=True, - substrs = ['15: command history -e 2','16: command history -s 12','17: command history -s end -c 3','command history -s end -e 15']) - - self.expect ("command history -s 5 -c 1", inHistory=True, - substrs = ['5: disassemble']) - - self.expect ("command history -c 1 -s 5", inHistory=True, - substrs = ['5: disassemble']) - - self.expect ("command history -c 1 -e 3", inHistory=True, - substrs = ['3: memory write']) - - self.expect ("command history -c 1 -e 3 -s 5",error=True, inHistory=True, - substrs = ['error: --count, --start-index and --end-index cannot be all specified in the same invocation']) + self.runCmd('breakpoint list', check=False, inHistory=True) # 0 + self.runCmd('register read', check=False, inHistory=True) # 1 + self.runCmd('apropos hello', check=False, inHistory=True) # 2 + self.runCmd('memory write', check=False, inHistory=True) # 3 + self.runCmd('log list', check=False, inHistory=True) # 4 + self.runCmd('disassemble', check=False, inHistory=True) # 5 + self.runCmd('expression 1', check=False, inHistory=True) # 6 + self.runCmd( + 'type summary list -w default', + check=False, + inHistory=True) # 7 + self.runCmd('version', check=False, inHistory=True) # 8 + self.runCmd('frame select 1', check=False, inHistory=True) # 9 + + self.expect( + "command history -s 3 -c 3", + inHistory=True, + substrs=[ + '3: memory write', + '4: log list', + '5: disassemble']) + + self.expect("command history -s 3 -e 3", inHistory=True, + substrs=['3: memory write']) + + self.expect( + "command history -s 6 -e 7", + inHistory=True, + substrs=[ + '6: expression 1', + '7: type summary list -w default']) + + self.expect("command history -c 2", inHistory=True, + substrs=['0: breakpoint list', '1: register read']) + + self.expect("command history -e 3 -c 1", inHistory=True, + substrs=['3: memory write']) + + self.expect( + "command history -e 2", + inHistory=True, + substrs=[ + '0: breakpoint list', + '1: register read', + '2: apropos hello']) + + self.expect( + "command history -s 12", + inHistory=True, + substrs=[ + '12: command history -s 6 -e 7', + '13: command history -c 2', + '14: command history -e 3 -c 1', + '15: command history -e 2', + '16: command history -s 12']) + + self.expect( + "command history -s end -c 3", + inHistory=True, + substrs=[ + '15: command history -e 2', + '16: command history -s 12', + '17: command history -s end -c 3']) + + self.expect( + "command history -s end -e 15", + inHistory=True, + substrs=[ + '15: command history -e 2', + '16: command history -s 12', + '17: command history -s end -c 3', + 'command history -s end -e 15']) + + self.expect("command history -s 5 -c 1", inHistory=True, + substrs=['5: disassemble']) + + self.expect("command history -c 1 -s 5", inHistory=True, + substrs=['5: disassemble']) + + self.expect("command history -c 1 -e 3", inHistory=True, + substrs=['3: memory write']) + + self.expect( + "command history -c 1 -e 3 -s 5", + error=True, + inHistory=True, + substrs=['error: --count, --start-index and --end-index cannot be all specified in the same invocation']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py index 5b680ec65de..e1c5b4b4825 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py @@ -5,18 +5,20 @@ Test lldb 'commands regex' command which allows the user to create a regular exp from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CommandRegexTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @no_debug_info_test def test_command_regex(self): """Test a simple scenario of 'command regex' invocation and subsequent use.""" @@ -25,7 +27,8 @@ class CommandRegexTestCase(TestBase): regex_prompt = "Enter one of more sed substitution commands in the form: 's/<regex>/<subst>/'.\r\nTerminate the substitution list with an empty line.\r\n" regex_prompt1 = "\r\n" - child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption)) + child = pexpect.spawn('%s %s' % + (lldbtest_config.lldbExec, self.lldbOption)) # Turn on logging for what the child sends back. if self.TraceOn(): child.logfile_read = sys.stdout @@ -44,11 +47,13 @@ class CommandRegexTestCase(TestBase): child.sendline('Help__') # If we see the familiar 'help' output, the test is done. child.expect('Debugger commands:') - # Try and incorrectly remove "Help__" using "command unalias" and verify we fail + # Try and incorrectly remove "Help__" using "command unalias" and + # verify we fail child.sendline('command unalias Help__') - child.expect_exact("error: 'Help__' is not an alias, it is a debugger command which can be removed using the 'command delete' command") + child.expect_exact( + "error: 'Help__' is not an alias, it is a debugger command which can be removed using the 'command delete' command") child.expect_exact(prompt) - + # Delete the regex command using "command delete" child.sendline('command delete Help__') child.expect_exact(prompt) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py index 97e52231e81..d562cb1511a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py @@ -5,33 +5,34 @@ Test lldb Python commands. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * + class CmdPythonTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def test (self): - self.build () - self.pycmd_tests () + def test(self): + self.build() + self.pycmd_tests() - def pycmd_tests (self): + def pycmd_tests(self): self.runCmd("command source py_import") # Verify command that specifies eCommandRequiresTarget returns failure # without a target. self.expect('targetname', - substrs = ['a.out'], matching=False, error=True) + substrs=['a.out'], matching=False, error=True) - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") self.expect("file " + exe, - patterns = [ "Current executable set to .*a.out" ]) + patterns=["Current executable set to .*a.out"]) self.expect('targetname', - substrs = ['a.out'], matching=True, error=False) + substrs=['a.out'], matching=True, error=False) # This is the function to remove the custom commands in order to have a # clean slate for the next test case. @@ -57,86 +58,89 @@ class CmdPythonTestCase(TestBase): self.HideStdout() self.expect('welcome Enrico', - substrs = ['Hello Enrico, welcome to LLDB']); - + substrs=['Hello Enrico, welcome to LLDB']) + self.expect("help welcome", - substrs = ['Just a docstring for welcome_impl', - 'A command that says hello to LLDB users']) + substrs=['Just a docstring for welcome_impl', + 'A command that says hello to LLDB users']) self.expect("help", - substrs = ['For more information run', - 'welcome']) + substrs=['For more information run', + 'welcome']) self.expect("help -a", - substrs = ['For more information run', - 'welcome']) + substrs=['For more information run', + 'welcome']) self.expect("help -u", matching=False, - substrs = ['For more information run']) + substrs=['For more information run']) - self.runCmd("command script delete welcome"); + self.runCmd("command script delete welcome") self.expect('welcome Enrico', matching=False, error=True, - substrs = ['Hello Enrico, welcome to LLDB']); + substrs=['Hello Enrico, welcome to LLDB']) self.expect('targetname fail', error=True, - substrs = ['a test for error in command']) + substrs=['a test for error in command']) self.expect('command script list', - substrs = ['targetname', - 'For more information run']) + substrs=['targetname', + 'For more information run']) self.expect("help targetname", - substrs = ['Expects', '\'raw\'', 'input', - 'help', 'raw-input']) + substrs=['Expects', '\'raw\'', 'input', + 'help', 'raw-input']) self.expect("longwait", - substrs = ['Done; if you saw the delays I am doing OK']) + substrs=['Done; if you saw the delays I am doing OK']) self.runCmd("b main") self.runCmd("run") self.runCmd("mysto 3") self.expect("frame variable array", - substrs = ['[0] = 79630','[1] = 388785018','[2] = 0']) + substrs=['[0] = 79630', '[1] = 388785018', '[2] = 0']) self.runCmd("mysto 3") self.expect("frame variable array", - substrs = ['[0] = 79630','[4] = 388785018','[5] = 0']) + substrs=['[0] = 79630', '[4] = 388785018', '[5] = 0']) # we cannot use the stepover command to check for async execution mode since LLDB # seems to get confused when events start to queue up self.expect("tell_sync", - substrs = ['running sync']) + substrs=['running sync']) self.expect("tell_async", - substrs = ['running async']) + substrs=['running async']) self.expect("tell_curr", - substrs = ['I am running sync']) - + substrs=['I am running sync']) + # check that the execution context is passed in to commands that ask for it - self.expect("takes_exe_ctx", substrs = ["a.out"]) + self.expect("takes_exe_ctx", substrs=["a.out"]) # Test that a python command can redefine itself self.expect('command script add -f foobar welcome -h "just some help"') - + self.runCmd("command script clear") # Test that re-defining an existing command works - self.runCmd('command script add my_command --class welcome.WelcomeCommand') - self.expect('my_command Blah', substrs = ['Hello Blah, welcome to LLDB']) + self.runCmd( + 'command script add my_command --class welcome.WelcomeCommand') + self.expect('my_command Blah', substrs=['Hello Blah, welcome to LLDB']) - self.runCmd('command script add my_command --class welcome.TargetnameCommand') - self.expect('my_command', substrs = ['a.out']) + self.runCmd( + 'command script add my_command --class welcome.TargetnameCommand') + self.expect('my_command', substrs=['a.out']) self.runCmd("command script clear") - + self.expect('command script list', matching=False, - substrs = ['targetname', - 'longwait']) + substrs=['targetname', + 'longwait']) self.expect('command script add -f foobar frame', error=True, - substrs = ['cannot add command']) + substrs=['cannot add command']) # http://llvm.org/bugs/show_bug.cgi?id=11569 - # LLDBSwigPythonCallCommand crashes when a command script returns an object + # LLDBSwigPythonCallCommand crashes when a command script returns an + # object self.runCmd('command script add -f bug11569 bug11569') # This should not crash. self.runCmd('bug11569', check=False) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py index 93897d88098..3c124de79bf 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py @@ -3,5 +3,4 @@ def bug11569(debugger, args, result, dict): http://llvm.org/bugs/show_bug.cgi?id=11569 LLDBSwigPythonCallCommand crashes when a command script returns an object. """ - return ["return", "a", "non-string", "should", "not", "crash", "LLDB"]; - + return ["return", "a", "non-string", "should", "not", "crash", "LLDB"] diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py index 01c3f35bf30..01e7902b0f3 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py @@ -3,13 +3,15 @@ from __future__ import print_function - -import os, sys, time +import os +import sys +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ImportTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -47,29 +49,31 @@ class ImportTestCase(TestBase): self.runCmd("command script import ./bar/bar.py --allow-reload") self.expect("command script import ./nosuchfile.py", - error=True, startstr='error: module importing failed') + error=True, startstr='error: module importing failed') self.expect("command script import ./nosuchfolder/", - error=True, startstr='error: module importing failed') + error=True, startstr='error: module importing failed') self.expect("command script import ./foo/foo.py", error=False) self.runCmd("command script import --allow-reload ./thepackage") - self.expect("TPcommandA",substrs=["hello world A"]) - self.expect("TPcommandB",substrs=["hello world B"]) + self.expect("TPcommandA", substrs=["hello world A"]) + self.expect("TPcommandB", substrs=["hello world B"]) self.runCmd("script import dummymodule") self.expect("command script import ./dummymodule.py", error=False) - self.expect("command script import --allow-reload ./dummymodule.py", error=False) + self.expect( + "command script import --allow-reload ./dummymodule.py", + error=False) self.runCmd("command script add -f foo.foo_function foocmd") self.runCmd("command script add -f foobar.foo_function foobarcmd") self.runCmd("command script add -f bar.bar_function barcmd") self.expect("foocmd hello", - substrs = ['foo says', 'hello']) + substrs=['foo says', 'hello']) self.expect("foo2cmd hello", - substrs = ['foo2 says', 'hello']) + substrs=['foo2 says', 'hello']) self.expect("barcmd hello", - substrs = ['barutil says', 'bar told me', 'hello']) + substrs=['barutil says', 'bar told me', 'hello']) self.expect("barothercmd hello", - substrs = ['barutil says', 'bar told me', 'hello']) + substrs=['barutil says', 'bar told me', 'hello']) self.expect("foobarcmd hello", - substrs = ['foobar says', 'hello']) + substrs=['foobar says', 'hello']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py index bbc41f3b217..444e00976ad 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py @@ -1,12 +1,15 @@ from __future__ import print_function + def bar_function(debugger, args, result, dict): - global UtilityModule - print(UtilityModule.barutil_function("bar told me " + args), file=result) - return None + global UtilityModule + print(UtilityModule.barutil_function("bar told me " + args), file=result) + return None + def __lldb_init_module(debugger, session_dict): - global UtilityModule - UtilityModule = __import__("barutil") - debugger.HandleCommand("command script add -f bar.bar_function barothercmd") - return None
\ No newline at end of file + global UtilityModule + UtilityModule = __import__("barutil") + debugger.HandleCommand( + "command script add -f bar.bar_function barothercmd") + return None diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py index 0d3d2eb1b2d..70ecea30057 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py @@ -1,2 +1,2 @@ def barutil_function(x): - return "barutil says: " + x + return "barutil says: " + x diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py index dcc724ec9c2..668a5b90ea4 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py @@ -1,2 +1,2 @@ def no_useful_code(foo): - return foo + return foo diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py index 659ded22c90..6ef71064c9a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py @@ -1,5 +1,6 @@ from __future__ import print_function + def foo_function(debugger, args, result, dict): - print("foobar says " + args, file=result) - return None + print("foobar says " + args, file=result) + return None diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py index 51cc0c3bab1..1ccc3892939 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py @@ -1,5 +1,6 @@ from __future__ import print_function + def foo_function(debugger, args, result, dict): - print("foo says " + args, file=result) - return None + print("foo says " + args, file=result) + return None diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py index 6863454ca6e..71657c299c2 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py @@ -1,9 +1,11 @@ from __future__ import print_function + def foo2_function(debugger, args, result, dict): - print("foo2 says " + args, file=result) - return None + print("foo2 says " + args, file=result) + return None + def __lldb_init_module(debugger, session_dict): - debugger.HandleCommand("command script add -f foo2.foo2_function foo2cmd") - return None
\ No newline at end of file + debugger.HandleCommand("command script add -f foo2.foo2_function foo2cmd") + return None diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py index 4f7ebebd4dd..01fd5138583 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py @@ -3,13 +3,15 @@ from __future__ import print_function - -import os, sys, time +import os +import sys +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class Rdar12586188TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,7 +29,11 @@ class Rdar12586188TestCase(TestBase): def run_test(self): """Check that we handle an ImportError in a special way when command script importing files.""" - self.expect("command script import ./fail12586188.py --allow-reload", - error=True, substrs = ['raise ImportError("I do not want to be imported")']) - self.expect("command script import ./fail212586188.py --allow-reload", - error=True, substrs = ['raise ValueError("I do not want to be imported")']) + self.expect( + "command script import ./fail12586188.py --allow-reload", + error=True, + substrs=['raise ImportError("I do not want to be imported")']) + self.expect( + "command script import ./fail212586188.py --allow-reload", + error=True, + substrs=['raise ValueError("I do not want to be imported")']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py index add85a73f85..ea385e03e04 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py @@ -1,4 +1,4 @@ def f(x): - return x + 1 + return x + 1 raise ImportError("I do not want to be imported") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py index 1549a036590..8dbc0e67ba1 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py @@ -1,4 +1,4 @@ def f(x): - return x + 1 + return x + 1 raise ValueError("I do not want to be imported") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py index fb65305d205..9694b084295 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py @@ -1,6 +1,7 @@ import six + def command(debugger, command, result, internal_dict): - result.PutCString(six.u("hello world A")) - return None + result.PutCString(six.u("hello world A")) + return None diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py index 60b31b89f6d..94a333bc696 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py @@ -1,6 +1,7 @@ import six + def command(debugger, command, result, internal_dict): - result.PutCString(six.u("hello world B")) - return None + result.PutCString(six.u("hello world B")) + return None diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py index 1181462af86..24cdea60f2c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py @@ -3,6 +3,9 @@ from __future__ import absolute_import from . import TPunitA from . import TPunitB -def __lldb_init_module(debugger,*args): - debugger.HandleCommand("command script add -f thepackage.TPunitA.command TPcommandA") - debugger.HandleCommand("command script add -f thepackage.TPunitB.command TPcommandB") + +def __lldb_init_module(debugger, *args): + debugger.HandleCommand( + "command script add -f thepackage.TPunitA.command TPcommandA") + debugger.HandleCommand( + "command script add -f thepackage.TPunitB.command TPcommandB") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/mysto.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/mysto.py index 656cd150293..88a20cb4567 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/mysto.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/mysto.py @@ -5,19 +5,21 @@ import sys import os import time + def StepOver(debugger, args, result, dict): - """ - Step over a given number of times instead of only just once - """ - arg_split = args.split(" ") - print(type(arg_split)) - count = int(arg_split[0]) - for i in range(0,count): - debugger.GetSelectedTarget().GetProcess().GetSelectedThread().StepOver(lldb.eOnlyThisThread) - print("step<%d>"%i) + """ + Step over a given number of times instead of only just once + """ + arg_split = args.split(" ") + print(type(arg_split)) + count = int(arg_split[0]) + for i in range(0, count): + debugger.GetSelectedTarget().GetProcess( + ).GetSelectedThread().StepOver(lldb.eOnlyThisThread) + print("step<%d>" % i) -def __lldb_init_module(debugger, session_dict): - # by default, --synchronicity is set to synchronous - debugger.HandleCommand("command script add -f mysto.StepOver mysto") - return None +def __lldb_init_module(debugger, session_dict): + # by default, --synchronicity is set to synchronous + debugger.HandleCommand("command script add -f mysto.StepOver mysto") + return None diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/welcome.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/welcome.py index 5dbf09fbbec..0539d7c1721 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script/welcome.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script/welcome.py @@ -1,18 +1,23 @@ from __future__ import print_function -import lldb, sys +import lldb +import sys + class WelcomeCommand(object): + def __init__(self, debugger, session_dict): pass - + def get_short_help(self): return "Just a docstring for welcome_impl\nA command that says hello to LLDB users" - + def __call__(self, debugger, args, exe_ctx, result): - print('Hello ' + args + ', welcome to LLDB', file=result); - return None; + print('Hello ' + args + ', welcome to LLDB', file=result) + return None + class TargetnameCommand(object): + def __init__(self, debugger, session_dict): pass @@ -22,10 +27,11 @@ class TargetnameCommand(object): print('Current target ' + file.GetFilename(), file=result) if args == 'fail': result.SetError('a test for error in command') - + def get_flags(self): return lldb.eCommandRequiresTarget + def print_wait_impl(debugger, args, result, dict): result.SetImmediateOutputFile(sys.stdout) print('Trying to do long task..', file=result) @@ -35,12 +41,13 @@ def print_wait_impl(debugger, args, result, dict): time.sleep(1) print('Done; if you saw the delays I am doing OK', file=result) + def check_for_synchro(debugger, args, result, dict): - if debugger.GetAsync() == True: + if debugger.GetAsync(): print('I am running async', file=result) if debugger.GetAsync() == False: print('I am running sync', file=result) + def takes_exe_ctx(debugger, args, exe_ctx, result, dict): print(str(exe_ctx.GetTarget()), file=result) - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/TestCommandScriptAlias.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/TestCommandScriptAlias.py index 694728a9f9c..eb63c707989 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/TestCommandScriptAlias.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/TestCommandScriptAlias.py @@ -5,18 +5,20 @@ Test lldb Python commands. from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * + class CommandScriptAliasTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def test (self): - self.pycmd_tests () + def test(self): + self.pycmd_tests() - def pycmd_tests (self): + def pycmd_tests(self): self.runCmd("command script import tcsacmd.py") self.runCmd("command script add -f tcsacmd.some_command_here attach") @@ -32,6 +34,7 @@ class CommandScriptAliasTestCase(TestBase): if not self.TraceOn(): self.HideStdout() - self.expect('attach a', substrs = ['Victory is mine']); + self.expect('attach a', substrs=['Victory is mine']) self.runCmd("command script delete attach") - self.runCmd('attach noprocessexistswiththisname', check=False) # this can't crash but we don't care whether the actual attach works + # this can't crash but we don't care whether the actual attach works + self.runCmd('attach noprocessexistswiththisname', check=False) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/tcsacmd.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/tcsacmd.py index 6c60e3ca1a5..d5bb6131210 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/tcsacmd.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_alias/tcsacmd.py @@ -1,11 +1,12 @@ from __future__ import print_function -import lldb, sys +import lldb +import sys -def some_command_here(debugger, command, result, d): - if command == "a": - print("Victory is mine", file=result) - return True - else: - print("Sadness for all", file=result) - return False +def some_command_here(debugger, command, result, d): + if command == "a": + print("Victory is mine", file=result) + return True + else: + print("Sadness for all", file=result) + return False diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py index a843d08a97d..975ad32689b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py @@ -5,14 +5,15 @@ Test that LLDB correctly allows scripted commands to set an immediate output fil from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * from lldbsuite.test import lldbutil + class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) @@ -22,10 +23,12 @@ class CommandScriptImmediateOutputTestCase (PExpectTest): # Call super's setUp(). PExpectTest.setUp(self) - @skipIfRemote # test not remote-ready llvm.org/pr24813 - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfRemote # test not remote-ready llvm.org/pr24813 + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr26139") - def test_command_script_immediate_output_console (self): + def test_command_script_immediate_output_console(self): """Test that LLDB correctly allows scripted commands to set immediate output to the console.""" self.launch(timeout=10) @@ -33,27 +36,33 @@ class CommandScriptImmediateOutputTestCase (PExpectTest): prompt = "\(lldb\) " self.sendline('command script import %s' % script, patterns=[prompt]) - self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) - self.sendline('mycommand', patterns='this is a test string, just a test string') + self.sendline( + 'command script add -f custom_command.command_function mycommand', + patterns=[prompt]) + self.sendline( + 'mycommand', + patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False) - @skipIfRemote # test not remote-ready llvm.org/pr24813 - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfRemote # test not remote-ready llvm.org/pr24813 + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr26139") - def test_command_script_immediate_output_file (self): + def test_command_script_immediate_output_file(self): """Test that LLDB correctly allows scripted commands to set immediate output to a file.""" self.launch(timeout=10) - test_files = {os.path.join(os.getcwd(), 'read.txt') :'r', - os.path.join(os.getcwd(), 'write.txt') :'w', - os.path.join(os.getcwd(), 'append.txt') :'a', - os.path.join(os.getcwd(), 'write_plus.txt') :'w+', - os.path.join(os.getcwd(), 'read_plus.txt') :'r+', - os.path.join(os.getcwd(), 'append_plus.txt') :'a+'} + test_files = {os.path.join(os.getcwd(), 'read.txt'): 'r', + os.path.join(os.getcwd(), 'write.txt'): 'w', + os.path.join(os.getcwd(), 'append.txt'): 'a', + os.path.join(os.getcwd(), 'write_plus.txt'): 'w+', + os.path.join(os.getcwd(), 'read_plus.txt'): 'r+', + os.path.join(os.getcwd(), 'append_plus.txt'): 'a+'} starter_string = 'Starter Garbage\n' - write_string = 'writing to file with mode: ' + write_string = 'writing to file with mode: ' for path, mode in test_files.iteritems(): with open(path, 'w+') as init: @@ -64,7 +73,9 @@ class CommandScriptImmediateOutputTestCase (PExpectTest): self.sendline('command script import %s' % script, patterns=[prompt]) - self.sendline('command script add -f custom_command.write_file mywrite', patterns=[prompt]) + self.sendline( + 'command script add -f custom_command.write_file mywrite', + patterns=[prompt]) for path, mode in test_files.iteritems(): command = 'mywrite "' + path + '" ' + mode @@ -79,8 +90,8 @@ class CommandScriptImmediateOutputTestCase (PExpectTest): if mode in ['r', 'a', 'a+']: self.assertEquals(result.readline(), starter_string) if mode in ['w', 'w+', 'r+', 'a', 'a+']: - self.assertEquals(result.readline(), write_string + mode + '\n') + self.assertEquals( + result.readline(), write_string + mode + '\n') self.assertTrue(os.path.isfile(path)) os.remove(path) - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/custom_command.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/custom_command.py index 30a3cfb9093..e0c24055c83 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/custom_command.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/custom_command.py @@ -3,15 +3,17 @@ from __future__ import print_function import sys import shlex + def command_function(debugger, command, exe_ctx, result, internal_dict): - result.SetImmediateOutputFile(sys.__stdout__) - print('this is a test string, just a test string', file=result) + result.SetImmediateOutputFile(sys.__stdout__) + print('this is a test string, just a test string', file=result) + def write_file(debugger, command, exe_ctx, result, internal_dict): - args = shlex.split(command) - path = args[0] - mode = args[1] - with open(path, mode) as f: - result.SetImmediateOutputFile(f) - if not mode in ['r']: - print('writing to file with mode: ' + mode, file=result) + args = shlex.split(command) + path = args[0] + mode = args[1] + with open(path, mode) as f: + result.SetImmediateOutputFile(f) + if not mode in ['r']: + print('writing to file with mode: ' + mode, file=result) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py index 0d4eb0776e7..cee9bd27218 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py @@ -7,13 +7,14 @@ See also http://llvm.org/viewvc/llvm-project?view=rev&revision=109673. from __future__ import print_function - -import os, sys +import os +import sys import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CommandSourceTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -35,4 +36,4 @@ class CommandSourceTestCase(TestBase): import datetime self.expect(result.GetOutput(), "script my.date() runs successfully", exe=False, - substrs = [str(datetime.date.today())]) + substrs=[str(datetime.date.today())]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/command_source/my.py b/lldb/packages/Python/lldbsuite/test/functionalities/command_source/my.py index cb2fd012e4b..bd97fda3cbb 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/command_source/my.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/command_source/my.py @@ -1,5 +1,6 @@ from __future__ import print_function + def date(): import datetime today = datetime.date.today() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py b/lldb/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py index 7a9ded03ad2..d4d9c58b0bc 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py @@ -5,7 +5,6 @@ Test the lldb command line completion mechanism. from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * @@ -13,6 +12,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbplatform from lldbsuite.test import lldbutil + class CommandLineCompletionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,29 +27,31 @@ class CommandLineCompletionTestCase(TestBase): pass @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_at(self): """Test that 'at' completes to 'attach '.""" self.complete_from_to('at', 'attach ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_de(self): """Test that 'de' completes to 'detach '.""" self.complete_from_to('de', 'detach ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_process_attach_dash_dash_con(self): """Test that 'process attach --con' completes to 'process attach --continue '.""" - self.complete_from_to('process attach --con', 'process attach --continue ') + self.complete_from_to( + 'process attach --con', + 'process attach --continue ') # <rdar://problem/11052829> @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_infinite_loop_while_completing(self): """Test that 'process print hello\' completes to itself and does not infinite loop.""" @@ -57,147 +59,176 @@ class CommandLineCompletionTestCase(TestBase): turn_off_re_match=True) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_co(self): """Test that 'watchpoint co' completes to 'watchpoint command '.""" self.complete_from_to('watchpoint co', 'watchpoint command ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_command_space(self): """Test that 'watchpoint command ' completes to ['Available completions:', 'add', 'delete', 'list'].""" - self.complete_from_to('watchpoint command ', ['Available completions:', 'add', 'delete', 'list']) + self.complete_from_to( + 'watchpoint command ', [ + 'Available completions:', 'add', 'delete', 'list']) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_command_a(self): """Test that 'watchpoint command a' completes to 'watchpoint command add '.""" - self.complete_from_to('watchpoint command a', 'watchpoint command add ') + self.complete_from_to( + 'watchpoint command a', + 'watchpoint command add ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_set_variable_dash_w(self): """Test that 'watchpoint set variable -w' completes to 'watchpoint set variable -w '.""" - self.complete_from_to('watchpoint set variable -w', 'watchpoint set variable -w ') + self.complete_from_to( + 'watchpoint set variable -w', + 'watchpoint set variable -w ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_set_variable_dash_w_space(self): """Test that 'watchpoint set variable -w ' completes to ['Available completions:', 'read', 'write', 'read_write'].""" - self.complete_from_to('watchpoint set variable -w ', ['Available completions:', 'read', 'write', 'read_write']) + self.complete_from_to('watchpoint set variable -w ', + ['Available completions:', 'read', 'write', 'read_write']) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_set_ex(self): """Test that 'watchpoint set ex' completes to 'watchpoint set expression '.""" - self.complete_from_to('watchpoint set ex', 'watchpoint set expression ') + self.complete_from_to( + 'watchpoint set ex', + 'watchpoint set expression ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_set_var(self): """Test that 'watchpoint set var' completes to 'watchpoint set variable '.""" self.complete_from_to('watchpoint set var', 'watchpoint set variable ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_watchpoint_set_variable_dash_w_read_underbar(self): """Test that 'watchpoint set variable -w read_' completes to 'watchpoint set variable -w read_write'.""" - self.complete_from_to('watchpoint set variable -w read_', 'watchpoint set variable -w read_write') + self.complete_from_to( + 'watchpoint set variable -w read_', + 'watchpoint set variable -w read_write') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_help_fi(self): """Test that 'help fi' completes to ['Available completions:', 'file', 'finish'].""" - self.complete_from_to('help fi', ['Available completions:', 'file', 'finish']) + self.complete_from_to( + 'help fi', [ + 'Available completions:', 'file', 'finish']) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_help_watchpoint_s(self): """Test that 'help watchpoint s' completes to 'help watchpoint set '.""" self.complete_from_to('help watchpoint s', 'help watchpoint set ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_append_target_er(self): """Test that 'settings append target.er' completes to 'settings append target.error-path'.""" - self.complete_from_to('settings append target.er', 'settings append target.error-path') + self.complete_from_to( + 'settings append target.er', + 'settings append target.error-path') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_insert_after_target_en(self): """Test that 'settings insert-after target.env' completes to 'settings insert-after target.env-vars'.""" - self.complete_from_to('settings insert-after target.env', 'settings insert-after target.env-vars') + self.complete_from_to( + 'settings insert-after target.env', + 'settings insert-after target.env-vars') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_insert_before_target_en(self): """Test that 'settings insert-before target.env' completes to 'settings insert-before target.env-vars'.""" - self.complete_from_to('settings insert-before target.env', 'settings insert-before target.env-vars') + self.complete_from_to( + 'settings insert-before target.env', + 'settings insert-before target.env-vars') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_replace_target_ru(self): """Test that 'settings replace target.ru' completes to 'settings replace target.run-args'.""" - self.complete_from_to('settings replace target.ru', 'settings replace target.run-args') + self.complete_from_to( + 'settings replace target.ru', + 'settings replace target.run-args') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_s(self): """Test that 'settings s' completes to ['Available completions:', 'set', 'show'].""" - self.complete_from_to('settings s', ['Available completions:', 'set', 'show']) + self.complete_from_to( + 'settings s', [ + 'Available completions:', 'set', 'show']) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_set_th(self): """Test that 'settings set th' completes to 'settings set thread-format'.""" self.complete_from_to('settings set th', 'settings set thread-format') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_s_dash(self): """Test that 'settings set -' completes to 'settings set -g'.""" self.complete_from_to('settings set -', 'settings set -g') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_clear_th(self): """Test that 'settings clear th' completes to 'settings clear thread-format'.""" - self.complete_from_to('settings clear th', 'settings clear thread-format') + self.complete_from_to( + 'settings clear th', + 'settings clear thread-format') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_set_ta(self): """Test that 'settings set ta' completes to 'settings set target.'.""" - self.complete_from_to('settings set target.ma', 'settings set target.max-') + self.complete_from_to( + 'settings set target.ma', + 'settings set target.max-') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_set_target_exec(self): """Test that 'settings set target.exec' completes to 'settings set target.exec-search-paths '.""" - self.complete_from_to('settings set target.exec', 'settings set target.exec-search-paths') + self.complete_from_to( + 'settings set target.exec', + 'settings set target.exec-search-paths') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_set_target_pr(self): """Test that 'settings set target.pr' completes to ['Available completions:', @@ -208,21 +239,25 @@ class CommandLineCompletionTestCase(TestBase): 'target.process.']) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_set_target_process(self): """Test that 'settings set target.process' completes to 'settings set target.process.'.""" - self.complete_from_to('settings set target.process', 'settings set target.process.') + self.complete_from_to( + 'settings set target.process', + 'settings set target.process.') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_set_target_process_dot(self): """Test that 'settings set target.process.t' completes to 'settings set target.process.thread.'.""" - self.complete_from_to('settings set target.process.t', 'settings set target.process.thread.') + self.complete_from_to( + 'settings set target.process.t', + 'settings set target.process.thread.') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_settings_set_target_process_thread_dot(self): """Test that 'settings set target.process.thread.' completes to ['Available completions:', @@ -233,31 +268,39 @@ class CommandLineCompletionTestCase(TestBase): 'target.process.thread.trace-thread']) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_target_space(self): """Test that 'target ' completes to ['Available completions:', 'create', 'delete', 'list', 'modules', 'select', 'stop-hook', 'variable'].""" self.complete_from_to('target ', - ['Available completions:', 'create', 'delete', 'list', - 'modules', 'select', 'stop-hook', 'variable']) + ['Available completions:', + 'create', + 'delete', + 'list', + 'modules', + 'select', + 'stop-hook', + 'variable']) @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_target_create_dash_co(self): """Test that 'target create --co' completes to 'target variable --core '.""" self.complete_from_to('target create --co', 'target create --core ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @skipIfFreeBSD # timing out on the FreeBSD buildbot + @skipIfFreeBSD # timing out on the FreeBSD buildbot @no_debug_info_test def test_target_va(self): """Test that 'target va' completes to 'target variable '.""" self.complete_from_to('target va', 'target variable ') @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr24679") - @expectedFailureAll(oslist=lldbplatform.darwin_all, bugnumber="llvm.org/pr25485") + @expectedFailureAll( + oslist=lldbplatform.darwin_all, + bugnumber="llvm.org/pr25485") def test_symbol_name(self): self.build() self.complete_from_to('''file a.out @@ -277,7 +320,7 @@ class CommandLineCompletionTestCase(TestBase): # later on. if not isinstance(patterns, list): patterns = [patterns] - + # The default lldb prompt. prompt = "(lldb) " @@ -304,7 +347,7 @@ class CommandLineCompletionTestCase(TestBase): # stop further logging. child.logfile_send = None child.logfile_read = None - + with open('child_send.txt', 'r') as fs: if self.TraceOn(): print("\n\nContents of child_send.txt:") @@ -318,10 +361,13 @@ class CommandLineCompletionTestCase(TestBase): # The matching could be verbatim or using generic re pattern. for p in patterns: # Test that str_input completes to our patterns or substrings. - # If each pattern/substring matches from_child, the completion mechanism works! + # If each pattern/substring matches from_child, the completion + # mechanism works! if turn_off_re_match: - self.expect(from_child, msg=COMPLETION_MSG(str_input, p), exe=False, - substrs = [p]) + self.expect( + from_child, msg=COMPLETION_MSG( + str_input, p), exe=False, substrs=[p]) else: - self.expect(from_child, msg=COMPLETION_MSG(str_input, p), exe=False, - patterns = [p]) + self.expect( + from_child, msg=COMPLETION_MSG( + str_input, p), exe=False, patterns=[p]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py index 7fcb44f0b3e..cec06e48f1c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py @@ -5,8 +5,8 @@ Test conditionally break on a function and inspect its variables. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * @@ -18,6 +18,7 @@ from lldbsuite.test import lldbutil # # This class currently fails for clang as well as llvm-gcc. + class ConditionalBreakTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -33,7 +34,9 @@ class ConditionalBreakTestCase(TestBase): self.build() self.simulate_conditional_break_by_user() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr26265: args in frames other than #0 are not evaluated correctly") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr26265: args in frames other than #0 are not evaluated correctly") def do_conditional_break(self): """Exercise some thread and frame APIs to break if c() is called by a().""" exe = os.path.join(os.getcwd(), "a.out") @@ -45,7 +48,8 @@ class ConditionalBreakTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) @@ -54,7 +58,8 @@ class ConditionalBreakTestCase(TestBase): STOPPED_DUE_TO_BREAKPOINT) # Find the line number where a's parent frame function is c. - line = line_number('main.c', + line = line_number( + 'main.c', "// Find the line number where c's parent frame is a here.") # Suppose we are only interested in the call scenario where c()'s @@ -66,15 +71,17 @@ class ConditionalBreakTestCase(TestBase): for j in range(10): if self.TraceOn(): print("j is: ", j) - thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, breakpoint) - self.assertIsNotNone(thread, "Expected one thread to be stopped at the breakpoint") - + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + self.assertIsNotNone( + thread, "Expected one thread to be stopped at the breakpoint") + if thread.GetNumFrames() >= 2: frame0 = thread.GetFrameAtIndex(0) name0 = frame0.GetFunction().GetName() frame1 = thread.GetFrameAtIndex(1) name1 = frame1.GetFunction().GetName() - #lldbutil.print_stacktrace(thread) + # lldbutil.print_stacktrace(thread) self.assertTrue(name0 == "c", "Break on function c()") if (name1 == "a"): # By design, we know that a() calls c() only from main.c:27. @@ -83,7 +90,8 @@ class ConditionalBreakTestCase(TestBase): self.assertTrue(frame1.GetLineEntry().GetLine() == line, "Immediate caller a() at main.c:%d" % line) - # And the local variable 'val' should have a value of (int) 3. + # And the local variable 'val' should have a value of (int) + # 3. val = frame1.FindVariable("val") self.assertEqual("int", val.GetTypeName()) self.assertEqual("3", val.GetValue()) @@ -109,28 +117,28 @@ class ConditionalBreakTestCase(TestBase): self.runCmd("file a.out") self.runCmd("command source .lldb") - self.runCmd ("break list") + self.runCmd("break list") if self.TraceOn(): print("About to run.") self.runCmd("run", RUN_SUCCEEDED) - self.runCmd ("break list") + self.runCmd("break list") if self.TraceOn(): print("Done running") # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The frame info for frame #0 points to a.out`c and its immediate caller # (frame #1) points to a.out`a. self.expect("frame info", "We should stop at c()", - substrs = ["a.out`c"]) + substrs=["a.out`c"]) # Select our parent frame as the current frame. self.runCmd("frame select 1") self.expect("frame info", "The immediate caller should be a()", - substrs = ["a.out`a"]) + substrs=["a.out`a"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py b/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py index b30a34e56b1..a62dd923af9 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py @@ -1,6 +1,7 @@ import sys import lldb + def stop_if_called_from_a(frame, bp_loc, dict): thread = frame.GetThread() @@ -19,12 +20,11 @@ def stop_if_called_from_a(frame, bp_loc, dict): should_stop = True if thread.GetNumFrames() >= 2: - if (thread.frames[0].function.name == 'c' and thread.frames[1].function.name == 'a'): + if (thread.frames[0].function.name == + 'c' and thread.frames[1].function.name == 'a'): should_stop = True else: should_stop = False dbg.SetAsync(old_async) return should_stop - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/TestDarwinLogFilterMatchActivityChain.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/TestDarwinLogFilterMatchActivityChain.py index fca56dd93a8..f8ce069478f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/TestDarwinLogFilterMatchActivityChain.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/TestDarwinLogFilterMatchActivityChain.py @@ -60,28 +60,31 @@ class TestDarwinLogFilterMatchActivityChain(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_chain_partial_match(self): """Test that fall-through reject, doesn't accept only partial match of activity-chain.""" self.do_test( ["--no-match-accepts false", - "--filter \"accept activity-chain match parent-activity:child-activity\"", # Match the second fully. + # Match the second fully. + "--filter \"accept activity-chain match parent-activity:child-activity\"", "--filter \"accept activity-chain match parent-ac\""]) # Only partially match the first. # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_chain_full_match(self): @@ -93,11 +96,12 @@ class TestDarwinLogFilterMatchActivityChain(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via activity-chain rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_activity_chain_second_rule(self): @@ -111,7 +115,9 @@ class TestDarwinLogFilterMatchActivityChain(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the activity-chain of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/TestDarwinLogFilterMatchActivity.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/TestDarwinLogFilterMatchActivity.py index edb5914bfbf..12a430295a7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/TestDarwinLogFilterMatchActivity.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/TestDarwinLogFilterMatchActivity.py @@ -60,29 +60,32 @@ class TestDarwinLogFilterMatchActivity(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_partial_match(self): """Test that fall-through reject, accept match activity via partial match does not accept.""" self.do_test( ["--no-match-accepts false", - "--filter \"accept activity match child-activity\"", # Fully match second message. + # Fully match second message. + "--filter \"accept activity match child-activity\"", "--filter \"accept activity match parent-\""] # Only partially match first message. ) # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_full_match(self): @@ -95,11 +98,12 @@ class TestDarwinLogFilterMatchActivity(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via activity rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_activity_second_rule(self): @@ -115,7 +119,9 @@ class TestDarwinLogFilterMatchActivity(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the activity of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/TestDarwinLogFilterMatchCategory.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/TestDarwinLogFilterMatchCategory.py index 21d8bfb9d6a..8ce4d4135d1 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/TestDarwinLogFilterMatchCategory.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/TestDarwinLogFilterMatchCategory.py @@ -60,27 +60,32 @@ class TestDarwinLogFilterMatchCategory(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that category. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_category_partial_match(self): """Test that fall-through reject, accept regex category via partial match works.""" self.do_test( ["--no-match-accepts false", - "--filter \"accept category match cat2\"", # Fully match the second message. + # Fully match the second message. + "--filter \"accept category match cat2\"", "--filter \"accept category match at1\""] # Only partially match first message. Should not show up. ) # We should only see the second log message as we only accept # that category. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_category_full_match(self): @@ -93,10 +98,12 @@ class TestDarwinLogFilterMatchCategory(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via category rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_category_second_rule(self): @@ -112,7 +119,9 @@ class TestDarwinLogFilterMatchCategory(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the category of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/TestDarwinLogFilterMatchMessage.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/TestDarwinLogFilterMatchMessage.py index c9b05184e36..8a6ab43a609 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/TestDarwinLogFilterMatchMessage.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/TestDarwinLogFilterMatchMessage.py @@ -40,7 +40,6 @@ class TestDarwinLogFilterMatchMessage(darwin_log.DarwinLogTestBase): # Turn on process monitor logging while we work out issues. self.enable_process_monitor_logging = True - def tearDown(self): # Shut down the process if it's still running. if self.child: @@ -58,7 +57,7 @@ class TestDarwinLogFilterMatchMessage(darwin_log.DarwinLogTestBase): EXPECT_REGEXES = [ re.compile(r"log message ([^-]+)-(\S+)"), re.compile(r"exited with status") - ] + ] @decorators.skipUnlessDarwin def test_filter_accept_message_full_match(self): @@ -72,10 +71,12 @@ class TestDarwinLogFilterMatchMessage(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that message contents. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_no_accept_message_partial_match(self): @@ -90,10 +91,12 @@ class TestDarwinLogFilterMatchMessage(darwin_log.DarwinLogTestBase): # We should only see the second log message as the partial match on # the first message should not pass. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_category_full_match(self): @@ -107,10 +110,12 @@ class TestDarwinLogFilterMatchMessage(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via message contents rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_category_second_rule(self): @@ -126,7 +131,9 @@ class TestDarwinLogFilterMatchMessage(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the category of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/TestDarwinLogFilterMatchSubsystem.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/TestDarwinLogFilterMatchSubsystem.py index e9cfa7def13..5afe649e16a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/TestDarwinLogFilterMatchSubsystem.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/TestDarwinLogFilterMatchSubsystem.py @@ -60,27 +60,32 @@ class TestDarwinLogFilterMatchSubsystem(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that subsystem. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_subsystem_partial_match(self): """Test that fall-through reject, doesn't accept match subsystem via partial-match.""" self.do_test( ["--no-match-accepts false", - "--filter \"accept subsystem match org.llvm.lldb.test.sub2\"", # Fully match second message subsystem. + # Fully match second message subsystem. + "--filter \"accept subsystem match org.llvm.lldb.test.sub2\"", "--filter \"accept subsystem match sub1\""] # Only partially match first subsystem. ) # We should only see the second log message as we only accept # that subsystem. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_subsystem_full_match(self): @@ -93,10 +98,12 @@ class TestDarwinLogFilterMatchSubsystem(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via subsystem rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_subsystem_second_rule(self): @@ -112,7 +119,9 @@ class TestDarwinLogFilterMatchSubsystem(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the subsystem of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/TestDarwinLogFilterRegexActivityChain.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/TestDarwinLogFilterRegexActivityChain.py index a2f5abf1a54..74be57aeef8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/TestDarwinLogFilterRegexActivityChain.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/TestDarwinLogFilterRegexActivityChain.py @@ -60,11 +60,12 @@ class TestDarwinLogFilterRegexActivityChain(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_activity_chain_partial_match(self): @@ -76,11 +77,12 @@ class TestDarwinLogFilterRegexActivityChain(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_chain_full_match(self): @@ -92,11 +94,12 @@ class TestDarwinLogFilterRegexActivityChain(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via activity-chain rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat1"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat1"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_chain_partial_match(self): @@ -108,11 +111,12 @@ class TestDarwinLogFilterRegexActivityChain(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via activity-chain rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_activity_chain_second_rule(self): @@ -126,7 +130,9 @@ class TestDarwinLogFilterRegexActivityChain(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the activity-chain of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/TestDarwinLogFilterRegexActivity.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/TestDarwinLogFilterRegexActivity.py index 286ad72953b..55f015403d1 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/TestDarwinLogFilterRegexActivity.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/TestDarwinLogFilterRegexActivity.py @@ -60,11 +60,12 @@ class TestDarwinLogFilterRegexActivity(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_activity_partial_match(self): @@ -77,11 +78,12 @@ class TestDarwinLogFilterRegexActivity(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that activity. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_full_match(self): @@ -94,11 +96,12 @@ class TestDarwinLogFilterRegexActivity(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via activity rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_activity_partial_match(self): @@ -111,11 +114,12 @@ class TestDarwinLogFilterRegexActivity(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via activity rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") - + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_activity_second_rule(self): @@ -131,7 +135,9 @@ class TestDarwinLogFilterRegexActivity(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the activity of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py index 0389f624e61..6786d6f009b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py @@ -60,10 +60,12 @@ class TestDarwinLogFilterRegexCategory(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that category. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_category_partial_match(self): @@ -76,10 +78,12 @@ class TestDarwinLogFilterRegexCategory(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that category. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_category_full_match(self): @@ -92,10 +96,12 @@ class TestDarwinLogFilterRegexCategory(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via category rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_category_partial_match(self): @@ -108,10 +114,12 @@ class TestDarwinLogFilterRegexCategory(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via category rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_category_second_rule(self): @@ -127,7 +135,9 @@ class TestDarwinLogFilterRegexCategory(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the category of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/TestDarwinLogFilterRegexSubsystem.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/TestDarwinLogFilterRegexSubsystem.py index 2134977aa94..28677b54c75 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/TestDarwinLogFilterRegexSubsystem.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/TestDarwinLogFilterRegexSubsystem.py @@ -77,10 +77,12 @@ class TestDarwinLogFilterRegexSubsystem(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that subsystem. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_subsystem_partial_match(self): @@ -93,10 +95,12 @@ class TestDarwinLogFilterRegexSubsystem(darwin_log.DarwinLogTestBase): # We should only see the second log message as we only accept # that subsystem. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_subsystem_full_match(self): @@ -109,10 +113,12 @@ class TestDarwinLogFilterRegexSubsystem(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via subsystem rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_reject_subsystem_partial_match(self): @@ -125,10 +131,12 @@ class TestDarwinLogFilterRegexSubsystem(darwin_log.DarwinLogTestBase): # We should only see the second log message as we rejected the first # via subsystem rejection. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_filter_accept_subsystem_second_rule(self): @@ -144,7 +152,9 @@ class TestDarwinLogFilterRegexSubsystem(darwin_log.DarwinLogTestBase): # the first filter doesn't match any, and the second filter matches # the subsystem of the second log message. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) == "sub2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/TestDarwinLogMessageFormat.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/TestDarwinLogMessageFormat.py index c5d98ae208e..65822cab430 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/TestDarwinLogMessageFormat.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/TestDarwinLogMessageFormat.py @@ -64,9 +64,8 @@ class TestDarwinLogMessageFormat(darwin_log.DarwinLogTestBase): # content. self.assertIsNotNone(self.child.match) self.assertFalse((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) != ""), - "we should not have seen a header") - + (self.child.match.group(1) != ""), + "we should not have seen a header") @decorators.skipUnlessDarwin def test_display_with_header_works(self): @@ -83,8 +82,8 @@ class TestDarwinLogMessageFormat(darwin_log.DarwinLogTestBase): # content. self.assertIsNotNone(self.child.match) self.assertTrue((len(self.child.match.groups()) > 0) and - (self.child.match.group(1) != ""), - "we should have printed a header") + (self.child.match.group(1) != ""), + "we should have printed a header") def assert_header_contains_timestamp(self, header): fields = header.split(',') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/TestDarwinLogSourceDebug.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/TestDarwinLogSourceDebug.py index d44437cd14b..85b8e30f606 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/TestDarwinLogSourceDebug.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/TestDarwinLogSourceDebug.py @@ -60,10 +60,12 @@ class TestDarwinLogSourceDebug(darwin_log.DarwinLogTestBase): # We should only see the second log message as the first is a # debug-level message and we're not including debug-level messages. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_source_explicitly_include_debug(self): diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/TestDarwinLogSourceInfo.py b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/TestDarwinLogSourceInfo.py index d47d85a27fd..44348374636 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/TestDarwinLogSourceInfo.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/TestDarwinLogSourceInfo.py @@ -61,10 +61,12 @@ class TestDarwinLogSourceInfo(darwin_log.DarwinLogTestBase): # We should only see the second log message as the first is an # info-level message and we're not including debug-level messages. self.assertIsNotNone(self.child.match) - self.assertTrue((len(self.child.match.groups()) > 1) and - (self.child.match.group(2) == "cat2"), - "first log line should not be present, second log line " - "should be") + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") @decorators.skipUnlessDarwin def test_source_include_info_level(self): diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py index 54272e59333..0459058f3ae 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DataFormatterBoolRefPtr(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -33,14 +34,15 @@ class DataFormatterBoolRefPtr(TestBase): """Test the formatters we use for BOOL& and BOOL* in Objective-C.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -56,23 +58,24 @@ class DataFormatterBoolRefPtr(TestBase): # Now check that we use the right summary for BOOL& self.expect('frame variable yes_ref', - substrs = ['YES']) + substrs=['YES']) self.expect('frame variable no_ref', - substrs = ['NO']) - if not(isiOS): self.expect('frame variable unset_ref', substrs = ['12']) - + substrs=['NO']) + if not(isiOS): + self.expect('frame variable unset_ref', substrs=['12']) # Now check that we use the right summary for BOOL* self.expect('frame variable yes_ptr', - substrs = ['YES']) + substrs=['YES']) self.expect('frame variable no_ptr', - substrs = ['NO']) - if not(isiOS): self.expect('frame variable unset_ptr', substrs = ['12']) - + substrs=['NO']) + if not(isiOS): + self.expect('frame variable unset_ptr', substrs=['12']) # Now check that we use the right summary for BOOL self.expect('frame variable yes', - substrs = ['YES']) + substrs=['YES']) self.expect('frame variable no', - substrs = ['NO']) - if not(isiOS): self.expect('frame variable unset', substrs = ['12']) + substrs=['NO']) + if not(isiOS): + self.expect('frame variable unset', substrs=['12']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py index 914c5260ac2..9b430c726e1 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CompactVectorsFormattingTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -28,14 +29,15 @@ class CompactVectorsFormattingTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -45,15 +47,17 @@ class CompactVectorsFormattingTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('frame variable', - substrs = ['(vFloat) valueFL = (1.25, 0, 0.25, 0)', - '(int16_t [8]) valueI16 = (1, 0, 4, 0, 0, 1, 0, 4)', - '(int32_t [4]) valueI32 = (1, 0, 4, 0)', - '(vDouble) valueDL = (1.25, 2.25)', - '(vUInt8) valueU8 = (0x01, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)', - '(vUInt16) valueU16 = (1, 0, 4, 0, 0, 1, 0, 4)', - '(vUInt32) valueU32 = (1, 2, 3, 4)', - "(vSInt8) valueS8 = (1, 0, 4, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0)", - '(vSInt16) valueS16 = (1, 0, 4, 0, 0, 1, 0, 4)', - '(vSInt32) valueS32 = (4, 3, 2, 1)', - '(vBool32) valueBool32 = (0, 1, 0, 1)']) + self.expect( + 'frame variable', + substrs=[ + '(vFloat) valueFL = (1.25, 0, 0.25, 0)', + '(int16_t [8]) valueI16 = (1, 0, 4, 0, 0, 1, 0, 4)', + '(int32_t [4]) valueI32 = (1, 0, 4, 0)', + '(vDouble) valueDL = (1.25, 2.25)', + '(vUInt8) valueU8 = (0x01, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)', + '(vUInt16) valueU16 = (1, 0, 4, 0, 0, 1, 0, 4)', + '(vUInt32) valueU32 = (1, 2, 3, 4)', + "(vSInt8) valueS8 = (1, 0, 4, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0)", + '(vSInt16) valueS16 = (1, 0, 4, 0, 0, 1, 0, 4)', + '(vSInt32) valueS32 = (4, 3, 2, 1)', + '(vBool32) valueBool32 = (0, 1, 0, 1)']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py index 8166d1540ca..050f5236445 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class AdvDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,103 +27,116 @@ class AdvDataFormatterTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): self.runCmd('type format clear', check=False) self.runCmd('type summary clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) - + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("type summary add --summary-string \"pippo\" \"i_am_cool\"") - self.runCmd("type summary add --summary-string \"pluto\" -x \"i_am_cool[a-z]*\"") + self.runCmd( + "type summary add --summary-string \"pluto\" -x \"i_am_cool[a-z]*\"") self.expect("frame variable cool_boy", - substrs = ['pippo']) + substrs=['pippo']) self.expect("frame variable cooler_boy", - substrs = ['pluto']) + substrs=['pluto']) self.runCmd("type summary delete i_am_cool") - + self.expect("frame variable cool_boy", - substrs = ['pluto']) + substrs=['pluto']) self.runCmd("type summary clear") - - self.runCmd("type summary add --summary-string \"${var[]}\" -x \"int \\[[0-9]\\]") + + self.runCmd( + "type summary add --summary-string \"${var[]}\" -x \"int \\[[0-9]\\]") self.expect("frame variable int_array", - substrs = ['1,2,3,4,5']) + substrs=['1,2,3,4,5']) # this will fail if we don't do [] as regex correctly - self.runCmd('type summary add --summary-string "${var[].integer}" "i_am_cool[]') - + self.runCmd( + 'type summary add --summary-string "${var[].integer}" "i_am_cool[]') + self.expect("frame variable cool_array", - substrs = ['1,1,1,1,6']) + substrs=['1,1,1,1,6']) self.runCmd("type summary clear") - - self.runCmd("type summary add --summary-string \"${var[1-0]%x}\" \"int\"") - + + self.runCmd( + "type summary add --summary-string \"${var[1-0]%x}\" \"int\"") + self.expect("frame variable iAmInt", - substrs = ['01']) - - self.runCmd("type summary add --summary-string \"${var[0-1]%x}\" \"int\"") - + substrs=['01']) + + self.runCmd( + "type summary add --summary-string \"${var[0-1]%x}\" \"int\"") + self.expect("frame variable iAmInt", - substrs = ['01']) + substrs=['01']) self.runCmd("type summary clear") self.runCmd("type summary add --summary-string \"${var[0-1]%x}\" int") - self.runCmd("type summary add --summary-string \"${var[0-31]%x}\" float") - + self.runCmd( + "type summary add --summary-string \"${var[0-31]%x}\" float") + self.expect("frame variable *pointer", - substrs = ['0x', - '2']) + substrs=['0x', + '2']) - # check fix for <rdar://problem/11338654> LLDB crashes when using a "type summary" that uses bitfields with no format + # check fix for <rdar://problem/11338654> LLDB crashes when using a + # "type summary" that uses bitfields with no format self.runCmd("type summary add --summary-string \"${var[0-1]}\" int") self.expect("frame variable iAmInt", - substrs = ['9 1']) + substrs=['9 1']) self.expect("frame variable cool_array[3].floating", - substrs = ['0x']) - - self.runCmd("type summary add --summary-string \"low bits are ${*var[0-1]} tgt is ${*var}\" \"int *\"") + substrs=['0x']) + + self.runCmd( + "type summary add --summary-string \"low bits are ${*var[0-1]} tgt is ${*var}\" \"int *\"") self.expect("frame variable pointer", - substrs = ['low bits are', - 'tgt is 6']) + substrs=['low bits are', + 'tgt is 6']) - self.expect("frame variable int_array --summary-string \"${*var[0-1]}\"", - substrs = ['3']) + self.expect( + "frame variable int_array --summary-string \"${*var[0-1]}\"", + substrs=['3']) self.runCmd("type summary clear") - - self.runCmd('type summary add --summary-string \"${var[0-1]}\" -x \"int \[[0-9]\]\"') + + self.runCmd( + 'type summary add --summary-string \"${var[0-1]}\" -x \"int \[[0-9]\]\"') self.expect("frame variable int_array", - substrs = ['1,2']) + substrs=['1,2']) - self.runCmd('type summary add --summary-string \"${var[0-1]}\" "int []"') + self.runCmd( + 'type summary add --summary-string \"${var[0-1]}\" "int []"') self.expect("frame variable int_array", - substrs = ['1,2']) + substrs=['1,2']) self.runCmd("type summary clear") @@ -130,156 +144,179 @@ class AdvDataFormatterTestCase(TestBase): self.runCmd("type summary add -c i_am_cool") self.expect("frame variable cool_array", - substrs = ['[0]', - '[1]', - '[2]', - '[3]', - '[4]', - 'integer', - 'character', - 'floating']) - - self.runCmd("type summary add --summary-string \"int = ${*var.int_pointer}, float = ${*var.float_pointer}\" IWrapPointers") + substrs=['[0]', + '[1]', + '[2]', + '[3]', + '[4]', + 'integer', + 'character', + 'floating']) + + self.runCmd( + "type summary add --summary-string \"int = ${*var.int_pointer}, float = ${*var.float_pointer}\" IWrapPointers") self.expect("frame variable wrapper", - substrs = ['int = 4', - 'float = 1.1']) + substrs=['int = 4', + 'float = 1.1']) + + self.runCmd( + "type summary add --summary-string \"low bits = ${*var.int_pointer[2]}\" IWrapPointers -p") - self.runCmd("type summary add --summary-string \"low bits = ${*var.int_pointer[2]}\" IWrapPointers -p") - self.expect("frame variable wrapper", - substrs = ['low bits = 1']) - + substrs=['low bits = 1']) + self.expect("frame variable *wrap_pointer", - substrs = ['low bits = 1']) + substrs=['low bits = 1']) self.runCmd("type summary clear") - self.expect("frame variable int_array --summary-string \"${var[0][0-2]%hex}\"", - substrs = ['0x', - '7']) + self.expect( + "frame variable int_array --summary-string \"${var[0][0-2]%hex}\"", + substrs=[ + '0x', + '7']) self.runCmd("type summary clear") - self.runCmd("type summary add --summary-string \"${*var[].x[0-3]%hex} is a bitfield on a set of integers\" -x \"SimpleWithPointers \[[0-9]\]\"") + self.runCmd( + "type summary add --summary-string \"${*var[].x[0-3]%hex} is a bitfield on a set of integers\" -x \"SimpleWithPointers \[[0-9]\]\"") - self.expect("frame variable couple --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\"", - substrs = ['1 are low bits of integer 9.', - 'If I pretend it is an array I get [9,']) + self.expect( + "frame variable couple --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\"", + substrs=[ + '1 are low bits of integer 9.', + 'If I pretend it is an array I get [9,']) # if the summary has an error, we still display the value - self.expect("frame variable couple --summary-string \"${*var.sp.foo[0-2]\"", - substrs = ['(Couple) couple = {','x = 0x','y = 0x','z = 0x','s = 0x']) - - - self.runCmd("type summary add --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\" Couple") + self.expect( + "frame variable couple --summary-string \"${*var.sp.foo[0-2]\"", + substrs=[ + '(Couple) couple = {', + 'x = 0x', + 'y = 0x', + 'z = 0x', + 's = 0x']) + + self.runCmd( + "type summary add --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\" Couple") self.expect("frame variable sparray", - substrs = ['[0x0000000f,0x0000000c,0x00000009]']) - - # check that we can format a variable in a summary even if a format is defined for its datatype + substrs=['[0x0000000f,0x0000000c,0x00000009]']) + + # check that we can format a variable in a summary even if a format is + # defined for its datatype self.runCmd("type format add -f hex int") - self.runCmd("type summary add --summary-string \"x=${var.x%d}\" Simple") + self.runCmd( + "type summary add --summary-string \"x=${var.x%d}\" Simple") self.expect("frame variable a_simple_object", - substrs = ['x=3']) + substrs=['x=3']) self.expect("frame variable a_simple_object", matching=False, - substrs = ['0x0']) + substrs=['0x0']) # now check that the default is applied if we do not hand out a format self.runCmd("type summary add --summary-string \"x=${var.x}\" Simple") self.expect("frame variable a_simple_object", matching=False, - substrs = ['x=3']) + substrs=['x=3']) self.expect("frame variable a_simple_object", matching=True, - substrs = ['x=0x00000003']) + substrs=['x=0x00000003']) # check that we can correctly cap the number of children shown self.runCmd("settings set target.max-children-count 5") self.expect('frame variable a_long_guy', matching=True, - substrs = ['a_1', - 'b_1', - 'c_1', - 'd_1', - 'e_1', - '...']) + substrs=['a_1', + 'b_1', + 'c_1', + 'd_1', + 'e_1', + '...']) # check that no further stuff is printed (not ALL values are checked!) self.expect('frame variable a_long_guy', matching=False, - substrs = ['f_1', - 'g_1', - 'h_1', - 'i_1', - 'j_1', - 'q_1', - 'a_2', - 'f_2', - 't_2', - 'w_2']) + substrs=['f_1', + 'g_1', + 'h_1', + 'i_1', + 'j_1', + 'q_1', + 'a_2', + 'f_2', + 't_2', + 'w_2']) self.runCmd("settings set target.max-children-count 1") self.expect('frame variable a_long_guy', matching=True, - substrs = ['a_1', - '...']) + substrs=['a_1', + '...']) self.expect('frame variable a_long_guy', matching=False, - substrs = ['b_1', - 'c_1', - 'd_1', - 'e_1']) + substrs=['b_1', + 'c_1', + 'd_1', + 'e_1']) self.expect('frame variable a_long_guy', matching=False, - substrs = ['f_1', - 'g_1', - 'h_1', - 'i_1', - 'j_1', - 'q_1', - 'a_2', - 'f_2', - 't_2', - 'w_2']) + substrs=['f_1', + 'g_1', + 'h_1', + 'i_1', + 'j_1', + 'q_1', + 'a_2', + 'f_2', + 't_2', + 'w_2']) self.runCmd("settings set target.max-children-count 30") self.expect('frame variable a_long_guy', matching=True, - substrs = ['a_1', - 'b_1', - 'c_1', - 'd_1', - 'e_1', - 'z_1', - 'a_2', - 'b_2', - 'c_2', - 'd_2', - '...']) + substrs=['a_1', + 'b_1', + 'c_1', + 'd_1', + 'e_1', + 'z_1', + 'a_2', + 'b_2', + 'c_2', + 'd_2', + '...']) self.expect('frame variable a_long_guy', matching=False, - substrs = ['e_2', - 'n_2', - 'r_2', - 'i_2', - 'k_2', - 'o_2']) - - # override the cap - self.expect('frame variable a_long_guy --show-all-children', matching=True, - substrs = ['a_1', - 'b_1', - 'c_1', - 'd_1', - 'e_1', - 'z_1', - 'a_2', - 'b_2', - 'c_2', - 'd_2']) - self.expect('frame variable a_long_guy --show-all-children', matching=True, - substrs = ['e_2', - 'n_2', - 'r_2', - 'i_2', - 'k_2', - 'o_2']) - self.expect('frame variable a_long_guy --show-all-children', matching=False, - substrs = ['...']) + substrs=['e_2', + 'n_2', + 'r_2', + 'i_2', + 'k_2', + 'o_2']) + + # override the cap + self.expect( + 'frame variable a_long_guy --show-all-children', + matching=True, + substrs=[ + 'a_1', + 'b_1', + 'c_1', + 'd_1', + 'e_1', + 'z_1', + 'a_2', + 'b_2', + 'c_2', + 'd_2']) + self.expect( + 'frame variable a_long_guy --show-all-children', + matching=True, + substrs=[ + 'e_2', + 'n_2', + 'r_2', + 'i_2', + 'k_2', + 'o_2']) + self.expect( + 'frame variable a_long_guy --show-all-children', + matching=False, + substrs=['...']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py index f8209f03d0c..2d01eb79e18 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CategoriesDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,14 +28,15 @@ class CategoriesDataFormatterTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case (most of these categories do not @@ -46,286 +48,312 @@ class CategoriesDataFormatterTestCase(TestBase): self.runCmd('type category delete Category2', check=False) self.runCmd('type category delete NewCategory', check=False) self.runCmd("type category delete CircleCategory", check=False) - self.runCmd("type category delete RectangleStarCategory", check=False) + self.runCmd( + "type category delete RectangleStarCategory", + check=False) self.runCmd("type category delete BaseCategory", check=False) - # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # Add a summary to a new category and check that it works - self.runCmd("type summary add Rectangle --summary-string \"ARectangle\" -w NewCategory") + self.runCmd( + "type summary add Rectangle --summary-string \"ARectangle\" -w NewCategory") self.expect("frame variable r1 r2 r3", matching=False, - substrs = ['r1 = ARectangle', - 'r2 = ARectangle', - 'r3 = ARectangle']) - + substrs=['r1 = ARectangle', + 'r2 = ARectangle', + 'r3 = ARectangle']) + self.runCmd("type category enable NewCategory") self.expect("frame variable r1 r2 r3", matching=True, - substrs = ['r1 = ARectangle', - 'r2 = ARectangle', - 'r3 = ARectangle']) - + substrs=['r1 = ARectangle', + 'r2 = ARectangle', + 'r3 = ARectangle']) + # Disable the category and check that the old stuff is there self.runCmd("type category disable NewCategory") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = {', - 'r2 = {', - 'r3 = {']) + substrs=['r1 = {', + 'r2 = {', + 'r3 = {']) # Re-enable the category and check that it works self.runCmd("type category enable NewCategory") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = ARectangle', - 'r2 = ARectangle', - 'r3 = ARectangle']) + substrs=['r1 = ARectangle', + 'r2 = ARectangle', + 'r3 = ARectangle']) # Delete the category and the old stuff should be there self.runCmd("type category delete NewCategory") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = {', - 'r2 = {', - 'r3 = {']) - - # Add summaries to two different categories and check that we can switch - self.runCmd("type summary add --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle -w Category1") + substrs=['r1 = {', + 'r2 = {', + 'r3 = {']) + + # Add summaries to two different categories and check that we can + # switch + self.runCmd( + "type summary add --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle -w Category1") self.runCmd("type summary add --python-script \"return 'Area = ' + str( int(valobj.GetChildMemberWithName('w').GetValue()) * int(valobj.GetChildMemberWithName('h').GetValue()) );\" Rectangle -w Category2") # check that enable A B is the same as enable B enable A self.runCmd("type category enable Category1 Category2") - + self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) self.runCmd("type category disable Category1") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Area = ', - 'r2 = Area = ', - 'r3 = Area = ']) + substrs=['r1 = Area = ', + 'r2 = Area = ', + 'r3 = Area = ']) # switch again self.runCmd("type category enable Category1") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) # Re-enable the category and show that the preference is persisted self.runCmd("type category disable Category2") self.runCmd("type category enable Category2") - + self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Area = ', - 'r2 = Area = ', - 'r3 = Area = ']) + substrs=['r1 = Area = ', + 'r2 = Area = ', + 'r3 = Area = ']) # Now delete the favorite summary self.runCmd("type summary delete Rectangle -w Category2") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) # Delete the summary from the default category (that does not have it) self.runCmd("type summary delete Rectangle", check=False) self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) # Now add another summary to another category and switch back and forth self.runCmd("type category delete Category1 Category2") - self.runCmd("type summary add Rectangle -w Category1 --summary-string \"Category1\"") - self.runCmd("type summary add Rectangle -w Category2 --summary-string \"Category2\"") + self.runCmd( + "type summary add Rectangle -w Category1 --summary-string \"Category1\"") + self.runCmd( + "type summary add Rectangle -w Category2 --summary-string \"Category2\"") self.runCmd("type category enable Category2") self.runCmd("type category enable Category1") - + self.runCmd("type summary list -w Category1") - self.expect("type summary list -w NoSuchCategoryHere", substrs=['no matching results found']) - + self.expect("type summary list -w NoSuchCategoryHere", + substrs=['no matching results found']) + self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Category1', - 'r2 = Category1', - 'r3 = Category1']) + substrs=['r1 = Category1', + 'r2 = Category1', + 'r3 = Category1']) self.runCmd("type category disable Category1") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Category2', - 'r2 = Category2', - 'r3 = Category2']) + substrs=['r1 = Category2', + 'r2 = Category2', + 'r3 = Category2']) # Check that re-enabling an enabled category works self.runCmd("type category enable Category1") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Category1', - 'r2 = Category1', - 'r3 = Category1']) + substrs=['r1 = Category1', + 'r2 = Category1', + 'r3 = Category1']) self.runCmd("type category delete Category1") self.runCmd("type category delete Category2") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = {', - 'r2 = {', - 'r3 = {']) - - # Check that multiple summaries can go into one category - self.runCmd("type summary add -w Category1 --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle") - self.runCmd("type summary add -w Category1 --summary-string \"Radius = ${var.r}\" Circle") - + substrs=['r1 = {', + 'r2 = {', + 'r3 = {']) + + # Check that multiple summaries can go into one category + self.runCmd( + "type summary add -w Category1 --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle") + self.runCmd( + "type summary add -w Category1 --summary-string \"Radius = ${var.r}\" Circle") + self.runCmd("type category enable Category1") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) self.expect("frame variable c1 c2 c3", - substrs = ['c1 = Radius = ', - 'c2 = Radius = ', - 'c3 = Radius = ']) + substrs=['c1 = Radius = ', + 'c2 = Radius = ', + 'c3 = Radius = ']) self.runCmd("type summary delete Circle -w Category1") - + self.expect("frame variable c1 c2 c3", - substrs = ['c1 = {', - 'c2 = {', - 'c3 = {']) + substrs=['c1 = {', + 'c2 = {', + 'c3 = {']) # Add a regex based summary to a category - self.runCmd("type summary add -w Category1 --summary-string \"Radius = ${var.r}\" -x Circle") + self.runCmd( + "type summary add -w Category1 --summary-string \"Radius = ${var.r}\" -x Circle") self.expect("frame variable r1 r2 r3", - substrs = ['r1 = Width = ', - 'r2 = Width = ', - 'r3 = Width = ']) + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) self.expect("frame variable c1 c2 c3", - substrs = ['c1 = Radius = ', - 'c2 = Radius = ', - 'c3 = Radius = ']) + substrs=['c1 = Radius = ', + 'c2 = Radius = ', + 'c3 = Radius = ']) # Delete it self.runCmd("type summary delete Circle -w Category1") self.expect("frame variable c1 c2 c3", - substrs = ['c1 = {', - 'c2 = {', - 'c3 = {']) - - # Change a summary inside a category and check that the change is reflected - self.runCmd("type summary add Circle -w Category1 --summary-string \"summary1\"") + substrs=['c1 = {', + 'c2 = {', + 'c3 = {']) + + # Change a summary inside a category and check that the change is + # reflected + self.runCmd( + "type summary add Circle -w Category1 --summary-string \"summary1\"") self.expect("frame variable c1 c2 c3", - substrs = ['c1 = summary1', - 'c2 = summary1', - 'c3 = summary1']) + substrs=['c1 = summary1', + 'c2 = summary1', + 'c3 = summary1']) + + self.runCmd( + "type summary add Circle -w Category1 --summary-string \"summary2\"") - self.runCmd("type summary add Circle -w Category1 --summary-string \"summary2\"") - self.expect("frame variable c1 c2 c3", - substrs = ['c1 = summary2', - 'c2 = summary2', - 'c3 = summary2']) + substrs=['c1 = summary2', + 'c2 = summary2', + 'c3 = summary2']) # Check that our order of priority works. Start by clearing categories self.runCmd("type category delete Category1") - self.runCmd("type summary add Shape -w BaseCategory --summary-string \"AShape\"") + self.runCmd( + "type summary add Shape -w BaseCategory --summary-string \"AShape\"") self.runCmd("type category enable BaseCategory") self.expect("print (Shape*)&c1", - substrs = ['AShape']) + substrs=['AShape']) self.expect("print (Shape*)&r1", - substrs = ['AShape']) + substrs=['AShape']) self.expect("print (Shape*)c_ptr", - substrs = ['AShape']) + substrs=['AShape']) self.expect("print (Shape*)r_ptr", - substrs = ['AShape']) + substrs=['AShape']) - self.runCmd("type summary add Circle -w CircleCategory --summary-string \"ACircle\"") - self.runCmd("type summary add Rectangle -w RectangleCategory --summary-string \"ARectangle\"") + self.runCmd( + "type summary add Circle -w CircleCategory --summary-string \"ACircle\"") + self.runCmd( + "type summary add Rectangle -w RectangleCategory --summary-string \"ARectangle\"") self.runCmd("type category enable CircleCategory") self.expect("frame variable c1", - substrs = ['ACircle']) + substrs=['ACircle']) self.expect("frame variable c_ptr", - substrs = ['ACircle']) + substrs=['ACircle']) - self.runCmd("type summary add \"Rectangle *\" -w RectangleStarCategory --summary-string \"ARectangleStar\"") + self.runCmd( + "type summary add \"Rectangle *\" -w RectangleStarCategory --summary-string \"ARectangleStar\"") self.runCmd("type category enable RectangleStarCategory") self.expect("frame variable c1 r1 c_ptr r_ptr", - substrs = ['ACircle', - 'ARectangleStar']) + substrs=['ACircle', + 'ARectangleStar']) self.runCmd("type category enable RectangleCategory") self.expect("frame variable c1 r1 c_ptr r_ptr", - substrs = ['ACircle', - 'ACircle', - 'ARectangle']) + substrs=['ACircle', + 'ACircle', + 'ARectangle']) # Check that abruptly deleting an enabled category does not crash us self.runCmd("type category delete RectangleCategory") self.expect("frame variable c1 r1 c_ptr r_ptr", - substrs = ['ACircle', - '(Rectangle) r1 = ', 'w = 5', 'h = 6', - 'ACircle', - 'ARectangleStar']) - + substrs=['ACircle', + '(Rectangle) r1 = ', 'w = 5', 'h = 6', + 'ACircle', + 'ARectangleStar']) + # check that list commands work self.expect("type category list", - substrs = ['RectangleStarCategory (enabled)']) + substrs=['RectangleStarCategory (enabled)']) self.expect("type summary list", - substrs = ['ARectangleStar']) + substrs=['ARectangleStar']) # Disable a category and check that it fallsback self.runCmd("type category disable CircleCategory") - + # check that list commands work self.expect("type category list", - substrs = ['CircleCategory (disabled']) + substrs=['CircleCategory (disabled']) self.expect("frame variable c1 r_ptr", - substrs = ['AShape', - 'ARectangleStar']) + substrs=['AShape', + 'ARectangleStar']) # check that filters work into categories - self.runCmd("type filter add Rectangle --child w --category RectangleCategory") + self.runCmd( + "type filter add Rectangle --child w --category RectangleCategory") self.runCmd("type category enable RectangleCategory") - self.runCmd("type summary add Rectangle --category RectangleCategory --summary-string \" \" -e") + self.runCmd( + "type summary add Rectangle --category RectangleCategory --summary-string \" \" -e") self.expect('frame variable r2', - substrs = ['w = 9']) + substrs=['w = 9']) self.runCmd("type summary add Rectangle --summary-string \" \" -e") self.expect('frame variable r2', matching=False, - substrs = ['h = 16']) + substrs=['h = 16']) # Now delete all categories - self.runCmd("type category delete CircleCategory RectangleStarCategory BaseCategory RectangleCategory") + self.runCmd( + "type category delete CircleCategory RectangleStarCategory BaseCategory RectangleCategory") # check that a deleted category with filter does not blow us up self.expect('frame variable r2', - substrs = ['w = 9', - 'h = 16']) + substrs=['w = 9', + 'h = 16']) # and also validate that one can print formatters for a language - self.expect('type summary list -l c++', substrs=['vector', 'map', 'list', 'string']) + self.expect( + 'type summary list -l c++', + substrs=[ + 'vector', + 'map', + 'list', + 'string']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py index 99443a04f67..0518a75051b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CppDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,24 +23,27 @@ class CppDataFormatterTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24462: Data formatters have problems on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24462: Data formatters have problems on Windows") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) self.expect("frame variable", - substrs = ['(Speed) SPILookHex = 5.55' # Speed by default is 5.55. - ]); + substrs=['(Speed) SPILookHex = 5.55' # Speed by default is 5.55. + ]) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -57,210 +61,238 @@ class CppDataFormatterTestCase(TestBase): # The type format list should show our custom formats. self.expect("type format list", - substrs = ['RealNumber', - 'Speed', - 'BitField', - 'Type1', - 'Type2']) + substrs=['RealNumber', + 'Speed', + 'BitField', + 'Type1', + 'Type2']) self.expect("frame variable", - patterns = ['\(Speed\) SPILookHex = 0x[0-9a-f]+' # Speed should look hex-ish now. - ]); - + patterns=['\(Speed\) SPILookHex = 0x[0-9a-f]+' # Speed should look hex-ish now. + ]) + # gcc4.2 on Mac OS X skips typedef chains in the DWARF output - if self.getCompiler() in ['clang', 'llvm-gcc']: + if self.getCompiler() in ['clang', 'llvm-gcc']: self.expect("frame variable", - patterns = ['\(SignalMask\) SMILookHex = 0x[0-9a-f]+' # SignalMask should look hex-ish now. - ]); + patterns=['\(SignalMask\) SMILookHex = 0x[0-9a-f]+' # SignalMask should look hex-ish now. + ]) self.expect("frame variable", matching=False, - patterns = ['\(Type4\) T4ILookChar = 0x[0-9a-f]+' # Type4 should NOT look hex-ish now. - ]); - + patterns=['\(Type4\) T4ILookChar = 0x[0-9a-f]+' # Type4 should NOT look hex-ish now. + ]) + # Now let's delete the 'Speed' custom format. self.runCmd("type format delete Speed") # The type format list should not show 'Speed' at this point. self.expect("type format list", matching=False, - substrs = ['Speed']) + substrs=['Speed']) # Delete type format for 'Speed', we should expect an error message. self.expect("type format delete Speed", error=True, - substrs = ['no custom formatter for Speed']) - - self.runCmd("type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v") - + substrs=['no custom formatter for Speed']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v") + self.expect("frame variable strarr", - substrs = ['arr = "Hello world!"']) - + substrs=['arr = "Hello world!"']) + self.runCmd("type summary clear") - - self.runCmd("type summary add --summary-string \"ptr = ${var%s}\" \"char *\" -v") - + + self.runCmd( + "type summary add --summary-string \"ptr = ${var%s}\" \"char *\" -v") + self.expect("frame variable strptr", - substrs = ['ptr = "Hello world!"']) - - self.runCmd("type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v") - + substrs=['ptr = "Hello world!"']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v") + self.expect("frame variable strarr", - substrs = ['arr = "Hello world!']) + substrs=['arr = "Hello world!']) - # check that rdar://problem/10011145 (Standard summary format for char[] doesn't work as the result of "expr".) is solved + # check that rdar://problem/10011145 (Standard summary format for + # char[] doesn't work as the result of "expr".) is solved self.expect("p strarr", - substrs = ['arr = "Hello world!']) + substrs=['arr = "Hello world!']) self.expect("frame variable strptr", - substrs = ['ptr = "Hello world!"']) + substrs=['ptr = "Hello world!"']) self.expect("p strptr", - substrs = ['ptr = "Hello world!"']) + substrs=['ptr = "Hello world!"']) - self.expect("p (char*)\"1234567890123456789012345678901234567890123456789012345678901234ABC\"", - substrs = ['(char *) $', ' = ptr = ', ' "1234567890123456789012345678901234567890123456789012345678901234ABC"']) + self.expect( + "p (char*)\"1234567890123456789012345678901234567890123456789012345678901234ABC\"", + substrs=[ + '(char *) $', + ' = ptr = ', + ' "1234567890123456789012345678901234567890123456789012345678901234ABC"']) self.runCmd("type summary add -c Point") - + self.expect("frame variable iAmSomewhere", - substrs = ['x = 4', - 'y = 6']) - + substrs=['x = 4', + 'y = 6']) + self.expect("type summary list", - substrs = ['Point', - 'one-line']) + substrs=['Point', + 'one-line']) self.runCmd("type summary add --summary-string \"y=${var.y%x}\" Point") self.expect("frame variable iAmSomewhere", - substrs = ['y=0x']) - - self.runCmd("type summary add --summary-string \"y=${var.y},x=${var.x}\" Point") - + substrs=['y=0x']) + + self.runCmd( + "type summary add --summary-string \"y=${var.y},x=${var.x}\" Point") + self.expect("frame variable iAmSomewhere", - substrs = ['y=6', - 'x=4']) + substrs=['y=6', + 'x=4']) self.runCmd("type summary add --summary-string \"hello\" Point -e") self.expect("type summary list", - substrs = ['Point', - 'show children']) - + substrs=['Point', + 'show children']) + self.expect("frame variable iAmSomewhere", - substrs = ['hello', - 'x = 4', - '}']) + substrs=['hello', + 'x = 4', + '}']) - self.runCmd("type summary add --summary-string \"Sign: ${var[31]%B} Exponent: ${var[23-30]%x} Mantissa: ${var[0-22]%u}\" ShowMyGuts") + self.runCmd( + "type summary add --summary-string \"Sign: ${var[31]%B} Exponent: ${var[23-30]%x} Mantissa: ${var[0-22]%u}\" ShowMyGuts") self.expect("frame variable cool_pointer->floating", - substrs = ['Sign: true', - 'Exponent: 0x', - '80']) + substrs=['Sign: true', + 'Exponent: 0x', + '80']) self.runCmd("type summary add --summary-string \"a test\" i_am_cool") self.expect("frame variable cool_pointer", - substrs = ['a test']) + substrs=['a test']) + + self.runCmd( + "type summary add --summary-string \"a test\" i_am_cool --skip-pointers") - self.runCmd("type summary add --summary-string \"a test\" i_am_cool --skip-pointers") - self.expect("frame variable cool_pointer", - substrs = ['a test'], - matching = False) + substrs=['a test'], + matching=False) - self.runCmd("type summary add --summary-string \"${var[1-3]}\" \"int [5]\"") + self.runCmd( + "type summary add --summary-string \"${var[1-3]}\" \"int [5]\"") self.expect("frame variable int_array", - substrs = ['2', - '3', - '4']) + substrs=['2', + '3', + '4']) self.runCmd("type summary clear") - self.runCmd("type summary add --summary-string \"${var[0-2].integer}\" \"i_am_cool *\"") - self.runCmd("type summary add --summary-string \"${var[2-4].integer}\" \"i_am_cool [5]\"") + self.runCmd( + "type summary add --summary-string \"${var[0-2].integer}\" \"i_am_cool *\"") + self.runCmd( + "type summary add --summary-string \"${var[2-4].integer}\" \"i_am_cool [5]\"") self.expect("frame variable cool_array", - substrs = ['1,1,6']) + substrs=['1,1,6']) self.expect("frame variable cool_pointer", - substrs = ['3,0,0']) + substrs=['3,0,0']) # test special symbols for formatting variables into summaries - self.runCmd("type summary add --summary-string \"cool object @ ${var%L}\" i_am_cool") + self.runCmd( + "type summary add --summary-string \"cool object @ ${var%L}\" i_am_cool") self.runCmd("type summary delete \"i_am_cool [5]\"") - + # this test might fail if the compiler tries to store # these values into registers.. hopefully this is not # going to be the case self.expect("frame variable cool_array", - substrs = ['[0] = cool object @ 0x', - '[1] = cool object @ 0x', - '[2] = cool object @ 0x', - '[3] = cool object @ 0x', - '[4] = cool object @ 0x']) - - # test getting similar output by exploiting ${var} = 'type @ location' for aggregates + substrs=['[0] = cool object @ 0x', + '[1] = cool object @ 0x', + '[2] = cool object @ 0x', + '[3] = cool object @ 0x', + '[4] = cool object @ 0x']) + + # test getting similar output by exploiting ${var} = 'type @ location' + # for aggregates self.runCmd("type summary add --summary-string \"${var}\" i_am_cool") - + # this test might fail if the compiler tries to store # these values into registers.. hopefully this is not # going to be the case self.expect("frame variable cool_array", - substrs = ['[0] = i_am_cool @ 0x', - '[1] = i_am_cool @ 0x', - '[2] = i_am_cool @ 0x', - '[3] = i_am_cool @ 0x', - '[4] = i_am_cool @ 0x']) - - - # test getting same output by exploiting %T and %L together for aggregates - self.runCmd("type summary add --summary-string \"${var%T} @ ${var%L}\" i_am_cool") - + substrs=['[0] = i_am_cool @ 0x', + '[1] = i_am_cool @ 0x', + '[2] = i_am_cool @ 0x', + '[3] = i_am_cool @ 0x', + '[4] = i_am_cool @ 0x']) + + # test getting same output by exploiting %T and %L together for + # aggregates + self.runCmd( + "type summary add --summary-string \"${var%T} @ ${var%L}\" i_am_cool") + # this test might fail if the compiler tries to store # these values into registers.. hopefully this is not # going to be the case self.expect("frame variable cool_array", - substrs = ['[0] = i_am_cool @ 0x', - '[1] = i_am_cool @ 0x', - '[2] = i_am_cool @ 0x', - '[3] = i_am_cool @ 0x', - '[4] = i_am_cool @ 0x']) - + substrs=['[0] = i_am_cool @ 0x', + '[1] = i_am_cool @ 0x', + '[2] = i_am_cool @ 0x', + '[3] = i_am_cool @ 0x', + '[4] = i_am_cool @ 0x']) + self.runCmd("type summary add --summary-string \"goofy\" i_am_cool") - self.runCmd("type summary add --summary-string \"${var.second_cool%S}\" i_am_cooler") + self.runCmd( + "type summary add --summary-string \"${var.second_cool%S}\" i_am_cooler") self.expect("frame variable the_coolest_guy", - substrs = ['(i_am_cooler) the_coolest_guy = goofy']) + substrs=['(i_am_cooler) the_coolest_guy = goofy']) # check that unwanted type specifiers are removed self.runCmd("type summary delete i_am_cool") - self.runCmd("type summary add --summary-string \"goofy\" \"class i_am_cool\"") + self.runCmd( + "type summary add --summary-string \"goofy\" \"class i_am_cool\"") self.expect("frame variable the_coolest_guy", - substrs = ['(i_am_cooler) the_coolest_guy = goofy']) + substrs=['(i_am_cooler) the_coolest_guy = goofy']) self.runCmd("type summary delete i_am_cool") - self.runCmd("type summary add --summary-string \"goofy\" \"enum i_am_cool\"") + self.runCmd( + "type summary add --summary-string \"goofy\" \"enum i_am_cool\"") self.expect("frame variable the_coolest_guy", - substrs = ['(i_am_cooler) the_coolest_guy = goofy']) + substrs=['(i_am_cooler) the_coolest_guy = goofy']) self.runCmd("type summary delete i_am_cool") - self.runCmd("type summary add --summary-string \"goofy\" \"struct i_am_cool\"") + self.runCmd( + "type summary add --summary-string \"goofy\" \"struct i_am_cool\"") self.expect("frame variable the_coolest_guy", - substrs = ['(i_am_cooler) the_coolest_guy = goofy']) + substrs=['(i_am_cooler) the_coolest_guy = goofy']) # many spaces, but we still do the right thing self.runCmd("type summary delete i_am_cool") - self.runCmd("type summary add --summary-string \"goofy\" \"union i_am_cool\"") + self.runCmd( + "type summary add --summary-string \"goofy\" \"union i_am_cool\"") self.expect("frame variable the_coolest_guy", - substrs = ['(i_am_cooler) the_coolest_guy = goofy']) + substrs=['(i_am_cooler) the_coolest_guy = goofy']) # but that not *every* specifier is removed self.runCmd("type summary delete i_am_cool") - self.runCmd("type summary add --summary-string \"goofy\" \"wrong i_am_cool\"") + self.runCmd( + "type summary add --summary-string \"goofy\" \"wrong i_am_cool\"") self.expect("frame variable the_coolest_guy", matching=False, - substrs = ['(i_am_cooler) the_coolest_guy = goofy']) - - # check that formats are not sticking since that is the behavior we want - self.expect("frame variable iAmInt --format hex", substrs = ['(int) iAmInt = 0x00000001']) - self.expect("frame variable iAmInt", matching=False, substrs = ['(int) iAmInt = 0x00000001']) - self.expect("frame variable iAmInt", substrs = ['(int) iAmInt = 1']) + substrs=['(i_am_cooler) the_coolest_guy = goofy']) + + # check that formats are not sticking since that is the behavior we + # want + self.expect("frame variable iAmInt --format hex", + substrs=['(int) iAmInt = 0x00000001']) + self.expect( + "frame variable iAmInt", + matching=False, + substrs=['(int) iAmInt = 0x00000001']) + self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py index 2c2e0843117..e192943f381 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DataFormatterDisablingTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,62 +23,69 @@ class DataFormatterDisablingTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") def test_with_run_command(self): """Check that we can properly disable all data formatter categories.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - self.runCmd('type category enable *', check=False) + self.runCmd('type category enable *', check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) #self.runCmd('type category enable system VectorTypes libcxx gnu-libstdc++ CoreGraphics CoreServices AppKit CoreFoundation objc default', check=False) - self.expect('type category list', substrs = ['system','enabled',]) + self.expect('type category list', substrs=['system', 'enabled', ]) self.expect("frame variable numbers", - substrs = ['[0] = 1', '[3] = 1234']) + substrs=['[0] = 1', '[3] = 1234']) - self.expect('frame variable string1', substrs = ['hello world']) + self.expect('frame variable string1', substrs=['hello world']) # now disable them all and check that nothing is formatted self.runCmd('type category disable *') self.expect("frame variable numbers", matching=False, - substrs = ['[0] = 1', '[3] = 1234']) + substrs=['[0] = 1', '[3] = 1234']) + + self.expect( + 'frame variable string1', + matching=False, + substrs=['hello world']) - self.expect('frame variable string1', matching=False, substrs = ['hello world']) + self.expect('type summary list', substrs=[ + 'Category: system (disabled)']) - self.expect('type summary list', substrs=['Category: system (disabled)']) + self.expect('type category list', substrs=['system', 'disabled', ]) - self.expect('type category list', substrs = ['system','disabled',]) - # now enable and check that we are back to normal self.runCmd("type category enable *") - self.expect('type category list', substrs = ['system','enabled']) + self.expect('type category list', substrs=['system', 'enabled']) self.expect("frame variable numbers", - substrs = ['[0] = 1', '[3] = 1234']) + substrs=['[0] = 1', '[3] = 1234']) - self.expect('frame variable string1', substrs = ['hello world']) + self.expect('frame variable string1', substrs=['hello world']) - self.expect('type category list', substrs = ['system','enabled']) + self.expect('type category list', substrs=['system', 'enabled']) # last check - our cleanup will re-enable everything self.runCmd('type category disable *') - self.expect('type category list', substrs = ['system','disabled']) + self.expect('type category list', substrs=['system', 'disabled']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py index 1659ade74a0..710cfa8fe12 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class EnumFormatTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,21 +27,22 @@ class EnumFormatTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) self.expect("frame variable", - substrs = ['(Foo) f = Case45', - '(int) x = 1', - '(int) y = 45', - '(int) z = 43' - ]); + substrs=['(Foo) f = Case45', + '(int) x = 1', + '(int) y = 45', + '(int) z = 43' + ]) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -55,11 +57,11 @@ class EnumFormatTestCase(TestBase): # The type format list should show our custom formats. self.expect("type format list -w default", - substrs = ['int: as type Foo']) + substrs=['int: as type Foo']) self.expect("frame variable", - substrs = ['(Foo) f = Case45', - '(int) x = Case1', - '(int) y = Case45', - '(int) z = 43' - ]); + substrs=['(Foo) f = Case45', + '(int) x = Case1', + '(int) y = Case45', + '(int) z = 43' + ]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py index df3bef091c8..d3d93dabc7f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class GlobalsDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,7 +27,8 @@ class GlobalsDataFormatterTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -41,27 +43,29 @@ class GlobalsDataFormatterTestCase(TestBase): # Simply check we can get at global variables self.expect("target variable g_point", - substrs = ['JustATest']) + substrs=['JustATest']) self.expect("target variable g_point_pointer", - substrs = ['(Point *) g_point_pointer =']) + substrs=['(Point *) g_point_pointer =']) # Print some information about the variables # (we ignore the actual values) - self.runCmd("type summary add --summary-string \"(x=${var.x},y=${var.y})\" Point") + self.runCmd( + "type summary add --summary-string \"(x=${var.x},y=${var.y})\" Point") self.expect("target variable g_point", - substrs = ['x=', - 'y=']) - + substrs=['x=', + 'y=']) + self.expect("target variable g_point_pointer", - substrs = ['(Point *) g_point_pointer =']) + substrs=['(Point *) g_point_pointer =']) # Test Python code on resulting SBValue - self.runCmd("type summary add --python-script \"return 'x=' + str(valobj.GetChildMemberWithName('x').GetValue());\" Point") + self.runCmd( + "type summary add --python-script \"return 'x=' + str(valobj.GetChildMemberWithName('x').GetValue());\" Point") self.expect("target variable g_point", - substrs = ['x=']) - + substrs=['x=']) + self.expect("target variable g_point_pointer", - substrs = ['(Point *) g_point_pointer =']) + substrs=['(Point *) g_point_pointer =']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py index e9ac79ad08e..f4f0a485989 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class NamedSummariesDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,15 +27,16 @@ class NamedSummariesDataFormatterTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): @@ -44,81 +46,88 @@ class NamedSummariesDataFormatterTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd("type summary add --summary-string \"AllUseIt: x=${var.x} {y=${var.y}} {z=${var.z}}\" --name AllUseIt") - self.runCmd("type summary add --summary-string \"First: x=${var.x} y=${var.y} dummy=${var.dummy}\" First") - self.runCmd("type summary add --summary-string \"Second: x=${var.x} y=${var.y%hex}\" Second") - self.runCmd("type summary add --summary-string \"Third: x=${var.x} z=${var.z}\" Third") - + self.runCmd( + "type summary add --summary-string \"AllUseIt: x=${var.x} {y=${var.y}} {z=${var.z}}\" --name AllUseIt") + self.runCmd( + "type summary add --summary-string \"First: x=${var.x} y=${var.y} dummy=${var.dummy}\" First") + self.runCmd( + "type summary add --summary-string \"Second: x=${var.x} y=${var.y%hex}\" Second") + self.runCmd( + "type summary add --summary-string \"Third: x=${var.x} z=${var.z}\" Third") + self.expect('type summary list', substrs=['AllUseIt']) - + self.expect("frame variable first", - substrs = ['First: x=12']) + substrs=['First: x=12']) self.expect("frame variable first --summary AllUseIt", - substrs = ['AllUseIt: x=12']) - + substrs=['AllUseIt: x=12']) + # We *DO NOT* remember the summary choice anymore self.expect("frame variable first", matching=False, - substrs = ['AllUseIt: x=12']) + substrs=['AllUseIt: x=12']) self.expect("frame variable first", - substrs = ['First: x=12']) + substrs=['First: x=12']) + + self.runCmd("thread step-over") # 2 - self.runCmd("thread step-over") # 2 - self.expect("frame variable first", - substrs = ['First: x=12']) - + substrs=['First: x=12']) + self.expect("frame variable first --summary AllUseIt", - substrs = ['AllUseIt: x=12', - 'y=34']) + substrs=['AllUseIt: x=12', + 'y=34']) self.expect("frame variable second --summary AllUseIt", - substrs = ['AllUseIt: x=65', - 'y=43.25']) + substrs=['AllUseIt: x=65', + 'y=43.25']) self.expect("frame variable third --summary AllUseIt", - substrs = ['AllUseIt: x=96', - 'z=', - 'E']) + substrs=['AllUseIt: x=96', + 'z=', + 'E']) + + self.runCmd("thread step-over") # 3 - self.runCmd("thread step-over") # 3 - self.expect("frame variable second", - substrs = ['Second: x=65', - 'y=0x']) - + substrs=['Second: x=65', + 'y=0x']) + # <rdar://problem/11576143> decided that invalid summaries will raise an error # instead of just defaulting to the base summary - self.expect("frame variable second --summary NoSuchSummary",error=True, - substrs = ['must specify a valid named summary']) - + self.expect( + "frame variable second --summary NoSuchSummary", + error=True, + substrs=['must specify a valid named summary']) + self.runCmd("thread step-over") - - self.runCmd("type summary add --summary-string \"FirstAndFriends: x=${var.x} {y=${var.y}} {z=${var.z}}\" First --name FirstAndFriends") - + + self.runCmd( + "type summary add --summary-string \"FirstAndFriends: x=${var.x} {y=${var.y}} {z=${var.z}}\" First --name FirstAndFriends") + self.expect("frame variable first", - substrs = ['FirstAndFriends: x=12', - 'y=34']) + substrs=['FirstAndFriends: x=12', + 'y=34']) self.runCmd("type summary delete First") - + self.expect("frame variable first --summary FirstAndFriends", - substrs = ['FirstAndFriends: x=12', - 'y=34']) - + substrs=['FirstAndFriends: x=12', + 'y=34']) + self.expect("frame variable first", matching=True, - substrs = ['x = 12', - 'y = 34']) - + substrs=['x = 12', + 'y = 34']) + self.runCmd("type summary delete FirstAndFriends") self.expect("type summary delete NoSuchSummary", error=True) self.runCmd("type summary delete AllUseIt") - + self.expect("frame variable first", matching=False, - substrs = ['FirstAndFriends']) + substrs=['FirstAndFriends']) - self.runCmd("thread step-over") # 4 + self.runCmd("thread step-over") # 4 - self.expect("frame variable first",matching=False, - substrs = ['FirstAndFriends: x=12', - 'y=34']) + self.expect("frame variable first", matching=False, + substrs=['FirstAndFriends: x=12', + 'y=34']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py index 4392cead5a1..6d38578dae7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py @@ -6,14 +6,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,7 +25,7 @@ class ObjCDataFormatterTestCase(TestBase): self.build() self.plain_data_formatter_commands() - def appkit_tester_impl(self,commands): + def appkit_tester_impl(self, commands): self.build() self.appkit_common_data_formatters_command() commands() @@ -49,25 +50,21 @@ class ObjCDataFormatterTestCase(TestBase): """Test formatters for NSURL.""" self.appkit_tester_impl(self.nsurl_data_formatter_commands) - @skipUnlessDarwin def test_nserror_with_run_command(self): """Test formatters for NSError.""" self.appkit_tester_impl(self.nserror_data_formatter_commands) - @skipUnlessDarwin def test_nsbundle_with_run_command(self): """Test formatters for NSBundle.""" self.appkit_tester_impl(self.nsbundle_data_formatter_commands) - @skipUnlessDarwin def test_nsexception_with_run_command(self): """Test formatters for NSException.""" self.appkit_tester_impl(self.nsexception_data_formatter_commands) - @skipUnlessDarwin def test_nsdate_with_run_command(self): """Test formatters for NSDate.""" @@ -101,14 +98,15 @@ class ObjCDataFormatterTestCase(TestBase): """Test basic ObjC formatting behavior.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -123,57 +121,58 @@ class ObjCDataFormatterTestCase(TestBase): self.runCmd("type summary add --summary-string \"${var%@}\" MyClass") self.expect("frame variable object2", - substrs = ['MyOtherClass']); - + substrs=['MyOtherClass']) + self.expect("frame variable *object2", - substrs = ['MyOtherClass']); + substrs=['MyOtherClass']) # Now let's delete the 'MyClass' custom summary. self.runCmd("type summary delete MyClass") # The type format list should not show 'MyClass' at this point. self.expect("type summary list", matching=False, - substrs = ['MyClass']) + substrs=['MyClass']) self.runCmd("type summary add --summary-string \"a test\" MyClass") - + self.expect("frame variable *object2", - substrs = ['*object2 =', - 'MyClass = a test', - 'backup = ']); - + substrs=['*object2 =', + 'MyClass = a test', + 'backup = ']) + self.expect("frame variable object2", matching=False, - substrs = ['a test']); - + substrs=['a test']) + self.expect("frame variable object", - substrs = ['a test']); - + substrs=['a test']) + self.expect("frame variable *object", - substrs = ['a test']); + substrs=['a test']) self.expect('frame variable myclass', - substrs = ['(Class) myclass = NSValue']) + substrs=['(Class) myclass = NSValue']) self.expect('frame variable myclass2', - substrs = ['(Class) myclass2 = ','NS','String']) + substrs=['(Class) myclass2 = ', 'NS', 'String']) self.expect('frame variable myclass3', - substrs = ['(Class) myclass3 = Molecule']) + substrs=['(Class) myclass3 = Molecule']) self.expect('frame variable myclass4', - substrs = ['(Class) myclass4 = NSMutableArray']) + substrs=['(Class) myclass4 = NSMutableArray']) self.expect('frame variable myclass5', - substrs = ['(Class) myclass5 = nil']) + substrs=['(Class) myclass5 = nil']) def appkit_common_data_formatters_command(self): """Test formatters for AppKit classes.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -184,132 +183,183 @@ class ObjCDataFormatterTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + def nsnumber_data_formatter_commands(self): # Now enable AppKit and check we are displaying Cocoa classes correctly self.expect('frame variable num1 num2 num3 num4 num5 num6 num7 num9', - substrs = ['(NSNumber *) num1 = ',' (int)5', - '(NSNumber *) num2 = ',' (float)3.1', - '(NSNumber *) num3 = ',' (double)3.14', - '(NSNumber *) num4 = ',' (long)-2', - '(NSNumber *) num5 = ',' (char)65', - '(NSNumber *) num6 = ',' (long)255', - '(NSNumber *) num7 = ','2000000', - '(NSNumber *) num9 = ',' (short)-31616']) + substrs=['(NSNumber *) num1 = ', ' (int)5', + '(NSNumber *) num2 = ', ' (float)3.1', + '(NSNumber *) num3 = ', ' (double)3.14', + '(NSNumber *) num4 = ', ' (long)-2', + '(NSNumber *) num5 = ', ' (char)65', + '(NSNumber *) num6 = ', ' (long)255', + '(NSNumber *) num7 = ', '2000000', + '(NSNumber *) num9 = ', ' (short)-31616']) self.expect('frame variable num_at1 num_at2 num_at3 num_at4', - substrs = ['(NSNumber *) num_at1 = ',' (int)12', - '(NSNumber *) num_at2 = ',' (int)-12', - '(NSNumber *) num_at3 = ',' (double)12.5', - '(NSNumber *) num_at4 = ',' (double)-12.5']) + substrs=['(NSNumber *) num_at1 = ', ' (int)12', + '(NSNumber *) num_at2 = ', ' (int)-12', + '(NSNumber *) num_at3 = ', ' (double)12.5', + '(NSNumber *) num_at4 = ', ' (double)-12.5']) def nscontainers_data_formatter_commands(self): - self.expect('frame variable newArray newDictionary newMutableDictionary cfarray_ref mutable_array_ref', - substrs = ['(NSArray *) newArray = ','@"50 elements"', - '(NSDictionary *) newDictionary = ',' 12 key/value pairs', - '(NSDictionary *) newMutableDictionary = ',' 21 key/value pairs', - '(CFArrayRef) cfarray_ref = ','@"3 elements"', - '(CFMutableArrayRef) mutable_array_ref = ','@"11 elements"']) + self.expect( + 'frame variable newArray newDictionary newMutableDictionary cfarray_ref mutable_array_ref', + substrs=[ + '(NSArray *) newArray = ', + '@"50 elements"', + '(NSDictionary *) newDictionary = ', + ' 12 key/value pairs', + '(NSDictionary *) newMutableDictionary = ', + ' 21 key/value pairs', + '(CFArrayRef) cfarray_ref = ', + '@"3 elements"', + '(CFMutableArrayRef) mutable_array_ref = ', + '@"11 elements"']) self.expect('frame variable iset1 iset2 imset', - substrs = ['4 indexes','512 indexes','10 indexes']) + substrs=['4 indexes', '512 indexes', '10 indexes']) - self.expect('frame variable binheap_ref', - substrs = ['(CFBinaryHeapRef) binheap_ref = ','@"21 items"']) + self.expect( + 'frame variable binheap_ref', + substrs=[ + '(CFBinaryHeapRef) binheap_ref = ', + '@"21 items"']) - self.expect('expression -d run -- [NSArray new]', substrs=['@"0 elements"']) + self.expect( + 'expression -d run -- [NSArray new]', + substrs=['@"0 elements"']) def nsdata_data_formatter_commands(self): - self.expect('frame variable immutableData mutableData data_ref mutable_data_ref mutable_string_ref', - substrs = ['(NSData *) immutableData = ',' 4 bytes', - '(NSData *) mutableData = ',' 14 bytes', - '(CFDataRef) data_ref = ','@"5 bytes"', - '(CFMutableDataRef) mutable_data_ref = ','@"5 bytes"', - '(CFMutableStringRef) mutable_string_ref = ',' @"Wish ya knew"']) + self.expect( + 'frame variable immutableData mutableData data_ref mutable_data_ref mutable_string_ref', + substrs=[ + '(NSData *) immutableData = ', + ' 4 bytes', + '(NSData *) mutableData = ', + ' 14 bytes', + '(CFDataRef) data_ref = ', + '@"5 bytes"', + '(CFMutableDataRef) mutable_data_ref = ', + '@"5 bytes"', + '(CFMutableStringRef) mutable_string_ref = ', + ' @"Wish ya knew"']) def nsurl_data_formatter_commands(self): - self.expect('frame variable cfurl_ref cfchildurl_ref cfgchildurl_ref', - substrs = ['(CFURLRef) cfurl_ref = ','@"http://www.foo.bar', - 'cfchildurl_ref = ','@"page.html -- http://www.foo.bar', - '(CFURLRef) cfgchildurl_ref = ','@"?whatever -- http://www.foo.bar/page.html"']) - - self.expect('frame variable nsurl nsurl2 nsurl3', - substrs = ['(NSURL *) nsurl = ','@"http://www.foo.bar', - '(NSURL *) nsurl2 =','@"page.html -- http://www.foo.bar', - '(NSURL *) nsurl3 = ','@"?whatever -- http://www.foo.bar/page.html"']) + self.expect( + 'frame variable cfurl_ref cfchildurl_ref cfgchildurl_ref', + substrs=[ + '(CFURLRef) cfurl_ref = ', + '@"http://www.foo.bar', + 'cfchildurl_ref = ', + '@"page.html -- http://www.foo.bar', + '(CFURLRef) cfgchildurl_ref = ', + '@"?whatever -- http://www.foo.bar/page.html"']) + + self.expect( + 'frame variable nsurl nsurl2 nsurl3', + substrs=[ + '(NSURL *) nsurl = ', + '@"http://www.foo.bar', + '(NSURL *) nsurl2 =', + '@"page.html -- http://www.foo.bar', + '(NSURL *) nsurl3 = ', + '@"?whatever -- http://www.foo.bar/page.html"']) def nserror_data_formatter_commands(self): self.expect('frame variable nserror', - substrs = ['domain: @"Foobar" - code: 12']) + substrs=['domain: @"Foobar" - code: 12']) self.expect('frame variable nserrorptr', - substrs = ['domain: @"Foobar" - code: 12']) + substrs=['domain: @"Foobar" - code: 12']) self.expect('frame variable nserror->_userInfo', - substrs = ['2 key/value pairs']) + substrs=['2 key/value pairs']) - self.expect('frame variable nserror->_userInfo --ptr-depth 1 -d run-target', - substrs = ['@"a"','@"b"',"1","2"]) + self.expect( + 'frame variable nserror->_userInfo --ptr-depth 1 -d run-target', + substrs=[ + '@"a"', + '@"b"', + "1", + "2"]) def nsbundle_data_formatter_commands(self): - self.expect('frame variable bundle_string bundle_url main_bundle', - substrs = ['(NSBundle *) bundle_string = ',' @"/System/Library/Frameworks/Accelerate.framework"', - '(NSBundle *) bundle_url = ',' @"/System/Library/Frameworks/Foundation.framework"', - '(NSBundle *) main_bundle = ','data-formatter-objc']) + self.expect( + 'frame variable bundle_string bundle_url main_bundle', + substrs=[ + '(NSBundle *) bundle_string = ', + ' @"/System/Library/Frameworks/Accelerate.framework"', + '(NSBundle *) bundle_url = ', + ' @"/System/Library/Frameworks/Foundation.framework"', + '(NSBundle *) main_bundle = ', + 'data-formatter-objc']) def nsexception_data_formatter_commands(self): - self.expect('frame variable except0 except1 except2 except3', - substrs = ['(NSException *) except0 = ','name: @"TheGuyWhoHasNoName" - reason: @"cuz it\'s funny"', - '(NSException *) except1 = ','name: @"TheGuyWhoHasNoName~1" - reason: @"cuz it\'s funny"', - '(NSException *) except2 = ','name: @"TheGuyWhoHasNoName`2" - reason: @"cuz it\'s funny"', - '(NSException *) except3 = ','name: @"TheGuyWhoHasNoName/3" - reason: @"cuz it\'s funny"']) + self.expect( + 'frame variable except0 except1 except2 except3', + substrs=[ + '(NSException *) except0 = ', + 'name: @"TheGuyWhoHasNoName" - reason: @"cuz it\'s funny"', + '(NSException *) except1 = ', + 'name: @"TheGuyWhoHasNoName~1" - reason: @"cuz it\'s funny"', + '(NSException *) except2 = ', + 'name: @"TheGuyWhoHasNoName`2" - reason: @"cuz it\'s funny"', + '(NSException *) except3 = ', + 'name: @"TheGuyWhoHasNoName/3" - reason: @"cuz it\'s funny"']) def nsdate_data_formatter_commands(self): - self.expect('frame variable date1 date2', - patterns = ['(1985-04-10|1985-04-11)','(2011-01-01|2010-12-31)']) + self.expect( + 'frame variable date1 date2', + patterns=[ + '(1985-04-10|1985-04-11)', + '(2011-01-01|2010-12-31)']) # this test might fail if we hit the breakpoint late on December 31st of some given year # and midnight comes between hitting the breakpoint and running this line of code # hopefully the output will be revealing enough in that case :-) now_year = '%s-' % str(datetime.datetime.now().year) - self.expect('frame variable date3', substrs = [now_year]) - self.expect('frame variable date4', substrs = ['1970']) - self.expect('frame variable date5', substrs = [now_year]) + self.expect('frame variable date3', substrs=[now_year]) + self.expect('frame variable date4', substrs=['1970']) + self.expect('frame variable date5', substrs=[now_year]) self.expect('frame variable date1_abs date2_abs', - substrs = ['1985-04','2011-01']) + substrs=['1985-04', '2011-01']) - self.expect('frame variable date3_abs', substrs = [now_year]) - self.expect('frame variable date4_abs', substrs = ['1970']) - self.expect('frame variable date5_abs', substrs = [now_year]) + self.expect('frame variable date3_abs', substrs=[now_year]) + self.expect('frame variable date4_abs', substrs=['1970']) + self.expect('frame variable date5_abs', substrs=[now_year]) self.expect('frame variable cupertino home europe', - substrs = ['@"America/Los_Angeles"', - '@"Europe/Rome"', - '@"Europe/Paris"']) + substrs=['@"America/Los_Angeles"', + '@"Europe/Rome"', + '@"Europe/Paris"']) self.expect('frame variable cupertino_ns home_ns europe_ns', - substrs = ['@"America/Los_Angeles"', - '@"Europe/Rome"', - '@"Europe/Paris"']) - - self.expect('frame variable mut_bv', - substrs = ['(CFMutableBitVectorRef) mut_bv = ', '1110 0110 1011 0000 1101 1010 1000 1111 0011 0101 1101 0001 00']) + substrs=['@"America/Los_Angeles"', + '@"Europe/Rome"', + '@"Europe/Paris"']) + self.expect( + 'frame variable mut_bv', + substrs=[ + '(CFMutableBitVectorRef) mut_bv = ', + '1110 0110 1011 0000 1101 1010 1000 1111 0011 0101 1101 0001 00']) def expr_objc_data_formatter_commands(self): """Test common cases of expression parser <--> formatters interaction.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -323,36 +373,41 @@ class ObjCDataFormatterTestCase(TestBase): # check that the formatters are able to deal safely and correctly # with ValueObjects that the expression parser returns - self.expect('expression ((id)@"Hello for long enough to avoid short string types")', matching=False, - substrs = ['Hello for long enough to avoid short string types']) + self.expect( + 'expression ((id)@"Hello for long enough to avoid short string types")', + matching=False, + substrs=['Hello for long enough to avoid short string types']) - self.expect('expression -d run -- ((id)@"Hello for long enough to avoid short string types")', - substrs = ['Hello for long enough to avoid short string types']) + self.expect( + 'expression -d run -- ((id)@"Hello for long enough to avoid short string types")', + substrs=['Hello for long enough to avoid short string types']) self.expect('expr -d run -- label1', - substrs = ['Process Name']) - - self.expect('expr -d run -- @"Hello for long enough to avoid short string types"', - substrs = ['Hello for long enough to avoid short string types']) + substrs=['Process Name']) - self.expect('expr -d run --object-description -- @"Hello for long enough to avoid short string types"', - substrs = ['Hello for long enough to avoid short string types']) - self.expect('expr -d run --object-description -- @"Hello"', matching=False, - substrs = ['@"Hello" Hello']) + self.expect( + 'expr -d run -- @"Hello for long enough to avoid short string types"', + substrs=['Hello for long enough to avoid short string types']) + self.expect( + 'expr -d run --object-description -- @"Hello for long enough to avoid short string types"', + substrs=['Hello for long enough to avoid short string types']) + self.expect('expr -d run --object-description -- @"Hello"', + matching=False, substrs=['@"Hello" Hello']) def cf_data_formatter_commands(self): """Test formatters for Core OSX frameworks.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -361,50 +416,53 @@ class ObjCDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type synth clear', check=False) - # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # check formatters for common Objective-C types - expect_strings = ['(CFGregorianUnits) cf_greg_units = 1 years, 3 months, 5 days, 12 hours, 5 minutes 7 seconds', - '(CFRange) cf_range = location=4 length=4', - '(NSPoint) ns_point = (x = 4, y = 4)', - '(NSRange) ns_range = location=4, length=4', - '(NSRect) ns_rect = (origin = (x = 1, y = 1), size = (width = 5, height = 5))', - '(NSRectArray) ns_rect_arr = ((x = 1, y = 1), (width = 5, height = 5)), ...', - '(NSSize) ns_size = (width = 5, height = 7)', - '(CGSize) cg_size = (width = 1, height = 6)', - '(CGPoint) cg_point = (x = 2, y = 7)', - '(CGRect) cg_rect = (origin = (x = 1, y = 2), size = (width = 7, height = 7))', - '(Rect) rect = (t=4, l=8, b=4, r=7)', - '(Rect *) rect_ptr = (t=4, l=8, b=4, r=7)', - '(Point) point = (v=7, h=12)', - '(Point *) point_ptr = (v=7, h=12)', - '1985', - 'foo_selector_impl']; - + expect_strings = [ + '(CFGregorianUnits) cf_greg_units = 1 years, 3 months, 5 days, 12 hours, 5 minutes 7 seconds', + '(CFRange) cf_range = location=4 length=4', + '(NSPoint) ns_point = (x = 4, y = 4)', + '(NSRange) ns_range = location=4, length=4', + '(NSRect) ns_rect = (origin = (x = 1, y = 1), size = (width = 5, height = 5))', + '(NSRectArray) ns_rect_arr = ((x = 1, y = 1), (width = 5, height = 5)), ...', + '(NSSize) ns_size = (width = 5, height = 7)', + '(CGSize) cg_size = (width = 1, height = 6)', + '(CGPoint) cg_point = (x = 2, y = 7)', + '(CGRect) cg_rect = (origin = (x = 1, y = 2), size = (width = 7, height = 7))', + '(Rect) rect = (t=4, l=8, b=4, r=7)', + '(Rect *) rect_ptr = (t=4, l=8, b=4, r=7)', + '(Point) point = (v=7, h=12)', + '(Point *) point_ptr = (v=7, h=12)', + '1985', + 'foo_selector_impl'] + if self.getArchitecture() in ['i386', 'x86_64']: expect_strings.append('(HIPoint) hi_point = (x=7, y=12)') - expect_strings.append('(HIRect) hi_rect = origin=(x = 3, y = 5) size=(width = 4, height = 6)') - expect_strings.append('(RGBColor) rgb_color = red=3 green=56 blue=35') - expect_strings.append('(RGBColor *) rgb_color_ptr = red=3 green=56 blue=35') - - self.expect("frame variable", - substrs = expect_strings) + expect_strings.append( + '(HIRect) hi_rect = origin=(x = 3, y = 5) size=(width = 4, height = 6)') + expect_strings.append( + '(RGBColor) rgb_color = red=3 green=56 blue=35') + expect_strings.append( + '(RGBColor *) rgb_color_ptr = red=3 green=56 blue=35') + self.expect("frame variable", + substrs=expect_strings) def kvo_data_formatter_commands(self): """Test the behavior of formatters when KVO is in use.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -420,18 +478,23 @@ class ObjCDataFormatterTestCase(TestBase): # we should be able to dynamically figure out that the KVO implementor class # is a subclass of Molecule, and use the appropriate summary for it self.runCmd("type summary add -s JustAMoleculeHere Molecule") - self.expect('frame variable molecule', substrs = ['JustAMoleculeHere']) + self.expect('frame variable molecule', substrs=['JustAMoleculeHere']) self.runCmd("next") self.expect("thread list", - substrs = ['stopped', - 'step over']) - self.expect('frame variable molecule', substrs = ['JustAMoleculeHere']) + substrs=['stopped', + 'step over']) + self.expect('frame variable molecule', substrs=['JustAMoleculeHere']) self.runCmd("next") - # check that NSMutableDictionary's formatter is not confused when dealing with a KVO'd dictionary - self.expect('frame variable newMutableDictionary', substrs = ['(NSDictionary *) newMutableDictionary = ',' 21 key/value pairs']) + # check that NSMutableDictionary's formatter is not confused when + # dealing with a KVO'd dictionary + self.expect( + 'frame variable newMutableDictionary', + substrs=[ + '(NSDictionary *) newMutableDictionary = ', + ' 21 key/value pairs']) - lldbutil.run_break_set_by_regexp (self, 'setAtoms') + lldbutil.run_break_set_by_regexp(self, 'setAtoms') self.runCmd("continue") - self.expect("frame variable _cmd",substrs = ['setAtoms:']) + self.expect("frame variable _cmd", substrs=['setAtoms:']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py index 89145553d35..5ef84b019df 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py @@ -6,30 +6,32 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import datetime import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NSIndexPathDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def appkit_tester_impl(self,commands): + def appkit_tester_impl(self, commands): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -38,7 +40,6 @@ class NSIndexPathDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type synth clear', check=False) - # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) commands() @@ -56,15 +57,58 @@ class NSIndexPathDataFormatterTestCase(TestBase): def nsindexpath_data_formatter_commands(self): # check 'frame variable' - self.expect('frame variable --ptr-depth=1 -d run -- indexPath1', substrs = ['[0] = 1']) - self.expect('frame variable --ptr-depth=1 -d run -- indexPath2', substrs = ['[0] = 1', '[1] = 2']) - self.expect('frame variable --ptr-depth=1 -d run -- indexPath3', substrs = ['[0] = 1', '[1] = 2', '[2] = 3']) - self.expect('frame variable --ptr-depth=1 -d run -- indexPath4', substrs = ['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4']) - self.expect('frame variable --ptr-depth=1 -d run -- indexPath5', substrs = ['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4', '[4] = 5']) - + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath1', + substrs=['[0] = 1']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath2', + substrs=[ + '[0] = 1', + '[1] = 2']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath3', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath4', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath5', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4', + '[4] = 5']) + # and 'expression' - self.expect('expression --ptr-depth=1 -d run -- indexPath1', substrs = ['[0] = 1']) - self.expect('expression --ptr-depth=1 -d run -- indexPath2', substrs = ['[0] = 1', '[1] = 2']) - self.expect('expression --ptr-depth=1 -d run -- indexPath3', substrs = ['[0] = 1', '[1] = 2', '[2] = 3']) - self.expect('expression --ptr-depth=1 -d run -- indexPath4', substrs = ['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4']) - self.expect('expression --ptr-depth=1 -d run -- indexPath5', substrs = ['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4', '[4] = 5']) + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath1', + substrs=['[0] = 1']) + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath2', + substrs=[ + '[0] = 1', + '[1] = 2']) + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath3', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3']) + self.expect('expression --ptr-depth=1 -d run -- indexPath4', + substrs=['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4']) + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath5', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4', + '[4] = 5']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py index f5c79259377..12e62f62ee9 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py @@ -6,30 +6,32 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import datetime import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NSStringDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def appkit_tester_impl(self,commands): + def appkit_tester_impl(self, commands): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -38,7 +40,6 @@ class NSStringDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type synth clear', check=False) - # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) commands() @@ -58,7 +59,6 @@ class NSStringDataFormatterTestCase(TestBase): """Test formatters for NSString.""" self.appkit_tester_impl(self.nsstring_withNULs_commands) - def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -67,42 +67,55 @@ class NSStringDataFormatterTestCase(TestBase): def rdar11106605_commands(self): """Check that Unicode characters come out of CFString summary correctly.""" - self.expect('frame variable italian', substrs = ['L\'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione.']) - self.expect('frame variable french', substrs = ['Que veut cette horde d\'esclaves, De traîtres, de rois conjurés?']) - self.expect('frame variable german', substrs = ['Über-Ich und aus den Ansprüchen der sozialen Umwelt']) - self.expect('frame variable japanese', substrs = ['色は匂へど散りぬるを']) - self.expect('frame variable hebrew', substrs = ['לילה טוב']) + self.expect('frame variable italian', substrs=[ + 'L\'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione.']) + self.expect('frame variable french', substrs=[ + 'Que veut cette horde d\'esclaves, De traîtres, de rois conjurés?']) + self.expect('frame variable german', substrs=[ + 'Über-Ich und aus den Ansprüchen der sozialen Umwelt']) + self.expect('frame variable japanese', substrs=['色は匂へど散りぬるを']) + self.expect('frame variable hebrew', substrs=['לילה טוב']) def nsstring_data_formatter_commands(self): self.expect('frame variable str0 str1 str2 str3 str4 str5 str6 str8 str9 str10 str11 label1 label2 processName str12', - substrs = ['(NSString *) str1 = ',' @"A rather short ASCII NSString object is here"', - # '(NSString *) str0 = ',' @"255"', - '(NSString *) str1 = ',' @"A rather short ASCII NSString object is here"', - '(NSString *) str2 = ',' @"A rather short UTF8 NSString object is here"', - '(NSString *) str3 = ',' @"A string made with the at sign is here"', - '(NSString *) str4 = ',' @"This is string number 4 right here"', - '(NSString *) str5 = ',' @"{{1, 1}, {5, 5}}"', - '(NSString *) str6 = ',' @"1ST"', - '(NSString *) str8 = ',' @"hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime', - '(NSString *) str9 = ',' @"a very much boring task to write a string this way!!', - '(NSString *) str10 = ',' @"This is a Unicode string σ number 4 right here"', - '(NSString *) str11 = ',' @"__NSCFString"', - '(NSString *) label1 = ',' @"Process Name: "', - '(NSString *) label2 = ',' @"Process Id: "', - '(NSString *) str12 = ',' @"Process Name: a.out Process Id:']) - self.expect('frame variable attrString mutableAttrString mutableGetConst', - substrs = ['(NSAttributedString *) attrString = ',' @"hello world from foo"', - '(NSAttributedString *) mutableAttrString = ',' @"hello world from foo"', - '(NSString *) mutableGetConst = ',' @"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear foo"']) - - self.expect('expr -d run-target -- path',substrs = ['usr/blah/stuff']) - self.expect('frame variable path',substrs = ['usr/blah/stuff']) + substrs=['(NSString *) str1 = ', ' @"A rather short ASCII NSString object is here"', + # '(NSString *) str0 = ',' @"255"', + '(NSString *) str1 = ', ' @"A rather short ASCII NSString object is here"', + '(NSString *) str2 = ', ' @"A rather short UTF8 NSString object is here"', + '(NSString *) str3 = ', ' @"A string made with the at sign is here"', + '(NSString *) str4 = ', ' @"This is string number 4 right here"', + '(NSString *) str5 = ', ' @"{{1, 1}, {5, 5}}"', + '(NSString *) str6 = ', ' @"1ST"', + '(NSString *) str8 = ', ' @"hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime', + '(NSString *) str9 = ', ' @"a very much boring task to write a string this way!!', + '(NSString *) str10 = ', ' @"This is a Unicode string σ number 4 right here"', + '(NSString *) str11 = ', ' @"__NSCFString"', + '(NSString *) label1 = ', ' @"Process Name: "', + '(NSString *) label2 = ', ' @"Process Id: "', + '(NSString *) str12 = ', ' @"Process Name: a.out Process Id:']) + self.expect( + 'frame variable attrString mutableAttrString mutableGetConst', + substrs=[ + '(NSAttributedString *) attrString = ', + ' @"hello world from foo"', + '(NSAttributedString *) mutableAttrString = ', + ' @"hello world from foo"', + '(NSString *) mutableGetConst = ', + ' @"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear foo"']) + + self.expect('expr -d run-target -- path', substrs=['usr/blah/stuff']) + self.expect('frame variable path', substrs=['usr/blah/stuff']) def nsstring_withNULs_commands(self): """Check that the NSString formatter supports embedded NULs in the text""" - self.expect('po strwithNULs', substrs=['a very much boring task to write']) + self.expect( + 'po strwithNULs', + substrs=['a very much boring task to write']) self.expect('expr [strwithNULs length]', substrs=['54']) - self.expect('frame variable strwithNULs', substrs=['@"a very much boring task to write\\0a string this way!!']) - self.expect('po strwithNULs2', substrs=['a very much boring task to write']) + self.expect('frame variable strwithNULs', substrs=[ + '@"a very much boring task to write\\0a string this way!!']) + self.expect('po strwithNULs2', substrs=[ + 'a very much boring task to write']) self.expect('expr [strwithNULs2 length]', substrs=['52']) - self.expect('frame variable strwithNULs2', substrs=['@"a very much boring task to write\\0a string this way!!']) + self.expect('frame variable strwithNULs2', substrs=[ + '@"a very much boring task to write\\0a string this way!!']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py index 3c9be04a2f6..bf600219bce 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DataFormatterOneIsSingularTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -33,14 +34,15 @@ class DataFormatterOneIsSingularTestCase(TestBase): """Test that 1 item is not as reported as 1 items.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -54,26 +56,26 @@ class DataFormatterOneIsSingularTestCase(TestBase): # Now check that we are displaying Cocoa classes correctly self.expect('frame variable key', - substrs = ['@"1 element"']) + substrs=['@"1 element"']) self.expect('frame variable key', matching=False, - substrs = ['1 elements']) + substrs=['1 elements']) self.expect('frame variable value', - substrs = ['@"1 element"']) + substrs=['@"1 element"']) self.expect('frame variable value', matching=False, - substrs = ['1 elements']) + substrs=['1 elements']) self.expect('frame variable dict', - substrs = ['1 key/value pair']) + substrs=['1 key/value pair']) self.expect('frame variable dict', matching=False, - substrs = ['1 key/value pairs']) + substrs=['1 key/value pairs']) self.expect('frame variable imset', - substrs = ['1 index']) + substrs=['1 index']) self.expect('frame variable imset', matching=False, - substrs = ['1 indexes']) + substrs=['1 indexes']) self.expect('frame variable binheap_ref', - substrs = ['@"1 item"']) + substrs=['@"1 item"']) self.expect('frame variable binheap_ref', matching=False, - substrs = ['1 items']) + substrs=['1 items']) self.expect('frame variable immutableData', - substrs = ['1 byte']) + substrs=['1 byte']) self.expect('frame variable immutableData', matching=False, - substrs = ['1 bytes']) + substrs=['1 bytes']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py index 86cd3c42728..ebabe307661 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class PtrToArrayDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,14 +31,15 @@ class PtrToArrayDataFormatterTestCase(TestBase): """Test that LLDB handles the clang typeclass Paren correctly.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -49,9 +51,9 @@ class PtrToArrayDataFormatterTestCase(TestBase): self.addTearDownHook(cleanup) self.expect('p *(int (*)[3])foo', - substrs = ['(int [3]) $','[0] = 1','[1] = 2','[2] = 3']) + substrs=['(int [3]) $', '[0] = 1', '[1] = 2', '[2] = 3']) self.expect('p *(int (*)[3])foo', matching=False, - substrs = ['01 00 00 00 02 00 00 00 03 00 00 00']) + substrs=['01 00 00 00 02 00 00 00 03 00 00 00']) self.expect('p *(int (*)[3])foo', matching=False, - substrs = ['0x000000030000000200000001']) + substrs=['0x000000030000000200000001']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py index c7ff28874c5..75d1853f6a7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py @@ -5,18 +5,19 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PythonSynthDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser def test_with_run_command(self): """Test data formatter commands.""" self.build() @@ -27,20 +28,22 @@ class PythonSynthDataFormatterTestCase(TestBase): self.build() self.rdar10960550_formatter_commands() - def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - self.line2 = line_number('main.cpp', '// Set cast break point at this line.') - self.line3 = line_number('main.cpp', '// Set second cast break point at this line.') + self.line2 = line_number('main.cpp', + '// Set cast break point at this line.') + self.line3 = line_number( + 'main.cpp', '// Set second cast break point at this line.') def data_formatter_commands(self): """Test using Python synthetic children provider.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) @@ -48,8 +51,8 @@ class PythonSynthDataFormatterTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -64,9 +67,9 @@ class PythonSynthDataFormatterTestCase(TestBase): # print the f00_1 variable without a synth self.expect("frame variable f00_1", - substrs = ['a = 1', - 'b = 2', - 'r = 34']); + substrs=['a = 1', + 'b = 2', + 'r = 34']) # now set up the synth self.runCmd("script from fooSynthProvider import *") @@ -81,30 +84,32 @@ class PythonSynthDataFormatterTestCase(TestBase): # check that we get the two real vars and the fake_a variables self.expect("frame variable f00_1", - substrs = ['r = 34', - 'fake_a = %d' % fake_a_val, - 'a = 1']); + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 1']) # check that we do not get the extra vars self.expect("frame variable f00_1", matching=False, - substrs = ['b = 2']); - + substrs=['b = 2']) + # check access to members by name self.expect('frame variable f00_1.fake_a', - substrs = ['%d' % fake_a_val]) - + substrs=['%d' % fake_a_val]) + # check access to members by index self.expect('frame variable f00_1[1]', - substrs = ['%d' % fake_a_val]) - + substrs=['%d' % fake_a_val]) + # put synthetic children in summary in several combinations - self.runCmd("type summary add --summary-string \"fake_a=${svar.fake_a}\" foo") + self.runCmd( + "type summary add --summary-string \"fake_a=${svar.fake_a}\" foo") self.expect('frame variable f00_1', - substrs = ['fake_a=%d' % fake_a_val]) - self.runCmd("type summary add --summary-string \"fake_a=${svar[1]}\" foo") + substrs=['fake_a=%d' % fake_a_val]) + self.runCmd( + "type summary add --summary-string \"fake_a=${svar[1]}\" foo") self.expect('frame variable f00_1', - substrs = ['fake_a=%d' % fake_a_val]) - + substrs=['fake_a=%d' % fake_a_val]) + # clear the summary self.runCmd("type summary delete foo") @@ -117,9 +122,9 @@ class PythonSynthDataFormatterTestCase(TestBase): fake_a_val = 0x00000200 self.expect("frame variable f00_1", - substrs = ['r = 34', - 'fake_a = %d' % fake_a_val, - 'a = 2']); + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 2']) # check that altering the object also alters fake_a self.runCmd("expr f00_1.a = 280") @@ -130,9 +135,9 @@ class PythonSynthDataFormatterTestCase(TestBase): fake_a_val = 0x00011800 self.expect("frame variable f00_1", - substrs = ['r = 34', - 'fake_a = %d' % fake_a_val, - 'a = 280']); + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 280']) # check that expanding a pointer does the right thing if process.GetByteOrder() == lldb.eByteOrderLittle: @@ -141,94 +146,97 @@ class PythonSynthDataFormatterTestCase(TestBase): fake_a_val = 0x00000c00 self.expect("frame variable --ptr-depth 1 f00_ptr", - substrs = ['r = 45', - 'fake_a = %d' % fake_a_val, - 'a = 12']) - + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) + # now add a filter.. it should fail self.expect("type filter add foo --child b --child j", error=True, - substrs = ['cannot add']) - + substrs=['cannot add']) + # we get the synth again.. self.expect('frame variable f00_1', matching=False, - substrs = ['b = 1', - 'j = 17']) + substrs=['b = 1', + 'j = 17']) self.expect("frame variable --ptr-depth 1 f00_ptr", - substrs = ['r = 45', - 'fake_a = %d' % fake_a_val, - 'a = 12']) - + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) + # now delete the synth and add the filter self.runCmd("type synth delete foo") self.runCmd("type filter add foo --child b --child j") - + self.expect('frame variable f00_1', - substrs = ['b = 2', - 'j = 18']) + substrs=['b = 2', + 'j = 18']) self.expect("frame variable --ptr-depth 1 f00_ptr", matching=False, - substrs = ['r = 45', - 'fake_a = %d' % fake_a_val, - 'a = 12']) - + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) + # now add the synth and it should fail self.expect("type synth add -l fooSynthProvider foo", error=True, - substrs = ['cannot add']) - + substrs=['cannot add']) + # check the listing self.expect('type synth list', matching=False, - substrs = ['foo', - 'Python class fooSynthProvider']) - self.expect('type filter list', - substrs = ['foo', - '.b', - '.j']) - + substrs=['foo', + 'Python class fooSynthProvider']) + self.expect('type filter list', + substrs=['foo', + '.b', + '.j']) + # delete the filter, add the synth self.runCmd("type filter delete foo") self.runCmd("type synth add -l fooSynthProvider foo") - + self.expect('frame variable f00_1', matching=False, - substrs = ['b = 2', - 'j = 18']) - self.expect("frame variable --ptr-depth 1 f00_ptr", - substrs = ['r = 45', - 'fake_a = %d' % fake_a_val, - 'a = 12']) + substrs=['b = 2', + 'j = 18']) + self.expect("frame variable --ptr-depth 1 f00_ptr", + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) # check the listing self.expect('type synth list', - substrs = ['foo', - 'Python class fooSynthProvider']) + substrs=['foo', + 'Python class fooSynthProvider']) self.expect('type filter list', matching=False, - substrs = ['foo', - '.b', - '.j']) - + substrs=['foo', + '.b', + '.j']) + # delete the synth and check that we get good output self.runCmd("type synth delete foo") - + self.expect("frame variable f00_1", - substrs = ['a = 280', - 'b = 2', - 'j = 18']); + substrs=['a = 280', + 'b = 2', + 'j = 18']) self.expect("frame variable f00_1", matching=False, - substrs = ['fake_a = ']) + substrs=['fake_a = ']) def rdar10960550_formatter_commands(self): """Test that synthetic children persist stoppoints.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - # The second breakpoint is on a multi-line expression, so the comment can't be on the right line... - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line2, num_expected_locations=1, loc_exact=False) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line3, num_expected_locations=1, loc_exact=True) + # The second breakpoint is on a multi-line expression, so the comment + # can't be on the right line... + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line2, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line3, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -248,25 +256,28 @@ class PythonSynthDataFormatterTestCase(TestBase): # but their values change correctly across stop-points - in order to do this, self.runCmd("next") # does not work because it forces a wipe of the stack frame - this is why we are using this more contrived # mechanism to achieve our goal of preserving test_cast as a VO - test_cast = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('test_cast') + test_cast = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('test_cast') str_cast = str(test_cast) if self.TraceOn(): - print(str_cast) + print(str_cast) self.assertTrue(str_cast.find('A') != -1, 'could not find A in output') self.assertTrue(str_cast.find('B') != -1, 'could not find B in output') self.assertTrue(str_cast.find('C') != -1, 'could not find C in output') self.assertTrue(str_cast.find('D') != -1, 'could not find D in output') - self.assertTrue(str_cast.find("4 = '\\0'") != -1, 'could not find item 4 == 0') + self.assertTrue( + str_cast.find("4 = '\\0'") != -1, + 'could not find item 4 == 0') self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().StepOver() str_cast = str(test_cast) if self.TraceOn(): - print(str_cast) + print(str_cast) # we detect that all the values of the child objects have changed - but the counter-generated item # is still fixed at 0 because it is cached - this would fail if update(self): in ftsp returned False @@ -275,4 +286,6 @@ class PythonSynthDataFormatterTestCase(TestBase): self.assertTrue(str_cast.find('X') != -1, 'could not find X in output') self.assertTrue(str_cast.find('T') != -1, 'could not find T in output') self.assertTrue(str_cast.find('F') != -1, 'could not find F in output') - self.assertTrue(str_cast.find("4 = '\\0'") != -1, 'could not find item 4 == 0') + self.assertTrue( + str_cast.find("4 = '\\0'") != -1, + 'could not find item 4 == 0') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py index 0dc2c233e2a..45fb00468e0 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py @@ -1,23 +1,30 @@ import lldb + + class fooSynthProvider: - def __init__(self, valobj, dict): - self.valobj = valobj; - self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) - def num_children(self): - return 3; - def get_child_at_index(self, index): - if index == 0: - child = self.valobj.GetChildMemberWithName('a'); - if index == 1: - child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); - if index == 2: - child = self.valobj.GetChildMemberWithName('r'); - return child; - def get_child_index(self, name): - if name == 'a': - return 0; - if name == 'fake_a': - return 1; - return 2; - def update(self): - return True
\ No newline at end of file + + def __init__(self, valobj, dict): + self.valobj = valobj + self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) + + def num_children(self): + return 3 + + def get_child_at_index(self, index): + if index == 0: + child = self.valobj.GetChildMemberWithName('a') + if index == 1: + child = self.valobj.CreateChildAtOffset('fake_a', 1, self.int_type) + if index == 2: + child = self.valobj.GetChildMemberWithName('r') + return child + + def get_child_index(self, name): + if name == 'a': + return 0 + if name == 'fake_a': + return 1 + return 2 + + def update(self): + return True diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py index d162b00db32..b96dbac6f50 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py @@ -2,31 +2,39 @@ import lldb counter = 0 + class ftsp: - def __init__(self, valobj, dict): - self.valobj = valobj; - def num_children(self): - if self.char.IsValid(): - return 5; - return 0; - def get_child_index(self,name): - return 0; - def get_child_at_index(self,index): - if index == 0: - return self.x.Cast(self.char) - if index == 4: - return self.valobj.CreateValueFromExpression(str(index),'(char)('+str(self.count)+')') - return self.x.CreateChildAtOffset(str(index), - index, - self.char); - def update(self): - self.x = self.valobj.GetChildMemberWithName('x'); - self.char = self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar) - global counter - self.count = counter - counter = counter + 1 - return True # important: if we return False here, or fail to return, the test will fail + + def __init__(self, valobj, dict): + self.valobj = valobj + + def num_children(self): + if self.char.IsValid(): + return 5 + return 0 + + def get_child_index(self, name): + return 0 + + def get_child_at_index(self, index): + if index == 0: + return self.x.Cast(self.char) + if index == 4: + return self.valobj.CreateValueFromExpression( + str(index), '(char)(' + str(self.count) + ')') + return self.x.CreateChildAtOffset(str(index), + index, + self.char) + + def update(self): + self.x = self.valobj.GetChildMemberWithName('x') + self.char = self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar) + global counter + self.count = counter + counter = counter + 1 + return True # important: if we return False here, or fail to return, the test will fail + def __lldb_init_module(debugger, dict): - global counter - counter = 0
\ No newline at end of file + global counter + counter = 0 diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py index 7ebc1c14ce1..3355ca16305 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class ScriptDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,14 +31,15 @@ class ScriptDataFormatterTestCase(TestBase): """Test that that file and class static variables display correctly.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -51,121 +53,133 @@ class ScriptDataFormatterTestCase(TestBase): # Set the script here to ease the formatting script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'Hello from Python, \' + a_val + \' time\'; return str + (\'!\' if a_val == \'1\' else \'s!\');' - self.runCmd("type summary add i_am_cool --python-script \"%s\"" % script) + self.runCmd( + "type summary add i_am_cool --python-script \"%s\"" % + script) self.expect('type summary list i_am_cool', substrs=[script]) self.expect("frame variable one", - substrs = ['Hello from Python', - '1 time!']) + substrs=['Hello from Python', + '1 time!']) self.expect("frame variable two", - substrs = ['Hello from Python', - '4 times!']) - - self.runCmd("n"); # skip ahead to make values change + substrs=['Hello from Python', + '4 times!']) + + self.runCmd("n") # skip ahead to make values change self.expect("frame variable three", - substrs = ['Hello from Python, 10 times!', - 'Hello from Python, 4 times!']) + substrs=['Hello from Python, 10 times!', + 'Hello from Python, 4 times!']) + + self.runCmd("n") # skip ahead to make values change - self.runCmd("n"); # skip ahead to make values change - self.expect("frame variable two", - substrs = ['Hello from Python', - '1 time!']) + substrs=['Hello from Python', + '1 time!']) script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'int says \' + a_val; return str;' # Check that changes in the script are immediately reflected - self.runCmd("type summary add i_am_cool --python-script \"%s\"" % script) + self.runCmd( + "type summary add i_am_cool --python-script \"%s\"" % + script) self.expect("frame variable two", - substrs = ['int says 1']) - + substrs=['int says 1']) + self.expect("frame variable twoptr", - substrs = ['int says 1']) + substrs=['int says 1']) # Change the summary - self.runCmd("type summary add --summary-string \"int says ${var.integer}, and float says ${var.floating}\" i_am_cool") + self.runCmd( + "type summary add --summary-string \"int says ${var.integer}, and float says ${var.floating}\" i_am_cool") self.expect("frame variable two", - substrs = ['int says 1', - 'and float says 2.71']) + substrs=['int says 1', + 'and float says 2.71']) # Try it for pointers self.expect("frame variable twoptr", - substrs = ['int says 1', - 'and float says 2.71']) + substrs=['int says 1', + 'and float says 2.71']) # Force a failure for pointers - self.runCmd("type summary add i_am_cool -p --python-script \"%s\"" % script) + self.runCmd( + "type summary add i_am_cool -p --python-script \"%s\"" % + script) self.expect("frame variable twoptr", matching=False, - substrs = ['and float says 2.71']) + substrs=['and float says 2.71']) - script = 'return \'Python summary\''; + script = 'return \'Python summary\'' - self.runCmd("type summary add --name test_summary --python-script \"%s\"" % script) + self.runCmd( + "type summary add --name test_summary --python-script \"%s\"" % + script) # attach the Python named summary to someone self.expect("frame variable one --summary test_summary", - substrs = ['Python summary']) + substrs=['Python summary']) # should not bind to the type self.expect("frame variable two", matching=False, - substrs = ['Python summary']) + substrs=['Python summary']) # and should not stick to the variable - self.expect("frame variable one",matching=False, - substrs = ['Python summary']) + self.expect("frame variable one", matching=False, + substrs=['Python summary']) - self.runCmd("type summary add i_am_cool --summary-string \"Text summary\"") + self.runCmd( + "type summary add i_am_cool --summary-string \"Text summary\"") # should be temporary only - self.expect("frame variable one",matching=False, - substrs = ['Python summary']) + self.expect("frame variable one", matching=False, + substrs=['Python summary']) # use the type summary self.expect("frame variable two", - substrs = ['Text summary']) + substrs=['Text summary']) - self.runCmd("n"); # skip ahead to make values change + self.runCmd("n") # skip ahead to make values change # both should use the type summary now self.expect("frame variable one", - substrs = ['Text summary']) - + substrs=['Text summary']) + self.expect("frame variable two", - substrs = ['Text summary']) + substrs=['Text summary']) # disable type summary for pointers, and make a Python regex summary - self.runCmd("type summary add i_am_cool -p --summary-string \"Text summary\"") + self.runCmd( + "type summary add i_am_cool -p --summary-string \"Text summary\"") self.runCmd("type summary add -x cool --python-script \"%s\"" % script) # variables should stick to the type summary self.expect("frame variable one", - substrs = ['Text summary']) + substrs=['Text summary']) self.expect("frame variable two", - substrs = ['Text summary']) + substrs=['Text summary']) # array and pointer should match the Python one self.expect("frame variable twoptr", - substrs = ['Python summary']) - + substrs=['Python summary']) + self.expect("frame variable array", - substrs = ['Python summary']) + substrs=['Python summary']) # return pointers to the type summary - self.runCmd("type summary add i_am_cool --summary-string \"Text summary\"") + self.runCmd( + "type summary add i_am_cool --summary-string \"Text summary\"") self.expect("frame variable one", - substrs = ['Text summary']) - + substrs=['Text summary']) + self.expect("frame variable two", - substrs = ['Text summary']) - + substrs=['Text summary']) + self.expect("frame variable twoptr", - substrs = ['Text summary']) - + substrs=['Text summary']) + self.expect("frame variable array", - substrs = ['Python summary']) + substrs=['Python summary']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py index c186f1465cf..5b52277e8b7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py @@ -5,19 +5,24 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SkipSummaryDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr20548 fails to build on lab.llvm.org buildbot") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr20548 fails to build on lab.llvm.org buildbot") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") def test_with_run_command(self): """Test data formatter commands.""" self.build() @@ -34,15 +39,15 @@ class SkipSummaryDataFormatterTestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) #import lldbsuite.test.lldbutil as lldbutil - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) - + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -55,122 +60,146 @@ class SkipSummaryDataFormatterTestCase(TestBase): # Setup the summaries for this scenario #self.runCmd("type summary add --summary-string \"${var._M_dataplus._M_p}\" std::string") - self.runCmd("type summary add --summary-string \"Level 1\" \"DeepData_1\"") - self.runCmd("type summary add --summary-string \"Level 2\" \"DeepData_2\" -e") - self.runCmd("type summary add --summary-string \"Level 3\" \"DeepData_3\"") - self.runCmd("type summary add --summary-string \"Level 4\" \"DeepData_4\"") - self.runCmd("type summary add --summary-string \"Level 5\" \"DeepData_5\"") - + self.runCmd( + "type summary add --summary-string \"Level 1\" \"DeepData_1\"") + self.runCmd( + "type summary add --summary-string \"Level 2\" \"DeepData_2\" -e") + self.runCmd( + "type summary add --summary-string \"Level 3\" \"DeepData_3\"") + self.runCmd( + "type summary add --summary-string \"Level 4\" \"DeepData_4\"") + self.runCmd( + "type summary add --summary-string \"Level 5\" \"DeepData_5\"") + # Default case, just print out summaries self.expect('frame variable', - substrs = ['(DeepData_1) data1 = Level 1', - '(DeepData_2) data2 = Level 2 {', - 'm_child1 = Level 3', - 'm_child2 = Level 3', - 'm_child3 = Level 3', - 'm_child4 = Level 3', - '}']) + substrs=['(DeepData_1) data1 = Level 1', + '(DeepData_2) data2 = Level 2 {', + 'm_child1 = Level 3', + 'm_child2 = Level 3', + 'm_child3 = Level 3', + 'm_child4 = Level 3', + '}']) # Skip the default (should be 1) levels of summaries self.expect('frame variable --no-summary-depth', - substrs = ['(DeepData_1) data1 = {', - 'm_child1 = 0x', - '}', - '(DeepData_2) data2 = {', - 'm_child1 = Level 3', - 'm_child2 = Level 3', - 'm_child3 = Level 3', - 'm_child4 = Level 3', - '}']) + substrs=['(DeepData_1) data1 = {', + 'm_child1 = 0x', + '}', + '(DeepData_2) data2 = {', + 'm_child1 = Level 3', + 'm_child2 = Level 3', + 'm_child3 = Level 3', + 'm_child4 = Level 3', + '}']) # Now skip 2 levels of summaries self.expect('frame variable --no-summary-depth=2', - substrs = ['(DeepData_1) data1 = {', - 'm_child1 = 0x', - '}', - '(DeepData_2) data2 = {', - 'm_child1 = {', - 'm_child1 = 0x', - 'Level 4', - 'm_child2 = {', - 'm_child3 = {', - '}']) + substrs=['(DeepData_1) data1 = {', + 'm_child1 = 0x', + '}', + '(DeepData_2) data2 = {', + 'm_child1 = {', + 'm_child1 = 0x', + 'Level 4', + 'm_child2 = {', + 'm_child3 = {', + '}']) # Check that no "Level 3" comes out - self.expect('frame variable data1.m_child1 --no-summary-depth=2', matching=False, - substrs = ['Level 3']) + self.expect( + 'frame variable data1.m_child1 --no-summary-depth=2', + matching=False, + substrs=['Level 3']) # Now expand a pointer with 2 level of skipped summaries self.expect('frame variable data1.m_child1 --no-summary-depth=2', - substrs = ['(DeepData_2 *) data1.m_child1 = 0x']) + substrs=['(DeepData_2 *) data1.m_child1 = 0x']) # Deref and expand said pointer self.expect('frame variable *data1.m_child1 --no-summary-depth=2', - substrs = ['(DeepData_2) *data1.m_child1 = {', - 'm_child2 = {', - 'm_child1 = 0x', - 'Level 4', - '}']) + substrs=['(DeepData_2) *data1.m_child1 = {', + 'm_child2 = {', + 'm_child1 = 0x', + 'Level 4', + '}']) # Expand an expression, skipping 2 layers of summaries - self.expect('frame variable data1.m_child1->m_child2 --no-summary-depth=2', - substrs = ['(DeepData_3) data1.m_child1->m_child2 = {', - 'm_child2 = {', - 'm_child1 = Level 5', - 'm_child2 = Level 5', - 'm_child3 = Level 5', - '}']) + self.expect( + 'frame variable data1.m_child1->m_child2 --no-summary-depth=2', + substrs=[ + '(DeepData_3) data1.m_child1->m_child2 = {', + 'm_child2 = {', + 'm_child1 = Level 5', + 'm_child2 = Level 5', + 'm_child3 = Level 5', + '}']) # Expand same expression, skipping only 1 layer of summaries - self.expect('frame variable data1.m_child1->m_child2 --no-summary-depth=1', - substrs = ['(DeepData_3) data1.m_child1->m_child2 = {', - 'm_child1 = 0x', - 'Level 4', - 'm_child2 = Level 4', - '}']) + self.expect( + 'frame variable data1.m_child1->m_child2 --no-summary-depth=1', + substrs=[ + '(DeepData_3) data1.m_child1->m_child2 = {', + 'm_child1 = 0x', + 'Level 4', + 'm_child2 = Level 4', + '}']) # Bad debugging info on SnowLeopard gcc (Apple Inc. build 5666). # Skip the following tests if the condition is met. if self.getCompiler().endswith('gcc') and not self.getCompiler().endswith('llvm-gcc'): - import re - gcc_version_output = system([[lldbutil.which(self.getCompiler()), "-v"]])[1] - #print("my output:", gcc_version_output) - for line in gcc_version_output.split(os.linesep): - m = re.search('\(Apple Inc\. build ([0-9]+)\)', line) - #print("line:", line) - if m: - gcc_build = int(m.group(1)) - #print("gcc build:", gcc_build) - if gcc_build >= 5666: - # rdar://problem/9804600" - self.skipTest("rdar://problem/9804600 wrong namespace for std::string in debug info") + import re + gcc_version_output = system( + [[lldbutil.which(self.getCompiler()), "-v"]])[1] + #print("my output:", gcc_version_output) + for line in gcc_version_output.split(os.linesep): + m = re.search('\(Apple Inc\. build ([0-9]+)\)', line) + #print("line:", line) + if m: + gcc_build = int(m.group(1)) + #print("gcc build:", gcc_build) + if gcc_build >= 5666: + # rdar://problem/9804600" + self.skipTest( + "rdar://problem/9804600 wrong namespace for std::string in debug info") # Expand same expression, skipping 3 layers of summaries - self.expect('frame variable data1.m_child1->m_child2 --show-types --no-summary-depth=3', - substrs = ['(DeepData_3) data1.m_child1->m_child2 = {', - 'm_some_text = "Just a test"', - 'm_child2 = {', - 'm_some_text = "Just a test"']) - - # Expand within a standard string (might depend on the implementation of the C++ stdlib you use) - self.expect('frame variable data1.m_child1->m_child2.m_child1.m_child2 --no-summary-depth=2', - substrs = ['(DeepData_5) data1.m_child1->m_child2.m_child1.m_child2 = {', - 'm_some_text = {', - '_M_dataplus = (_M_p = "Just a test")']) + self.expect( + 'frame variable data1.m_child1->m_child2 --show-types --no-summary-depth=3', + substrs=[ + '(DeepData_3) data1.m_child1->m_child2 = {', + 'm_some_text = "Just a test"', + 'm_child2 = {', + 'm_some_text = "Just a test"']) + + # Expand within a standard string (might depend on the implementation + # of the C++ stdlib you use) + self.expect( + 'frame variable data1.m_child1->m_child2.m_child1.m_child2 --no-summary-depth=2', + substrs=[ + '(DeepData_5) data1.m_child1->m_child2.m_child1.m_child2 = {', + 'm_some_text = {', + '_M_dataplus = (_M_p = "Just a test")']) # Repeat the above, but only skip 1 level of summaries - self.expect('frame variable data1.m_child1->m_child2.m_child1.m_child2 --no-summary-depth=1', - substrs = ['(DeepData_5) data1.m_child1->m_child2.m_child1.m_child2 = {', - 'm_some_text = "Just a test"', - '}']) - - # Change summary and expand, first without --no-summary-depth then with --no-summary-depth - self.runCmd("type summary add --summary-string \"${var.m_some_text}\" DeepData_5") - - self.expect('fr var data2.m_child4.m_child2.m_child2', - substrs = ['(DeepData_5) data2.m_child4.m_child2.m_child2 = "Just a test"']) - - self.expect('fr var data2.m_child4.m_child2.m_child2 --no-summary-depth', - substrs = ['(DeepData_5) data2.m_child4.m_child2.m_child2 = {', - 'm_some_text = "Just a test"', - '}']) + self.expect( + 'frame variable data1.m_child1->m_child2.m_child1.m_child2 --no-summary-depth=1', + substrs=[ + '(DeepData_5) data1.m_child1->m_child2.m_child1.m_child2 = {', + 'm_some_text = "Just a test"', + '}']) + + # Change summary and expand, first without --no-summary-depth then with + # --no-summary-depth + self.runCmd( + "type summary add --summary-string \"${var.m_some_text}\" DeepData_5") + + self.expect('fr var data2.m_child4.m_child2.m_child2', substrs=[ + '(DeepData_5) data2.m_child4.m_child2.m_child2 = "Just a test"']) + + self.expect( + 'fr var data2.m_child4.m_child2.m_child2 --no-summary-depth', + substrs=[ + '(DeepData_5) data2.m_child4.m_child2.m_child2 = {', + 'm_some_text = "Just a test"', + '}']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py index b3f8ba7d048..9e82f11ff36 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py @@ -5,18 +5,21 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SmartArrayDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") def test_with_run_command(self): """Test data formatter commands.""" self.build() @@ -32,7 +35,8 @@ class SmartArrayDataFormatterTestCase(TestBase): """Test that that file and class static variables display correctly.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) @@ -40,9 +44,9 @@ class SmartArrayDataFormatterTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): @@ -56,338 +60,400 @@ class SmartArrayDataFormatterTestCase(TestBase): self.runCmd("type summary add --summary-string \"${var%V}\" SomeData") self.expect("frame variable data", - substrs = ['SomeData @ 0x']) + substrs=['SomeData @ 0x']) # ${var%s} - self.runCmd("type summary add --summary-string \"ptr = ${var%s}\" \"char *\"") + self.runCmd( + "type summary add --summary-string \"ptr = ${var%s}\" \"char *\"") self.expect("frame variable strptr", - substrs = ['ptr = \"', - 'Hello world!']) + substrs=['ptr = \"', + 'Hello world!']) self.expect("frame variable other.strptr", - substrs = ['ptr = \"', - 'Nested Hello world!']) - - self.runCmd("type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\"") - + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\"") + self.expect("frame variable strarr", - substrs = ['arr = \"', - 'Hello world!']) - + substrs=['arr = \"', + 'Hello world!']) + self.expect("frame variable other.strarr", - substrs = ['arr = \"', - 'Nested Hello world!']) + substrs=['arr = \"', + 'Nested Hello world!']) self.expect("p strarr", - substrs = ['arr = \"', - 'Hello world!']) + substrs=['arr = \"', + 'Hello world!']) self.expect("p other.strarr", - substrs = ['arr = \"', - 'Nested Hello world!']) + substrs=['arr = \"', + 'Nested Hello world!']) # ${var%c} - self.runCmd("type summary add --summary-string \"ptr = ${var%c}\" \"char *\"") - + self.runCmd( + "type summary add --summary-string \"ptr = ${var%c}\" \"char *\"") + self.expect("frame variable strptr", - substrs = ['ptr = \"', - 'Hello world!']) - + substrs=['ptr = \"', + 'Hello world!']) + self.expect("frame variable other.strptr", - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) self.expect("p strptr", - substrs = ['ptr = \"', - 'Hello world!']) + substrs=['ptr = \"', + 'Hello world!']) self.expect("p other.strptr", - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) - self.runCmd("type summary add --summary-string \"arr = ${var%c}\" -x \"char \\[[0-9]+\\]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%c}\" -x \"char \\[[0-9]+\\]\"") self.expect("frame variable strarr", - substrs = ['arr = \"', - 'Hello world!']) + substrs=['arr = \"', + 'Hello world!']) self.expect("frame variable other.strarr", - substrs = ['arr = \"', - 'Nested Hello world!']) - + substrs=['arr = \"', + 'Nested Hello world!']) + self.expect("p strarr", - substrs = ['arr = \"', - 'Hello world!']) + substrs=['arr = \"', + 'Hello world!']) self.expect("p other.strarr", - substrs = ['arr = \"', - 'Nested Hello world!']) + substrs=['arr = \"', + 'Nested Hello world!']) # ${var%char[]} - self.runCmd("type summary add --summary-string \"arr = ${var%char[]}\" -x \"char \\[[0-9]+\\]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%char[]}\" -x \"char \\[[0-9]+\\]\"") self.expect("frame variable strarr", - substrs = ['arr = \"', - 'Hello world!']) + substrs=['arr = \"', + 'Hello world!']) self.expect("frame variable other.strarr", - substrs = ['arr = ', - 'Nested Hello world!']) + substrs=['arr = ', + 'Nested Hello world!']) self.expect("p strarr", - substrs = ['arr = \"', - 'Hello world!']) + substrs=['arr = \"', + 'Hello world!']) self.expect("p other.strarr", - substrs = ['arr = ', - 'Nested Hello world!']) + substrs=['arr = ', + 'Nested Hello world!']) - self.runCmd("type summary add --summary-string \"ptr = ${var%char[]}\" \"char *\"") + self.runCmd( + "type summary add --summary-string \"ptr = ${var%char[]}\" \"char *\"") self.expect("frame variable strptr", - substrs = ['ptr = \"', - 'Hello world!']) - + substrs=['ptr = \"', + 'Hello world!']) + self.expect("frame variable other.strptr", - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) self.expect("p strptr", - substrs = ['ptr = \"', - 'Hello world!']) + substrs=['ptr = \"', + 'Hello world!']) self.expect("p other.strptr", - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) # ${var%a} - self.runCmd("type summary add --summary-string \"arr = ${var%a}\" -x \"char \\[[0-9]+\\]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%a}\" -x \"char \\[[0-9]+\\]\"") self.expect("frame variable strarr", - substrs = ['arr = \"', - 'Hello world!']) + substrs=['arr = \"', + 'Hello world!']) self.expect("frame variable other.strarr", - substrs = ['arr = ', - 'Nested Hello world!']) + substrs=['arr = ', + 'Nested Hello world!']) self.expect("p strarr", - substrs = ['arr = \"', - 'Hello world!']) + substrs=['arr = \"', + 'Hello world!']) self.expect("p other.strarr", - substrs = ['arr = ', - 'Nested Hello world!']) + substrs=['arr = ', + 'Nested Hello world!']) - self.runCmd("type summary add --summary-string \"ptr = ${var%a}\" \"char *\"") + self.runCmd( + "type summary add --summary-string \"ptr = ${var%a}\" \"char *\"") self.expect("frame variable strptr", - substrs = ['ptr = \"', - 'Hello world!']) + substrs=['ptr = \"', + 'Hello world!']) self.expect("frame variable other.strptr", - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) self.expect("p strptr", - substrs = ['ptr = \"', - 'Hello world!']) + substrs=['ptr = \"', + 'Hello world!']) self.expect("p other.strptr", - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.runCmd( + "type summary add --summary-string \"ptr = ${var[]%char[]}\" \"char *\"") - self.runCmd("type summary add --summary-string \"ptr = ${var[]%char[]}\" \"char *\"") - # I do not know the size of the data, but you are asking for a full array slice.. # use the ${var%char[]} to obtain a string as result self.expect("frame variable strptr", matching=False, - substrs = ['ptr = \"', - 'Hello world!']) - + substrs=['ptr = \"', + 'Hello world!']) + self.expect("frame variable other.strptr", matching=False, - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) self.expect("p strptr", matching=False, - substrs = ['ptr = \"', - 'Hello world!']) + substrs=['ptr = \"', + 'Hello world!']) self.expect("p other.strptr", matching=False, - substrs = ['ptr = \"', - 'Nested Hello world!']) + substrs=['ptr = \"', + 'Nested Hello world!']) # You asked an array-style printout... - self.runCmd("type summary add --summary-string \"ptr = ${var[0-1]%char[]}\" \"char *\"") - + self.runCmd( + "type summary add --summary-string \"ptr = ${var[0-1]%char[]}\" \"char *\"") + self.expect("frame variable strptr", - substrs = ['ptr = ', - '[{H},{e}]']) - + substrs=['ptr = ', + '[{H},{e}]']) + self.expect("frame variable other.strptr", - substrs = ['ptr = ', - '[{N},{e}]']) + substrs=['ptr = ', + '[{N},{e}]']) self.expect("p strptr", - substrs = ['ptr = ', - '[{H},{e}]']) + substrs=['ptr = ', + '[{H},{e}]']) self.expect("p other.strptr", - substrs = ['ptr = ', - '[{N},{e}]']) + substrs=['ptr = ', + '[{N},{e}]']) # using [] is required here - self.runCmd("type summary add --summary-string \"arr = ${var%x}\" \"int [5]\"") - - self.expect("frame variable intarr",matching=False, - substrs = ['0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) - - self.expect("frame variable other.intarr", matching=False, - substrs = ['0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) - - self.runCmd("type summary add --summary-string \"arr = ${var[]%x}\" \"int [5]\"") - - self.expect("frame variable intarr", - substrs = ['intarr = arr =', - '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) - - self.expect("frame variable other.intarr", - substrs = ['intarr = arr =', - '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + self.runCmd( + "type summary add --summary-string \"arr = ${var%x}\" \"int [5]\"") + + self.expect("frame variable intarr", matching=False, substrs=[ + '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + + self.expect("frame variable other.intarr", matching=False, substrs=[ + '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var[]%x}\" \"int [5]\"") + + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr =', + '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) # printing each array item as an array - self.runCmd("type summary add --summary-string \"arr = ${var[]%uint32_t[]}\" \"int [5]\"") - - self.expect("frame variable intarr", - substrs = ['intarr = arr =', - '{0x00000001},{0x00000001},{0x00000002},{0x00000003},{0x00000005}']) - - self.expect("frame variable other.intarr", - substrs = ['intarr = arr = ', - '{0x00000009},{0x00000008},{0x00000007},{0x00000006},{0x00000005}']) + self.runCmd( + "type summary add --summary-string \"arr = ${var[]%uint32_t[]}\" \"int [5]\"") + + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '{0x00000001},{0x00000001},{0x00000002},{0x00000003},{0x00000005}']) + + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr = ', + '{0x00000009},{0x00000008},{0x00000007},{0x00000006},{0x00000005}']) # printing full array as an array - self.runCmd("type summary add --summary-string \"arr = ${var%uint32_t[]}\" \"int [5]\"") - - self.expect("frame variable intarr", - substrs = ['intarr = arr =', - '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + self.runCmd( + "type summary add --summary-string \"arr = ${var%uint32_t[]}\" \"int [5]\"") - self.expect("frame variable other.intarr", - substrs = ['intarr = arr =', - '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr =', + '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) # printing each array item as an array - self.runCmd("type summary add --summary-string \"arr = ${var[]%float32[]}\" \"float [7]\"") - - self.expect("frame variable flarr", - substrs = ['flarr = arr =', - '{78.5},{77.25},{78},{76.125},{76.75},{76.875},{77}']) - - self.expect("frame variable other.flarr", - substrs = ['flarr = arr = ', - '{25.5},{25.25},{25.125},{26.75},{27.375},{27.5},{26.125}']) - + self.runCmd( + "type summary add --summary-string \"arr = ${var[]%float32[]}\" \"float [7]\"") + + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '{78.5},{77.25},{78},{76.125},{76.75},{76.875},{77}']) + + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr = ', + '{25.5},{25.25},{25.125},{26.75},{27.375},{27.5},{26.125}']) + # printing full array as an array - self.runCmd("type summary add --summary-string \"arr = ${var%float32[]}\" \"float [7]\"") - + self.runCmd( + "type summary add --summary-string \"arr = ${var%float32[]}\" \"float [7]\"") + self.expect("frame variable flarr", - substrs = ['flarr = arr =', - '78.5,77.25,78,76.125,76.75,76.875,77']) - + substrs=['flarr = arr =', + '78.5,77.25,78,76.125,76.75,76.875,77']) + self.expect("frame variable other.flarr", - substrs = ['flarr = arr =', - '25.5,25.25,25.125,26.75,27.375,27.5,26.125']) + substrs=['flarr = arr =', + '25.5,25.25,25.125,26.75,27.375,27.5,26.125']) # using array smart summary strings for pointers should make no sense - self.runCmd("type summary add --summary-string \"arr = ${var%float32[]}\" \"float *\"") - self.runCmd("type summary add --summary-string \"arr = ${var%int32_t[]}\" \"int *\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%float32[]}\" \"float *\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%int32_t[]}\" \"int *\"") self.expect("frame variable flptr", matching=False, - substrs = ['78.5,77.25,78,76.125,76.75,76.875,77']) - + substrs=['78.5,77.25,78,76.125,76.75,76.875,77']) + self.expect("frame variable intptr", matching=False, - substrs = ['1,1,2,3,5']) + substrs=['1,1,2,3,5']) # use y and Y - self.runCmd("type summary add --summary-string \"arr = ${var%y}\" \"float [7]\"") - self.runCmd("type summary add --summary-string \"arr = ${var%y}\" \"int [5]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%y}\" \"float [7]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%y}\" \"int [5]\"") if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable flarr", - substrs = ['flarr = arr =', - '00 00 9d 42,00 80 9a 42,00 00 9c 42,00 40 98 42,00 80 99 42,00 c0 99 42,00 00 9a 42']) + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '00 00 9d 42,00 80 9a 42,00 00 9c 42,00 40 98 42,00 80 99 42,00 c0 99 42,00 00 9a 42']) else: - self.expect("frame variable flarr", - substrs = ['flarr = arr =', - '42 9d 00 00,42 9a 80 00,42 9c 00 00,42 98 40 00,42 99 80 00,42 99 c0 00,42 9a 00 00']) + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '42 9d 00 00,42 9a 80 00,42 9c 00 00,42 98 40 00,42 99 80 00,42 99 c0 00,42 9a 00 00']) if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable other.flarr", - substrs = ['flarr = arr =', - '00 00 cc 41,00 00 ca 41,00 00 c9 41,00 00 d6 41,00 00 db 41,00 00 dc 41,00 00 d1 41']) + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '00 00 cc 41,00 00 ca 41,00 00 c9 41,00 00 d6 41,00 00 db 41,00 00 dc 41,00 00 d1 41']) else: - self.expect("frame variable other.flarr", - substrs = ['flarr = arr =', - '41 cc 00 00,41 ca 00 00,41 c9 00 00,41 d6 00 00,41 db 00 00,41 dc 00 00,41 d1 00 00']) + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '41 cc 00 00,41 ca 00 00,41 c9 00 00,41 d6 00 00,41 db 00 00,41 dc 00 00,41 d1 00 00']) if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable intarr", - substrs = ['intarr = arr =', - '01 00 00 00,01 00 00 00,02 00 00 00,03 00 00 00,05 00 00 00']) + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '01 00 00 00,01 00 00 00,02 00 00 00,03 00 00 00,05 00 00 00']) else: - self.expect("frame variable intarr", - substrs = ['intarr = arr =', - '00 00 00 01,00 00 00 01,00 00 00 02,00 00 00 03,00 00 00 05']) + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '00 00 00 01,00 00 00 01,00 00 00 02,00 00 00 03,00 00 00 05']) if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable other.intarr", - substrs = ['intarr = arr = ', - '09 00 00 00,08 00 00 00,07 00 00 00,06 00 00 00,05 00 00 00']) + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr = ', + '09 00 00 00,08 00 00 00,07 00 00 00,06 00 00 00,05 00 00 00']) else: - self.expect("frame variable other.intarr", - substrs = ['intarr = arr = ', - '00 00 00 09,00 00 00 08,00 00 00 07,00 00 00 06,00 00 00 05']) - - self.runCmd("type summary add --summary-string \"arr = ${var%Y}\" \"float [7]\"") - self.runCmd("type summary add --summary-string \"arr = ${var%Y}\" \"int [5]\"") - + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr = ', + '00 00 00 09,00 00 00 08,00 00 00 07,00 00 00 06,00 00 00 05']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%Y}\" \"float [7]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%Y}\" \"int [5]\"") + if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable flarr", - substrs = ['flarr = arr =', - '00 00 9d 42 ...B,00 80 9a 42 ...B,00 00 9c 42 ...B,00 40 98 42 .@.B,00 80 99 42 ...B,00 c0 99 42 ...B,00 00 9a 42 ...B']) + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '00 00 9d 42 ...B,00 80 9a 42 ...B,00 00 9c 42 ...B,00 40 98 42 .@.B,00 80 99 42 ...B,00 c0 99 42 ...B,00 00 9a 42 ...B']) else: - self.expect("frame variable flarr", - substrs = ['flarr = arr =', - '42 9d 00 00 B...,42 9a 80 00 B...,42 9c 00 00 B...,42 98 40 00 B.@.,42 99 80 00 B...,42 99 c0 00 B...,42 9a 00 00 B...']) + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '42 9d 00 00 B...,42 9a 80 00 B...,42 9c 00 00 B...,42 98 40 00 B.@.,42 99 80 00 B...,42 99 c0 00 B...,42 9a 00 00 B...']) if process.GetByteOrder() == lldb.eByteOrderLittle: - self.expect("frame variable other.flarr", - substrs = ['flarr = arr =', - '00 00 cc 41 ...A,00 00 ca 41 ...A,00 00 c9 41 ...A,00 00 d6 41 ...A,00 00 db 41 ...A,00 00 dc 41 ...A,00 00 d1 41 ...A']) + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '00 00 cc 41 ...A,00 00 ca 41 ...A,00 00 c9 41 ...A,00 00 d6 41 ...A,00 00 db 41 ...A,00 00 dc 41 ...A,00 00 d1 41 ...A']) else: - self.expect("frame variable other.flarr", - substrs = ['flarr = arr =', - '41 cc 00 00 A...,41 ca 00 00 A...,41 c9 00 00 A...,41 d6 00 00 A...,41 db 00 00 A...,41 dc 00 00 A...,41 d1 00 00 A...']) + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '41 cc 00 00 A...,41 ca 00 00 A...,41 c9 00 00 A...,41 d6 00 00 A...,41 db 00 00 A...,41 dc 00 00 A...,41 d1 00 00 A...']) if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect("frame variable intarr", - substrs = ['intarr = arr =', - '....,01 00 00 00', - '....,05 00 00 00']) + substrs=['intarr = arr =', + '....,01 00 00 00', + '....,05 00 00 00']) else: self.expect("frame variable intarr", - substrs = ['intarr = arr =', - '....,00 00 00 01', - '....,00 00 00 05']) + substrs=['intarr = arr =', + '....,00 00 00 01', + '....,00 00 00 05']) if process.GetByteOrder() == lldb.eByteOrderLittle: self.expect("frame variable other.intarr", - substrs = ['intarr = arr = ', - '09 00 00 00', - '....,07 00 00 00']) + substrs=['intarr = arr = ', + '09 00 00 00', + '....,07 00 00 00']) else: self.expect("frame variable other.intarr", - substrs = ['intarr = arr = ', - '00 00 00 09', - '....,00 00 00 07']) + substrs=['intarr = arr = ', + '00 00 00 09', + '....,00 00 00 07']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py index 083f713c259..2b63dbb1c83 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibCxxAtomicTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,30 +24,39 @@ class LibCxxAtomicTestCase(TestBase): return var @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test(self): """Test that std::atomic as defined by libc++ is correctly printed by LLDB""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")) + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + s = self.get_variable('s') i = self.get_variable('i') - - if self.TraceOn(): print(s) - if self.TraceOn(): print(i) - + + if self.TraceOn(): + print(s) + if self.TraceOn(): + print(i) + self.assertTrue(i.GetValueAsUnsigned(0) == 5, "i == 5") self.assertTrue(s.GetNumChildren() == 2, "s has two children") - self.assertTrue(s.GetChildAtIndex(0).GetValueAsUnsigned(0) == 1, "s.x == 1") - self.assertTrue(s.GetChildAtIndex(1).GetValueAsUnsigned(0) == 2, "s.y == 2") + self.assertTrue( + s.GetChildAtIndex(0).GetValueAsUnsigned(0) == 1, + "s.x == 1") + self.assertTrue( + s.GetChildAtIndex(1).GetValueAsUnsigned(0) == 2, + "s.y == 2") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py index a5eec8a0362..6a832e02990 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibCxxFunctionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,28 +24,33 @@ class LibCxxFunctionTestCase(TestBase): return var @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test(self): """Test that std::function as defined by libc++ is correctly printed by LLDB""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")) + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + f1 = self.get_variable('f1') f2 = self.get_variable('f2') - - if self.TraceOn(): print(f1) - if self.TraceOn(): print(f2) - + + if self.TraceOn(): + print(f1) + if self.TraceOn(): + print(f2) + self.assertTrue(f1.GetValueAsUnsigned(0) != 0, 'f1 has a valid value') self.assertTrue(f2.GetValueAsUnsigned(0) != 0, 'f2 has a valid value') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py index d452c1be69b..f0857f420fc 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py @@ -5,37 +5,44 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class InitializerListTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet @skipIf(compiler="gcc") - @expectedFailureAll(oslist=["linux"], bugnumber="fails on clang 3.5 and tot") + @expectedFailureAll( + oslist=["linux"], + bugnumber="fails on clang 3.5 and tot") def test(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")) + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) - self.expect("frame variable ili", substrs = ['[1] = 2','[4] = 5']) - self.expect("frame variable ils", substrs = ['[4] = "surprise it is a long string!! yay!!"']) + self.expect("frame variable ili", substrs=['[1] = 2', '[4] = 5']) + self.expect("frame variable ils", substrs=[ + '[4] = "surprise it is a long string!! yay!!"']) - self.expect('image list', substrs = self.getLibcPlusPlusLibs()) + self.expect('image list', substrs=self.getLibcPlusPlusLibs()) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py index 23f6956cf3f..cbcdc2ce739 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxIteratorDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,22 +24,24 @@ class LibcxxIteratorDataFormatterTestCase(TestBase): self.line = line_number('main.cpp', '// Set break point at this line.') @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test_with_run_command(self): """Test that libc++ iterators format properly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,21 +50,31 @@ class LibcxxIteratorDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('image list', substrs = self.getLibcPlusPlusLibs()) + self.expect('image list', substrs=self.getLibcPlusPlusLibs()) - self.expect('frame variable ivI', substrs = ['item = 3']) - self.expect('expr ivI', substrs = ['item = 3']) + self.expect('frame variable ivI', substrs=['item = 3']) + self.expect('expr ivI', substrs=['item = 3']) - self.expect('frame variable iimI', substrs = ['first = 0','second = 12']) - self.expect('expr iimI', substrs = ['first = 0','second = 12']) + self.expect( + 'frame variable iimI', + substrs=[ + 'first = 0', + 'second = 12']) + self.expect('expr iimI', substrs=['first = 0', 'second = 12']) - self.expect('frame variable simI', substrs = ['first = "world"','second = 42']) - self.expect('expr simI', substrs = ['first = "world"','second = 42']) + self.expect( + 'frame variable simI', + substrs=[ + 'first = "world"', + 'second = 42']) + self.expect('expr simI', substrs=['first = "world"', 'second = 42']) - self.expect('frame variable svI', substrs = ['item = "hello"']) - self.expect('expr svI', substrs = ['item = "hello"']) + self.expect('frame variable svI', substrs=['item = "hello"']) + self.expect('expr svI', substrs=['item = "hello"']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py index 6fcdc37465d..61101411f65 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py @@ -5,13 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time, re +import os +import time +import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxListDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,31 +23,39 @@ class LibcxxListDataFormatterTestCase(TestBase): TestBase.setUp(self) # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - self.line2 = line_number('main.cpp', '// Set second break point at this line.') - self.line3 = line_number('main.cpp', '// Set third break point at this line.') - self.line4 = line_number('main.cpp', '// Set fourth break point at this line.') + self.line2 = line_number('main.cpp', + '// Set second break point at this line.') + self.line3 = line_number('main.cpp', + '// Set third break point at this line.') + self.line4 = line_number('main.cpp', + '// Set fourth break point at this line.') @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet @expectedFailureAll(oslist=["macosx"], bugnumber="rdar://25499635") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line2, num_expected_locations=-1) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line3, num_expected_locations=-1) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line4, num_expected_locations=-1) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line2, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line3, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line4, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -54,135 +64,154 @@ class LibcxxListDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("frame variable numbers_list --show-types") - self.runCmd("type summary add std::int_list std::string_list int_list string_list --summary-string \"list has ${svar%#} items\" -e") + self.runCmd( + "type summary add std::int_list std::string_list int_list string_list --summary-string \"list has ${svar%#} items\" -e") self.runCmd("type format add -f hex int") self.expect("frame variable numbers_list --raw", matching=False, - substrs = ['list has 0 items', - '{}']) + substrs=['list has 0 items', + '{}']) self.expect("frame variable numbers_list", - substrs = ['list has 0 items', - '{}']) + substrs=['list has 0 items', + '{}']) self.expect("p numbers_list", - substrs = ['list has 0 items', - '{}']) + substrs=['list has 0 items', + '{}']) self.runCmd("n") self.expect("frame variable numbers_list", - substrs = ['list has 1 items', - '[0] = ', - '0x12345678']) + substrs=['list has 1 items', + '[0] = ', + '0x12345678']) - self.runCmd("n");self.runCmd("n");self.runCmd("n"); + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") self.expect("frame variable numbers_list", - substrs = ['list has 4 items', - '[0] = ', - '0x12345678', - '[1] =', - '0x11223344', - '[2] =', - '0xbeeffeed', - '[3] =', - '0x00abba00']) - - self.runCmd("n");self.runCmd("n"); + substrs=['list has 4 items', + '[0] = ', + '0x12345678', + '[1] =', + '0x11223344', + '[2] =', + '0xbeeffeed', + '[3] =', + '0x00abba00']) + + self.runCmd("n") + self.runCmd("n") self.expect("frame variable numbers_list", - substrs = ['list has 6 items', - '[0] = ', - '0x12345678', - '0x11223344', - '0xbeeffeed', - '0x00abba00', - '[4] =', - '0x0abcdef0', - '[5] =', - '0x0cab0cab']) + substrs=['list has 6 items', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) self.expect("p numbers_list", - substrs = ['list has 6 items', - '[0] = ', - '0x12345678', - '0x11223344', - '0xbeeffeed', - '0x00abba00', - '[4] =', - '0x0abcdef0', - '[5] =', - '0x0cab0cab']) + substrs=['list has 6 items', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) # check access-by-index self.expect("frame variable numbers_list[0]", - substrs = ['0x12345678']); + substrs=['0x12345678']) self.expect("frame variable numbers_list[1]", - substrs = ['0x11223344']); + substrs=['0x11223344']) self.runCmd("n") - + self.expect("frame variable numbers_list", - substrs = ['list has 0 items', - '{}']) + substrs=['list has 0 items', + '{}']) + + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") - self.runCmd("n");self.runCmd("n");self.runCmd("n");self.runCmd("n"); - self.expect("frame variable numbers_list", - substrs = ['list has 4 items', - '[0] = ', '1', - '[1] = ', '2', - '[2] = ', '3', - '[3] = ', '4']) + substrs=['list has 4 items', + '[0] = ', '1', + '[1] = ', '2', + '[2] = ', '3', + '[3] = ', '4']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("numbers_list").MightHaveChildren(), "numbers_list.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("numbers_list").MightHaveChildren(), + "numbers_list.MightHaveChildren() says False for non empty!") self.runCmd("type format delete int") self.runCmd("c") self.expect("frame variable text_list", - substrs = ['list has 3 items', - '[0]', 'goofy', - '[1]', 'is', - '[2]', 'smart']) + substrs=['list has 3 items', + '[0]', 'goofy', + '[1]', 'is', + '[2]', 'smart']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("text_list").MightHaveChildren(), "text_list.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("text_list").MightHaveChildren(), + "text_list.MightHaveChildren() says False for non empty!") self.expect("p text_list", - substrs = ['list has 3 items', - '\"goofy\"', - '\"is\"', - '\"smart\"']) - + substrs=['list has 3 items', + '\"goofy\"', + '\"is\"', + '\"smart\"']) + self.runCmd("n") # check access-by-index self.expect("frame variable text_list[0]", - substrs = ['goofy']); + substrs=['goofy']) self.expect("frame variable text_list[3]", - substrs = ['!!!']); - + substrs=['!!!']) + self.runCmd("continue") - + # check that the list provider correctly updates if elements move countingList = self.frame().FindVariable("countingList") countingList.SetPreferDynamicValue(True) countingList.SetPreferSyntheticValue(True) - - self.assertTrue(countingList.GetChildAtIndex(0).GetValueAsUnsigned(0) == 3141, "list[0] == 3141") - self.assertTrue(countingList.GetChildAtIndex(1).GetValueAsUnsigned(0) == 3141, "list[1] == 3141") - + + self.assertTrue(countingList.GetChildAtIndex( + 0).GetValueAsUnsigned(0) == 3141, "list[0] == 3141") + self.assertTrue(countingList.GetChildAtIndex( + 1).GetValueAsUnsigned(0) == 3141, "list[1] == 3141") + self.runCmd("continue") - self.assertTrue(countingList.GetChildAtIndex(0).GetValueAsUnsigned(0) == 3141, "uniqued list[0] == 3141") - self.assertTrue(countingList.GetChildAtIndex(1).GetValueAsUnsigned(0) == 3142, "uniqued list[1] == 3142") + self.assertTrue( + countingList.GetChildAtIndex(0).GetValueAsUnsigned(0) == 3141, + "uniqued list[0] == 3141") + self.assertTrue( + countingList.GetChildAtIndex(1).GetValueAsUnsigned(0) == 3142, + "uniqued list[1] == 3142") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py index 9e68e1dbc00..e2e082c795f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py @@ -6,19 +6,21 @@ corruption). from __future__ import print_function - -import os, time, re +import os +import time +import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxListDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet @add_test_categories(["pyapi"]) @skipIfDarwin # rdar://25499635 def test_with_run_command(self): @@ -27,29 +29,47 @@ class LibcxxListDataFormatterTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target and target.IsValid(), "Target is valid") - file_spec = lldb.SBFileSpec ("main.cpp", False) - breakpoint1 = target.BreakpointCreateBySourceRegex('// Set break point at this line.', file_spec) + file_spec = lldb.SBFileSpec("main.cpp", False) + breakpoint1 = target.BreakpointCreateBySourceRegex( + '// Set break point at this line.', file_spec) self.assertTrue(breakpoint1 and breakpoint1.IsValid()) - breakpoint2 = target.BreakpointCreateBySourceRegex('// Set second break point at this line.', file_spec) + breakpoint2 = target.BreakpointCreateBySourceRegex( + '// Set second break point at this line.', file_spec) self.assertTrue(breakpoint2 and breakpoint2.IsValid()) # Run the program, it should stop at breakpoint 1. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) - lldbutil.skip_if_library_missing(self, target, lldbutil.PrintableRegex("libc\+\+")) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + lldbutil.skip_if_library_missing( + self, target, lldbutil.PrintableRegex("libc\+\+")) self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) - self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1)), 1) + self.assertEqual( + len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1)), 1) # verify our list is displayed correctly - self.expect("frame variable *numbers_list", substrs=['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4', '[5] = 6']) + self.expect( + "frame variable *numbers_list", + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4', + '[5] = 6']) # Continue to breakpoint 2. process.Continue() self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) - self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2)), 1) + self.assertEqual( + len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2)), 1) # The list is now inconsistent. However, we should be able to get the first three # elements at least (and most importantly, not crash). - self.expect("frame variable *numbers_list", substrs=['[0] = 1', '[1] = 2', '[2] = 3']) + self.expect( + "frame variable *numbers_list", + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3']) # Run to completion. process.Continue() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py index cecc3178b31..7433a0b0da2 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py @@ -5,34 +5,38 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxMapDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")) + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -41,259 +45,269 @@ class LibcxxMapDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('image list', substrs = self.getLibcPlusPlusLibs()) - + self.expect('image list', substrs=self.getLibcPlusPlusLibs()) + self.expect('frame variable ii', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect('frame variable ii', - substrs = ['size=2', - '[0] = ', - 'first = 0', - 'second = 0', - '[1] = ', - 'first = 1', - 'second = 1']) + substrs=['size=2', + '[0] = ', + 'first = 0', + 'second = 0', + '[1] = ', + 'first = 1', + 'second = 1']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect('frame variable ii', - substrs = ['size=4', - '[2] = ', - 'first = 2', - 'second = 0', - '[3] = ', - 'first = 3', - 'second = 1']) + substrs=['size=4', + '[2] = ', + 'first = 2', + 'second = 0', + '[3] = ', + 'first = 3', + 'second = 1']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable ii", - substrs = ['size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + substrs=['size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) self.expect("p ii", - substrs = ['size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + substrs=['size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) # check access-by-index self.expect("frame variable ii[0]", - substrs = ['first = 0', - 'second = 0']); + substrs=['first = 0', + 'second = 0']) self.expect("frame variable ii[3]", - substrs = ['first =', - 'second =']); + substrs=['first =', + 'second =']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("ii").MightHaveChildren(), "ii.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("ii").MightHaveChildren(), + "ii.MightHaveChildren() says False for non empty!") # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression ii[8]", matching=False, error=True, + # self.expect("expression ii[8]", matching=False, error=True, # substrs = ['1234567']) - self.runCmd("continue"); - + self.runCmd("continue") + self.expect('frame variable ii', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) self.expect('frame variable si', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) - self.runCmd("continue"); + self.runCmd("continue") self.expect('frame variable si', - substrs = ['size=1', - '[0] = ', - 'first = \"zero\"', - 'second = 0']) + substrs=['size=1', + '[0] = ', + 'first = \"zero\"', + 'second = 0']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable si", - substrs = ['size=4', - '[0] = ', - 'first = \"zero\"', - 'second = 0', - '[1] = ', - 'first = \"one\"', - 'second = 1', - '[2] = ', - 'first = \"two\"', - 'second = 2', - '[3] = ', - 'first = \"three\"', - 'second = 3']) + substrs=['size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) self.expect("p si", - substrs = ['size=4', - '[0] = ', - 'first = \"zero\"', - 'second = 0', - '[1] = ', - 'first = \"one\"', - 'second = 1', - '[2] = ', - 'first = \"two\"', - 'second = 2', - '[3] = ', - 'first = \"three\"', - 'second = 3']) + substrs=['size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("si").MightHaveChildren(), "si.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("si").MightHaveChildren(), + "si.MightHaveChildren() says False for non empty!") # check access-by-index self.expect("frame variable si[0]", - substrs = ['first = ', 'one', - 'second = 1']); - + substrs=['first = ', 'one', + 'second = 1']) + # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression si[0]", matching=False, error=True, + # self.expect("expression si[0]", matching=False, error=True, # substrs = ['first = ', 'zero']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable si', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable is', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable is", - substrs = ['size=4', - '[0] = ', - 'second = \"goofy\"', - 'first = 85', - '[1] = ', - 'second = \"is\"', - 'first = 1', - '[2] = ', - 'second = \"smart\"', - 'first = 2', - '[3] = ', - 'second = \"!!!\"', - 'first = 3']) - + substrs=['size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + self.expect("p is", - substrs = ['size=4', - '[0] = ', - 'second = \"goofy\"', - 'first = 85', - '[1] = ', - 'second = \"is\"', - 'first = 1', - '[2] = ', - 'second = \"smart\"', - 'first = 2', - '[3] = ', - 'second = \"!!!\"', - 'first = 3']) + substrs=['size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("is").MightHaveChildren(), "is.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("is").MightHaveChildren(), + "is.MightHaveChildren() says False for non empty!") # check access-by-index self.expect("frame variable is[0]", - substrs = ['first = ', - 'second =']); - + substrs=['first = ', + 'second =']) + # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression is[0]", matching=False, error=True, + # self.expect("expression is[0]", matching=False, error=True, # substrs = ['first = ', 'goofy']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable is', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable ss', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable ss", - substrs = ['size=3', - '[0] = ', - 'second = \"hello\"', - 'first = \"ciao\"', - '[1] = ', - 'second = \"house\"', - 'first = \"casa\"', - '[2] = ', - 'second = \"cat\"', - 'first = \"gatto\"']) - + substrs=['size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) + self.expect("p ss", - substrs = ['size=3', - '[0] = ', - 'second = \"hello\"', - 'first = \"ciao\"', - '[1] = ', - 'second = \"house\"', - 'first = \"casa\"', - '[2] = ', - 'second = \"cat\"', - 'first = \"gatto\"']) + substrs=['size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("ss").MightHaveChildren(), "ss.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("ss").MightHaveChildren(), + "ss.MightHaveChildren() says False for non empty!") # check access-by-index self.expect("frame variable ss[2]", - substrs = ['gatto', 'cat']); - + substrs=['gatto', 'cat']) + # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression ss[3]", matching=False, error=True, + # self.expect("expression ss[3]", matching=False, error=True, # substrs = ['gatto']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable ss', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py index eb74818c91f..66091e6e113 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py @@ -5,35 +5,39 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxMultiMapDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet @skipIf(compiler="gcc") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -42,259 +46,269 @@ class LibcxxMultiMapDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('image list', substrs = self.getLibcPlusPlusLibs()) - + self.expect('image list', substrs=self.getLibcPlusPlusLibs()) + self.expect('frame variable ii', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect('frame variable ii', - substrs = ['size=2', - '[0] = ', - 'first = 0', - 'second = 0', - '[1] = ', - 'first = 1', - 'second = 1']) + substrs=['size=2', + '[0] = ', + 'first = 0', + 'second = 0', + '[1] = ', + 'first = 1', + 'second = 1']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect('frame variable ii', - substrs = ['size=4', - '[2] = ', - 'first = 2', - 'second = 0', - '[3] = ', - 'first = 3', - 'second = 1']) + substrs=['size=4', + '[2] = ', + 'first = 2', + 'second = 0', + '[3] = ', + 'first = 3', + 'second = 1']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable ii", - substrs = ['size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + substrs=['size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) self.expect("p ii", - substrs = ['size=8', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + substrs=['size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) # check access-by-index self.expect("frame variable ii[0]", - substrs = ['first = 0', - 'second = 0']); + substrs=['first = 0', + 'second = 0']) self.expect("frame variable ii[3]", - substrs = ['first =', - 'second =']); + substrs=['first =', + 'second =']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("ii").MightHaveChildren(), "ii.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("ii").MightHaveChildren(), + "ii.MightHaveChildren() says False for non empty!") # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression ii[8]", matching=False, error=True, + # self.expect("expression ii[8]", matching=False, error=True, # substrs = ['1234567']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable ii', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) self.expect('frame variable si', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect('frame variable si', - substrs = ['size=1', - '[0] = ', - 'first = \"zero\"', - 'second = 0']) + substrs=['size=1', + '[0] = ', + 'first = \"zero\"', + 'second = 0']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable si", - substrs = ['size=4', - '[0] = ', - 'first = \"zero\"', - 'second = 0', - '[1] = ', - 'first = \"one\"', - 'second = 1', - '[2] = ', - 'first = \"two\"', - 'second = 2', - '[3] = ', - 'first = \"three\"', - 'second = 3']) + substrs=['size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) self.expect("p si", - substrs = ['size=4', - '[0] = ', - 'first = \"zero\"', - 'second = 0', - '[1] = ', - 'first = \"one\"', - 'second = 1', - '[2] = ', - 'first = \"two\"', - 'second = 2', - '[3] = ', - 'first = \"three\"', - 'second = 3']) + substrs=['size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("si").MightHaveChildren(), "si.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("si").MightHaveChildren(), + "si.MightHaveChildren() says False for non empty!") # check access-by-index self.expect("frame variable si[0]", - substrs = ['first = ', 'one', - 'second = 1']); - + substrs=['first = ', 'one', + 'second = 1']) + # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression si[0]", matching=False, error=True, + # self.expect("expression si[0]", matching=False, error=True, # substrs = ['first = ', 'zero']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable si', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable is', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable is", - substrs = ['size=4', - '[0] = ', - 'second = \"goofy\"', - 'first = 85', - '[1] = ', - 'second = \"is\"', - 'first = 1', - '[2] = ', - 'second = \"smart\"', - 'first = 2', - '[3] = ', - 'second = \"!!!\"', - 'first = 3']) - + substrs=['size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + self.expect("p is", - substrs = ['size=4', - '[0] = ', - 'second = \"goofy\"', - 'first = 85', - '[1] = ', - 'second = \"is\"', - 'first = 1', - '[2] = ', - 'second = \"smart\"', - 'first = 2', - '[3] = ', - 'second = \"!!!\"', - 'first = 3']) + substrs=['size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("is").MightHaveChildren(), "is.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("is").MightHaveChildren(), + "is.MightHaveChildren() says False for non empty!") # check access-by-index self.expect("frame variable is[0]", - substrs = ['first = ', - 'second =']); - + substrs=['first = ', + 'second =']) + # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression is[0]", matching=False, error=True, + # self.expect("expression is[0]", matching=False, error=True, # substrs = ['first = ', 'goofy']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable is', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable ss', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable ss", - substrs = ['size=3', - '[0] = ', - 'second = \"hello\"', - 'first = \"ciao\"', - '[1] = ', - 'second = \"house\"', - 'first = \"casa\"', - '[2] = ', - 'second = \"cat\"', - 'first = \"gatto\"']) - + substrs=['size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) + self.expect("p ss", - substrs = ['size=3', - '[0] = ', - 'second = \"hello\"', - 'first = \"ciao\"', - '[1] = ', - 'second = \"house\"', - 'first = \"casa\"', - '[2] = ', - 'second = \"cat\"', - 'first = \"gatto\"']) + substrs=['size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("ss").MightHaveChildren(), "ss.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("ss").MightHaveChildren(), + "ss.MightHaveChildren() says False for non empty!") # check access-by-index self.expect("frame variable ss[2]", - substrs = ['gatto', 'cat']); - + substrs=['gatto', 'cat']) + # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression ss[3]", matching=False, error=True, + # self.expect("expression ss[3]", matching=False, error=True, # substrs = ['gatto']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect('frame variable ss', - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py index cfdfd07ddec..d40bce83e0a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py @@ -5,34 +5,38 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxMultiSetDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -41,30 +45,78 @@ class LibcxxMultiSetDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('image list', substrs = self.getLibcPlusPlusLibs()) + self.expect('image list', substrs=self.getLibcPlusPlusLibs()) - self.expect("frame variable ii",substrs = ["size=0","{}"]) + self.expect("frame variable ii", substrs=["size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ii",substrs = ["size=6","[0] = 0","[1] = 1", "[2] = 2", "[3] = 3", "[4] = 4", "[5] = 5"]) + self.expect( + "frame variable ii", + substrs=[ + "size=6", + "[0] = 0", + "[1] = 1", + "[2] = 2", + "[3] = 3", + "[4] = 4", + "[5] = 5"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ii",substrs = ["size=7","[2] = 2", "[3] = 3", "[6] = 6"]) - self.expect("p ii",substrs = ["size=7","[2] = 2", "[3] = 3", "[6] = 6"]) - self.expect("frame variable ii[2]",substrs = [" = 2"]) + self.expect( + "frame variable ii", + substrs=[ + "size=7", + "[2] = 2", + "[3] = 3", + "[6] = 6"]) + self.expect( + "p ii", + substrs=[ + "size=7", + "[2] = 2", + "[3] = 3", + "[6] = 6"]) + self.expect("frame variable ii[2]", substrs=[" = 2"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ii",substrs = ["size=0","{}"]) + self.expect("frame variable ii", substrs=["size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ii",substrs = ["size=0","{}"]) - self.expect("frame variable ss",substrs = ["size=0","{}"]) + self.expect("frame variable ii", substrs=["size=0", "{}"]) + self.expect("frame variable ss", substrs=["size=0", "{}"]) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ss",substrs = ["size=2",'[0] = "a"','[1] = "a very long string is right here"']) + self.expect( + "frame variable ss", + substrs=[ + "size=2", + '[0] = "a"', + '[1] = "a very long string is right here"']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ss",substrs = ["size=4",'[2] = "b"','[3] = "c"','[0] = "a"','[1] = "a very long string is right here"']) - self.expect("p ss",substrs = ["size=4",'[2] = "b"','[3] = "c"','[0] = "a"','[1] = "a very long string is right here"']) - self.expect("frame variable ss[2]",substrs = [' = "b"']) + self.expect( + "frame variable ss", + substrs=[ + "size=4", + '[2] = "b"', + '[3] = "c"', + '[0] = "a"', + '[1] = "a very long string is right here"']) + self.expect( + "p ss", + substrs=[ + "size=4", + '[2] = "b"', + '[3] = "c"', + '[0] = "a"', + '[1] = "a very long string is right here"']) + self.expect("frame variable ss[2]", substrs=[' = "b"']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - self.expect("frame variable ss",substrs = ["size=3",'[0] = "a"','[1] = "a very long string is right here"','[2] = "c"']) + self.expect( + "frame variable ss", + substrs=[ + "size=3", + '[0] = "a"', + '[1] = "a very long string is right here"', + '[2] = "c"']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py index 00c1e548cf6..be1547ea5d8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py @@ -5,24 +5,25 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxSetDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - + # bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")) self.runCmd("run", RUN_SUCCEEDED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py index 76eedb8c891..b0e84121dde 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py @@ -1,4 +1,4 @@ -#coding=utf8 +# coding=utf8 """ Test lldb data formatter subsystem. """ @@ -6,13 +6,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxStringDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,22 +25,24 @@ class LibcxxStringDataFormatterTestCase(TestBase): self.line = line_number('main.cpp', '// Set break point at this line.') @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -48,40 +51,51 @@ class LibcxxStringDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect("frame variable", - substrs = ['(std::__1::wstring) s = L"hello world! מזל טוב!"', - '(std::__1::wstring) S = L"!!!!"', - '(const wchar_t *) mazeltov = 0x','L"מזל טוב"', - '(std::__1::string) q = "hello world"', - '(std::__1::string) Q = "quite a long std::strin with lots of info inside it"', - '(std::__1::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"', - '(std::__1::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"']) + self.expect( + "frame variable", + substrs=[ + '(std::__1::wstring) s = L"hello world! מזל טוב!"', + '(std::__1::wstring) S = L"!!!!"', + '(const wchar_t *) mazeltov = 0x', + 'L"מזל טוב"', + '(std::__1::string) q = "hello world"', + '(std::__1::string) Q = "quite a long std::strin with lots of info inside it"', + '(std::__1::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"', + '(std::__1::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"']) self.runCmd("n") - TheVeryLongOne = self.frame().FindVariable("TheVeryLongOne"); + TheVeryLongOne = self.frame().FindVariable("TheVeryLongOne") summaryOptions = lldb.SBTypeSummaryOptions() summaryOptions.SetCapping(lldb.eTypeSummaryUncapped) uncappedSummaryStream = lldb.SBStream() - TheVeryLongOne.GetSummary(uncappedSummaryStream,summaryOptions) + TheVeryLongOne.GetSummary(uncappedSummaryStream, summaryOptions) uncappedSummary = uncappedSummaryStream.GetData() - self.assertTrue(uncappedSummary.find("someText") > 0, "uncappedSummary does not include the full string") + self.assertTrue(uncappedSummary.find("someText") > 0, + "uncappedSummary does not include the full string") summaryOptions.SetCapping(lldb.eTypeSummaryCapped) cappedSummaryStream = lldb.SBStream() - TheVeryLongOne.GetSummary(cappedSummaryStream,summaryOptions) + TheVeryLongOne.GetSummary(cappedSummaryStream, summaryOptions) cappedSummary = cappedSummaryStream.GetData() - self.assertTrue(cappedSummary.find("someText") <= 0, "cappedSummary includes the full string") - - self.expect("frame variable", - substrs = ['(std::__1::wstring) s = L"hello world! מזל טוב!"', - '(std::__1::wstring) S = L"!!!!!"', - '(const wchar_t *) mazeltov = 0x','L"מזל טוב"', - '(std::__1::string) q = "hello world"', - '(std::__1::string) Q = "quite a long std::strin with lots of info inside it"', - '(std::__1::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"', - '(std::__1::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"']) + self.assertTrue( + cappedSummary.find("someText") <= 0, + "cappedSummary includes the full string") + + self.expect( + "frame variable", + substrs=[ + '(std::__1::wstring) s = L"hello world! מזל טוב!"', + '(std::__1::wstring) S = L"!!!!!"', + '(const wchar_t *) mazeltov = 0x', + 'L"מזל טוב"', + '(std::__1::string) q = "hello world"', + '(std::__1::string) Q = "quite a long std::strin with lots of info inside it"', + '(std::__1::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"', + '(std::__1::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py index 4765cd70f67..8a08d38975c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py @@ -5,34 +5,37 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxUnorderedDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet @skipIf(compiler="gcc") def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -41,12 +44,14 @@ class LibcxxUnorderedDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('image list', substrs = self.getLibcPlusPlusLibs()) + self.expect('image list', substrs=self.getLibcPlusPlusLibs()) self.look_for_content_and_continue( "map", ['size=5 {', 'hello', 'world', 'this', 'is', 'me']) @@ -72,6 +77,6 @@ class LibcxxUnorderedDataFormatterTestCase(TestBase): '(\[\d\] = "world"(\\n|.)+){2}']) def look_for_content_and_continue(self, var_name, patterns): - self.expect( ("frame variable %s" % var_name), patterns=patterns) - self.expect( ("frame variable %s" % var_name), patterns=patterns) + self.expect(("frame variable %s" % var_name), patterns=patterns) + self.expect(("frame variable %s" % var_name), patterns=patterns) self.runCmd("continue") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py index fe3b6c115e3..43d5ad4f103 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxVBoolDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,22 +24,24 @@ class LibcxxVBoolDataFormatterTestCase(TestBase): self.line = line_number('main.cpp', '// Set break point at this line.') @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows. + @skipIfWindows # libc++ not ported to Windows. def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,13 +50,33 @@ class LibcxxVBoolDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect("frame variable vBool", - substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true']) - - self.expect("expr vBool", - substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true']) + self.expect( + "frame variable vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) + + self.expect( + "expr vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py index 9a145fba73e..719ed730050 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py @@ -5,34 +5,38 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LibcxxVectorDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf(compiler="gcc") - @skipIfWindows # libc++ not ported to Windows yet + @skipIfWindows # libc++ not ported to Windows yet def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - - lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+")) - bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "break here")) + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "break here")) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -41,51 +45,54 @@ class LibcxxVectorDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # empty vectors (and storage pointers SHOULD BOTH BE NULL..) self.expect("frame variable numbers", - substrs = ['numbers = size=0']) + substrs=['numbers = size=0']) lldbutil.continue_to_breakpoint(self.process(), bkpt) - + # first value added self.expect("frame variable numbers", - substrs = ['numbers = size=1', - '[0] = 1', - '}']) + substrs=['numbers = size=1', + '[0] = 1', + '}']) # add some more data lldbutil.continue_to_breakpoint(self.process(), bkpt) - + self.expect("frame variable numbers", - substrs = ['numbers = size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) + substrs=['numbers = size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) self.expect("p numbers", - substrs = ['$', 'size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) - - + substrs=['$', 'size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) + # check access to synthetic children - self.runCmd("type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") + self.runCmd( + "type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") self.expect('frame variable numbers', - substrs = ['item 0 is 1']); - - self.runCmd("type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") + substrs=['item 0 is 1']) + + self.runCmd( + "type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") self.expect('frame variable numbers', - substrs = ['item 0 is 1']); + substrs=['item 0 is 1']) # move on with synths self.runCmd("type summary delete std::int_vect") self.runCmd("type summary delete int_vect") @@ -94,88 +101,89 @@ class LibcxxVectorDataFormatterTestCase(TestBase): lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable numbers", - substrs = ['numbers = size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) - + substrs=['numbers = size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) + self.expect("p numbers", - substrs = ['$', 'size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) + substrs=['$', 'size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) # check access-by-index self.expect("frame variable numbers[0]", - substrs = ['1']); + substrs=['1']) self.expect("frame variable numbers[1]", - substrs = ['12']); + substrs=['12']) self.expect("frame variable numbers[2]", - substrs = ['123']); + substrs=['123']) self.expect("frame variable numbers[3]", - substrs = ['1234']); + substrs=['1234']) # clear out the vector and see that we do the right thing once again lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable numbers", - substrs = ['numbers = size=0']) + substrs=['numbers = size=0']) lldbutil.continue_to_breakpoint(self.process(), bkpt) # first value added self.expect("frame variable numbers", - substrs = ['numbers = size=1', - '[0] = 7', - '}']) + substrs=['numbers = size=1', + '[0] = 7', + '}']) # check if we can display strings self.expect("frame variable strings", - substrs = ['goofy', - 'is', - 'smart']) + substrs=['goofy', + 'is', + 'smart']) self.expect("p strings", - substrs = ['goofy', - 'is', - 'smart']) + substrs=['goofy', + 'is', + 'smart']) # test summaries based on synthetic children - self.runCmd("type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") + self.runCmd( + "type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") self.expect("frame variable strings", - substrs = ['vector has 3 items', - 'goofy', - 'is', - 'smart']) + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) self.expect("p strings", - substrs = ['vector has 3 items', - 'goofy', - 'is', - 'smart']) + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable strings", - substrs = ['vector has 4 items']) - + substrs=['vector has 4 items']) + # check access-by-index self.expect("frame variable strings[0]", - substrs = ['goofy']); + substrs=['goofy']) self.expect("frame variable strings[1]", - substrs = ['is']); + substrs=['is']) lldbutil.continue_to_breakpoint(self.process(), bkpt) self.expect("frame variable strings", - substrs = ['vector has 0 items']) + substrs=['vector has 0 items']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py index dbaa37daa2d..53ab11bcc8c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StdIteratorDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,21 +23,24 @@ class StdIteratorDataFormatterTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - @skipIfWindows # libstdcpp not ported to Windows - @expectedFailureAll(compiler="icc", bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") + @skipIfWindows # libstdcpp not ported to Windows + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") def test_with_run_command(self): """Test that libstdcpp iterators format properly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -45,19 +49,29 @@ class StdIteratorDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('frame variable ivI', substrs = ['item = 3']) - self.expect('expr ivI', substrs = ['item = 3']) - - self.expect('frame variable iimI', substrs = ['first = 0','second = 12']) - self.expect('expr iimI', substrs = ['first = 0','second = 12']) - - self.expect('frame variable simI', substrs = ['first = "world"','second = 42']) - self.expect('expr simI', substrs = ['first = "world"','second = 42']) - - self.expect('frame variable svI', substrs = ['item = "hello"']) - self.expect('expr svI', substrs = ['item = "hello"']) + self.expect('frame variable ivI', substrs=['item = 3']) + self.expect('expr ivI', substrs=['item = 3']) + + self.expect( + 'frame variable iimI', + substrs=[ + 'first = 0', + 'second = 12']) + self.expect('expr iimI', substrs=['first = 0', 'second = 12']) + + self.expect( + 'frame variable simI', + substrs=[ + 'first = "world"', + 'second = 42']) + self.expect('expr simI', substrs=['first = "world"', 'second = 42']) + + self.expect('frame variable svI', substrs=['item = "hello"']) + self.expect('expr svI', substrs=['item = "hello"']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py index 55658af1f2a..a7f8c4b1e17 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StdListDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,23 +22,26 @@ class StdListDataFormatterTestCase(TestBase): TestBase.setUp(self) # Find the line numbers to break at for the different tests. self.line = line_number('main.cpp', '// Set break point at this line.') - self.optional_line = line_number('main.cpp', '// Optional break point at this line.') - self.final_line = line_number('main.cpp', '// Set final break point at this line.') + self.optional_line = line_number( + 'main.cpp', '// Optional break point at this line.') + self.final_line = line_number( + 'main.cpp', '// Set final break point at this line.') - @skipIfWindows # libstdcpp not ported to Windows + @skipIfWindows # libstdcpp not ported to Windows def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -46,7 +50,9 @@ class StdListDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -56,134 +62,148 @@ class StdListDataFormatterTestCase(TestBase): self.runCmd("type format add -f hex int") self.expect("frame variable numbers_list --raw", matching=False, - substrs = ['size=0', - '{}']) - self.expect("frame variable &numbers_list._M_impl._M_node --raw", matching=False, - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) + self.expect( + "frame variable &numbers_list._M_impl._M_node --raw", + matching=False, + substrs=[ + 'size=0', + '{}']) self.expect("frame variable numbers_list", - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) self.expect("p numbers_list", - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) self.runCmd("n") self.expect("frame variable numbers_list", - substrs = ['size=1', - '[0] = ', - '0x12345678']) + substrs=['size=1', + '[0] = ', + '0x12345678']) - self.runCmd("n");self.runCmd("n");self.runCmd("n"); + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") self.expect("frame variable numbers_list", - substrs = ['size=4', - '[0] = ', - '0x12345678', - '[1] =', - '0x11223344', - '[2] =', - '0xbeeffeed', - '[3] =', - '0x00abba00']) - - self.runCmd("n");self.runCmd("n"); + substrs=['size=4', + '[0] = ', + '0x12345678', + '[1] =', + '0x11223344', + '[2] =', + '0xbeeffeed', + '[3] =', + '0x00abba00']) + + self.runCmd("n") + self.runCmd("n") self.expect("frame variable numbers_list", - substrs = ['size=6', - '[0] = ', - '0x12345678', - '0x11223344', - '0xbeeffeed', - '0x00abba00', - '[4] =', - '0x0abcdef0', - '[5] =', - '0x0cab0cab']) + substrs=['size=6', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) self.expect("p numbers_list", - substrs = ['size=6', - '[0] = ', - '0x12345678', - '0x11223344', - '0xbeeffeed', - '0x00abba00', - '[4] =', - '0x0abcdef0', - '[5] =', - '0x0cab0cab']) + substrs=['size=6', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) # check access-by-index self.expect("frame variable numbers_list[0]", - substrs = ['0x12345678']); + substrs=['0x12345678']) self.expect("frame variable numbers_list[1]", - substrs = ['0x11223344']); - + substrs=['0x11223344']) + # but check that expression does not rely on us self.expect("expression numbers_list[0]", matching=False, error=True, - substrs = ['0x12345678']) + substrs=['0x12345678']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("numbers_list").MightHaveChildren(), "numbers_list.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("numbers_list").MightHaveChildren(), + "numbers_list.MightHaveChildren() says False for non empty!") self.runCmd("n") - + self.expect("frame variable numbers_list", - substrs = ['size=0', - '{}']) + substrs=['size=0', + '{}']) + + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") - self.runCmd("n");self.runCmd("n");self.runCmd("n");self.runCmd("n"); - self.expect("frame variable numbers_list", - substrs = ['size=4', - '[0] = ', '1', - '[1] = ', '2', - '[2] = ', '3', - '[3] = ', '4']) + substrs=['size=4', + '[0] = ', '1', + '[1] = ', '2', + '[2] = ', '3', + '[3] = ', '4']) self.runCmd("type format delete int") self.runCmd("n") - + self.expect("frame variable text_list", - substrs = ['size=0', - '{}']) - - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.final_line, num_expected_locations=-1) + substrs=['size=0', + '{}']) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.final_line, num_expected_locations=-1) self.runCmd("c", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) self.expect("frame variable text_list", - substrs = ['size=4', - '[0]', 'goofy', - '[1]', 'is', - '[2]', 'smart', - '[3]', '!!!']) + substrs=['size=4', + '[0]', 'goofy', + '[1]', 'is', + '[2]', 'smart', + '[3]', '!!!']) self.expect("p text_list", - substrs = ['size=4', - '\"goofy\"', - '\"is\"', - '\"smart\"', - '\"!!!\"']) - + substrs=['size=4', + '\"goofy\"', + '\"is\"', + '\"smart\"', + '\"!!!\"']) + # check access-by-index self.expect("frame variable text_list[0]", - substrs = ['goofy']); + substrs=['goofy']) self.expect("frame variable text_list[3]", - substrs = ['!!!']); - + substrs=['!!!']) + # but check that expression does not rely on us self.expect("expression text_list[0]", matching=False, error=True, - substrs = ['goofy']) + substrs=['goofy']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("text_list").MightHaveChildren(), "text_list.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("text_list").MightHaveChildren(), + "text_list.MightHaveChildren() says False for non empty!") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py index ff99255aec0..f5dbadb6958 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StdMapDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,22 +23,25 @@ class StdMapDataFormatterTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - @expectedFailureAll(compiler="icc", bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") - @skipIfWindows # libstdcpp not ported to Windows + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") + @skipIfWindows # libstdcpp not ported to Windows @skipIfFreeBSD def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -46,278 +50,289 @@ class StdMapDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("frame variable ii --show-types") - - self.runCmd("type summary add -x \"std::map<\" --summary-string \"map has ${svar%#} items\" -e") - + + self.runCmd( + "type summary add -x \"std::map<\" --summary-string \"map has ${svar%#} items\" -e") + self.expect('frame variable ii', - substrs = ['map has 0 items', - '{}']) + substrs=['map has 0 items', + '{}']) - self.runCmd("c"); + self.runCmd("c") self.expect('frame variable ii', - substrs = ['map has 2 items', - '[0] = ', - 'first = 0', - 'second = 0', - '[1] = ', - 'first = 1', - 'second = 1']) + substrs=['map has 2 items', + '[0] = ', + 'first = 0', + 'second = 0', + '[1] = ', + 'first = 1', + 'second = 1']) - self.runCmd("c"); + self.runCmd("c") self.expect('frame variable ii', - substrs = ['map has 4 items', - '[2] = ', - 'first = 2', - 'second = 0', - '[3] = ', - 'first = 3', - 'second = 1']) + substrs=['map has 4 items', + '[2] = ', + 'first = 2', + 'second = 0', + '[3] = ', + 'first = 3', + 'second = 1']) - self.runCmd("c"); + self.runCmd("c") self.expect("frame variable ii", - substrs = ['map has 9 items', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) - + substrs=['map has 9 items', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) + self.expect("p ii", - substrs = ['map has 9 items', - '[5] = ', - 'first = 5', - 'second = 0', - '[7] = ', - 'first = 7', - 'second = 1']) + substrs=['map has 9 items', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) # check access-by-index self.expect("frame variable ii[0]", - substrs = ['first = 0', - 'second = 0']); + substrs=['first = 0', + 'second = 0']) self.expect("frame variable ii[3]", - substrs = ['first =', - 'second =']); - + substrs=['first =', + 'second =']) + self.expect("frame variable ii[8]", matching=True, - substrs = ['1234567']) + substrs=['1234567']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("ii").MightHaveChildren(), "ii.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("ii").MightHaveChildren(), + "ii.MightHaveChildren() says False for non empty!") # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression ii[8]", matching=False, error=True, + # self.expect("expression ii[8]", matching=False, error=True, # substrs = ['1234567']) self.runCmd("c") - + self.expect('frame variable ii', - substrs = ['map has 0 items', - '{}']) - + substrs=['map has 0 items', + '{}']) + self.runCmd("frame variable si --show-types") self.expect('frame variable si', - substrs = ['map has 0 items', - '{}']) + substrs=['map has 0 items', + '{}']) self.runCmd("c") self.expect('frame variable si', - substrs = ['map has 1 items', - '[0] = ', - 'first = \"zero\"', - 'second = 0']) + substrs=['map has 1 items', + '[0] = ', + 'first = \"zero\"', + 'second = 0']) - self.runCmd("c"); + self.runCmd("c") self.expect("frame variable si", - substrs = ['map has 5 items', - '[0] = ', - 'first = \"zero\"', - 'second = 0', - '[1] = ', - 'first = \"one\"', - 'second = 1', - '[2] = ', - 'first = \"two\"', - 'second = 2', - '[3] = ', - 'first = \"three\"', - 'second = 3', - '[4] = ', - 'first = \"four\"', - 'second = 4']) + substrs=['map has 5 items', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3', + '[4] = ', + 'first = \"four\"', + 'second = 4']) self.expect("p si", - substrs = ['map has 5 items', - '[0] = ', - 'first = \"zero\"', - 'second = 0', - '[1] = ', - 'first = \"one\"', - 'second = 1', - '[2] = ', - 'first = \"two\"', - 'second = 2', - '[3] = ', - 'first = \"three\"', - 'second = 3', - '[4] = ', - 'first = \"four\"', - 'second = 4']) + substrs=['map has 5 items', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3', + '[4] = ', + 'first = \"four\"', + 'second = 4']) # check access-by-index self.expect("frame variable si[0]", - substrs = ['first = ', 'four', - 'second = 4']); + substrs=['first = ', 'four', + 'second = 4']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("si").MightHaveChildren(), "si.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("si").MightHaveChildren(), + "si.MightHaveChildren() says False for non empty!") # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression si[0]", matching=False, error=True, + # self.expect("expression si[0]", matching=False, error=True, # substrs = ['first = ', 'zero']) self.runCmd("c") - + self.expect('frame variable si', - substrs = ['map has 0 items', - '{}']) + substrs=['map has 0 items', + '{}']) self.runCmd("frame variable is --show-types") - + self.expect('frame variable is', - substrs = ['map has 0 items', - '{}']) + substrs=['map has 0 items', + '{}']) - self.runCmd("c"); + self.runCmd("c") self.expect("frame variable is", - substrs = ['map has 4 items', - '[0] = ', - 'second = \"goofy\"', - 'first = 85', - '[1] = ', - 'second = \"is\"', - 'first = 1', - '[2] = ', - 'second = \"smart\"', - 'first = 2', - '[3] = ', - 'second = \"!!!\"', - 'first = 3']) - + substrs=['map has 4 items', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + self.expect("p is", - substrs = ['map has 4 items', - '[0] = ', - 'second = \"goofy\"', - 'first = 85', - '[1] = ', - 'second = \"is\"', - 'first = 1', - '[2] = ', - 'second = \"smart\"', - 'first = 2', - '[3] = ', - 'second = \"!!!\"', - 'first = 3']) + substrs=['map has 4 items', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) # check access-by-index self.expect("frame variable is[0]", - substrs = ['first = ', - 'second =']); + substrs=['first = ', + 'second =']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("is").MightHaveChildren(), "is.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("is").MightHaveChildren(), + "is.MightHaveChildren() says False for non empty!") # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression is[0]", matching=False, error=True, + # self.expect("expression is[0]", matching=False, error=True, # substrs = ['first = ', 'goofy']) self.runCmd("c") - + self.expect('frame variable is', - substrs = ['map has 0 items', - '{}']) + substrs=['map has 0 items', + '{}']) self.runCmd("frame variable ss --show-types") - + self.expect('frame variable ss', - substrs = ['map has 0 items', - '{}']) + substrs=['map has 0 items', + '{}']) - self.runCmd("c"); + self.runCmd("c") self.expect("frame variable ss", - substrs = ['map has 4 items', - '[0] = ', - 'second = \"hello\"', - 'first = \"ciao\"', - '[1] = ', - 'second = \"house\"', - 'first = \"casa\"', - '[2] = ', - 'second = \"cat\"', - 'first = \"gatto\"', - '[3] = ', - 'second = \"..is always a Mac!\"', - 'first = \"a Mac..\"']) - + substrs=['map has 4 items', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"', + '[3] = ', + 'second = \"..is always a Mac!\"', + 'first = \"a Mac..\"']) + self.expect("p ss", - substrs = ['map has 4 items', - '[0] = ', - 'second = \"hello\"', - 'first = \"ciao\"', - '[1] = ', - 'second = \"house\"', - 'first = \"casa\"', - '[2] = ', - 'second = \"cat\"', - 'first = \"gatto\"', - '[3] = ', - 'second = \"..is always a Mac!\"', - 'first = \"a Mac..\"']) + substrs=['map has 4 items', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"', + '[3] = ', + 'second = \"..is always a Mac!\"', + 'first = \"a Mac..\"']) # check access-by-index self.expect("frame variable ss[3]", - substrs = ['gatto', 'cat']); + substrs=['gatto', 'cat']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("ss").MightHaveChildren(), "ss.MightHaveChildren() says False for non empty!") - + self.assertTrue( + self.frame().FindVariable("ss").MightHaveChildren(), + "ss.MightHaveChildren() says False for non empty!") + # check that the expression parser does not make use of # synthetic children instead of running code # TOT clang has a fix for this, which makes the expression command here succeed # since this would make the test fail or succeed depending on clang version in use # this is safer commented for the time being - #self.expect("expression ss[3]", matching=False, error=True, + # self.expect("expression ss[3]", matching=False, error=True, # substrs = ['gatto']) self.runCmd("c") - + self.expect('frame variable ss', - substrs = ['map has 0 items', - '{}']) + substrs=['map has 0 items', + '{}']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py index 20b1a3d2115..8d940c2686a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py @@ -4,43 +4,46 @@ Test lldb data formatter subsystem. from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StdSmartPtrDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIfFreeBSD - @skipIfWindows # libstdcpp not ported to Windows - @skipIfDarwin # doesn't compile on Darwin + @skipIfWindows # libstdcpp not ported to Windows + @skipIfDarwin # doesn't compile on Darwin def test_with_run_command(self): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("frame variable nsp", substrs=['nsp = nullptr']) + self.expect("frame variable isp", substrs=['isp = 123']) + self.expect("frame variable ssp", substrs=['ssp = "foobar"']) - self.expect("frame variable nsp", substrs = ['nsp = nullptr']) - self.expect("frame variable isp", substrs = ['isp = 123']) - self.expect("frame variable ssp", substrs = ['ssp = "foobar"']) + self.expect("frame variable nwp", substrs=['nwp = nullptr']) + self.expect("frame variable iwp", substrs=['iwp = 123']) + self.expect("frame variable swp", substrs=['swp = "foobar"']) - self.expect("frame variable nwp", substrs = ['nwp = nullptr']) - self.expect("frame variable iwp", substrs = ['iwp = 123']) - self.expect("frame variable swp", substrs = ['swp = "foobar"']) - self.runCmd("continue") - self.expect("frame variable nsp", substrs = ['nsp = nullptr']) - self.expect("frame variable isp", substrs = ['isp = nullptr']) - self.expect("frame variable ssp", substrs = ['ssp = nullptr']) + self.expect("frame variable nsp", substrs=['nsp = nullptr']) + self.expect("frame variable isp", substrs=['isp = nullptr']) + self.expect("frame variable ssp", substrs=['ssp = nullptr']) - self.expect("frame variable nwp", substrs = ['nwp = nullptr']) - self.expect("frame variable iwp", substrs = ['iwp = nullptr']) - self.expect("frame variable swp", substrs = ['swp = nullptr']) + self.expect("frame variable nwp", substrs=['nwp = nullptr']) + self.expect("frame variable iwp", substrs=['iwp = nullptr']) + self.expect("frame variable swp", substrs=['swp = nullptr']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py index fde2f791183..67823c95f13 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py @@ -1,4 +1,4 @@ -#coding=utf8 +# coding=utf8 """ Test lldb data formatter subsystem. """ @@ -6,13 +6,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StdStringDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,20 +24,21 @@ class StdStringDataFormatterTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - @skipIfWindows # libstdcpp not ported to Windows + @skipIfWindows # libstdcpp not ported to Windows def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -45,7 +47,9 @@ class StdStringDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -56,12 +60,22 @@ class StdStringDataFormatterTestCase(TestBase): var_q = self.frame().FindVariable('q') var_Q = self.frame().FindVariable('Q') - self.assertTrue(var_s.GetSummary() == 'L"hello world! מזל טוב!"', "s summary wrong") + self.assertTrue( + var_s.GetSummary() == 'L"hello world! מזל טוב!"', + "s summary wrong") self.assertTrue(var_S.GetSummary() == 'L"!!!!"', "S summary wrong") - self.assertTrue(var_mazeltov.GetSummary() == 'L"מזל טוב"', "mazeltov summary wrong") - self.assertTrue(var_q.GetSummary() == '"hello world"', "q summary wrong") - self.assertTrue(var_Q.GetSummary() == '"quite a long std::strin with lots of info inside it"', "Q summary wrong") + self.assertTrue( + var_mazeltov.GetSummary() == 'L"מזל טוב"', + "mazeltov summary wrong") + self.assertTrue( + var_q.GetSummary() == '"hello world"', + "q summary wrong") + self.assertTrue( + var_Q.GetSummary() == '"quite a long std::strin with lots of info inside it"', + "Q summary wrong") self.runCmd("next") - self.assertTrue(var_S.GetSummary() == 'L"!!!!!"', "new S summary wrong") + self.assertTrue( + var_S.GetSummary() == 'L"!!!!!"', + "new S summary wrong") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py index f5cf7c04c3a..eff5feedd42 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StdVBoolDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,23 +23,28 @@ class StdVBoolDataFormatterTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr20548 fails to build on lab.llvm.org buildbot') - @expectedFailureAll(compiler="icc", bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") - @skipIfWindows # libstdcpp not ported to Windows. + @expectedFailureAll( + oslist=['freebsd'], + bugnumber='llvm.org/pr20548 fails to build on lab.llvm.org buildbot') + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") + @skipIfWindows # libstdcpp not ported to Windows. @skipIfDarwin def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,13 +53,33 @@ class StdVBoolDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect("frame variable vBool", - substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true']) + self.expect( + "frame variable vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) - self.expect("expr vBool", - substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true']) + self.expect( + "expr vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py index 4a352ef41c1..5de64f636cc 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StdVectorDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,21 +24,24 @@ class StdVectorDataFormatterTestCase(TestBase): self.line = line_number('main.cpp', '// Set break point at this line.') @skipIfFreeBSD - @expectedFailureAll(compiler="icc", bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") - @skipIfWindows # libstdcpp not ported to Windows + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr15301 LLDB prints incorrect sizes of STL containers") + @skipIfWindows # libstdcpp not ported to Windows def test_with_run_command(self): """Test that that file and class static variables display correctly.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.") + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -46,163 +50,171 @@ class StdVectorDataFormatterTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) # empty vectors (and storage pointers SHOULD BOTH BE NULL..) self.expect("frame variable numbers", - substrs = ['numbers = size=0']) + substrs=['numbers = size=0']) self.runCmd("c") - + # first value added self.expect("frame variable numbers", - substrs = ['numbers = size=1', - '[0] = 1', - '}']) + substrs=['numbers = size=1', + '[0] = 1', + '}']) # add some more data - self.runCmd("c"); - + self.runCmd("c") + self.expect("frame variable numbers", - substrs = ['numbers = size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) + substrs=['numbers = size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) self.expect("p numbers", - substrs = ['$', 'size=4', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '}']) - - + substrs=['$', 'size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) + # check access to synthetic children - self.runCmd("type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") + self.runCmd( + "type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") self.expect('frame variable numbers', - substrs = ['item 0 is 1']); - - self.runCmd("type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") + substrs=['item 0 is 1']) + + self.runCmd( + "type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") #import time - #time.sleep(19) + # time.sleep(19) self.expect('frame variable numbers', - substrs = ['item 0 is 1']); + substrs=['item 0 is 1']) # move on with synths self.runCmd("type summary delete std::int_vect") self.runCmd("type summary delete int_vect") # add some more data - self.runCmd("c"); + self.runCmd("c") self.expect("frame variable numbers", - substrs = ['numbers = size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) - + substrs=['numbers = size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) + self.expect("p numbers", - substrs = ['$', 'size=7', - '[0] = 1', - '[1] = 12', - '[2] = 123', - '[3] = 1234', - '[4] = 12345', - '[5] = 123456', - '[6] = 1234567', - '}']) + substrs=['$', 'size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) # check access-by-index self.expect("frame variable numbers[0]", - substrs = ['1']); + substrs=['1']) self.expect("frame variable numbers[1]", - substrs = ['12']); + substrs=['12']) self.expect("frame variable numbers[2]", - substrs = ['123']); + substrs=['123']) self.expect("frame variable numbers[3]", - substrs = ['1234']); - + substrs=['1234']) + # but check that expression does not rely on us # (when expression gets to call into STL code correctly, we will have to find # another way to check this) self.expect("expression numbers[6]", matching=False, error=True, - substrs = ['1234567']) + substrs=['1234567']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("numbers").MightHaveChildren(), "numbers.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("numbers").MightHaveChildren(), + "numbers.MightHaveChildren() says False for non empty!") # clear out the vector and see that we do the right thing once again self.runCmd("c") self.expect("frame variable numbers", - substrs = ['numbers = size=0']) + substrs=['numbers = size=0']) self.runCmd("c") # first value added self.expect("frame variable numbers", - substrs = ['numbers = size=1', - '[0] = 7', - '}']) + substrs=['numbers = size=1', + '[0] = 7', + '}']) # check if we can display strings self.runCmd("c") self.expect("frame variable strings", - substrs = ['goofy', - 'is', - 'smart']) + substrs=['goofy', + 'is', + 'smart']) self.expect("p strings", - substrs = ['goofy', - 'is', - 'smart']) + substrs=['goofy', + 'is', + 'smart']) # test summaries based on synthetic children - self.runCmd("type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") + self.runCmd( + "type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") self.expect("frame variable strings", - substrs = ['vector has 3 items', - 'goofy', - 'is', - 'smart']) + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) self.expect("p strings", - substrs = ['vector has 3 items', - 'goofy', - 'is', - 'smart']) + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) - self.runCmd("c"); + self.runCmd("c") self.expect("frame variable strings", - substrs = ['vector has 4 items']) - + substrs=['vector has 4 items']) + # check access-by-index self.expect("frame variable strings[0]", - substrs = ['goofy']); + substrs=['goofy']) self.expect("frame variable strings[1]", - substrs = ['is']); - + substrs=['is']) + # but check that expression does not rely on us # (when expression gets to call into STL code correctly, we will have to find # another way to check this) self.expect("expression strings[0]", matching=False, error=True, - substrs = ['goofy']) + substrs=['goofy']) # check that MightHaveChildren() gets it right - self.assertTrue(self.frame().FindVariable("strings").MightHaveChildren(), "strings.MightHaveChildren() says False for non empty!") + self.assertTrue( + self.frame().FindVariable("strings").MightHaveChildren(), + "strings.MightHaveChildren() says False for non empty!") self.runCmd("c") self.expect("frame variable strings", - substrs = ['vector has 0 items']) + substrs=['vector has 0 items']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py index 8cebf20ddd2..8fff07d89dc 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class SynthDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,14 +27,15 @@ class SynthDataFormatterTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -48,158 +50,171 @@ class SynthDataFormatterTestCase(TestBase): # Pick some values and check that the basics work self.runCmd("type filter add BagOfInts --child x --child z") self.expect("frame variable int_bag", - substrs = ['x = 6', - 'z = 8']) + substrs=['x = 6', + 'z = 8']) # Check we can still access the missing child by summary - self.runCmd("type summary add BagOfInts --summary-string \"y=${var.y}\"") + self.runCmd( + "type summary add BagOfInts --summary-string \"y=${var.y}\"") self.expect('frame variable int_bag', - substrs = ['y=7']) - - # Even if we have synth children, the summary prevails + substrs=['y=7']) + + # Even if we have synth children, the summary prevails self.expect("frame variable int_bag", matching=False, - substrs = ['x = 6', - 'z = 8']) - + substrs=['x = 6', + 'z = 8']) + # if we skip synth and summary show y - self.expect("frame variable int_bag --synthetic-type false --no-summary-depth=1", - substrs = ['x = 6', - 'y = 7', - 'z = 8']) - + self.expect( + "frame variable int_bag --synthetic-type false --no-summary-depth=1", + substrs=[ + 'x = 6', + 'y = 7', + 'z = 8']) + # if we ask for raw output same happens self.expect("frame variable int_bag --raw-output", - substrs = ['x = 6', - 'y = 7', - 'z = 8']) - + substrs=['x = 6', + 'y = 7', + 'z = 8']) + # Summary+Synth must work together - self.runCmd("type summary add BagOfInts --summary-string \"x=${var.x}\" -e") + self.runCmd( + "type summary add BagOfInts --summary-string \"x=${var.x}\" -e") self.expect('frame variable int_bag', - substrs = ['x=6', - 'x = 6', - 'z = 8']) - + substrs=['x=6', + 'x = 6', + 'z = 8']) + # Same output, but using Python - self.runCmd("type summary add BagOfInts --python-script \"return 'x=%s' % valobj.GetChildMemberWithName('x').GetValue()\" -e") + self.runCmd( + "type summary add BagOfInts --python-script \"return 'x=%s' % valobj.GetChildMemberWithName('x').GetValue()\" -e") self.expect('frame variable int_bag', - substrs = ['x=6', - 'x = 6', - 'z = 8']) + substrs=['x=6', + 'x = 6', + 'z = 8']) # If I skip summaries, still give me the artificial children self.expect("frame variable int_bag --no-summary-depth=1", - substrs = ['x = 6', - 'z = 8']) + substrs=['x = 6', + 'z = 8']) # Delete synth and check that the view reflects it immediately self.runCmd("type filter delete BagOfInts") self.expect("frame variable int_bag", - substrs = ['x = 6', - 'y = 7', - 'z = 8']) + substrs=['x = 6', + 'y = 7', + 'z = 8']) - # Add the synth again and check that it's honored deeper in the hierarchy + # Add the synth again and check that it's honored deeper in the + # hierarchy self.runCmd("type filter add BagOfInts --child x --child z") self.expect('frame variable bag_bag', - substrs = ['x = x=69 {', - 'x = 69', - 'z = 71', - 'y = x=66 {', - 'x = 66', - 'z = 68']) + substrs=['x = x=69 {', + 'x = 69', + 'z = 71', + 'y = x=66 {', + 'x = 66', + 'z = 68']) self.expect('frame variable bag_bag', matching=False, - substrs = ['y = 70', - 'y = 67']) + substrs=['y = 70', + 'y = 67']) # Check that a synth can expand nested stuff self.runCmd("type filter add BagOfBags --child x.y --child y.z") self.expect('frame variable bag_bag', - substrs = ['x.y = 70', - 'y.z = 68']) + substrs=['x.y = 70', + 'y.z = 68']) # ...even if we get -> and . wrong self.runCmd("type filter add BagOfBags --child x.y --child \"y->z\"") self.expect('frame variable bag_bag', - substrs = ['x.y = 70', - 'y->z = 68']) + substrs=['x.y = 70', + 'y->z = 68']) # ...even bitfields - self.runCmd("type filter add BagOfBags --child x.y --child \"y->z[1-2]\"") + self.runCmd( + "type filter add BagOfBags --child x.y --child \"y->z[1-2]\"") self.expect('frame variable bag_bag --show-types', - substrs = ['x.y = 70', - '(int:2) y->z[1-2] = 2']) + substrs=['x.y = 70', + '(int:2) y->z[1-2] = 2']) # ...even if we format the bitfields - self.runCmd("type filter add BagOfBags --child x.y --child \"y->y[0-0]\"") + self.runCmd( + "type filter add BagOfBags --child x.y --child \"y->y[0-0]\"") self.runCmd("type format add \"int:1\" -f bool") self.expect('frame variable bag_bag --show-types', - substrs = ['x.y = 70', - '(int:1) y->y[0-0] = true']) - + substrs=['x.y = 70', + '(int:1) y->y[0-0] = true']) + # ...even if we use one-liner summaries self.runCmd("type summary add -c BagOfBags") - self.expect('frame variable bag_bag', - substrs = ['(BagOfBags) bag_bag = (x.y = 70, y->y[0-0] = true)']) - + self.expect('frame variable bag_bag', substrs=[ + '(BagOfBags) bag_bag = (x.y = 70, y->y[0-0] = true)']) + self.runCmd("type summary delete BagOfBags") # now check we are dynamic (and arrays work) - self.runCmd("type filter add Plenty --child bitfield --child array[0] --child array[2]") + self.runCmd( + "type filter add Plenty --child bitfield --child array[0] --child array[2]") self.expect('frame variable plenty_of_stuff', - substrs = ['bitfield = 1', - 'array[0] = 5', - 'array[2] = 3']) - + substrs=['bitfield = 1', + 'array[0] = 5', + 'array[2] = 3']) + self.runCmd("n") self.expect('frame variable plenty_of_stuff', - substrs = ['bitfield = 17', - 'array[0] = 5', - 'array[2] = 3']) - + substrs=['bitfield = 17', + 'array[0] = 5', + 'array[2] = 3']) + # skip synthetic children self.expect('frame variable plenty_of_stuff --synthetic-type no', - substrs = ['some_values = 0x', - 'array = 0x', - 'array_size = 5']) + substrs=['some_values = 0x', + 'array = 0x', + 'array_size = 5']) - # check flat printing with synthetic children self.expect('frame variable plenty_of_stuff --flat', - substrs = ['plenty_of_stuff.bitfield = 17', - '*(plenty_of_stuff.array) = 5', - '*(plenty_of_stuff.array) = 3']) - + substrs=['plenty_of_stuff.bitfield = 17', + '*(plenty_of_stuff.array) = 5', + '*(plenty_of_stuff.array) = 3']) + # check that we do not lose location information for our children self.expect('frame variable plenty_of_stuff --location', - substrs = ['0x', - ': bitfield = 17']) + substrs=['0x', + ': bitfield = 17']) # check we work across pointer boundaries self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1', - substrs = ['(BagOfInts *) plenty_of_stuff.some_values', - 'x = 5', - 'z = 7']) + substrs=['(BagOfInts *) plenty_of_stuff.some_values', + 'x = 5', + 'z = 7']) # but not if we don't want to self.runCmd("type filter add BagOfInts --child x --child z -p") self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1', - substrs = ['(BagOfInts *) plenty_of_stuff.some_values', - 'x = 5', - 'y = 6', - 'z = 7']) + substrs=['(BagOfInts *) plenty_of_stuff.some_values', + 'x = 5', + 'y = 6', + 'z = 7']) # check we're dynamic even if nested self.runCmd("type filter add BagOfBags --child x.z") self.expect('frame variable bag_bag', - substrs = ['x.z = 71']) + substrs=['x.z = 71']) self.runCmd("n") self.expect('frame variable bag_bag', - substrs = ['x.z = 12']) + substrs=['x.z = 12']) - self.runCmd('type summary add -e -s "I am always empty but have" EmptyStruct') - self.expect('frame variable es', substrs = ["I am always empty but have {}"]) + self.runCmd( + 'type summary add -e -s "I am always empty but have" EmptyStruct') + self.expect('frame variable es', substrs=[ + "I am always empty but have {}"]) self.runCmd('type summary add -e -h -s "I am really empty" EmptyStruct') - self.expect('frame variable es', substrs = ["I am really empty"]) - self.expect('frame variable es', substrs = ["I am really empty {}"], matching=False) + self.expect('frame variable es', substrs=["I am really empty"]) + self.expect( + 'frame variable es', + substrs=["I am really empty {}"], + matching=False) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py index 6a03456e5c3..75d3b4e5f5c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DataFormatterSynthTypeTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,20 +23,21 @@ class DataFormatterSynthTypeTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', 'break here') - @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser def test_with_run_command(self): """Test using Python synthetic children provider to provide a typename.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py index 42737140b11..fa47ca2cfe6 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py @@ -1,22 +1,30 @@ class myIntSynthProvider(object): - def __init__(self, valobj, dict): - self.valobj = valobj; - self.val = self.valobj.GetChildMemberWithName("theValue") - def num_children(self): - return 0; - def get_child_at_index(self, index): - return None - def get_child_index(self, name): - return None - def update(self): - return False - def has_children(self): - return False - def get_type_name(self): - return "ThisTestPasses" + + def __init__(self, valobj, dict): + self.valobj = valobj + self.val = self.valobj.GetChildMemberWithName("theValue") + + def num_children(self): + return 0 + + def get_child_at_index(self, index): + return None + + def get_child_index(self, name): + return None + + def update(self): + return False + + def has_children(self): + return False + + def get_type_name(self): + return "ThisTestPasses" class myArraySynthProvider(object): + def __init__(self, valobj, dict): self.valobj = valobj self.array = self.valobj.GetChildMemberWithName("array") @@ -27,10 +35,10 @@ class myArraySynthProvider(object): return max_count def get_child_at_index(self, index): - return None # Keep it simple when this is not tested here. + return None # Keep it simple when this is not tested here. def get_child_index(self, name): - return None # Keep it simple when this is not tested here. + return None # Keep it simple when this is not tested here. def has_children(self): return True diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py index 5d796f9bf99..6e7ac2c13f3 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DataFormatterSynthValueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,21 +23,24 @@ class DataFormatterSynthValueTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', 'break here') - @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") def test_with_run_command(self): """Test using Python synthetic children provider to provide a value.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -48,7 +52,7 @@ class DataFormatterSynthValueTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + x = self.frame().FindVariable("x") x.SetPreferSyntheticValue(True) y = self.frame().FindVariable("y") @@ -62,9 +66,11 @@ class DataFormatterSynthValueTestCase(TestBase): y_val = y.GetValueAsUnsigned z_val = z.GetValueAsUnsigned q_val = q.GetValueAsUnsigned - + if self.TraceOn(): - print("x_val = %s; y_val = %s; z_val = %s; q_val = %s" % (x_val(),y_val(),z_val(),q_val())) + print( + "x_val = %s; y_val = %s; z_val = %s; q_val = %s" % + (x_val(), y_val(), z_val(), q_val())) self.assertFalse(x_val() == 3, "x == 3 before synthetics") self.assertFalse(y_val() == 4, "y == 4 before synthetics") @@ -76,23 +82,34 @@ class DataFormatterSynthValueTestCase(TestBase): self.runCmd("type synth add -l myIntSynthProvider myInt") self.runCmd("type synth add -l myArraySynthProvider myArray") self.runCmd("type synth add -l myIntSynthProvider myIntAndStuff") - + if self.TraceOn(): - print("x_val = %s; y_val = %s; z_val = %s; q_val = %s" % (x_val(),y_val(),z_val(),q_val())) - + print( + "x_val = %s; y_val = %s; z_val = %s; q_val = %s" % + (x_val(), y_val(), z_val(), q_val())) + self.assertTrue(x_val() == 3, "x != 3 after synthetics") self.assertTrue(y_val() == 4, "y != 4 after synthetics") self.assertTrue(z_val() == 7, "z != 7 after synthetics") self.assertTrue(q_val() == 8, "q != 8 after synthetics") - + self.expect("frame variable x", substrs=['3']) - self.expect("frame variable x", substrs=['theValue = 3'], matching=False) + self.expect( + "frame variable x", + substrs=['theValue = 3'], + matching=False) self.expect("frame variable q", substrs=['8']) - self.expect("frame variable q", substrs=['theValue = 8'], matching=False) - - # check that an aptly defined synthetic provider does not affect one-lining - self.expect("expression struct S { myInt theInt{12}; }; S()", substrs = ['(theInt = 12)']) - + self.expect( + "frame variable q", + substrs=['theValue = 8'], + matching=False) + + # check that an aptly defined synthetic provider does not affect + # one-lining + self.expect( + "expression struct S { myInt theInt{12}; }; S()", + substrs=['(theInt = 12)']) + # check that we can use a synthetic value in a summary self.runCmd("type summary add hasAnInt -s ${var.theInt}") hi = self.frame().FindVariable("hi") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py index c8517a44293..82da6f9da92 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py @@ -1,22 +1,30 @@ class myIntSynthProvider(object): - def __init__(self, valobj, dict): - self.valobj = valobj; - self.val = self.valobj.GetChildMemberWithName("theValue") - def num_children(self): - return 0; - def get_child_at_index(self, index): - return None - def get_child_index(self, name): - return None - def update(self): - return False - def has_children(self): - return False - def get_value(self): - return self.val + + def __init__(self, valobj, dict): + self.valobj = valobj + self.val = self.valobj.GetChildMemberWithName("theValue") + + def num_children(self): + return 0 + + def get_child_at_index(self, index): + return None + + def get_child_index(self, name): + return None + + def update(self): + return False + + def has_children(self): + return False + + def get_value(self): + return self.val class myArraySynthProvider(object): + def __init__(self, valobj, dict): self.valobj = valobj self.array = self.valobj.GetChildMemberWithName("array") @@ -27,10 +35,10 @@ class myArraySynthProvider(object): return max_count def get_child_at_index(self, index): - return None # Keep it simple when this is not tested here. + return None # Keep it simple when this is not tested here. def get_child_index(self, name): - return None # Keep it simple when this is not tested here. + return None # Keep it simple when this is not tested here. def has_children(self): return True diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py index 886d09fda45..734e711fb7f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py @@ -2,4 +2,7 @@ from __future__ import absolute_import from lldbsuite.test import lldbinline -lldbinline.MakeInlineTest(__file__, globals(), [lldbinline.expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663")]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + lldbinline.expectedFailureAll( + oslist=["windows"], bugnumber="llvm.org/pr24663")]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py index 5cb7c82c9e0..0c15c793e1f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py @@ -5,12 +5,13 @@ Check if changing Format on an SBValue correctly propagates that new format to c from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class FormatPropagationTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,14 +28,15 @@ class FormatPropagationTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,18 +49,24 @@ class FormatPropagationTestCase(TestBase): # extract the parent and the children frame = self.frame() parent = self.frame().FindVariable("f") - self.assertTrue(parent != None and parent.IsValid(),"could not find f") + self.assertTrue( + parent is not None and parent.IsValid(), + "could not find f") X = parent.GetChildMemberWithName("X") - self.assertTrue(X != None and X.IsValid(),"could not find X") + self.assertTrue(X is not None and X.IsValid(), "could not find X") Y = parent.GetChildMemberWithName("Y") - self.assertTrue(Y != None and Y.IsValid(),"could not find Y") + self.assertTrue(Y is not None and Y.IsValid(), "could not find Y") # check their values now self.assertTrue(X.GetValue() == "1", "X has an invalid value") self.assertTrue(Y.GetValue() == "2", "Y has an invalid value") # set the format on the parent parent.SetFormat(lldb.eFormatHex) - self.assertTrue(X.GetValue() == "0x00000001", "X has not changed format") - self.assertTrue(Y.GetValue() == "0x00000002", "Y has not changed format") + self.assertTrue( + X.GetValue() == "0x00000001", + "X has not changed format") + self.assertTrue( + Y.GetValue() == "0x00000002", + "Y has not changed format") # Step and check if the values make sense still self.runCmd("next") self.assertTrue(X.GetValue() == "0x00000004", "X has not become 4") @@ -71,5 +79,7 @@ class FormatPropagationTestCase(TestBase): parent.SetFormat(lldb.eFormatDefault) X.SetFormat(lldb.eFormatHex) Y.SetFormat(lldb.eFormatDefault) - self.assertTrue(X.GetValue() == "0x00000004", "X is not hex as it asked") + self.assertTrue( + X.GetValue() == "0x00000004", + "X is not hex as it asked") self.assertTrue(Y.GetValue() == "2", "Y is not defaulted") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py index 555351998c2..d6303fe8b73 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py @@ -5,12 +5,13 @@ Test that the user can input a format but it will not prevail over summary forma from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class FrameFormatSmallStructTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,13 +27,14 @@ class FrameFormatSmallStructTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) - self.expect("thread list", substrs = ['addPair(p=(x = 3, y = -3))']) + self.expect("thread list", substrs=['addPair(p=(x = 3, y = -3))']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py index 3c28b68056f..32fbf48dcc6 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class DataFormatterHexCapsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,14 +27,15 @@ class DataFormatterHexCapsTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -45,38 +47,43 @@ class DataFormatterHexCapsTestCase(TestBase): self.addTearDownHook(cleanup) self.runCmd("type format add -f uppercase int") - + self.expect('frame variable mine', - substrs = ['mine = ', - 'first = 0x001122AA', 'second = 0x1122BB44']) + substrs=['mine = ', + 'first = 0x001122AA', 'second = 0x1122BB44']) self.runCmd("type format add -f hex int") self.expect('frame variable mine', - substrs = ['mine = ', - 'first = 0x001122aa', 'second = 0x1122bb44']) + substrs=['mine = ', + 'first = 0x001122aa', 'second = 0x1122bb44']) self.runCmd("type format delete int") - self.runCmd("type summary add -s \"${var.first%X} and ${var.second%x}\" foo") + self.runCmd( + "type summary add -s \"${var.first%X} and ${var.second%x}\" foo") self.expect('frame variable mine', - substrs = ['(foo) mine = 0x001122AA and 0x1122bb44']) + substrs=['(foo) mine = 0x001122AA and 0x1122bb44']) - self.runCmd("type summary add -s \"${var.first%X} and ${var.second%X}\" foo") + self.runCmd( + "type summary add -s \"${var.first%X} and ${var.second%X}\" foo") self.runCmd("next") self.runCmd("next") self.expect('frame variable mine', - substrs = ['(foo) mine = 0xAABBCCDD and 0x1122BB44']) + substrs=['(foo) mine = 0xAABBCCDD and 0x1122BB44']) - self.runCmd("type summary add -s \"${var.first%x} and ${var.second%X}\" foo") + self.runCmd( + "type summary add -s \"${var.first%x} and ${var.second%X}\" foo") self.expect('frame variable mine', - substrs = ['(foo) mine = 0xaabbccdd and 0x1122BB44']) + substrs=['(foo) mine = 0xaabbccdd and 0x1122BB44']) self.runCmd("next") self.runCmd("next") - self.runCmd("type summary add -s \"${var.first%x} and ${var.second%x}\" foo") + self.runCmd( + "type summary add -s \"${var.first%x} and ${var.second%x}\" foo") self.expect('frame variable mine', - substrs = ['(foo) mine = 0xaabbccdd and 0xff00ff00']) - self.runCmd("type summary add -s \"${var.first%X} and ${var.second%X}\" foo") + substrs=['(foo) mine = 0xaabbccdd and 0xff00ff00']) + self.runCmd( + "type summary add -s \"${var.first%X} and ${var.second%X}\" foo") self.expect('frame variable mine', - substrs = ['(foo) mine = 0xAABBCCDD and 0xFF00FF00']) + substrs=['(foo) mine = 0xAABBCCDD and 0xFF00FF00']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py index f30733d2d81..b7f60cfac41 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class LanguageCategoryUpdatesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,7 +27,11 @@ class LanguageCategoryUpdatesTestCase(TestBase): # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): - if hasattr(self, 'type_category') and hasattr(self, 'type_specifier'): + if hasattr( + self, + 'type_category') and hasattr( + self, + 'type_specifier'): self.type_category.DeleteTypeSummary(self.type_specifier) # Execute the cleanup function during test case tear down. @@ -35,25 +40,47 @@ class LanguageCategoryUpdatesTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - - self.expect("frame variable", substrs = ['(S)', 'object', '123', '456'], matching=True) - - self.type_category = self.dbg.GetCategory(lldb.eLanguageTypeC_plus_plus) - type_summary = lldb.SBTypeSummary.CreateWithSummaryString("this is an object of type S") + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect( + "frame variable", + substrs=[ + '(S)', + 'object', + '123', + '456'], + matching=True) + + self.type_category = self.dbg.GetCategory( + lldb.eLanguageTypeC_plus_plus) + type_summary = lldb.SBTypeSummary.CreateWithSummaryString( + "this is an object of type S") self.type_specifier = lldb.SBTypeNameSpecifier('S') self.type_category.AddTypeSummary(self.type_specifier, type_summary) - self.expect("frame variable", substrs = ['this is an object of type S'], matching=True) - - self.type_category.DeleteTypeSummary(self.type_specifier) - self.expect("frame variable", substrs = ['this is an object of type S'], matching=False) - self.expect("frame variable", substrs = ['(S)', 'object', '123', '456'], matching=True) + self.expect( + "frame variable", + substrs=['this is an object of type S'], + matching=True) + self.type_category.DeleteTypeSummary(self.type_specifier) + self.expect( + "frame variable", + substrs=['this is an object of type S'], + matching=False) + self.expect( + "frame variable", + substrs=[ + '(S)', + 'object', + '123', + '456'], + matching=True) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py index 871cc19373a..87fc2d1802b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NSArraySyntheticTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,14 +30,15 @@ class NSArraySyntheticTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -50,19 +52,59 @@ class NSArraySyntheticTestCase(TestBase): # Now check that we are displaying Cocoa classes correctly self.expect('frame variable arr', - substrs = ['@"6 elements"']) + substrs=['@"6 elements"']) self.expect('frame variable other_arr', - substrs = ['@"4 elements"']) - self.expect('frame variable arr --ptr-depth 1', - substrs = ['@"6 elements"','[0] = 0x','[1] = 0x','[2] = 0x','[3] = 0x','[4] = 0x','[5] = 0x']) - self.expect('frame variable other_arr --ptr-depth 1', - substrs = ['@"4 elements"','[0] = 0x','[1] = 0x','[2] = 0x','[3] = 0x']) - self.expect('frame variable arr --ptr-depth 1 -d no-run-target', - substrs = ['@"6 elements"','@"hello"','@"world"','@"this"','@"is"','@"me"','@"http://www.apple.com']) - self.expect('frame variable other_arr --ptr-depth 1 -d no-run-target', - substrs = ['@"4 elements"','(int)5','@"a string"','@"6 elements"']) - self.expect('frame variable other_arr --ptr-depth 2 -d no-run-target', - substrs = ['@"4 elements"','@"6 elements" {','@"hello"','@"world"','@"this"','@"is"','@"me"','@"http://www.apple.com']) + substrs=['@"4 elements"']) + self.expect( + 'frame variable arr --ptr-depth 1', + substrs=[ + '@"6 elements"', + '[0] = 0x', + '[1] = 0x', + '[2] = 0x', + '[3] = 0x', + '[4] = 0x', + '[5] = 0x']) + self.expect( + 'frame variable other_arr --ptr-depth 1', + substrs=[ + '@"4 elements"', + '[0] = 0x', + '[1] = 0x', + '[2] = 0x', + '[3] = 0x']) + self.expect( + 'frame variable arr --ptr-depth 1 -d no-run-target', + substrs=[ + '@"6 elements"', + '@"hello"', + '@"world"', + '@"this"', + '@"is"', + '@"me"', + '@"http://www.apple.com']) + self.expect( + 'frame variable other_arr --ptr-depth 1 -d no-run-target', + substrs=[ + '@"4 elements"', + '(int)5', + '@"a string"', + '@"6 elements"']) + self.expect( + 'frame variable other_arr --ptr-depth 2 -d no-run-target', + substrs=[ + '@"4 elements"', + '@"6 elements" {', + '@"hello"', + '@"world"', + '@"this"', + '@"is"', + '@"me"', + '@"http://www.apple.com']) - self.assertTrue(self.frame().FindVariable("arr").MightHaveChildren(), "arr says it does not have children!") - self.assertTrue(self.frame().FindVariable("other_arr").MightHaveChildren(), "arr says it does not have children!") + self.assertTrue( + self.frame().FindVariable("arr").MightHaveChildren(), + "arr says it does not have children!") + self.assertTrue( + self.frame().FindVariable("other_arr").MightHaveChildren(), + "arr says it does not have children!") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py index 5ee54c3a295..85675d21123 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NSDictionarySyntheticTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,14 +30,15 @@ class NSDictionarySyntheticTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -50,21 +52,73 @@ class NSDictionarySyntheticTestCase(TestBase): # Now check that we are displaying Cocoa classes correctly self.expect('frame variable dictionary', - substrs = ['3 key/value pairs']) + substrs=['3 key/value pairs']) self.expect('frame variable mutabledict', - substrs = ['4 key/value pairs']) - self.expect('frame variable dictionary --ptr-depth 1', - substrs = ['3 key/value pairs','[0] = ','key = 0x','value = 0x','[1] = ','[2] = ']) - self.expect('frame variable mutabledict --ptr-depth 1', - substrs = ['4 key/value pairs','[0] = ','key = 0x','value = 0x','[1] = ','[2] = ','[3] = ']) - self.expect('frame variable dictionary --ptr-depth 1 --dynamic-type no-run-target', - substrs = ['3 key/value pairs','@"bar"','@"2 elements"','@"baz"','2 key/value pairs']) - self.expect('frame variable mutabledict --ptr-depth 1 --dynamic-type no-run-target', - substrs = ['4 key/value pairs','(int)23','@"123"','@"http://www.apple.com"','@"sourceofstuff"','3 key/value pairs']) - self.expect('frame variable mutabledict --ptr-depth 2 --dynamic-type no-run-target', - substrs = ['4 key/value pairs','(int)23','@"123"','@"http://www.apple.com"','@"sourceofstuff"','3 key/value pairs','@"bar"','@"2 elements"']) - self.expect('frame variable mutabledict --ptr-depth 3 --dynamic-type no-run-target', - substrs = ['4 key/value pairs','(int)23','@"123"','@"http://www.apple.com"','@"sourceofstuff"','3 key/value pairs','@"bar"','@"2 elements"','(int)1','@"two"']) + substrs=['4 key/value pairs']) + self.expect( + 'frame variable dictionary --ptr-depth 1', + substrs=[ + '3 key/value pairs', + '[0] = ', + 'key = 0x', + 'value = 0x', + '[1] = ', + '[2] = ']) + self.expect( + 'frame variable mutabledict --ptr-depth 1', + substrs=[ + '4 key/value pairs', + '[0] = ', + 'key = 0x', + 'value = 0x', + '[1] = ', + '[2] = ', + '[3] = ']) + self.expect( + 'frame variable dictionary --ptr-depth 1 --dynamic-type no-run-target', + substrs=[ + '3 key/value pairs', + '@"bar"', + '@"2 elements"', + '@"baz"', + '2 key/value pairs']) + self.expect( + 'frame variable mutabledict --ptr-depth 1 --dynamic-type no-run-target', + substrs=[ + '4 key/value pairs', + '(int)23', + '@"123"', + '@"http://www.apple.com"', + '@"sourceofstuff"', + '3 key/value pairs']) + self.expect( + 'frame variable mutabledict --ptr-depth 2 --dynamic-type no-run-target', + substrs=[ + '4 key/value pairs', + '(int)23', + '@"123"', + '@"http://www.apple.com"', + '@"sourceofstuff"', + '3 key/value pairs', + '@"bar"', + '@"2 elements"']) + self.expect( + 'frame variable mutabledict --ptr-depth 3 --dynamic-type no-run-target', + substrs=[ + '4 key/value pairs', + '(int)23', + '@"123"', + '@"http://www.apple.com"', + '@"sourceofstuff"', + '3 key/value pairs', + '@"bar"', + '@"2 elements"', + '(int)1', + '@"two"']) - self.assertTrue(self.frame().FindVariable("dictionary").MightHaveChildren(), "dictionary says it does not have children!") - self.assertTrue(self.frame().FindVariable("mutabledict").MightHaveChildren(), "mutable says it does not have children!") + self.assertTrue( + self.frame().FindVariable("dictionary").MightHaveChildren(), + "dictionary says it does not have children!") + self.assertTrue( + self.frame().FindVariable("mutabledict").MightHaveChildren(), + "mutable says it does not have children!") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py index d1680434d3b..6affc5a71fa 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NSSetSyntheticTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,14 +30,15 @@ class NSSetSyntheticTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -50,26 +52,64 @@ class NSSetSyntheticTestCase(TestBase): # Now check that we are displaying Cocoa classes correctly self.expect('frame variable set', - substrs = ['4 elements']) + substrs=['4 elements']) self.expect('frame variable mutable', - substrs = ['9 elements']) - self.expect('frame variable set --ptr-depth 1 -d run -T', - substrs = ['4 elements','[0]','[1]','[2]','[3]','hello','world','(int)1','(int)2']) - self.expect('frame variable mutable --ptr-depth 1 -d run -T', - substrs = ['9 elements','(int)5','@"3 elements"','@"www.apple.com"','(int)3','@"world"','(int)4']) + substrs=['9 elements']) + self.expect( + 'frame variable set --ptr-depth 1 -d run -T', + substrs=[ + '4 elements', + '[0]', + '[1]', + '[2]', + '[3]', + 'hello', + 'world', + '(int)1', + '(int)2']) + self.expect( + 'frame variable mutable --ptr-depth 1 -d run -T', + substrs=[ + '9 elements', + '(int)5', + '@"3 elements"', + '@"www.apple.com"', + '(int)3', + '@"world"', + '(int)4']) self.runCmd("next") self.expect('frame variable mutable', - substrs = ['0 elements']) + substrs=['0 elements']) self.runCmd("next") self.expect('frame variable mutable', - substrs = ['4 elements']) - self.expect('frame variable mutable --ptr-depth 1 -d run -T', - substrs = ['4 elements','[0]','[1]','[2]','[3]','hello','world','(int)1','(int)2']) + substrs=['4 elements']) + self.expect( + 'frame variable mutable --ptr-depth 1 -d run -T', + substrs=[ + '4 elements', + '[0]', + '[1]', + '[2]', + '[3]', + 'hello', + 'world', + '(int)1', + '(int)2']) self.runCmd("next") self.expect('frame variable mutable', - substrs = ['4 elements']) - self.expect('frame variable mutable --ptr-depth 1 -d run -T', - substrs = ['4 elements','[0]','[1]','[2]','[3]','hello','world','(int)1','(int)2']) + substrs=['4 elements']) + self.expect( + 'frame variable mutable --ptr-depth 1 -d run -T', + substrs=[ + '4 elements', + '[0]', + '[1]', + '[2]', + '[3]', + 'hello', + 'world', + '(int)1', + '(int)2']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py index 4158ec8a661..7ffddc5ec67 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DataFormatterOSTypeTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,14 +30,15 @@ class DataFormatterOSTypeTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -50,4 +52,4 @@ class DataFormatterOSTypeTestCase(TestBase): # Now check that we use the right summary for OSType self.expect('frame variable', - substrs = ["'test'","'best'"]) + substrs=["'test'", "'best'"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/TestPrintArray.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/TestPrintArray.py index 700b7418118..49cda4ae6cc 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/TestPrintArray.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/TestPrintArray.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PrintArrayTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -32,14 +33,15 @@ class PrintArrayTestCase(TestBase): """Test that expr -Z works""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -50,21 +52,85 @@ class PrintArrayTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - - self.expect('expr --element-count 3 -- data', substrs=['[0] = 1', '[1] = 3', '[2] = 5']) + + self.expect( + 'expr --element-count 3 -- data', + substrs=[ + '[0] = 1', + '[1] = 3', + '[2] = 5']) self.expect('expr data', substrs=['int *', '$', '0x']) - self.expect('expr -f binary --element-count 0 -- data', substrs=['int *', '$', '0b']) - self.expect('expr -f hex --element-count 3 -- data', substrs=['[0] = 0x', '1', '[1] = 0x', '3', '[2] = 0x', '5']) - self.expect('expr -f binary --element-count 2 -- data', substrs=['int *', '$', '0x', '[0] = 0b', '1', '[1] = 0b', '11']) + self.expect( + 'expr -f binary --element-count 0 -- data', + substrs=[ + 'int *', + '$', + '0b']) + self.expect( + 'expr -f hex --element-count 3 -- data', + substrs=[ + '[0] = 0x', + '1', + '[1] = 0x', + '3', + '[2] = 0x', + '5']) + self.expect( + 'expr -f binary --element-count 2 -- data', + substrs=[ + 'int *', + '$', + '0x', + '[0] = 0b', + '1', + '[1] = 0b', + '11']) self.expect('parray 3 data', substrs=['[0] = 1', '[1] = 3', '[2] = 5']) - self.expect('parray `1 + 1 + 1` data', substrs=['[0] = 1', '[1] = 3', '[2] = 5']) - self.expect('parray `data[1]` data', substrs=['[0] = 1', '[1] = 3', '[2] = 5']) - self.expect('parray/x 3 data', substrs=['[0] = 0x', '1', '[1] = 0x', '3', '[2] = 0x', '5']) - self.expect('parray/x `data[1]` data', substrs=['[0] = 0x', '1', '[1] = 0x', '3', '[2] = 0x', '5']) + self.expect( + 'parray `1 + 1 + 1` data', + substrs=[ + '[0] = 1', + '[1] = 3', + '[2] = 5']) + self.expect( + 'parray `data[1]` data', + substrs=[ + '[0] = 1', + '[1] = 3', + '[2] = 5']) + self.expect( + 'parray/x 3 data', + substrs=[ + '[0] = 0x', + '1', + '[1] = 0x', + '3', + '[2] = 0x', + '5']) + self.expect( + 'parray/x `data[1]` data', + substrs=[ + '[0] = 0x', + '1', + '[1] = 0x', + '3', + '[2] = 0x', + '5']) # check error conditions - self.expect('expr --element-count 10 -- 123', error=True, substrs=['expression cannot be used with --element-count as it does not refer to a pointer']) - self.expect('expr --element-count 10 -- (void*)123', error=True, substrs=['expression cannot be used with --element-count as it refers to a pointer to void']) - self.expect('parray data', error=True, substrs=["invalid element count 'data'"]) - self.expect('parray data data', error=True, substrs=["invalid element count 'data'"]) - self.expect('parray', error=True, substrs=['Not enough arguments provided']) + self.expect( + 'expr --element-count 10 -- 123', + error=True, + substrs=['expression cannot be used with --element-count as it does not refer to a pointer']) + self.expect( + 'expr --element-count 10 -- (void*)123', + error=True, + substrs=['expression cannot be used with --element-count as it refers to a pointer to void']) + self.expect('parray data', error=True, substrs=[ + "invalid element count 'data'"]) + self.expect( + 'parray data data', + error=True, + substrs=["invalid element count 'data'"]) + self.expect('parray', error=True, substrs=[ + 'Not enough arguments provided']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py index 7eb26a56986..83408e7b456 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PrintObjectArrayTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -33,14 +34,15 @@ class PrintObjectArrayTestCase(TestBase): """Test that expr -O -Z works""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -52,9 +54,59 @@ class PrintObjectArrayTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.expect('expr --element-count 3 --object-description -- objects', substrs=['3735928559', '4276993775', '3203398366', 'Hello', 'World', 'Two =', '1 =']) - self.expect('poarray 3 objects', substrs=['3735928559', '4276993775', '3203398366', 'Hello', 'World', 'Two =', '1 =']) - self.expect('expr --element-count 3 --object-description --description-verbosity=full -- objects', substrs=['[0] =', '3735928559', '4276993775', '3203398366', '[1] =', 'Hello', 'World', '[2] =', 'Two =', '1 =']) - self.expect('parray 3 objects', substrs=['[0] = 0x', '[1] = 0x', '[2] = 0x']) - self.expect('expr --element-count 3 -d run -- objects', substrs=['3 elements', '2 elements', '2 key/value pairs']) - self.expect('expr --element-count 3 -d run --ptr-depth=1 -- objects', substrs=['3 elements', '2 elements', '2 key/value pairs', '3735928559', '4276993775', '3203398366', '"Hello"', '"World"']) + self.expect( + 'expr --element-count 3 --object-description -- objects', + substrs=[ + '3735928559', + '4276993775', + '3203398366', + 'Hello', + 'World', + 'Two =', + '1 =']) + self.expect( + 'poarray 3 objects', + substrs=[ + '3735928559', + '4276993775', + '3203398366', + 'Hello', + 'World', + 'Two =', + '1 =']) + self.expect( + 'expr --element-count 3 --object-description --description-verbosity=full -- objects', + substrs=[ + '[0] =', + '3735928559', + '4276993775', + '3203398366', + '[1] =', + 'Hello', + 'World', + '[2] =', + 'Two =', + '1 =']) + self.expect( + 'parray 3 objects', + substrs=[ + '[0] = 0x', + '[1] = 0x', + '[2] = 0x']) + self.expect( + 'expr --element-count 3 -d run -- objects', + substrs=[ + '3 elements', + '2 elements', + '2 key/value pairs']) + self.expect( + 'expr --element-count 3 -d run --ptr-depth=1 -- objects', + substrs=[ + '3 elements', + '2 elements', + '2 key/value pairs', + '3735928559', + '4276993775', + '3203398366', + '"Hello"', + '"World"']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py index bf98559cd0c..69b9dd04887 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class PtrRef2TypedefTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,20 +21,21 @@ class PtrRef2TypedefTestCase(TestBase): TestBase.setUp(self) # Find the line number to break at. self.line = line_number('main.cpp', '// Set breakpoint here') - + def test_with_run_command(self): """Test that a pointer/reference to a typedef is formatted as we want.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -48,10 +50,18 @@ class PtrRef2TypedefTestCase(TestBase): self.runCmd('type summary add --cascade true -s "IntLRef" "int &"') self.runCmd('type summary add --cascade true -s "IntRRef" "int &&"') - self.expect("frame variable x", substrs = ['(Foo *) x = 0x','IntPointer']) + self.expect( + "frame variable x", + substrs=[ + '(Foo *) x = 0x', + 'IntPointer']) # note: Ubuntu 12.04 x86_64 build with gcc 4.8.2 is getting a # const after the ref that isn't showing up on FreeBSD. This # tweak changes the behavior so that the const is not part of # the match. - self.expect("frame variable y", substrs = ['(Foo &', ') y = 0x','IntLRef']) - self.expect("frame variable z", substrs = ['(Foo &&', ') z = 0x','IntRRef']) + self.expect( + "frame variable y", substrs=[ + '(Foo &', ') y = 0x', 'IntLRef']) + self.expect( + "frame variable z", substrs=[ + '(Foo &&', ') z = 0x', 'IntRRef']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py index db2d5806e09..2ff27ae2047 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PyObjectSynthProviderTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -33,14 +34,15 @@ class PyObjectSynthProviderTestCase(TestBase): """Test that the PythonObjectSyntheticChildProvider helper class works""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -51,9 +53,20 @@ class PyObjectSynthProviderTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + self.runCmd('command script import provider.py') - self.runCmd('type synthetic add Foo --python-class provider.SyntheticChildrenProvider') + self.runCmd( + 'type synthetic add Foo --python-class provider.SyntheticChildrenProvider') self.expect('frame variable f.Name', substrs=['"Enrico"']) - self.expect('frame variable f', substrs=['ID = 123456', 'Name = "Enrico"', 'Rate = 1.25']) - self.expect('expression f', substrs=['ID = 123456', 'Name = "Enrico"', 'Rate = 1.25']) + self.expect( + 'frame variable f', + substrs=[ + 'ID = 123456', + 'Name = "Enrico"', + 'Rate = 1.25']) + self.expect( + 'expression f', + substrs=[ + 'ID = 123456', + 'Name = "Enrico"', + 'Rate = 1.25']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/provider.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/provider.py index 134ae83aa1c..c263190c102 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/provider.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/provider.py @@ -2,12 +2,15 @@ import lldb import lldb.formatters import lldb.formatters.synth -class SyntheticChildrenProvider(lldb.formatters.synth.PythonObjectSyntheticChildProvider): + +class SyntheticChildrenProvider( + lldb.formatters.synth.PythonObjectSyntheticChildProvider): + def __init__(self, value, internal_dict): - lldb.formatters.synth.PythonObjectSyntheticChildProvider.__init__(self, value, internal_dict) + lldb.formatters.synth.PythonObjectSyntheticChildProvider.__init__( + self, value, internal_dict) def make_children(self): - return [("ID", 123456), - ("Name", "Enrico"), - ("Rate", 1.25)] - + return [("ID", 123456), + ("Name", "Enrico"), + ("Rate", 1.25)] diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py index 13b84e9f74c..0a039107d84 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py @@ -5,12 +5,13 @@ Test that ValueObjectPrinter does not cause an infinite loop when a reference to from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class DataFormatterRefPtrRecursionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,16 +27,17 @@ class DataFormatterRefPtrRecursionTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) - self.expect("frame variable foo", substrs = []); - self.expect("frame variable foo --ptr-depth=1", substrs = ['ID = 1']); - self.expect("frame variable foo --ptr-depth=2", substrs = ['ID = 1']); - self.expect("frame variable foo --ptr-depth=3", substrs = ['ID = 1']); + self.expect("frame variable foo", substrs=[]) + self.expect("frame variable foo --ptr-depth=1", substrs=['ID = 1']) + self.expect("frame variable foo --ptr-depth=2", substrs=['ID = 1']) + self.expect("frame variable foo --ptr-depth=3", substrs=['ID = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py index 791ce27dad0..804905106df 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py @@ -1,4 +1,6 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, decorators.skipIfWindows]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py index e26344f2711..c76b421a1ea 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py @@ -1,4 +1,7 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24772")]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + oslist=["windows"], bugnumber="llvm.org/pr24772")]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py index 2873e35368f..d7862d2327c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class Radar9974002DataFormatterTestCase(TestBase): # test for rdar://problem/9974002 () @@ -26,18 +27,20 @@ class Radar9974002DataFormatterTestCase(TestBase): """Test that that file and class static variables display correctly.""" self.build() if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): - self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,87 +50,98 @@ class Radar9974002DataFormatterTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") - + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + self.expect('frame variable mine', - substrs = ['mine = ', - '1', '<parent is NULL>']) + substrs=['mine = ', + '1', '<parent is NULL>']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '0x000000']) + substrs=['mine = ', + '1', '0x000000']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '0x000000']) + substrs=['mine = ', + '1', '0x000000']) self.runCmd("type summary add -s foo contained") self.expect('frame variable mine', - substrs = ['mine = ', - '1', 'foo']) + substrs=['mine = ', + '1', 'foo']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', 'foo']) + substrs=['mine = ', + '1', 'foo']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '0x000000']) + substrs=['mine = ', + '1', '0x000000']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '<parent is NULL>']) + substrs=['mine = ', + '1', '<parent is NULL>']) self.runCmd("type summary delete contained") self.runCmd("n") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '<parent is NULL>']) + substrs=['mine = ', + '1', '<parent is NULL>']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '0x000000']) + substrs=['mine = ', + '1', '0x000000']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '0x000000']) + substrs=['mine = ', + '1', '0x000000']) self.runCmd("type summary add -s foo contained") self.expect('frame variable mine', - substrs = ['mine = ', - '1', 'foo']) + substrs=['mine = ', + '1', 'foo']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', 'foo']) + substrs=['mine = ', + '1', 'foo']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '0x000000']) + substrs=['mine = ', + '1', '0x000000']) - self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") self.expect('frame variable mine', - substrs = ['mine = ', - '1', '<parent is NULL>']) + substrs=['mine = ', + '1', '<parent is NULL>']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py index e8b6c1ad95f..6d519761b7b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py @@ -5,13 +5,14 @@ Check for an issue where capping does not work because the Target pointer appear from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SyntheticCappingTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,7 +28,8 @@ class SyntheticCappingTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) @@ -35,8 +37,8 @@ class SyntheticCappingTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -45,7 +47,9 @@ class SyntheticCappingTestCase(TestBase): self.runCmd('type summary clear', check=False) self.runCmd('type filter clear', check=False) self.runCmd('type synth clear', check=False) - self.runCmd("settings set target.max-children-count 256", check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) @@ -60,25 +64,25 @@ class SyntheticCappingTestCase(TestBase): else: fake_a_val = 0x00000100 - # check that the synthetic children work, so we know we are doing the right thing + # check that the synthetic children work, so we know we are doing the + # right thing self.expect("frame variable f00_1", - substrs = ['r = 34', - 'fake_a = %d' % fake_a_val, - 'a = 1']); + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 1']) # check that capping works self.runCmd("settings set target.max-children-count 2", check=False) - + self.expect("frame variable f00_1", - substrs = ['...', - 'fake_a = %d' % fake_a_val, - 'a = 1']); - + substrs=['...', + 'fake_a = %d' % fake_a_val, + 'a = 1']) + self.expect("frame variable f00_1", matching=False, - substrs = ['r = 34']); + substrs=['r = 34']) - self.runCmd("settings set target.max-children-count 256", check=False) self.expect("frame variable f00_1", matching=True, - substrs = ['r = 34']); + substrs=['r = 34']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py index 1a7e5679c0b..124eb5d31ba 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py @@ -1,21 +1,27 @@ import lldb + + class fooSynthProvider: + def __init__(self, valobj, dict): - self.valobj = valobj; + self.valobj = valobj self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) + def num_children(self): - return 3; + return 3 + def get_child_at_index(self, index): if index == 0: - child = self.valobj.GetChildMemberWithName('a'); + child = self.valobj.GetChildMemberWithName('a') if index == 1: - child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type); + child = self.valobj.CreateChildAtOffset('fake_a', 1, self.int_type) if index == 2: - child = self.valobj.GetChildMemberWithName('r'); - return child; + child = self.valobj.GetChildMemberWithName('r') + return child + def get_child_index(self, name): if name == 'a': - return 0; + return 0 if name == 'fake_a': - return 1; - return 2; + return 1 + return 2 diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py index 23a31da685d..29c1214564d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SyntheticFilterRecomputingTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,14 +30,15 @@ class SyntheticFilterRecomputingTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -49,27 +51,37 @@ class SyntheticFilterRecomputingTestCase(TestBase): self.addTearDownHook(cleanup) # Now run the bulk of the test - id_x = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable("x") + id_x = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable("x") id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) id_x.SetPreferSyntheticValue(True) - + if self.TraceOn(): self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x") - self.assertTrue(id_x.GetSummary() == '@"5 elements"', "array does not get correct summary") + self.assertTrue( + id_x.GetSummary() == '@"5 elements"', + "array does not get correct summary") self.runCmd("next") self.runCmd("frame select 0") - id_x = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable("x") + id_x = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable("x") id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) id_x.SetPreferSyntheticValue(True) if self.TraceOn(): self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x") - self.assertTrue(id_x.GetNumChildren() == 7, "dictionary does not have 7 children") + self.assertTrue( + id_x.GetNumChildren() == 7, + "dictionary does not have 7 children") id_x.SetPreferSyntheticValue(False) - self.assertFalse(id_x.GetNumChildren() == 7, "dictionary still looks synthetic") + self.assertFalse( + id_x.GetNumChildren() == 7, + "dictionary still looks synthetic") id_x.SetPreferSyntheticValue(True) - self.assertTrue(id_x.GetSummary() == "7 key/value pairs", "dictionary does not get correct summary") + self.assertTrue( + id_x.GetSummary() == "7 key/value pairs", + "dictionary does not get correct summary") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py index 6568056f761..1cc2a0e431a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TypeSummaryListArgumentTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,9 +24,28 @@ class TypeSummaryListArgumentTestCase(TestBase): @no_debug_info_test def test_type_summary_list_with_arg(self): """Test that the 'type summary list' command handles command line arguments properly""" - self.expect('type summary list Foo', substrs=['Category: default', 'Category: system']) - self.expect('type summary list char', substrs=['char *', 'unsigned char']) - - self.expect('type summary list -w default', substrs=['system'], matching=False) - self.expect('type summary list -w system unsigned', substrs=['default', '0-9'], matching=False) - self.expect('type summary list -w system char', substrs=['unsigned char *'], matching=True) + self.expect( + 'type summary list Foo', + substrs=[ + 'Category: default', + 'Category: system']) + self.expect( + 'type summary list char', + substrs=[ + 'char *', + 'unsigned char']) + + self.expect( + 'type summary list -w default', + substrs=['system'], + matching=False) + self.expect( + 'type summary list -w system unsigned', + substrs=[ + 'default', + '0-9'], + matching=False) + self.expect( + 'type summary list -w system char', + substrs=['unsigned char *'], + matching=True) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py index 63a4a3a4ba8..2e66b800b15 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py @@ -5,13 +5,14 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TypeSummaryListScriptTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -31,14 +32,15 @@ class TypeSummaryListScriptTestCase(TestBase): """Test printing out Python summary formatters.""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -53,9 +55,11 @@ class TypeSummaryListScriptTestCase(TestBase): self.runCmd("command script import tslsformatters.py") - self.expect("frame variable myStruct", substrs=['A data formatter at work']) - - self.expect('type summary list', substrs=['Struct_SummaryFormatter']) - self.expect('type summary list Struct', substrs=['Struct_SummaryFormatter']) - + self.expect( + "frame variable myStruct", + substrs=['A data formatter at work']) + self.expect('type summary list', substrs=['Struct_SummaryFormatter']) + self.expect( + 'type summary list Struct', + substrs=['Struct_SummaryFormatter']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/tslsformatters.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/tslsformatters.py index d1ce8b7db17..03fe17bfe76 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/tslsformatters.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/tslsformatters.py @@ -1,10 +1,12 @@ import lldb + def Struct_SummaryFormatter(valobj, internal_dict): return 'A data formatter at work' category = lldb.debugger.CreateCategory("TSLSFormatters") category.SetEnabled(True) -summary = lldb.SBTypeSummary.CreateWithFunctionName("tslsformatters.Struct_SummaryFormatter", lldb.eTypeOptionCascade) +summary = lldb.SBTypeSummary.CreateWithFunctionName( + "tslsformatters.Struct_SummaryFormatter", lldb.eTypeOptionCascade) spec = lldb.SBTypeNameSpecifier("Struct", False) category.AddTypeSummary(spec, summary) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py index 41b8c3499cc..7e67f73b709 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py @@ -1,4 +1,7 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.expectedFailureAll(compiler="gcc")]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + compiler="gcc")]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py index dba2816d264..d970d11a2ba 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py @@ -5,12 +5,13 @@ Test that the user can input a format but it will not prevail over summary forma from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class UserFormatVSSummaryTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,16 +27,18 @@ class UserFormatVSSummaryTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) - self.expect("frame variable p1", substrs = ['(Pair) p1 = (x = 3, y = -3)']); + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = (x = 3, y = -3)']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -48,12 +51,24 @@ class UserFormatVSSummaryTestCase(TestBase): self.runCmd('type summary add Pair -s "x=${var.x%d},y=${var.y%u}"') - self.expect("frame variable p1", substrs = ['(Pair) p1 = x=3,y=4294967293']); - self.expect("frame variable -f x p1", substrs = ['(Pair) p1 = x=0x00000003,y=0xfffffffd'], matching=False); - self.expect("frame variable -f d p1", substrs = ['(Pair) p1 = x=3,y=-3'], matching=False); - self.expect("frame variable p1", substrs = ['(Pair) p1 = x=3,y=4294967293']); + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = x=3,y=4294967293']) + self.expect( + "frame variable -f x p1", + substrs=['(Pair) p1 = x=0x00000003,y=0xfffffffd'], + matching=False) + self.expect( + "frame variable -f d p1", + substrs=['(Pair) p1 = x=3,y=-3'], + matching=False) + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = x=3,y=4294967293']) self.runCmd('type summary add Pair -s "x=${var.x%x},y=${var.y%u}"') - self.expect("frame variable p1", substrs = ['(Pair) p1 = x=0x00000003,y=4294967293']); - self.expect("frame variable -f d p1", substrs = ['(Pair) p1 = x=3,y=-3'],matching=False); + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = x=0x00000003,y=4294967293']) + self.expect( + "frame variable -f d p1", + substrs=['(Pair) p1 = x=3,y=-3'], + matching=False) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py index 5899469651d..53073f6d910 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class VarInAggregateMisuseTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,14 +27,15 @@ class VarInAggregateMisuseTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -43,32 +45,36 @@ class VarInAggregateMisuseTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.runCmd("type summary add --summary-string \"SUMMARY SUCCESS ${var}\" Summarize") - + self.runCmd( + "type summary add --summary-string \"SUMMARY SUCCESS ${var}\" Summarize") + self.expect('frame variable mine_ptr', - substrs = ['SUMMARY SUCCESS summarize_ptr_t @ ']) + substrs=['SUMMARY SUCCESS summarize_ptr_t @ ']) self.expect('frame variable *mine_ptr', - substrs = ['SUMMARY SUCCESS summarize_t @']) + substrs=['SUMMARY SUCCESS summarize_t @']) - self.runCmd("type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") + self.runCmd( + "type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") self.expect('frame variable mine_ptr', - substrs = ['SUMMARY SUCCESS 10']) + substrs=['SUMMARY SUCCESS 10']) self.expect('frame variable *mine_ptr', - substrs = ['SUMMARY SUCCESS 10']) + substrs=['SUMMARY SUCCESS 10']) self.runCmd("type summary add --summary-string \"${var}\" Summarize") - self.runCmd("type summary add --summary-string \"${var}\" -e TwoSummarizes") - + self.runCmd( + "type summary add --summary-string \"${var}\" -e TwoSummarizes") + self.expect('frame variable', - substrs = ['(TwoSummarizes) twos = TwoSummarizes @ ', - 'first = summarize_t @ ', - 'second = summarize_t @ ']) - - self.runCmd("type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") + substrs=['(TwoSummarizes) twos = TwoSummarizes @ ', + 'first = summarize_t @ ', + 'second = summarize_t @ ']) + + self.runCmd( + "type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") self.expect('frame variable', - substrs = ['(TwoSummarizes) twos = TwoSummarizes @ ', - 'first = SUMMARY SUCCESS 1', - 'second = SUMMARY SUCCESS 3']) + substrs=['(TwoSummarizes) twos = TwoSummarizes @ ', + 'first = SUMMARY SUCCESS 1', + 'second = SUMMARY SUCCESS 3']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py index f3eced62589..cde0ef40962 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py @@ -5,14 +5,15 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import os.path import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PythonSynthDataFormatterTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,20 +24,21 @@ class PythonSynthDataFormatterTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', ' // Set breakpoint here.') - @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser def test_with_run_command(self): """Test using Python synthetic children provider.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -48,10 +50,11 @@ class PythonSynthDataFormatterTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - + self.runCmd("command script import helperfunc.py") - self.runCmd('type summary add -x "^something<.*>$" -s "T is a ${script.var:helperfunc.f}"') + self.runCmd( + 'type summary add -x "^something<.*>$" -s "T is a ${script.var:helperfunc.f}"') + + self.expect("frame variable x", substrs=['T is a non-pointer type']) - self.expect("frame variable x", substrs = ['T is a non-pointer type']); - - self.expect("frame variable y", substrs = ['T is a pointer type']); + self.expect("frame variable y", substrs=['T is a pointer type']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py index 01562c5baa8..75654e4b4ed 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py @@ -1,5 +1,6 @@ import lldb -def f(value,d): - return "pointer type" if value.GetType().GetTemplateArgumentType(0).IsPointerType() else "non-pointer type" +def f(value, d): + return "pointer type" if value.GetType().GetTemplateArgumentType( + 0).IsPointerType() else "non-pointer type" diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py index 365ddff3c7e..2d4cd5782fd 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py @@ -5,13 +5,14 @@ Check that vector types format properly from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class VectorTypesFormattingTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,20 +24,21 @@ class VectorTypesFormattingTestCase(TestBase): self.line = line_number('main.cpp', '// break here') # rdar://problem/14035604 - @skipIf(compiler='gcc') # gcc don't have ext_vector_type extension + @skipIf(compiler='gcc') # gcc don't have ext_vector_type extension def test_with_run_command(self): """Check that vector types format properly""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -46,29 +48,43 @@ class VectorTypesFormattingTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - pass # my code never fails - + pass # my code never fails + v = self.frame().FindVariable("v") v.SetPreferSyntheticValue(True) v.SetFormat(lldb.eFormatVectorOfFloat32) - - if self.TraceOn(): print(v) - - self.assertTrue(v.GetNumChildren() == 4, "v as float32[] has 4 children") - self.assertTrue(v.GetChildAtIndex(0).GetData().float[0] == 1.25, "child 0 == 1.25") - self.assertTrue(v.GetChildAtIndex(1).GetData().float[0] == 1.25, "child 1 == 1.25") - self.assertTrue(v.GetChildAtIndex(2).GetData().float[0] == 2.50, "child 2 == 2.50") - self.assertTrue(v.GetChildAtIndex(3).GetData().float[0] == 2.50, "child 3 == 2.50") - - self.expect("expr -f int16_t[] -- v", substrs=['(0, 16288, 0, 16288, 0, 16416, 0, 16416)']) - self.expect("expr -f uint128_t[] -- v", substrs=['(85236745249553456609335044694184296448)']) - self.expect("expr -f float32[] -- v", substrs=['(1.25, 1.25, 2.5, 2.5)']) - + + if self.TraceOn(): + print(v) + + self.assertTrue( + v.GetNumChildren() == 4, + "v as float32[] has 4 children") + self.assertTrue(v.GetChildAtIndex(0).GetData().float[ + 0] == 1.25, "child 0 == 1.25") + self.assertTrue(v.GetChildAtIndex(1).GetData().float[ + 0] == 1.25, "child 1 == 1.25") + self.assertTrue(v.GetChildAtIndex(2).GetData().float[ + 0] == 2.50, "child 2 == 2.50") + self.assertTrue(v.GetChildAtIndex(3).GetData().float[ + 0] == 2.50, "child 3 == 2.50") + + self.expect("expr -f int16_t[] -- v", + substrs=['(0, 16288, 0, 16288, 0, 16416, 0, 16416)']) + self.expect("expr -f uint128_t[] -- v", + substrs=['(85236745249553456609335044694184296448)']) + self.expect( + "expr -f float32[] -- v", + substrs=['(1.25, 1.25, 2.5, 2.5)']) + oldValue = v.GetChildAtIndex(0).GetValue() v.SetFormat(lldb.eFormatHex) newValue = v.GetChildAtIndex(0).GetValue() - self.assertFalse(oldValue == newValue, "values did not change along with format") - + self.assertFalse(oldValue == newValue, + "values did not change along with format") + v.SetFormat(lldb.eFormatVectorOfFloat32) oldValueAgain = v.GetChildAtIndex(0).GetValue() - self.assertTrue(oldValue == oldValueAgain, "same format but different values") + self.assertTrue( + oldValue == oldValueAgain, + "same format but different values") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py b/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py index efbaa69eef5..355d60ade90 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py @@ -5,21 +5,26 @@ Test that breakpoint works correctly in the presence of dead-code stripping. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DeadStripTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") @expectedFailureAll(debug_info="dwo", bugnumber="llvm.org/pr25087") - @expectedFailureAll(oslist=["linux"], debug_info="gmodules", bugnumber="llvm.org/pr27865") - @skipIfFreeBSD # The -dead_strip linker option isn't supported on FreeBSD versions of ld. + @expectedFailureAll( + oslist=["linux"], + debug_info="gmodules", + bugnumber="llvm.org/pr27865") + # The -dead_strip linker option isn't supported on FreeBSD versions of ld. + @skipIfFreeBSD def test(self): """Test breakpoint works correctly with dead-code stripping.""" self.build() @@ -27,34 +32,37 @@ class DeadStripTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break by function name f1 (live code). - lldbutil.run_break_set_by_symbol (self, "f1", num_expected_locations=1, module_name="a.out") + lldbutil.run_break_set_by_symbol( + self, "f1", num_expected_locations=1, module_name="a.out") # Break by function name f2 (dead code). - lldbutil.run_break_set_by_symbol (self, "f2", num_expected_locations=0, module_name="a.out") + lldbutil.run_break_set_by_symbol( + self, "f2", num_expected_locations=0, module_name="a.out") # Break by function name f3 (live code). - lldbutil.run_break_set_by_symbol (self, "f3", num_expected_locations=1, module_name="a.out") + lldbutil.run_break_set_by_symbol( + self, "f3", num_expected_locations=1, module_name="a.out") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint (breakpoint #1). self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'a.out`f1', - 'stop reason = breakpoint']) + substrs=['stopped', + 'a.out`f1', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f 1", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) self.runCmd("continue") # The stop reason of the thread should be breakpoint (breakpoint #3). self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'a.out`f3', - 'stop reason = breakpoint']) + substrs=['stopped', + 'a.out`f3', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f 3", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py index be0ea144133..e5d81d8cefc 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py @@ -5,29 +5,37 @@ Test some lldb command abbreviations. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DisassemblyTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows"], bugnumber="function names print fully demangled instead of name-only") + @expectedFailureAll( + oslist=["windows"], + bugnumber="function names print fully demangled instead of name-only") def test(self): self.build() - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") self.expect("file " + exe, - patterns = [ "Current executable set to .*a.out.*" ]) + patterns=["Current executable set to .*a.out.*"]) - match_object = lldbutil.run_break_set_command (self, "br s -n sum") - lldbutil.check_breakpoint_result (self, match_object, symbol_name='sum', symbol_match_exact=False, num_locations=1) + match_object = lldbutil.run_break_set_command(self, "br s -n sum") + lldbutil.check_breakpoint_result( + self, + match_object, + symbol_name='sum', + symbol_match_exact=False, + num_locations=1) self.expect("run", - patterns = [ "Process .* launched: "]) + patterns=["Process .* launched: "]) self.runCmd("dis -f") disassembly = self.res.GetOutput() @@ -40,7 +48,7 @@ class DisassemblyTestCase(TestBase): elif arch in ["arm", "aarch64"]: breakpoint_opcodes = ["brk", "udf"] instructions = [' add ', ' ldr ', ' str '] - elif re.match("mips" , arch): + elif re.match("mips", arch): breakpoint_opcodes = ["break"] instructions = ['lw', 'sw'] elif arch in ["s390x"]: @@ -48,11 +56,17 @@ class DisassemblyTestCase(TestBase): instructions = [' l ', ' a ', ' st '] else: # TODO please add your arch here - self.fail('unimplemented for arch = "{arch}"'.format(arch=self.getArchitecture())) + self.fail( + 'unimplemented for arch = "{arch}"'.format( + arch=self.getArchitecture())) # make sure that the software breakpoint has been removed for op in breakpoint_opcodes: self.assertFalse(op in disassembly) # make sure a few reasonable assembly instructions are here - self.expect(disassembly, exe=False, startstr = "a.out`sum", substrs = instructions) + self.expect( + disassembly, + exe=False, + startstr="a.out`sum", + substrs=instructions) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py b/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py index 37593768f4a..79e4e627592 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py @@ -5,32 +5,33 @@ Test that dynamic values update their child count correctly from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DynamicValueChildCountTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): - # Call super's setUp(). + # Call super's setUp(). TestBase.setUp(self) - # Find the line number to break for main.c. + # Find the line number to break for main.c. - self.main_third_call_line = line_number('pass-to-base.cpp', - '// Break here and check b has 0 children') - self.main_fourth_call_line = line_number('pass-to-base.cpp', - '// Break here and check b still has 0 children') - self.main_fifth_call_line = line_number('pass-to-base.cpp', - '// Break here and check b has one child now') - self.main_sixth_call_line = line_number('pass-to-base.cpp', - '// Break here and check b has 0 children again') + self.main_third_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b has 0 children') + self.main_fourth_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b still has 0 children') + self.main_fifth_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b has one child now') + self.main_sixth_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b has 0 children again') @add_test_categories(['pyapi']) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663") @@ -42,26 +43,31 @@ class DynamicValueChildCountTestCase(TestBase): # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoints: - third_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_third_call_line) + third_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_third_call_line) self.assertTrue(third_call_bpt, VALID_BREAKPOINT) - fourth_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_fourth_call_line) + fourth_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_fourth_call_line) self.assertTrue(fourth_call_bpt, VALID_BREAKPOINT) - fifth_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_fifth_call_line) + fifth_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_fifth_call_line) self.assertTrue(fifth_call_bpt, VALID_BREAKPOINT) - sixth_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_sixth_call_line) + sixth_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_sixth_call_line) self.assertTrue(sixth_call_bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) @@ -73,4 +79,6 @@ class DynamicValueChildCountTestCase(TestBase): self.runCmd("continue") self.assertTrue(b.GetNumChildren() != 0, "b now has 1 child") self.runCmd("continue") - self.assertTrue(b.GetNumChildren() == 0, "b didn't go back to 0 children") + self.assertTrue( + b.GetNumChildren() == 0, + "b didn't go back to 0 children") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py b/lldb/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py index 4b1880dee96..604249e14cf 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py @@ -3,13 +3,13 @@ from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ConvenienceVariablesCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,9 +20,11 @@ class ConvenienceVariablesCase(TestBase): # Find the line number to break on inside main.cpp. self.line = line_number('main.c', 'Hello world.') - @skipIfFreeBSD # llvm.org/pr17228 + @skipIfFreeBSD # llvm.org/pr17228 @skipIfRemote - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_with_run_commands(self): """Test convenience variables lldb.debugger, lldb.target, lldb.process, lldb.thread, and lldb.frame.""" self.build() @@ -32,7 +34,9 @@ class ConvenienceVariablesCase(TestBase): python_prompt = ">>> " # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe)) + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) child = self.child # Turn on logging for what the child sends back. if self.TraceOn(): @@ -56,25 +60,33 @@ class ConvenienceVariablesCase(TestBase): child.sendline('print(lldb.debugger)') child.expect_exact(python_prompt) self.expect(child.before, exe=False, - patterns = ['Debugger \(instance: .*, id: \d\)']) + patterns=['Debugger \(instance: .*, id: \d\)']) child.sendline('print(lldb.target)') child.expect_exact(python_prompt) self.expect(child.before, exe=False, - substrs = ['a.out']) + substrs=['a.out']) child.sendline('print(lldb.process)') child.expect_exact(python_prompt) - self.expect(child.before, exe=False, - patterns = ['SBProcess: pid = \d+, state = stopped, threads = \d, executable = a.out']) + self.expect(child.before, exe=False, patterns=[ + 'SBProcess: pid = \d+, state = stopped, threads = \d, executable = a.out']) child.sendline('print(lldb.thread)') child.expect_exact(python_prompt) # Linux outputs decimal tid and 'name' instead of 'queue' - self.expect(child.before, exe=False, - patterns = ['thread #1: tid = (0x[0-9a-f]+|[0-9]+), 0x[0-9a-f]+ a\.out`main\(argc=1, argv=0x[0-9a-f]+\) \+ \d+ at main\.c:%d, (name|queue) = \'.+\', stop reason = breakpoint 1\.1' % self.line]) + self.expect( + child.before, + exe=False, + patterns=[ + 'thread #1: tid = (0x[0-9a-f]+|[0-9]+), 0x[0-9a-f]+ a\.out`main\(argc=1, argv=0x[0-9a-f]+\) \+ \d+ at main\.c:%d, (name|queue) = \'.+\', stop reason = breakpoint 1\.1' % + self.line]) child.sendline('print(lldb.frame)') child.expect_exact(python_prompt) - self.expect(child.before, exe=False, - patterns = ['frame #0: 0x[0-9a-f]+ a\.out`main\(argc=1, argv=0x[0-9a-f]+\) \+ \d+ at main\.c:%d' % self.line]) + self.expect( + child.before, + exe=False, + patterns=[ + 'frame #0: 0x[0-9a-f]+ a\.out`main\(argc=1, argv=0x[0-9a-f]+\) \+ \d+ at main\.c:%d' % + self.line]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py b/lldb/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py index 912d51fb6b0..98b002eb288 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py @@ -4,7 +4,6 @@ Test some lldb command abbreviations. from __future__ import print_function - import lldb import os import time @@ -13,14 +12,16 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -def execute_command (command): + +def execute_command(command): #print('%% %s' % (command)) (exit_status, output) = seven.get_command_status_output(command) - #if output: + # if output: # print(output) #print('status = %u' % (exit_status)) return exit_status + class ExecTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -28,35 +29,42 @@ class ExecTestCase(TestBase): @skipUnlessDarwin def test(self): if self.getArchitecture() == 'x86_64': - source = os.path.join (os.getcwd(), "main.cpp") - o_file = os.path.join (os.getcwd(), "main.o") - execute_command ("'%s' -g -O0 -arch i386 -arch x86_64 '%s' -c -o '%s'" % (os.environ["CC"], source, o_file)) - execute_command ("'%s' -g -O0 -arch i386 -arch x86_64 '%s'" % (os.environ["CC"], o_file)) + source = os.path.join(os.getcwd(), "main.cpp") + o_file = os.path.join(os.getcwd(), "main.o") + execute_command( + "'%s' -g -O0 -arch i386 -arch x86_64 '%s' -c -o '%s'" % + (os.environ["CC"], source, o_file)) + execute_command( + "'%s' -g -O0 -arch i386 -arch x86_64 '%s'" % + (os.environ["CC"], o_file)) if self.debug_info != "dsym": - dsym_path = os.path.join (os.getcwd(), "a.out.dSYM") - execute_command ("rm -rf '%s'" % (dsym_path)) + dsym_path = os.path.join(os.getcwd(), "a.out.dSYM") + execute_command("rm -rf '%s'" % (dsym_path)) else: self.build() - exe = os.path.join (os.getcwd(), "a.out") - + exe = os.path.join(os.getcwd(), "a.out") + # Create the target target = self.dbg.CreateTarget(exe) - + # Create any breakpoints we need - breakpoint = target.BreakpointCreateBySourceRegex ('Set breakpoint 1 here', lldb.SBFileSpec ("main.cpp", False)) + breakpoint = target.BreakpointCreateBySourceRegex( + 'Set breakpoint 1 here', lldb.SBFileSpec("main.cpp", False)) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - + for i in range(6): # The stop reason of the thread should be breakpoint. self.assertTrue(process.GetState() == lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT) - threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) self.assertTrue(len(threads) == 1) # We had a deadlock tearing down the TypeSystemMap on exec, but only if some @@ -65,21 +73,28 @@ class ExecTestCase(TestBase): thread = threads[0] value = thread.frames[0].EvaluateExpression("1 + 2") - self.assertTrue(value.IsValid(), "Expression evaluated successfully") + self.assertTrue( + value.IsValid(), + "Expression evaluated successfully") int_value = value.GetValueAsSigned() self.assertTrue(int_value == 3, "Expression got the right result.") # Run and we should stop due to exec process.Continue() - + self.assertTrue(process.GetState() == lldb.eStateStopped, "Process should be stopped at __dyld_start") - - threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonExec) - self.assertTrue(len(threads) == 1, "We got a thread stopped for exec.") - # Run and we should stop at breakpoint in main after exec - process.Continue() + threads = lldbutil.get_stopped_threads( + process, lldb.eStopReasonExec) + self.assertTrue( + len(threads) == 1, + "We got a thread stopped for exec.") + + # Run and we should stop at breakpoint in main after exec + process.Continue() - threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint) - self.assertTrue(len(threads) == 1, "Stopped at breakpoint in exec'ed process.") + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1, + "Stopped at breakpoint in exec'ed process.") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py b/lldb/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py index 1492fe06922..21d4357a6ff 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py @@ -5,14 +5,15 @@ Test that expr will time out and allow other threads to run if it blocks. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExprDoesntDeadlockTestCase(TestBase): def getCategories(self): @@ -21,7 +22,9 @@ class ExprDoesntDeadlockTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr17946') - @expectedFailureAll(oslist=["windows"], bugnumber="Windows doesn't have pthreads, test needs to be ported") + @expectedFailureAll( + oslist=["windows"], + bugnumber="Windows doesn't have pthreads, test needs to be ported") def test_with_run_command(self): """Test that expr will time out and allow other threads to run if it blocks.""" self.build() @@ -31,10 +34,12 @@ class ExprDoesntDeadlockTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - # Now create a breakpoint at source line before call_me_to_get_lock gets called. + # Now create a breakpoint at source line before call_me_to_get_lock + # gets called. - main_file_spec = lldb.SBFileSpec ("locking.c") - breakpoint = target.BreakpointCreateBySourceRegex('Break here', main_file_spec) + main_file_spec = lldb.SBFileSpec("locking.c") + breakpoint = target.BreakpointCreateBySourceRegex( + 'Break here', main_file_spec) if self.TraceOn(): print("breakpoint:", breakpoint) self.assertTrue(breakpoint and @@ -42,16 +47,19 @@ class ExprDoesntDeadlockTestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1 and the break condition should hold. from lldbsuite.test.lldbutil import get_stopped_thread thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) - var = frame0.EvaluateExpression ("call_me_to_get_lock()") - self.assertTrue (var.IsValid()) - self.assertTrue (var.GetValueAsSigned (0) == 567) + var = frame0.EvaluateExpression("call_me_to_get_lock()") + self.assertTrue(var.IsValid()) + self.assertTrue(var.GetValueAsSigned(0) == 567) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py b/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py index 6d2763c1ead..1feab9d1c4b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py @@ -4,7 +4,6 @@ Test some lldb command abbreviations. from __future__ import print_function - import lldb import os import time @@ -13,7 +12,8 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -def execute_command (command): + +def execute_command(command): # print('%% %s' % (command)) (exit_status, output) = seven.get_command_status_output(command) # if output: @@ -21,39 +21,48 @@ def execute_command (command): # print('status = %u' % (exit_status)) return exit_status + class FatArchiveTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipUnlessDarwin - def test (self): + def test(self): if self.getArchitecture() == 'x86_64': - execute_command ("make CC='%s'" % (os.environ["CC"])) - self.main () + execute_command("make CC='%s'" % (os.environ["CC"])) + self.main() else: - self.skipTest("This test requires x86_64 as the architecture for the inferior") + self.skipTest( + "This test requires x86_64 as the architecture for the inferior") - def main (self): + def main(self): '''This test compiles a quick example by making a fat file (universal) full of skinny .o files and makes sure we can use them to resolve breakpoints when doing DWARF in .o file debugging. The only thing this test needs to do is to compile and set a breakpoint in the target and verify any breakpoint locations have valid debug info for the function, and source file and line.''' - exe = os.path.join (os.getcwd(), "a.out") - + exe = os.path.join(os.getcwd(), "a.out") + # Create the target target = self.dbg.CreateTarget(exe) - + # Create a breakpoint by name - breakpoint = target.BreakpointCreateByName ('foo', exe) + breakpoint = target.BreakpointCreateByName('foo', exe) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Make sure the breakpoint resolves to a function, file and line for bp_loc in breakpoint: - # Get a section offset address (lldb.SBAddress) from the breakpoint location + # Get a section offset address (lldb.SBAddress) from the breakpoint + # location bp_loc_addr = bp_loc.GetAddress() line_entry = bp_loc_addr.GetLineEntry() function = bp_loc_addr.GetFunction() - self.assertTrue(function.IsValid(), "Verify breakpoint in fat BSD archive has valid function debug info") - self.assertTrue(line_entry.GetFileSpec(), "Verify breakpoint in fat BSD archive has source file information") - self.assertTrue(line_entry.GetLine() != 0, "Verify breakpoint in fat BSD archive has source line information") + self.assertTrue( + function.IsValid(), + "Verify breakpoint in fat BSD archive has valid function debug info") + self.assertTrue( + line_entry.GetFileSpec(), + "Verify breakpoint in fat BSD archive has source file information") + self.assertTrue( + line_entry.GetLine() != 0, + "Verify breakpoint in fat BSD archive has source line information") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/format/TestFormats.py b/lldb/packages/Python/lldbsuite/test/functionalities/format/TestFormats.py index 0ba036124b0..b7592c93704 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/format/TestFormats.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/format/TestFormats.py @@ -5,24 +5,28 @@ Test the command history mechanism from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestFormats(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_formats(self): """Test format string functionality.""" self.build() import pexpect prompt = "(lldb) " - child = pexpect.spawn('%s %s -x -o "b main" -o r a.out' % (lldbtest_config.lldbExec, self.lldbOption)) + child = pexpect.spawn( + '%s %s -x -o "b main" -o r a.out' % + (lldbtest_config.lldbExec, self.lldbOption)) # Turn on logging for what the child sends back. if self.TraceOn(): child.logfile_read = sys.stdout @@ -30,13 +34,13 @@ class TestFormats(TestBase): self.child = child # Substitute 'Help!' for 'help' using the 'commands regex' mechanism. - child.expect_exact(prompt + 'target create "a.out"') - child.expect_exact(prompt + 'b main') - child.expect_exact(prompt + 'r') + child.expect_exact(prompt + 'target create "a.out"') + child.expect_exact(prompt + 'b main') + child.expect_exact(prompt + 'r') child.expect_exact(prompt) child.sendline() - # child.expect_exact(prompt + "target create") - # + # child.expect_exact(prompt + "target create") + # # child.sendline("command regex 'Help__'") # child.expect_exact(regex_prompt) # child.sendline('s/^$/help/') @@ -51,7 +55,7 @@ class TestFormats(TestBase): # child.sendline('command unalias Help__') # child.expect_exact("error: 'Help__' is not an alias, it is a debugger command which can be removed using the 'command delete' command") # child.expect_exact(prompt) - # + # # # Delete the regex command using "command delete" # child.sendline('command delete Help__') # child.expect_exact(prompt) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/array/TestArray.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/array/TestArray.py index 0f1c109676c..46264f3dfe8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/array/TestArray.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/array/TestArray.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestArray(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,8 @@ class TestArray(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", substrs=["a[10]"]) + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + substrs=["a[10]"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/bad-reference/TestBadReference.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/bad-reference/TestBadReference.py index e90e8668f7f..dd8ff949fa9 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/bad-reference/TestBadReference.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/bad-reference/TestBadReference.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestBadReference(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,5 @@ class TestBadReference(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", "f->b") + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "f->b") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/complicated-expression/TestComplicatedExpression.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/complicated-expression/TestComplicatedExpression.py index bd25a29fab0..a8708169bb3 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/complicated-expression/TestComplicatedExpression.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/complicated-expression/TestComplicatedExpression.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestDiagnoseDereferenceArgument(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,8 @@ class TestDiagnoseDereferenceArgument(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", "f->b->d") + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + "f->b->d") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py index 28872929b91..80128eec1f7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestDiagnoseDereferenceArgument(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,8 @@ class TestDiagnoseDereferenceArgument(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", "f->b->d") + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + "f->b->d") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py index 597ced3c0d9..672b1e9814b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestDiagnoseDereferenceFunctionReturn(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,6 +22,10 @@ class TestDiagnoseDereferenceFunctionReturn(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", substrs = ["GetAFoo", "->b"]) - + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + substrs=[ + "GetAFoo", + "->b"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-this/TestDiagnoseDereferenceThis.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-this/TestDiagnoseDereferenceThis.py index fe71e528d8f..233c9e403bd 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-this/TestDiagnoseDereferenceThis.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/dereference-this/TestDiagnoseDereferenceThis.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestDiagnoseDereferenceThis(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,8 @@ class TestDiagnoseDereferenceThis(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", "this->a") + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + "this->a") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/inheritance/TestDiagnoseInheritance.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/inheritance/TestDiagnoseInheritance.py index 1438747c1a1..267223ad085 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/inheritance/TestDiagnoseInheritance.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/inheritance/TestDiagnoseInheritance.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestDiagnoseInheritance(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,5 @@ class TestDiagnoseInheritance(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", "d") + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "d") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/local-variable/TestLocalVariable.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/local-variable/TestLocalVariable.py index cdddd8483a6..a1a17c94176 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/local-variable/TestLocalVariable.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/local-variable/TestLocalVariable.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestLocalVariable(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,5 @@ class TestLocalVariable(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", "myInt") + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "myInt") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py index 6f7e55b4629..adf092d8615 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/frame-diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestDiagnoseVirtualMethodCall(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,5 +22,5 @@ class TestDiagnoseVirtualMethodCall(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", "Thread should be stopped", - substrs = ['stopped']) - self.expect("frame diagnose", "Crash diagnosis was accurate", "foo") + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "foo") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py index ceeb2eadaf4..7b048fedebb 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py @@ -3,79 +3,117 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test import lldbutil from lldbsuite.test import lldbplatformutil from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * + class AssertingInferiorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") - @expectedFailureAll(oslist=["linux"], archs=["arm"], bugnumber="llvm.org/pr25338") - @expectedFailureAll(bugnumber="llvm.org/pr26592", triple = '^mips') + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') def test_inferior_asserting(self): """Test that lldb reliably catches the inferior asserting (command).""" self.build() self.inferior_asserting() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") - @expectedFailureAndroid(api_levels=list(range(16 + 1))) # b.android.com/179836 + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAndroid( + api_levels=list( + range( + 16 + + 1))) # b.android.com/179836 def test_inferior_asserting_register(self): """Test that lldb reliably reads registers from the inferior after asserting (command).""" self.build() self.inferior_asserting_registers() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") - @expectedFailureAll(oslist=["linux"], archs=["aarch64", "arm"], bugnumber="llvm.org/pr25338") - @expectedFailureAll(bugnumber="llvm.org/pr26592", triple = '^mips') + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=[ + "aarch64", + "arm"], + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') def test_inferior_asserting_disassemble(self): """Test that lldb reliably disassembles frames after asserting (command).""" self.build() self.inferior_asserting_disassemble() @add_test_categories(['pyapi']) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") def test_inferior_asserting_python(self): """Test that lldb reliably catches the inferior asserting (Python API).""" self.build() self.inferior_asserting_python() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") - @expectedFailureAll(oslist=["linux"], archs=["aarch64", "arm"], bugnumber="llvm.org/pr25338") - @expectedFailureAll(bugnumber="llvm.org/pr26592", triple = '^mips') + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=[ + "aarch64", + "arm"], + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') def test_inferior_asserting_expr(self): """Test that the lldb expression interpreter can read from the inferior after asserting (command).""" self.build() self.inferior_asserting_expr() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") - @expectedFailureAll(oslist=["linux"], archs=["aarch64", "arm"], bugnumber="llvm.org/pr25338") - @expectedFailureAll(bugnumber="llvm.org/pr26592", triple = '^mips') + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=[ + "aarch64", + "arm"], + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') def test_inferior_asserting_step(self): """Test that lldb functions correctly after stepping through a call to assert().""" self.build() self.inferior_asserting_step() def set_breakpoint(self, line): - lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) def check_stop_reason(self): - matched = lldbplatformutil.match_android_device(self.getArchitecture(), valid_api_levels=list(range(1, 16+1))) + matched = lldbplatformutil.match_android_device( + self.getArchitecture(), valid_api_levels=list(range(1, 16 + 1))) if matched: - # On android until API-16 the abort() call ended in a sigsegv instead of in a sigabrt + # On android until API-16 the abort() call ended in a sigsegv + # instead of in a sigabrt stop_reason = 'stop reason = signal SIGSEGV' else: stop_reason = 'stop reason = signal SIGABRT' # The stop reason of the thread should be an abort signal or exception. self.expect("thread list", STOPPED_DUE_TO_ASSERT, - substrs = ['stopped', - stop_reason]) + substrs=['stopped', + stop_reason]) return stop_reason @@ -95,12 +133,12 @@ class AssertingInferiorTestCase(TestBase): # And it should report a backtrace that includes the assert site. self.expect("thread backtrace all", - substrs = [stop_reason, 'main', 'argc', 'argv']) + substrs=[stop_reason, 'main', 'argc', 'argv']) # And it should report the correct line number. self.expect("thread backtrace all", - substrs = [stop_reason, - 'main.c:%d' % self.line]) + substrs=[stop_reason, + 'main.c:%d' % self.line]) def inferior_asserting_python(self): """Inferior asserts upon launching; lldb should catch the event and stop.""" @@ -111,7 +149,8 @@ class AssertingInferiorTestCase(TestBase): # Now launch the process, and do not stop at entry point. # Both argv and envp are null. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if process.GetState() != lldb.eStateStopped: self.fail("Process should be in the 'stopped' state, " @@ -133,7 +172,8 @@ class AssertingInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - # lldb should be able to read from registers from the inferior after asserting. + # lldb should be able to read from registers from the inferior after + # asserting. lldbplatformutil.check_first_register_readable(self) def inferior_asserting_disassemble(self): @@ -145,7 +185,7 @@ class AssertingInferiorTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Launch the process, and do not stop at the entry point. - target.LaunchSimple (None, None, self.get_process_working_directory()) + target.LaunchSimple(None, None, self.get_process_working_directory()) self.check_stop_reason() process = target.GetProcess() @@ -154,17 +194,20 @@ class AssertingInferiorTestCase(TestBase): thread = process.GetThreadAtIndex(0) self.assertTrue(thread.IsValid(), "current thread is valid") - lastframeID = thread.GetFrameAtIndex(thread.GetNumFrames() - 1).GetFrameID() + lastframeID = thread.GetFrameAtIndex( + thread.GetNumFrames() - 1).GetFrameID() isi386Arch = False if "i386" in self.getArchitecture(): isi386Arch = True - # lldb should be able to disassemble frames from the inferior after asserting. + # lldb should be able to disassemble frames from the inferior after + # asserting. for frame in thread: self.assertTrue(frame.IsValid(), "current frame is valid") - self.runCmd("frame select " + str(frame.GetFrameID()), RUN_SUCCEEDED) + self.runCmd("frame select " + + str(frame.GetFrameID()), RUN_SUCCEEDED) # Don't expect the function name to be in the disassembly as the assert # function might be a no-return function where the PC is past the end @@ -174,11 +217,14 @@ class AssertingInferiorTestCase(TestBase): pc_backup_offset = 1 if frame.GetFrameID() == 0: pc_backup_offset = 0 - if isi386Arch == True: + if isi386Arch: if lastframeID == frame.GetFrameID(): pc_backup_offset = 0 - self.expect("disassemble -a %s" % (frame.GetPC() - pc_backup_offset), - substrs = ['<+0>: ']) + self.expect( + "disassemble -a %s" % + (frame.GetPC() - + pc_backup_offset), + substrs=['<+0>: ']) def check_expr_in_main(self, thread): depth = thread.GetNumFrames() @@ -186,17 +232,19 @@ class AssertingInferiorTestCase(TestBase): frame = thread.GetFrameAtIndex(i) self.assertTrue(frame.IsValid(), "current frame is valid") if self.TraceOn(): - print("Checking if function %s is main" % frame.GetFunctionName()) + print( + "Checking if function %s is main" % + frame.GetFunctionName()) if 'main' == frame.GetFunctionName(): frame_id = frame.GetFrameID() self.runCmd("frame select " + str(frame_id), RUN_SUCCEEDED) - self.expect("p argc", substrs = ['(int)', ' = 1']) - self.expect("p hello_world", substrs = ['Hello']) - self.expect("p argv[0]", substrs = ['a.out']) - self.expect("p null_ptr", substrs = ['= 0x0']) - return True - return False + self.expect("p argc", substrs=['(int)', ' = 1']) + self.expect("p hello_world", substrs=['Hello']) + self.expect("p argv[0]", substrs=['a.out']) + self.expect("p null_ptr", substrs=['= 0x0']) + return True + return False def inferior_asserting_expr(self): """Test that the lldb expression interpreter can read symbols after asserting.""" @@ -207,7 +255,7 @@ class AssertingInferiorTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Launch the process, and do not stop at the entry point. - target.LaunchSimple (None, None, self.get_process_working_directory()) + target.LaunchSimple(None, None, self.get_process_working_directory()) self.check_stop_reason() process = target.GetProcess() @@ -216,8 +264,11 @@ class AssertingInferiorTestCase(TestBase): thread = process.GetThreadAtIndex(0) self.assertTrue(thread.IsValid(), "current thread is valid") - # The lldb expression interpreter should be able to read from addresses of the inferior after a call to assert(). - self.assertTrue(self.check_expr_in_main(thread), "cannot find 'main' in the backtrace") + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a call to assert(). + self.assertTrue( + self.check_expr_in_main(thread), + "cannot find 'main' in the backtrace") def inferior_asserting_step(self): """Test that lldb functions correctly after stepping through a call to assert().""" @@ -229,20 +280,21 @@ class AssertingInferiorTestCase(TestBase): # Launch the process, and do not stop at the entry point. self.set_breakpoint(self.line) - target.LaunchSimple (None, None, self.get_process_working_directory()) + target.LaunchSimple(None, None, self.get_process_working_directory()) self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['main.c:%d' % self.line, - 'stop reason = breakpoint']) + substrs=['main.c:%d' % self.line, + 'stop reason = breakpoint']) self.runCmd("next") stop_reason = self.check_stop_reason() - # lldb should be able to read from registers from the inferior after asserting. + # lldb should be able to read from registers from the inferior after + # asserting. if "x86_64" in self.getArchitecture(): - self.expect("register read rbp", substrs = ['rbp = 0x']) + self.expect("register read rbp", substrs=['rbp = 0x']) if "i386" in self.getArchitecture(): - self.expect("register read ebp", substrs = ['ebp = 0x']) + self.expect("register read ebp", substrs=['ebp = 0x']) process = target.GetProcess() self.assertTrue(process.IsValid(), "current process is valid") @@ -250,10 +302,13 @@ class AssertingInferiorTestCase(TestBase): thread = process.GetThreadAtIndex(0) self.assertTrue(thread.IsValid(), "current thread is valid") - # The lldb expression interpreter should be able to read from addresses of the inferior after a call to assert(). - self.assertTrue(self.check_expr_in_main(thread), "cannot find 'main' in the backtrace") + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a call to assert(). + self.assertTrue( + self.check_expr_in_main(thread), + "cannot find 'main' in the backtrace") # And it should report the correct line number. self.expect("thread backtrace all", - substrs = [stop_reason, - 'main.c:%d' % self.line]) + substrs=[stop_reason, + 'main.c:%d' % self.line]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py index 359846c314f..3620de61a2e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py @@ -3,14 +3,15 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import configuration from lldbsuite.test import lldbutil + class ChangedInferiorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -47,12 +48,12 @@ class ChangedInferiorTestCase(TestBase): # We should have one crashing thread self.assertEqual( - len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), - 1, - STOPPED_DUE_TO_EXC_BAD_ACCESS) + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) # And it should report the correct line number. - self.expect("thread backtrace all", substrs = ['main.c:%d' % self.line1]) + self.expect("thread backtrace all", substrs=['main.c:%d' % self.line1]) def inferior_not_crashing(self): """Test lldb reloads the inferior after it was changed during the session.""" @@ -61,22 +62,23 @@ class ChangedInferiorTestCase(TestBase): self.runCmd("process status") self.assertNotEqual( - len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), - 1, - "Inferior changed, but lldb did not perform a reload") + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + "Inferior changed, but lldb did not perform a reload") # Break inside the main. - lldbutil.run_break_set_by_file_and_line (self, "main2.c", self.line2, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main2.c", self.line2, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) self.runCmd("frame variable int_ptr") self.expect("frame variable *int_ptr", - substrs = ['= 7']) + substrs=['= 7']) self.expect("expression *int_ptr", - substrs = ['= 7']) + substrs=['= 7']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py index f6d79ca06e7..d058b1cac56 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py @@ -3,74 +3,94 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test import lldbutil from lldbsuite.test import lldbplatformutil from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * + class CrashingInferiorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr23699 SIGSEGV is reported as exception, not signal") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr23699 SIGSEGV is reported as exception, not signal") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") def test_inferior_crashing(self): """Test that lldb reliably catches the inferior crashing (command).""" self.build() self.inferior_crashing() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") def test_inferior_crashing_register(self): """Test that lldb reliably reads registers from the inferior after crashing (command).""" self.build() self.inferior_crashing_registers() @add_test_categories(['pyapi']) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") def test_inferior_crashing_python(self): """Test that lldb reliably catches the inferior crashing (Python API).""" self.build() self.inferior_crashing_python() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") def test_inferior_crashing_expr(self): """Test that the lldb expression interpreter can read from the inferior after crashing (command).""" self.build() self.inferior_crashing_expr() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") def test_inferior_crashing_step(self): """Test that stepping after a crash behaves correctly.""" self.build() self.inferior_crashing_step() @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr24939') - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") - @skipIfTargetAndroid() # debuggerd interferes with this test on Android + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") + @skipIfTargetAndroid() # debuggerd interferes with this test on Android def test_inferior_crashing_step_after_break(self): """Test that lldb functions correctly after stepping through a crash.""" self.build() self.inferior_crashing_step_after_break() - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") - @skipIfLinux # Inferior exits after stepping after a segfault. This is working as intended IMHO. + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24778, This actually works, but the test relies on the output format instead of the API") + # Inferior exits after stepping after a segfault. This is working as + # intended IMHO. + @skipIfLinux def test_inferior_crashing_expr_step_and_expr(self): """Test that lldb expressions work before and after stepping after a crash.""" self.build() self.inferior_crashing_expr_step_expr() def set_breakpoint(self, line): - lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) def check_stop_reason(self): # We should have one crashing thread self.assertEqual( - len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), - 1, - STOPPED_DUE_TO_EXC_BAD_ACCESS) + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) def get_api_stop_reason(self): return lldb.eStopReasonException @@ -95,13 +115,13 @@ class CrashingInferiorTestCase(TestBase): else: stop_reason = 'stop reason = invalid address' self.expect("thread list", STOPPED_DUE_TO_EXC_BAD_ACCESS, - substrs = ['stopped', - stop_reason]) + substrs=['stopped', + stop_reason]) # And it should report the correct line number. self.expect("thread backtrace all", - substrs = [stop_reason, - 'main.c:%d' % self.line]) + substrs=[stop_reason, + 'main.c:%d' % self.line]) def inferior_crashing_python(self): """Inferior crashes upon launching; lldb should catch the event and stop.""" @@ -112,7 +132,8 @@ class CrashingInferiorTestCase(TestBase): # Now launch the process, and do not stop at entry point. # Both argv and envp are null. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if process.GetState() != lldb.eStateStopped: self.fail("Process should be in the 'stopped' state, " @@ -120,7 +141,10 @@ class CrashingInferiorTestCase(TestBase): lldbutil.state_type_to_str(process.GetState())) threads = lldbutil.get_crashed_threads(self, process) - self.assertEqual(len(threads), 1, "Failed to stop the thread upon bad access exception") + self.assertEqual( + len(threads), + 1, + "Failed to stop the thread upon bad access exception") if self.TraceOn(): lldbutil.print_stacktrace(threads[0]) @@ -133,7 +157,8 @@ class CrashingInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - # lldb should be able to read from registers from the inferior after crashing. + # lldb should be able to read from registers from the inferior after + # crashing. lldbplatformutil.check_first_register_readable(self) def inferior_crashing_expr(self): @@ -144,12 +169,13 @@ class CrashingInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - # The lldb expression interpreter should be able to read from addresses of the inferior after a crash. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. self.expect("p argc", - startstr = '(int) $0 = 1') + startstr='(int) $0 = 1') self.expect("p hello_world", - substrs = ['Hello']) + substrs=['Hello']) def inferior_crashing_step(self): """Test that lldb functions correctly after stepping through a crash.""" @@ -160,24 +186,26 @@ class CrashingInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['main.c:%d' % self.line, - 'stop reason = breakpoint']) + substrs=['main.c:%d' % self.line, + 'stop reason = breakpoint']) self.runCmd("next") self.check_stop_reason() - # The lldb expression interpreter should be able to read from addresses of the inferior after a crash. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. self.expect("p argv[0]", - substrs = ['a.out']) + substrs=['a.out']) self.expect("p null_ptr", - substrs = ['= 0x0']) + substrs=['= 0x0']) - # lldb should be able to read from registers from the inferior after crashing. + # lldb should be able to read from registers from the inferior after + # crashing. lldbplatformutil.check_first_register_readable(self) # And it should report the correct line number. self.expect("thread backtrace all", - substrs = ['main.c:%d' % self.line]) + substrs=['main.c:%d' % self.line]) def inferior_crashing_step_after_break(self): """Test that lldb behaves correctly when stepping after a crash.""" @@ -187,15 +215,20 @@ class CrashingInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - expected_state = 'exited' # Provide the exit code. + expected_state = 'exited' # Provide the exit code. if self.platformIsDarwin(): - expected_state = 'stopped' # TODO: Determine why 'next' and 'continue' have no effect after a crash. + # TODO: Determine why 'next' and 'continue' have no effect after a + # crash. + expected_state = 'stopped' self.expect("next", - substrs = ['Process', expected_state]) + substrs=['Process', expected_state]) if expected_state == 'exited': - self.expect("thread list", error=True,substrs = ['Process must be launched']) + self.expect( + "thread list", + error=True, + substrs=['Process must be launched']) else: self.check_stop_reason() @@ -207,13 +240,15 @@ class CrashingInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - # The lldb expression interpreter should be able to read from addresses of the inferior after a crash. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. self.expect("p argv[0]", - substrs = ['a.out']) + substrs=['a.out']) self.runCmd("next") self.check_stop_reason() - # The lldb expression interpreter should be able to read from addresses of the inferior after a crash. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. self.expect("p argv[0]", - substrs = ['a.out']) + substrs=['a.out']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py index 82e55a575f1..f04173a3e8d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py @@ -3,19 +3,22 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbplatformutil from lldbsuite.test import lldbutil + class CrashingRecursiveInferiorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr23699 SIGSEGV is reported as exception, not signal") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr23699 SIGSEGV is reported as exception, not signal") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") def test_recursive_inferior_crashing(self): """Test that lldb reliably catches the inferior crashing (command).""" @@ -49,13 +52,15 @@ class CrashingRecursiveInferiorTestCase(TestBase): @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr24939') @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") - @skipIfTargetAndroid() # debuggerd interferes with this test on Android + @skipIfTargetAndroid() # debuggerd interferes with this test on Android def test_recursive_inferior_crashing_step_after_break(self): """Test that lldb functions correctly after stepping through a crash.""" self.build() self.recursive_inferior_crashing_step_after_break() - @skipIfLinux # Inferior exits after stepping after a segfault. This is working as intended IMHO. + # Inferior exits after stepping after a segfault. This is working as + # intended IMHO. + @skipIfLinux @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") def test_recursive_inferior_crashing_expr_step_and_expr(self): """Test that lldb expressions work before and after stepping after a crash.""" @@ -63,14 +68,15 @@ class CrashingRecursiveInferiorTestCase(TestBase): self.recursive_inferior_crashing_expr_step_expr() def set_breakpoint(self, line): - lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) def check_stop_reason(self): # We should have one crashing thread self.assertEqual( - len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), - 1, - STOPPED_DUE_TO_EXC_BAD_ACCESS) + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) def setUp(self): # Call super's setUp(). @@ -93,17 +99,24 @@ class CrashingRecursiveInferiorTestCase(TestBase): else: stop_reason = 'stop reason = invalid address' self.expect("thread list", STOPPED_DUE_TO_EXC_BAD_ACCESS, - substrs = ['stopped', - stop_reason]) - - # And it should report a backtrace that includes main and the crash site. - self.expect("thread backtrace all", - substrs = [stop_reason, 'main', 'argc', 'argv', 'recursive_function']) + substrs=['stopped', + stop_reason]) + + # And it should report a backtrace that includes main and the crash + # site. + self.expect( + "thread backtrace all", + substrs=[ + stop_reason, + 'main', + 'argc', + 'argv', + 'recursive_function']) # And it should report the correct line number. self.expect("thread backtrace all", - substrs = [stop_reason, - 'main.c:%d' % self.line]) + substrs=[stop_reason, + 'main.c:%d' % self.line]) def recursive_inferior_crashing_python(self): """Inferior crashes upon launching; lldb should catch the event and stop.""" @@ -114,7 +127,8 @@ class CrashingRecursiveInferiorTestCase(TestBase): # Now launch the process, and do not stop at entry point. # Both argv and envp are null. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if process.GetState() != lldb.eStateStopped: self.fail("Process should be in the 'stopped' state, " @@ -122,7 +136,10 @@ class CrashingRecursiveInferiorTestCase(TestBase): lldbutil.state_type_to_str(process.GetState())) threads = lldbutil.get_crashed_threads(self, process) - self.assertEqual(len(threads), 1, "Failed to stop the thread upon bad access exception") + self.assertEqual( + len(threads), + 1, + "Failed to stop the thread upon bad access exception") if self.TraceOn(): lldbutil.print_stacktrace(threads[0]) @@ -135,7 +152,8 @@ class CrashingRecursiveInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - # lldb should be able to read from registers from the inferior after crashing. + # lldb should be able to read from registers from the inferior after + # crashing. lldbplatformutil.check_first_register_readable(self) def recursive_inferior_crashing_expr(self): @@ -146,9 +164,10 @@ class CrashingRecursiveInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - # The lldb expression interpreter should be able to read from addresses of the inferior after a crash. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. self.expect("p i", - startstr = '(int) $0 =') + startstr='(int) $0 =') def recursive_inferior_crashing_step(self): """Test that lldb functions correctly after stepping through a crash.""" @@ -159,22 +178,24 @@ class CrashingRecursiveInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['main.c:%d' % self.line, - 'stop reason = breakpoint']) + substrs=['main.c:%d' % self.line, + 'stop reason = breakpoint']) self.runCmd("next") self.check_stop_reason() - # The lldb expression interpreter should be able to read from addresses of the inferior after a crash. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. self.expect("p i", - substrs = ['(int) $0 =']) + substrs=['(int) $0 =']) - # lldb should be able to read from registers from the inferior after crashing. + # lldb should be able to read from registers from the inferior after + # crashing. lldbplatformutil.check_first_register_readable(self) # And it should report the correct line number. self.expect("thread backtrace all", - substrs = ['main.c:%d' % self.line]) + substrs=['main.c:%d' % self.line]) def recursive_inferior_crashing_step_after_break(self): """Test that lldb behaves correctly when stepping after a crash.""" @@ -184,15 +205,20 @@ class CrashingRecursiveInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - expected_state = 'exited' # Provide the exit code. + expected_state = 'exited' # Provide the exit code. if self.platformIsDarwin(): - expected_state = 'stopped' # TODO: Determine why 'next' and 'continue' have no effect after a crash. + # TODO: Determine why 'next' and 'continue' have no effect after a + # crash. + expected_state = 'stopped' self.expect("next", - substrs = ['Process', expected_state]) + substrs=['Process', expected_state]) if expected_state == 'exited': - self.expect("thread list", error=True,substrs = ['Process must be launched']) + self.expect( + "thread list", + error=True, + substrs=['Process must be launched']) else: self.check_stop_reason() @@ -204,14 +230,16 @@ class CrashingRecursiveInferiorTestCase(TestBase): self.runCmd("run", RUN_SUCCEEDED) self.check_stop_reason() - # The lldb expression interpreter should be able to read from addresses of the inferior after a crash. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. self.expect("p null", - startstr = '(char *) $0 = 0x0') + startstr='(char *) $0 = 0x0') self.runCmd("next") - # The lldb expression interpreter should be able to read from addresses of the inferior after a step. + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a step. self.expect("p null", - startstr = '(char *) $1 = 0x0') + startstr='(char *) $1 = 0x0') self.check_stop_reason() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py b/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py index 8257106888d..cb801242aa5 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py @@ -3,19 +3,23 @@ from __future__ import print_function - -import os, time, sys +import os +import time +import sys import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestInlineStepping(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(['pyapi']) - @expectedFailureAll(compiler="icc", bugnumber="# Not really a bug. ICC combines two inlined functions.") + @expectedFailureAll( + compiler="icc", + bugnumber="# Not really a bug. ICC combines two inlined functions.") def test_with_python_api(self): """Test stepping over and into inlined functions.""" self.build() @@ -26,7 +30,7 @@ class TestInlineStepping(TestBase): """Test stepping over and into inlined functions.""" self.build() self.inline_stepping_step_over() - + @add_test_categories(['pyapi']) def test_step_in_template_with_python_api(self): """Test stepping in to templated functions.""" @@ -39,10 +43,21 @@ class TestInlineStepping(TestBase): # Find the line numbers that we will step to in main: self.main_source = "calling.cpp" self.source_lines = {} - functions = ['caller_ref_1', 'caller_ref_2', 'inline_ref_1', 'inline_ref_2', 'called_by_inline_ref', 'caller_trivial_1', 'caller_trivial_2', 'inline_trivial_1', 'inline_trivial_2', 'called_by_inline_trivial' ] + functions = [ + 'caller_ref_1', + 'caller_ref_2', + 'inline_ref_1', + 'inline_ref_2', + 'called_by_inline_ref', + 'caller_trivial_1', + 'caller_trivial_2', + 'inline_trivial_1', + 'inline_trivial_2', + 'called_by_inline_trivial'] for name in functions: - self.source_lines[name] = line_number(self.main_source, "// In " + name + ".") - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.source_lines[name] = line_number( + self.main_source, "// In " + name + ".") + self.main_source_spec = lldb.SBFileSpec(self.main_source) def do_step(self, step_type, destination_line_entry, test_stack_depth): expected_stack_depth = self.thread.GetNumFrames() @@ -55,58 +70,79 @@ class TestInlineStepping(TestBase): elif step_type == "over": self.thread.StepOver() else: - self.fail ("Unrecognized step type: " + step_type) + self.fail("Unrecognized step type: " + step_type) - threads = lldbutil.get_stopped_threads (self.process, lldb.eStopReasonPlanComplete) + threads = lldbutil.get_stopped_threads( + self.process, lldb.eStopReasonPlanComplete) if len(threads) != 1: destination_description = lldb.SBStream() destination_line_entry.GetDescription(destination_description) - self.fail ("Failed to stop due to step " + step_type + " operation stepping to: " + destination_description.GetData()) + self.fail( + "Failed to stop due to step " + + step_type + + " operation stepping to: " + + destination_description.GetData()) self.thread = threads[0] stop_line_entry = self.thread.GetFrameAtIndex(0).GetLineEntry() - self.assertTrue (stop_line_entry.IsValid(), "Stop line entry was not valid.") - - # Don't use the line entry equal operator because we don't care about the column number. - stop_at_right_place = (stop_line_entry.GetFileSpec() == destination_line_entry.GetFileSpec() and stop_line_entry.GetLine() == destination_line_entry.GetLine()) - if stop_at_right_place == False: + self.assertTrue( + stop_line_entry.IsValid(), + "Stop line entry was not valid.") + + # Don't use the line entry equal operator because we don't care about + # the column number. + stop_at_right_place = (stop_line_entry.GetFileSpec() == destination_line_entry.GetFileSpec( + ) and stop_line_entry.GetLine() == destination_line_entry.GetLine()) + if not stop_at_right_place: destination_description = lldb.SBStream() destination_line_entry.GetDescription(destination_description) actual_description = lldb.SBStream() stop_line_entry.GetDescription(actual_description) - self.fail ("Step " + step_type + " stopped at wrong place: expected: " + destination_description.GetData() + " got: " + actual_description.GetData() + ".") + self.fail( + "Step " + + step_type + + " stopped at wrong place: expected: " + + destination_description.GetData() + + " got: " + + actual_description.GetData() + + ".") real_stack_depth = self.thread.GetNumFrames() if test_stack_depth and real_stack_depth != expected_stack_depth: destination_description = lldb.SBStream() destination_line_entry.GetDescription(destination_description) - self.fail ("Step %s to %s got wrong number of frames, should be: %d was: %d."%(step_type, destination_description.GetData(), expected_stack_depth, real_stack_depth)) - + self.fail( + "Step %s to %s got wrong number of frames, should be: %d was: %d." % + (step_type, + destination_description.GetData(), + expected_stack_depth, + real_stack_depth)) + def run_step_sequence(self, step_sequence): """This function takes a list of duples instructing how to run the program. The first element in each duple is a source pattern for the target location, and the second is the operation that will take you from the current source location to the target location. It will then run all the steps in the sequence. - It will check that you arrived at the expected source location at each step, and that the stack depth changed + It will check that you arrived at the expected source location at each step, and that the stack depth changed correctly for the operation in the sequence.""" target_line_entry = lldb.SBLineEntry() target_line_entry.SetFileSpec(self.main_source_spec) test_stack_depth = True - # Work around for <rdar://problem/16363195>, the darwin unwinder seems flakey about whether it duplicates the first frame + # Work around for <rdar://problem/16363195>, the darwin unwinder seems flakey about whether it duplicates the first frame # or not, which makes counting stack depth unreliable. if self.platformIsDarwin(): test_stack_depth = False for step_pattern in step_sequence: - step_stop_line = line_number (self.main_source, step_pattern[0]) + step_stop_line = line_number(self.main_source, step_pattern[0]) target_line_entry.SetLine(step_stop_line) - self.do_step (step_pattern[1], target_line_entry, test_stack_depth) - + self.do_step(step_pattern[1], target_line_entry, test_stack_depth) + def inline_stepping(self): """Use Python APIs to test stepping over and hitting breakpoints.""" exe = os.path.join(os.getcwd(), "a.out") @@ -114,19 +150,22 @@ class TestInlineStepping(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - break_1_in_main = target.BreakpointCreateBySourceRegex ('// Stop here and step over to set up stepping over.', self.main_source_spec) + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// Stop here and step over to set up stepping over.', self.main_source_spec) self.assertTrue(break_1_in_main, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - self.process = target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, break_1_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, break_1_in_main) if len(threads) != 1: - self.fail ("Failed to stop at first breakpoint in main.") + self.fail("Failed to stop at first breakpoint in main.") self.thread = threads[0] @@ -135,60 +174,73 @@ class TestInlineStepping(TestBase): # gets set past the insertion line in the function. # Then test stepping over a simple inlined function. Note, to test all the parts of the inlined stepping # the calls inline_stepping_1 and inline_stepping_2 should line up at the same address, that way we will test - # the "virtual" stepping. + # the "virtual" stepping. # FIXME: Put in a check to see if that is true and warn if it is not. - step_sequence = [["// At inline_trivial_1 called from main.", "over"], + step_sequence = [["// At inline_trivial_1 called from main.", "over"], ["// At first call of caller_trivial_1 in main.", "over"]] self.run_step_sequence(step_sequence) - + # Now step from caller_ref_1 all the way into called_by_inline_trivial - step_sequence = [["// In caller_trivial_1.", "into"], - ["// In caller_trivial_2.", "into"], + step_sequence = [["// In caller_trivial_1.", "into"], + ["// In caller_trivial_2.", "into"], ["// In inline_trivial_1.", "into"], ["// In inline_trivial_2.", "into"], ["// At caller_by_inline_trivial in inline_trivial_2.", "over"], ["// In called_by_inline_trivial.", "into"]] self.run_step_sequence(step_sequence) - # Now run to the inline_trivial_1 just before the immediate step into inline_trivial_2: + # Now run to the inline_trivial_1 just before the immediate step into + # inline_trivial_2: - break_2_in_main = target.BreakpointCreateBySourceRegex ('// At second call of caller_trivial_1 in main.', self.main_source_spec) + break_2_in_main = target.BreakpointCreateBySourceRegex( + '// At second call of caller_trivial_1 in main.', self.main_source_spec) self.assertTrue(break_2_in_main, VALID_BREAKPOINT) - threads = lldbutil.continue_to_breakpoint (self.process, break_2_in_main) - self.assertTrue (len(threads) == 1, "Successfully ran to call site of second caller_trivial_1 call.") + threads = lldbutil.continue_to_breakpoint( + self.process, break_2_in_main) + self.assertTrue( + len(threads) == 1, + "Successfully ran to call site of second caller_trivial_1 call.") self.thread = threads[0] - - step_sequence = [["// In caller_trivial_1.", "into"], - ["// In caller_trivial_2.", "into"], + + step_sequence = [["// In caller_trivial_1.", "into"], + ["// In caller_trivial_2.", "into"], ["// In inline_trivial_1.", "into"]] self.run_step_sequence(step_sequence) - # Then call some trivial function, and make sure we end up back where we were in the inlined call stack: - + # Then call some trivial function, and make sure we end up back where + # we were in the inlined call stack: + frame = self.thread.GetFrameAtIndex(0) before_line_entry = frame.GetLineEntry() - value = frame.EvaluateExpression ("function_to_call()") + value = frame.EvaluateExpression("function_to_call()") after_line_entry = frame.GetLineEntry() - self.assertTrue (before_line_entry.GetLine() == after_line_entry.GetLine(), "Line entry before and after function calls are the same.") + self.assertTrue( + before_line_entry.GetLine() == after_line_entry.GetLine(), + "Line entry before and after function calls are the same.") - # Now make sure stepping OVER in the middle of the stack works, and then check finish from the inlined frame: + # Now make sure stepping OVER in the middle of the stack works, and + # then check finish from the inlined frame: step_sequence = [["// At increment in inline_trivial_1.", "over"], ["// At increment in caller_trivial_2.", "out"]] self.run_step_sequence(step_sequence) + # Now run to the place in main just before the first call to + # caller_ref_1: - # Now run to the place in main just before the first call to caller_ref_1: - - break_3_in_main = target.BreakpointCreateBySourceRegex ('// At first call of caller_ref_1 in main.', self.main_source_spec) + break_3_in_main = target.BreakpointCreateBySourceRegex( + '// At first call of caller_ref_1 in main.', self.main_source_spec) self.assertTrue(break_3_in_main, VALID_BREAKPOINT) - threads = lldbutil.continue_to_breakpoint (self.process, break_3_in_main) - self.assertTrue (len(threads) == 1, "Successfully ran to call site of first caller_ref_1 call.") + threads = lldbutil.continue_to_breakpoint( + self.process, break_3_in_main) + self.assertTrue( + len(threads) == 1, + "Successfully ran to call site of first caller_ref_1 call.") self.thread = threads[0] step_sequence = [["// In caller_ref_1.", "into"], @@ -201,7 +253,7 @@ class TestInlineStepping(TestBase): ["// At increment in inline_ref_1.", "over"], ["// In caller_ref_2.", "out"], ["// At increment in caller_ref_2.", "over"]] - self.run_step_sequence (step_sequence) + self.run_step_sequence(step_sequence) def inline_stepping_step_over(self): """Use Python APIs to test stepping over and hitting breakpoints.""" @@ -210,26 +262,29 @@ class TestInlineStepping(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - break_1_in_main = target.BreakpointCreateBySourceRegex ('// At second call of caller_ref_1 in main.', self.main_source_spec) + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// At second call of caller_ref_1 in main.', self.main_source_spec) self.assertTrue(break_1_in_main, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - self.process = target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, break_1_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, break_1_in_main) if len(threads) != 1: - self.fail ("Failed to stop at first breakpoint in main.") + self.fail("Failed to stop at first breakpoint in main.") self.thread = threads[0] step_sequence = [["// In caller_ref_1.", "into"], ["// In caller_ref_2.", "into"], ["// At increment in caller_ref_2.", "over"]] - self.run_step_sequence (step_sequence) + self.run_step_sequence(step_sequence) def step_in_template(self): """Use Python APIs to test stepping in to templated functions.""" @@ -238,30 +293,38 @@ class TestInlineStepping(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - break_1_in_main = target.BreakpointCreateBySourceRegex ('// Call max_value template', self.main_source_spec) + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// Call max_value template', self.main_source_spec) self.assertTrue(break_1_in_main, VALID_BREAKPOINT) - - break_2_in_main = target.BreakpointCreateBySourceRegex ('// Call max_value specialized', self.main_source_spec) + + break_2_in_main = target.BreakpointCreateBySourceRegex( + '// Call max_value specialized', self.main_source_spec) self.assertTrue(break_2_in_main, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - self.process = target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, break_1_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, break_1_in_main) if len(threads) != 1: - self.fail ("Failed to stop at first breakpoint in main.") + self.fail("Failed to stop at first breakpoint in main.") self.thread = threads[0] step_sequence = [["// In max_value template", "into"]] self.run_step_sequence(step_sequence) - - threads = lldbutil.continue_to_breakpoint (self.process, break_2_in_main) - self.assertEqual(len(threads), 1, "Successfully ran to call site of second caller_trivial_1 call.") + + threads = lldbutil.continue_to_breakpoint( + self.process, break_2_in_main) + self.assertEqual( + len(threads), + 1, + "Successfully ran to call site of second caller_trivial_1 call.") self.thread = threads[0] - + step_sequence = [["// In max_value specialized", "into"]] self.run_step_sequence(step_sequence) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py b/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py index 336260a8e4a..7ccfaa688b8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py @@ -15,7 +15,9 @@ class JITLoaderGDBTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipTestIfFn(lambda : "Skipped because the test crashes the test runner", bugnumber="llvm.org/pr24702") + @skipTestIfFn( + lambda: "Skipped because the test crashes the test runner", + bugnumber="llvm.org/pr24702") @unittest2.expectedFailure("llvm.org/pr24702") def test_bogus_values(self): """Test that we handle inferior misusing the GDB JIT interface""" @@ -27,10 +29,12 @@ class JITLoaderGDBTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # launch the process, do not stop at entry point. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - # The inferior will now pass bogus values over the interface. Make sure we don't crash. + # The inferior will now pass bogus values over the interface. Make sure + # we don't crash. self.assertEqual(process.GetState(), lldb.eStateExited) self.assertEqual(process.GetExitStatus(), 0) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py b/lldb/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py index 28d8cccacfc..0ebb99d3fd4 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py @@ -4,7 +4,6 @@ Test that argdumper is a viable launching strategy. from __future__ import print_function - import lldb import os import time @@ -12,40 +11,50 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LaunchWithShellExpandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows", "linux", "freebsd"], bugnumber="llvm.org/pr24778 llvm.org/pr22627") + @expectedFailureAll( + oslist=[ + "windows", + "linux", + "freebsd"], + bugnumber="llvm.org/pr24778 llvm.org/pr22627") def test(self): self.build() - exe = os.path.join (os.getcwd(), "a.out") - + exe = os.path.join(os.getcwd(), "a.out") + self.runCmd("target create %s" % exe) - + # Create the target target = self.dbg.CreateTarget(exe) - + # Create any breakpoints we need - breakpoint = target.BreakpointCreateBySourceRegex ('break here', lldb.SBFileSpec ("main.cpp", False)) + breakpoint = target.BreakpointCreateBySourceRegex( + 'break here', lldb.SBFileSpec("main.cpp", False)) self.assertTrue(breakpoint, VALID_BREAKPOINT) - self.runCmd("process launch -X true -w %s -- fi*.tx? () > <" % (os.getcwd())) + self.runCmd( + "process launch -X true -w %s -- fi*.tx? () > <" % + (os.getcwd())) process = self.process() self.assertTrue(process.GetState() == lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT) - thread = process.GetThreadAtIndex (0) + thread = process.GetThreadAtIndex(0) - self.assertTrue (thread.IsValid(), - "Process stopped at 'main' should have a valid thread"); + self.assertTrue(thread.IsValid(), + "Process stopped at 'main' should have a valid thread") stop_reason = thread.GetStopReason() - - self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint, - "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint"); + + self.assertTrue( + stop_reason == lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") self.expect("frame variable argv[1]", substrs=['file1.txt']) self.expect("frame variable argv[2]", substrs=['file2.txt']) @@ -54,47 +63,57 @@ class LaunchWithShellExpandTestCase(TestBase): self.expect("frame variable argv[5]", substrs=['()']) self.expect("frame variable argv[6]", substrs=['>']) self.expect("frame variable argv[7]", substrs=['<']) - self.expect("frame variable argv[5]", substrs=['file5.tyx'], matching=False) - self.expect("frame variable argv[8]", substrs=['file5.tyx'], matching=False) + self.expect( + "frame variable argv[5]", + substrs=['file5.tyx'], + matching=False) + self.expect( + "frame variable argv[8]", + substrs=['file5.tyx'], + matching=False) self.runCmd("process kill") - self.runCmd('process launch -X true -w %s -- "foo bar"' % (os.getcwd())) - + self.runCmd( + 'process launch -X true -w %s -- "foo bar"' % + (os.getcwd())) + process = self.process() self.assertTrue(process.GetState() == lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT) - thread = process.GetThreadAtIndex (0) + thread = process.GetThreadAtIndex(0) - self.assertTrue (thread.IsValid(), - "Process stopped at 'main' should have a valid thread"); + self.assertTrue(thread.IsValid(), + "Process stopped at 'main' should have a valid thread") stop_reason = thread.GetStopReason() - - self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint, - "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint"); - + + self.assertTrue( + stop_reason == lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + self.expect("frame variable argv[1]", substrs=['foo bar']) self.runCmd("process kill") self.runCmd('process launch -X true -w %s -- foo\ bar' % (os.getcwd())) - + process = self.process() self.assertTrue(process.GetState() == lldb.eStateStopped, STOPPED_DUE_TO_BREAKPOINT) - thread = process.GetThreadAtIndex (0) + thread = process.GetThreadAtIndex(0) - self.assertTrue (thread.IsValid(), - "Process stopped at 'main' should have a valid thread"); + self.assertTrue(thread.IsValid(), + "Process stopped at 'main' should have a valid thread") stop_reason = thread.GetStopReason() - - self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint, - "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint"); - + + self.assertTrue( + stop_reason == lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + self.expect("frame variable argv[1]", substrs=['foo bar']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/llvm/TestLLVM.py b/lldb/packages/Python/lldbsuite/test/functionalities/llvm/TestLLVM.py index a2a43bf2fab..85741f548f3 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/llvm/TestLLVM.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/llvm/TestLLVM.py @@ -5,24 +5,26 @@ Test lldb 'commands regex' command which allows the user to create a regular exp from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestHomeDirectory(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @no_debug_info_test def test_tilde_home_directory(self): - """Test that we can resolve "~/" in paths correctly. + """Test that we can resolve "~/" in paths correctly. When a path starts with "~/", we use llvm::sys::path::home_directory() to resolve the home directory. This currently relies on "HOME" being set in the - environment. While this is usually set, we can't rely upon that. We might + environment. While this is usually set, we can't rely upon that. We might eventually get a fix into llvm::sys::path::home_directory() so it doesn't rely on having to have an environment variable set, but until then we have work around code in FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path) to ensure @@ -31,7 +33,9 @@ class TestHomeDirectory(TestBase): import pexpect prompt = "(lldb) " - child = pexpect.spawn('%s --no-use-colors %s' % (lldbtest_config.lldbExec, self.lldbOption)) + child = pexpect.spawn( + '%s --no-use-colors %s' % + (lldbtest_config.lldbExec, self.lldbOption)) # Turn on logging for what the child sends back. if self.TraceOn(): child.logfile_read = sys.stdout @@ -39,7 +43,7 @@ class TestHomeDirectory(TestBase): self.child = child # Resolve "~/." to the full path of our home directory + "/." - if 'HOME' in os.environ: + if 'HOME' in os.environ: home_dir = os.environ['HOME'] if self.TraceOn(): print("home directory is: '%s'" % (home_dir)) @@ -49,11 +53,14 @@ class TestHomeDirectory(TestBase): child.sendline('''script str(lldb.SBFileSpec("~/.", True))''') child.expect_exact(home_dir) child.expect_exact(prompt) - child.sendline('''script import os; os.unsetenv('HOME'); str(lldb.SBFileSpec("~/", True))'''); + child.sendline( + '''script import os; os.unsetenv('HOME'); str(lldb.SBFileSpec("~/", True))''') child.expect_exact(home_dir) child.expect_exact(prompt) elif self.TraceOn(): - print('''home directory "%s" doesn't exist, skipping home directory test''' % (home_dir)) + print( + '''home directory "%s" doesn't exist, skipping home directory test''' % + (home_dir)) elif self.TraceOn(): print('"HOME" not in environment, skipping home directory test') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py b/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py index 3a703b2ee04..8b3ce441ced 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py @@ -5,18 +5,19 @@ Test that breakpoint by symbol name works correctly with dynamic libs. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -@skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + +@skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently class LoadUnloadTestCase(TestBase): - def getCategories (self): + def getCategories(self): return ['basic_process'] mydir = TestBase.compute_mydir(__file__) @@ -25,19 +26,30 @@ class LoadUnloadTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break for main.cpp. - self.line = line_number('main.cpp', - '// Set break point at this line for test_lldb_process_load_and_unload_commands().') - self.line_d_function = line_number('d.cpp', - '// Find this line number within d_dunction().') + self.line = line_number( + 'main.cpp', + '// Set break point at this line for test_lldb_process_load_and_unload_commands().') + self.line_d_function = line_number( + 'd.cpp', '// Find this line number within d_dunction().') if not self.platformIsDarwin(): if not lldb.remote_platform and "LD_LIBRARY_PATH" in os.environ: - self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + os.environ["LD_LIBRARY_PATH"] + ":" + os.getcwd()) + self.runCmd( + "settings set target.env-vars " + + self.dylibPath + + "=" + + os.environ["LD_LIBRARY_PATH"] + + ":" + + os.getcwd()) else: if lldb.remote_platform: wd = lldb.remote_platform.GetWorkingDirectory() else: wd = os.getcwd() - self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + wd) + self.runCmd( + "settings set target.env-vars " + + self.dylibPath + + "=" + + wd) def copy_shlibs_to_remote(self, hidden_dir=False): """ Copies the shared libs required by this test suite to remote. @@ -72,9 +84,9 @@ class LoadUnloadTestCase(TestBase): "Unable copy 'libloadunload_d.so' to '%s'.\n>>> %s" % (wd, err.GetCString())) - @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support @not_remote_testsuite_ready - @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently def test_modules_search_paths(self): """Test target modules list after loading a different copy of the library libd.dylib, and verifies that it works with 'target modules search-paths add'.""" @@ -96,17 +108,22 @@ class LoadUnloadTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) self.expect("target modules list", - substrs = [old_dylib]) - #self.expect("target modules list -t 3", + substrs=[old_dylib]) + # self.expect("target modules list -t 3", # patterns = ["%s-[^-]*-[^-]*" % self.getArchitecture()]) # Add an image search path substitution pair. - self.runCmd("target modules search-paths add %s %s" % (os.getcwd(), new_dir)) + self.runCmd( + "target modules search-paths add %s %s" % + (os.getcwd(), new_dir)) self.expect("target modules search-paths list", - substrs = [os.getcwd(), new_dir]) + substrs=[os.getcwd(), new_dir]) - self.expect("target modules search-paths query %s" % os.getcwd(), "Image search path successfully transformed", - substrs = [new_dir]) + self.expect( + "target modules search-paths query %s" % + os.getcwd(), + "Image search path successfully transformed", + substrs=[new_dir]) # Obliterate traces of libd from the old location. os.remove(old_dylib) @@ -118,16 +135,19 @@ class LoadUnloadTestCase(TestBase): self.runCmd("settings show target.env-vars") remove_dyld_path_cmd = "settings remove target.env-vars " + self.dylibPath - self.addTearDownHook(lambda: self.dbg.HandleCommand(remove_dyld_path_cmd)) + self.addTearDownHook( + lambda: self.dbg.HandleCommand(remove_dyld_path_cmd)) self.runCmd("run") - self.expect("target modules list", "LLDB successfully locates the relocated dynamic library", - substrs = [new_dylib]) + self.expect( + "target modules list", + "LLDB successfully locates the relocated dynamic library", + substrs=[new_dylib]) - @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support - @expectedFailureAndroid # wrong source file shows up for hidden library - @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @expectedFailureAndroid # wrong source file shows up for hidden library + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently def test_dyld_library_path(self): """Test (DY)LD_LIBRARY_PATH after moving libd.dylib, which defines d_function, somewhere else.""" @@ -156,15 +176,17 @@ class LoadUnloadTestCase(TestBase): old_dylib = os.path.join(old_dir, dylibName) remove_dyld_path_cmd = "settings remove target.env-vars " + self.dylibPath - self.addTearDownHook(lambda: self.dbg.HandleCommand(remove_dyld_path_cmd)) + self.addTearDownHook( + lambda: self.dbg.HandleCommand(remove_dyld_path_cmd)) # For now we don't track (DY)LD_LIBRARY_PATH, so the old library will be in # the modules list. self.expect("target modules list", - substrs = [os.path.basename(old_dylib)], + substrs=[os.path.basename(old_dylib)], matching=True) - lldbutil.run_break_set_by_file_and_line (self, "d.cpp", self.line_d_function, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "d.cpp", self.line_d_function, num_expected_locations=1) # After run, make sure the non-hidden library is picked up. self.expect("run", substrs=["return", "700"]) @@ -180,9 +202,14 @@ class LoadUnloadTestCase(TestBase): # This time, the hidden library should be picked up. self.expect("run", substrs=["return", "12345"]) - @expectedFailureAll(bugnumber="llvm.org/pr25805", hostoslist=["windows"], compiler="gcc", archs=["i386"], triple='.*-android') - @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support - @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @expectedFailureAll( + bugnumber="llvm.org/pr25805", + hostoslist=["windows"], + compiler="gcc", + archs=["i386"], + triple='.*-android') + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently def test_lldb_process_load_and_unload_commands(self): """Test that lldb process load/unload command work correctly.""" @@ -196,7 +223,8 @@ class LoadUnloadTestCase(TestBase): # Break at main.cpp before the call to dlopen(). # Use lldb's process load command to load the dylib, instead. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) @@ -211,13 +239,23 @@ class LoadUnloadTestCase(TestBase): dylibName = 'libloadunload_a.so' # Make sure that a_function does not exist at this point. - self.expect("image lookup -n a_function", "a_function should not exist yet", - error=True, matching=False, patterns = ["1 match found"]) + self.expect( + "image lookup -n a_function", + "a_function should not exist yet", + error=True, + matching=False, + patterns=["1 match found"]) # Use lldb 'process load' to load the dylib. - self.expect("process load %s --install" % dylibName, "%s loaded correctly" % dylibName, - patterns = ['Loading "%s".*ok' % dylibName, - 'Image [0-9]+ loaded']) + self.expect( + "process load %s --install" % + dylibName, + "%s loaded correctly" % + dylibName, + patterns=[ + 'Loading "%s".*ok' % + dylibName, + 'Image [0-9]+ loaded']) # Search for and match the "Image ([0-9]+) loaded" pattern. output = self.res.GetOutput() @@ -230,16 +268,26 @@ class LoadUnloadTestCase(TestBase): index = match.group(1) # Now we should have an entry for a_function. - self.expect("image lookup -n a_function", "a_function should now exist", - patterns = ["1 match found .*%s" % dylibName]) + self.expect( + "image lookup -n a_function", + "a_function should now exist", + patterns=[ + "1 match found .*%s" % + dylibName]) # Use lldb 'process unload' to unload the dylib. - self.expect("process unload %s" % index, "%s unloaded correctly" % dylibName, - patterns = ["Unloading .* with index %s.*ok" % index]) + self.expect( + "process unload %s" % + index, + "%s unloaded correctly" % + dylibName, + patterns=[ + "Unloading .* with index %s.*ok" % + index]) self.runCmd("process continue") - @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support def test_load_unload(self): """Test breakpoint by name works correctly with dlopen'ing.""" @@ -251,19 +299,20 @@ class LoadUnloadTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break by function name a_function (not yet loaded). - lldbutil.run_break_set_by_symbol (self, "a_function", num_expected_locations=0) + lldbutil.run_break_set_by_symbol( + self, "a_function", num_expected_locations=0) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint and at a_function. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'a_function', - 'stop reason = breakpoint']) + substrs=['stopped', + 'a_function', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Issue the 'contnue' command. We should stop agaian at a_function. # The stop reason of the thread should be breakpoint and at a_function. @@ -272,17 +321,17 @@ class LoadUnloadTestCase(TestBase): # rdar://problem/8508987 # The a_function breakpoint should be encountered twice. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'a_function', - 'stop reason = breakpoint']) + substrs=['stopped', + 'a_function', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 2. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 2']) + substrs=[' resolved, hit count = 2']) - @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support - @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently - def test_step_over_load (self): + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + def test_step_over_load(self): """Test stepping over code that loads a shared library works correctly.""" # Invoke the default build rule. @@ -293,26 +342,29 @@ class LoadUnloadTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break by function name a_function (not yet loaded). - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint and at a_function. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) + + self.runCmd( + "thread step-over", + "Stepping over function that loads library") - self.runCmd("thread step-over", "Stepping over function that loads library") - # The stop reason should be step end. - self.expect("thread list", "step over succeeded.", - substrs = ['stopped', - 'stop reason = step over']) + self.expect("thread list", "step over succeeded.", + substrs=['stopped', + 'stop reason = step over']) - @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support - @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently @unittest2.expectedFailure("llvm.org/pr25806") - def test_static_init_during_load (self): + def test_static_init_during_load(self): """Test that we can set breakpoints correctly in static initializers""" self.build() @@ -321,33 +373,36 @@ class LoadUnloadTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - a_init_bp_num = lldbutil.run_break_set_by_symbol(self, "a_init", num_expected_locations=0) - b_init_bp_num = lldbutil.run_break_set_by_symbol(self, "b_init", num_expected_locations=0) - d_init_bp_num = lldbutil.run_break_set_by_symbol(self, "d_init", num_expected_locations=1) + a_init_bp_num = lldbutil.run_break_set_by_symbol( + self, "a_init", num_expected_locations=0) + b_init_bp_num = lldbutil.run_break_set_by_symbol( + self, "b_init", num_expected_locations=0) + d_init_bp_num = lldbutil.run_break_set_by_symbol( + self, "d_init", num_expected_locations=1) self.runCmd("run", RUN_SUCCEEDED) self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'd_init', - 'stop reason = breakpoint %d' % d_init_bp_num]) + substrs=['stopped', + 'd_init', + 'stop reason = breakpoint %d' % d_init_bp_num]) self.runCmd("continue") self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'a_init', - 'stop reason = breakpoint %d' % a_init_bp_num]) + substrs=['stopped', + 'a_init', + 'stop reason = breakpoint %d' % a_init_bp_num]) self.expect("thread backtrace", - substrs = ['a_init', - 'dlopen', - 'main']) + substrs=['a_init', + 'dlopen', + 'main']) self.runCmd("continue") self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'b_init', - 'stop reason = breakpoint %d' % b_init_bp_num]) + substrs=['stopped', + 'b_init', + 'stop reason = breakpoint %d' % b_init_bp_num]) self.expect("thread backtrace", - substrs = ['b_init', - 'dlopen', - 'main']) + substrs=['b_init', + 'dlopen', + 'main']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py b/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py index d9f2b223189..dd4ab4cab2a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py @@ -5,13 +5,13 @@ Test the use of setjmp/longjmp for non-local goto operations in a single-threade from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LongjmpTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,8 +19,8 @@ class LongjmpTestCase(TestBase): def setUp(self): TestBase.setUp(self) - @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp - @skipIfFreeBSD # llvm.org/pr17214 + @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp + @skipIfFreeBSD # llvm.org/pr17214 @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20231") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") def test_step_out(self): @@ -28,8 +28,8 @@ class LongjmpTestCase(TestBase): self.build() self.step_out() - @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp - @skipIfFreeBSD # llvm.org/pr17214 + @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp + @skipIfFreeBSD # llvm.org/pr17214 @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20231") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") def test_step_over(self): @@ -37,8 +37,8 @@ class LongjmpTestCase(TestBase): self.build() self.step_over() - @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp - @skipIfFreeBSD # llvm.org/pr17214 + @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp + @skipIfFreeBSD # llvm.org/pr17214 @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20231") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") def test_step_back_out(self): @@ -52,19 +52,20 @@ class LongjmpTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main(). - lldbutil.run_break_set_by_symbol (self, symbol, num_expected_locations=-1) + lldbutil.run_break_set_by_symbol( + self, symbol, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) def check_status(self): # Note: Depending on the generated mapping of DWARF to assembly, # the process may have stopped or exited. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* exited with status = 0']) + patterns=['Process .* exited with status = 0']) def step_out(self): self.start_test("do_jump") @@ -79,7 +80,7 @@ class LongjmpTestCase(TestBase): def step_back_out(self): self.start_test("main") - + self.runCmd("thread step-over", RUN_SUCCEEDED) self.runCmd("thread step-in", RUN_SUCCEEDED) self.runCmd("thread step-out", RUN_SUCCEEDED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/TestMemoryCache.py b/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/TestMemoryCache.py index a65882d3fa4..f2126e9ffd5 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/TestMemoryCache.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/TestMemoryCache.py @@ -5,14 +5,15 @@ Test the MemoryCache L1 flush. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class MemoryCacheTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -31,17 +32,18 @@ class MemoryCacheTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main() after the variables are assigned values. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Read a chunk of memory containing &my_ints[0]. The number of bytes read # must be greater than m_L2_cache_line_byte_size to make sure the L1 diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/TestMemoryFind.py b/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/TestMemoryFind.py index 6cdf5bf48e9..ddbe6409cb8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/TestMemoryFind.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/TestMemoryFind.py @@ -5,14 +5,15 @@ Test the 'memory find' command. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.decorators import * + class MemoryFindTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,31 +31,40 @@ class MemoryFindTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main() aftre the variables are assigned values. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Test the memory find commands. - self.expect('memory find -s "in const" `stringdata` `stringdata+(int)strlen(stringdata)`', - substrs = ['data found at location: 0x', '69 6e 20 63', 'in const']) - - self.expect('memory find -e "(uint8_t)0x22" `&bytedata[0]` `&bytedata[15]`', - substrs = ['data found at location: 0x', '22 33 44 55 66']) - - self.expect('memory find -e "(uint8_t)0x22" `&bytedata[0]` `&bytedata[2]`', - substrs = ['data not found within the range.']) + self.expect( + 'memory find -s "in const" `stringdata` `stringdata+(int)strlen(stringdata)`', + substrs=[ + 'data found at location: 0x', + '69 6e 20 63', + 'in const']) + + self.expect( + 'memory find -e "(uint8_t)0x22" `&bytedata[0]` `&bytedata[15]`', + substrs=[ + 'data found at location: 0x', + '22 33 44 55 66']) + + self.expect( + 'memory find -e "(uint8_t)0x22" `&bytedata[0]` `&bytedata[2]`', + substrs=['data not found within the range.']) self.expect('memory find -s "nothere" `stringdata` `stringdata+5`', - substrs = ['data not found within the range.']) + substrs=['data not found within the range.']) self.expect('memory find -s "nothere" `stringdata` `stringdata+10`', - substrs = ['data not found within the range.']) + substrs=['data not found within the range.']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py b/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py index 7410650ad65..9d4e44c96bb 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py @@ -5,13 +5,14 @@ Test the 'memory read' command. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class MemoryReadTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,17 +30,18 @@ class MemoryReadTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main() aftre the variables are assigned values. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Test the memory read commands. @@ -61,39 +63,58 @@ class MemoryReadTestCase(TestBase): # 0x7fff5fbff9a4: {0x00000000} # 0x7fff5fbff9a8: {0x0ec0bf27} # 0x7fff5fbff9ac: {0x215db505} - self.runCmd("memory read --format uint32_t[] --size 4 --count 4 `&argc`") + self.runCmd( + "memory read --format uint32_t[] --size 4 --count 4 `&argc`") lines = self.res.GetOutput().splitlines() for i in range(4): if i == 0: # Verify that the printout for argc is correct. - self.assertTrue(argc == int(lines[i].split(':')[1].strip(' {}'), 0)) + self.assertTrue( + argc == int( + lines[i].split(':')[1].strip(' {}'), 0)) addr = int(lines[i].split(':')[0], 0) # Verify that the printout for addr is incremented correctly. - self.assertTrue(addr == (address + i*4)) + self.assertTrue(addr == (address + i * 4)) # (lldb) memory read --format char[] --size 7 --count 1 `&my_string` # 0x7fff5fbff990: {abcdefg} - self.expect("memory read --format char[] --size 7 --count 1 `&my_string`", - substrs = ['abcdefg']) + self.expect( + "memory read --format char[] --size 7 --count 1 `&my_string`", + substrs=['abcdefg']) # (lldb) memory read --format 'hex float' --size 16 `&argc` - # 0x7fff5fbff5b0: error: unsupported byte size (16) for hex float format - self.expect("memory read --format 'hex float' --size 16 `&argc`", - substrs = ['unsupported byte size (16) for hex float format']) + # 0x7fff5fbff5b0: error: unsupported byte size (16) for hex float + # format + self.expect( + "memory read --format 'hex float' --size 16 `&argc`", + substrs=['unsupported byte size (16) for hex float format']) - self.expect("memory read --format 'float' --count 1 --size 8 `&my_double`", - substrs = ['1234.']) + self.expect( + "memory read --format 'float' --count 1 --size 8 `&my_double`", + substrs=['1234.']) # (lldb) memory read --format 'float' --count 1 --size 20 `&my_double` # 0x7fff5fbff598: error: unsupported byte size (20) for float format - self.expect("memory read --format 'float' --count 1 --size 20 `&my_double`", - substrs = ['unsupported byte size (20) for float format']) + self.expect( + "memory read --format 'float' --count 1 --size 20 `&my_double`", + substrs=['unsupported byte size (20) for float format']) self.expect('memory read --type int --count 5 `&my_ints[0]`', - substrs=['(int) 0x', '2','4','6','8','10']) - - self.expect('memory read --type int --count 5 --format hex `&my_ints[0]`', - substrs=['(int) 0x', '0x','0a']) - - self.expect('memory read --type int --count 5 --offset 5 `&my_ints[0]`', - substrs=['(int) 0x', '12', '14','16','18', '20']) + substrs=['(int) 0x', '2', '4', '6', '8', '10']) + + self.expect( + 'memory read --type int --count 5 --format hex `&my_ints[0]`', + substrs=[ + '(int) 0x', + '0x', + '0a']) + + self.expect( + 'memory read --type int --count 5 --offset 5 `&my_ints[0]`', + substrs=[ + '(int) 0x', + '12', + '14', + '16', + '18', + '20']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/multidebugger_commands/TestMultipleDebuggersCommands.py b/lldb/packages/Python/lldbsuite/test/functionalities/multidebugger_commands/TestMultipleDebuggersCommands.py index 7d959ec504c..9cdd7158516 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/multidebugger_commands/TestMultipleDebuggersCommands.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/multidebugger_commands/TestMultipleDebuggersCommands.py @@ -5,13 +5,14 @@ Test that commands do not try and hold on to stale CommandInterpreters in a mult from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MultipleDebuggersCommandsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,28 +22,33 @@ class MultipleDebuggersCommandsTestCase(TestBase): """Test that commands do not try and hold on to stale CommandInterpreters in a multiple debuggers scenario""" source_init_files = False magic_text = "The following commands may relate to 'env'" - + debugger_1 = lldb.SBDebugger.Create(source_init_files) interpreter_1 = debugger_1.GetCommandInterpreter() - + retobj = lldb.SBCommandReturnObject() interpreter_1.HandleCommand("apropos env", retobj) - self.assertTrue(magic_text in str(retobj), "[interpreter_1]: the output does not contain the correct words") - - if self.TraceOn(): print(str(retobj)) - + self.assertTrue( + magic_text in str(retobj), + "[interpreter_1]: the output does not contain the correct words") + + if self.TraceOn(): + print(str(retobj)) + lldb.SBDebugger.Destroy(debugger_1) - + # now do this again with a different debugger - we shouldn't crash - + debugger_2 = lldb.SBDebugger.Create(source_init_files) interpreter_2 = debugger_2.GetCommandInterpreter() - + retobj = lldb.SBCommandReturnObject() interpreter_2.HandleCommand("apropos env", retobj) - self.assertTrue(magic_text in str(retobj), "[interpreter_2]: the output does not contain the correct words") - - if self.TraceOn(): print(str(retobj)) - + self.assertTrue( + magic_text in str(retobj), + "[interpreter_2]: the output does not contain the correct words") + + if self.TraceOn(): + print(str(retobj)) + lldb.SBDebugger.Destroy(debugger_2) - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/nested_alias/TestNestedAlias.py b/lldb/packages/Python/lldbsuite/test/functionalities/nested_alias/TestNestedAlias.py index 6a74ddb727d..86c5e41b093 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/nested_alias/TestNestedAlias.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/nested_alias/TestNestedAlias.py @@ -5,13 +5,14 @@ Test that an alias can reference other aliases without crashing. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class NestedAliasTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,17 +30,18 @@ class NestedAliasTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main() aftre the variables are assigned values. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # This is the function to remove the custom aliases in order to have a # clean slate for the next test case. @@ -54,15 +56,38 @@ class NestedAliasTestCase(TestBase): self.runCmd('command alias read memory read -f A') self.runCmd('command alias rd read -c 3') - - self.expect('memory read -f A -c 3 `&my_ptr[0]`', substrs=['deadbeef', 'main.cpp:', 'feedbeef']) - self.expect('rd `&my_ptr[0]`', substrs=['deadbeef', 'main.cpp:', 'feedbeef']) - self.expect('memory read -f A -c 3 `&my_ptr[0]`', substrs=['deadfeed'], matching=False) + self.expect( + 'memory read -f A -c 3 `&my_ptr[0]`', + substrs=[ + 'deadbeef', + 'main.cpp:', + 'feedbeef']) + self.expect( + 'rd `&my_ptr[0]`', + substrs=[ + 'deadbeef', + 'main.cpp:', + 'feedbeef']) + + self.expect( + 'memory read -f A -c 3 `&my_ptr[0]`', + substrs=['deadfeed'], + matching=False) self.expect('rd `&my_ptr[0]`', substrs=['deadfeed'], matching=False) self.runCmd('command alias fo frame variable -O --') self.runCmd('command alias foself fo self') - - self.expect('help foself', substrs=['--show-all-children', '--raw-output'], matching=False) - self.expect('help foself', substrs=['Show variables for the current', 'stack frame.'], matching=True) + + self.expect( + 'help foself', + substrs=[ + '--show-all-children', + '--raw-output'], + matching=False) + self.expect( + 'help foself', + substrs=[ + 'Show variables for the current', + 'stack frame.'], + matching=True) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py b/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py index 5c53cfaf912..bbaba956acf 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py @@ -4,11 +4,11 @@ from out of scope to in scope when stopped at the breakpoint.""" from __future__ import print_function - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class NonOverlappingIndexVariableCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -16,7 +16,8 @@ class NonOverlappingIndexVariableCase(TestBase): def setUp(self): TestBase.setUp(self) self.source = 'main.cpp' - self.line_to_break = line_number(self.source, '// Set breakpoint here.') + self.line_to_break = line_number( + self.source, '// Set breakpoint here.') # rdar://problem/9890530 def test_eval_index_variable(self): @@ -26,14 +27,19 @@ class NonOverlappingIndexVariableCase(TestBase): exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file %s" % exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, self.source, self.line_to_break, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + self.source, + self.line_to_break, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) self.runCmd('frame variable i') self.runCmd('expr i') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py b/lldb/packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py index 7a6c98d92c3..be89e36b5ce 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py @@ -4,24 +4,28 @@ Test that using a non-existent architecture name does not crash LLDB. from __future__ import print_function - import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class NoSuchArchTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - def test (self): + def test(self): self.build() - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") - # Check that passing an invalid arch via the command-line fails but doesn't crash - self.expect("target crete --arch nothingtoseehere %s" % (exe), error=True) + # Check that passing an invalid arch via the command-line fails but + # doesn't crash + self.expect( + "target crete --arch nothingtoseehere %s" % + (exe), error=True) - # Check that passing an invalid arch via the SB API fails but doesn't crash - target = self.dbg.CreateTargetWithFileAndArch(exe,"nothingtoseehere") + # Check that passing an invalid arch via the SB API fails but doesn't + # crash + target = self.dbg.CreateTargetWithFileAndArch(exe, "nothingtoseehere") self.assertFalse(target.IsValid(), "This target should not be valid") # Now just create the target with the default arch and check it's fine diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py b/lldb/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py index 0fdc43bb9fe..93eac1ecd10 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py @@ -7,7 +7,6 @@ foreign-architecture object files. from __future__ import print_function - import os.path import re @@ -16,6 +15,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestImageListMultiArchitecture(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -35,7 +35,11 @@ class TestImageListMultiArchitecture(TestBase): } for image_name in images: - file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), "bin", image_name)) + file_name = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + "bin", + image_name)) expected_triple_and_arch_regex = images[image_name] self.runCmd("file {}".format(file_name)) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py b/lldb/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py index db577dc5bac..7fc9a743d32 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py @@ -4,7 +4,6 @@ Test some lldb command abbreviations. from __future__ import print_function - import lldb import os import time @@ -12,25 +11,26 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestPaths(TestBase): mydir = TestBase.compute_mydir(__file__) @no_debug_info_test - def test_paths (self): + def test_paths(self): '''Test to make sure no file names are set in the lldb.SBFileSpec objects returned by lldb.SBHostOS.GetLLDBPath() for paths that are directories''' - dir_path_types = [lldb.ePathTypeLLDBShlibDir, - lldb.ePathTypeSupportExecutableDir, - lldb.ePathTypeHeaderDir, - lldb.ePathTypePythonDir, - lldb.ePathTypeLLDBSystemPlugins, - lldb.ePathTypeLLDBUserPlugins, - lldb.ePathTypeLLDBTempSystemDir] - + dir_path_types = [lldb.ePathTypeLLDBShlibDir, + lldb.ePathTypeSupportExecutableDir, + lldb.ePathTypeHeaderDir, + lldb.ePathTypePythonDir, + lldb.ePathTypeLLDBSystemPlugins, + lldb.ePathTypeLLDBUserPlugins, + lldb.ePathTypeLLDBTempSystemDir] + for path_type in dir_path_types: - f = lldb.SBHostOS.GetLLDBPath(path_type); + f = lldb.SBHostOS.GetLLDBPath(path_type) # No directory path types should have the filename set - self.assertTrue (f.GetFilename() == None); + self.assertTrue(f.GetFilename() is None) @no_debug_info_test def test_directory_doesnt_end_with_slash(self): @@ -41,9 +41,12 @@ class TestPaths(TestBase): @skipUnlessPlatform(["windows"]) @no_debug_info_test - def test_windows_double_slash (self): + def test_windows_double_slash(self): '''Test to check the path with double slash is handled correctly ''' # Create a path and see if lldb gets the directory and file right - fspec = lldb.SBFileSpec("C:\\dummy1\\dummy2//unknown_file", True); - self.assertEqual(os.path.normpath(fspec.GetDirectory()), os.path.normpath("C:/dummy1/dummy2")); - self.assertEqual(fspec.GetFilename(), "unknown_file"); + fspec = lldb.SBFileSpec("C:\\dummy1\\dummy2//unknown_file", True) + self.assertEqual( + os.path.normpath( + fspec.GetDirectory()), + os.path.normpath("C:/dummy1/dummy2")) + self.assertEqual(fspec.GetFilename(), "unknown_file") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py b/lldb/packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py index 9599f83d6a5..302201a9256 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py @@ -5,13 +5,14 @@ Test some lldb platform commands. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PlatformCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,45 +24,58 @@ class PlatformCommandTestCase(TestBase): @no_debug_info_test def test_list(self): self.expect("platform list", - patterns = ['^Available platforms:']) + patterns=['^Available platforms:']) @no_debug_info_test def test_process_list(self): self.expect("platform process list", - substrs = ['PID', 'TRIPLE', 'NAME']) + substrs=['PID', 'TRIPLE', 'NAME']) @no_debug_info_test def test_process_info_with_no_arg(self): """This is expected to fail and to return a proper error message.""" self.expect("platform process info", error=True, - substrs = ['one or more process id(s) must be specified']) + substrs=['one or more process id(s) must be specified']) @no_debug_info_test def test_status(self): - self.expect("platform status", - substrs = ['Platform', 'Triple', 'OS Version', 'Kernel', 'Hostname']) + self.expect( + "platform status", + substrs=[ + 'Platform', + 'Triple', + 'OS Version', + 'Kernel', + 'Hostname']) @no_debug_info_test def test_shell(self): """ Test that the platform shell command can invoke ls. """ triple = self.dbg.GetSelectedPlatform().GetTriple() if re.match(".*-.*-windows", triple): - self.expect("platform shell dir c:\\", substrs = ["Windows", "Program Files"]) + self.expect( + "platform shell dir c:\\", substrs=[ + "Windows", "Program Files"]) elif re.match(".*-.*-.*-android", triple): - self.expect("platform shell ls /", substrs = ["cache", "dev", "system"]) + self.expect( + "platform shell ls /", + substrs=[ + "cache", + "dev", + "system"]) else: - self.expect("platform shell ls /", substrs = ["dev", "tmp", "usr"]) + self.expect("platform shell ls /", substrs=["dev", "tmp", "usr"]) @no_debug_info_test def test_shell_builtin(self): """ Test a shell built-in command (echo) """ self.expect("platform shell echo hello lldb", - substrs = ["hello lldb"]) + substrs=["hello lldb"]) - #FIXME: re-enable once platform shell -t can specify the desired timeout + # FIXME: re-enable once platform shell -t can specify the desired timeout @no_debug_info_test def test_shell_timeout(self): """ Test a shell built-in command (sleep) that times out """ self.skipTest("due to taking too long to complete.") - self.expect("platform shell sleep 15", error=True, - substrs = ["error: timed out waiting for shell command to complete"]) + self.expect("platform shell sleep 15", error=True, substrs=[ + "error: timed out waiting for shell command to complete"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py index 619ed7afe32..9341ff97e6f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py @@ -5,20 +5,23 @@ Test that plugins that load commands work correctly. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class PluginCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIfNoSBHeaders - @skipIfHostIncompatibleWithRemote # Requires a compatible arch and platform to link against the host's built lldb lib. + # Requires a compatible arch and platform to link against the host's built + # lldb lib. + @skipIfHostIncompatibleWithRemote @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") @no_debug_info_test def test_load_plugin(self): @@ -37,23 +40,26 @@ class PluginCommandTestCase(TestBase): retobj = lldb.SBCommandReturnObject() - retval = debugger.GetCommandInterpreter().HandleCommand("plugin load %s" % plugin_lib_name, retobj) + retval = debugger.GetCommandInterpreter().HandleCommand( + "plugin load %s" % plugin_lib_name, retobj) retobj.Clear() - retval = debugger.GetCommandInterpreter().HandleCommand("plugin_loaded_command child abc def ghi",retobj) + retval = debugger.GetCommandInterpreter().HandleCommand( + "plugin_loaded_command child abc def ghi", retobj) if self.TraceOn(): print(retobj.GetOutput()) - self.expect(retobj,substrs = ['abc def ghi'], exe=False) + self.expect(retobj, substrs=['abc def ghi'], exe=False) retobj.Clear() # check that abbreviations work correctly in plugin commands. - retval = debugger.GetCommandInterpreter().HandleCommand("plugin_loaded_ ch abc def ghi",retobj) + retval = debugger.GetCommandInterpreter().HandleCommand( + "plugin_loaded_ ch abc def ghi", retobj) if self.TraceOn(): print(retobj.GetOutput()) - self.expect(retobj,substrs = ['abc def ghi'], exe=False) + self.expect(retobj, substrs=['abc def ghi'], exe=False) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py index ebd96d9d4c0..9a5d320dce5 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py @@ -5,13 +5,14 @@ Test that the Python operating system plugin works correctly from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class PluginPythonOSPlugin(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -31,9 +32,11 @@ class PluginPythonOSPlugin(TestBase): registers = frame.GetRegisters().GetValueAtIndex(0) reg_value = thread.GetThreadID() + 1 for reg in registers: - self.assertTrue(reg.GetValueAsUnsigned() == reg_value, "Verify the registers contains the correct value") + self.assertTrue( + reg.GetValueAsUnsigned() == reg_value, + "Verify the registers contains the correct value") reg_value = reg_value + 1 - + def run_python_os_funcionality(self): """Test that the Python operating system plugin works correctly""" @@ -47,52 +50,76 @@ class PluginPythonOSPlugin(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - # Set breakpoints inside and outside methods that take pointers to the containing struct. - lldbutil.run_break_set_by_source_regexp (self, "// Set breakpoint here") + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. + lldbutil.run_break_set_by_source_regexp(self, "// Set breakpoint here") - # Register our shared libraries for remote targets so they get automatically uploaded + # Register our shared libraries for remote targets so they get + # automatically uploaded arguments = None - environment = None + environment = None # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (arguments, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - # Make sure there are no OS plug-in created thread when we first stop at our breakpoint in main - thread = process.GetThreadByID(0x111111111); - self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x111111111 before we load the python OS plug-in"); - thread = process.GetThreadByID(0x222222222); - self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x222222222 before we load the python OS plug-in"); - thread = process.GetThreadByID(0x333333333); - self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x333333333 before we load the python OS plug-in"); - + # Make sure there are no OS plug-in created thread when we first stop + # at our breakpoint in main + thread = process.GetThreadByID(0x111111111) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x111111111 before we load the python OS plug-in") + thread = process.GetThreadByID(0x222222222) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x222222222 before we load the python OS plug-in") + thread = process.GetThreadByID(0x333333333) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x333333333 before we load the python OS plug-in") # Now load the python OS plug-in which should update the thread list and we should have - # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, 0x333333333 + # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, + # 0x333333333 command = "settings set target.process.python-os-plugin-path '%s'" % python_os_plugin_path self.dbg.HandleCommand(command) # Verify our OS plug-in threads showed up - thread = process.GetThreadByID(0x111111111); - self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x111111111 after we load the python OS plug-in"); + thread = process.GetThreadByID(0x111111111) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x111111111 after we load the python OS plug-in") self.verify_os_thread_registers(thread) - thread = process.GetThreadByID(0x222222222); - self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x222222222 after we load the python OS plug-in"); + thread = process.GetThreadByID(0x222222222) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x222222222 after we load the python OS plug-in") self.verify_os_thread_registers(thread) - thread = process.GetThreadByID(0x333333333); - self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x333333333 after we load the python OS plug-in"); + thread = process.GetThreadByID(0x333333333) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x333333333 after we load the python OS plug-in") self.verify_os_thread_registers(thread) - - # Now clear the OS plug-in path to make the OS plug-in created threads dissappear - self.dbg.HandleCommand("settings clear target.process.python-os-plugin-path") - + + # Now clear the OS plug-in path to make the OS plug-in created threads + # dissappear + self.dbg.HandleCommand( + "settings clear target.process.python-os-plugin-path") + # Verify the threads are gone after unloading the python OS plug-in - thread = process.GetThreadByID(0x111111111); - self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x111111111 after we unload the python OS plug-in"); - thread = process.GetThreadByID(0x222222222); - self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x222222222 after we unload the python OS plug-in"); - thread = process.GetThreadByID(0x333333333); - self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x333333333 after we unload the python OS plug-in"); + thread = process.GetThreadByID(0x111111111) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x111111111 after we unload the python OS plug-in") + thread = process.GetThreadByID(0x222222222) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x222222222 after we unload the python OS plug-in") + thread = process.GetThreadByID(0x333333333) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x333333333 after we unload the python OS plug-in") def run_python_os_step(self): """Test that the Python operating system plugin works correctly and allows single stepping of a virtual thread that is backed by a real thread""" @@ -107,44 +134,64 @@ class PluginPythonOSPlugin(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - # Set breakpoints inside and outside methods that take pointers to the containing struct. - lldbutil.run_break_set_by_source_regexp (self, "// Set breakpoint here") + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. + lldbutil.run_break_set_by_source_regexp(self, "// Set breakpoint here") - # Register our shared libraries for remote targets so they get automatically uploaded + # Register our shared libraries for remote targets so they get + # automatically uploaded arguments = None - environment = None + environment = None # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (arguments, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - # Make sure there are no OS plug-in created thread when we first stop at our breakpoint in main - thread = process.GetThreadByID(0x111111111); - self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x111111111 before we load the python OS plug-in"); - + # Make sure there are no OS plug-in created thread when we first stop + # at our breakpoint in main + thread = process.GetThreadByID(0x111111111) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x111111111 before we load the python OS plug-in") # Now load the python OS plug-in which should update the thread list and we should have - # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, 0x333333333 + # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, + # 0x333333333 command = "settings set target.process.python-os-plugin-path '%s'" % python_os_plugin_path self.dbg.HandleCommand(command) # Verify our OS plug-in threads showed up - thread = process.GetThreadByID(0x111111111); - self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x111111111 after we load the python OS plug-in"); + thread = process.GetThreadByID(0x111111111) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x111111111 after we load the python OS plug-in") frame = thread.GetFrameAtIndex(0) - self.assertTrue(frame.IsValid(), "Make sure we get a frame from thread 0x111111111") + self.assertTrue( + frame.IsValid(), + "Make sure we get a frame from thread 0x111111111") line_entry = frame.GetLineEntry() - self.assertTrue(line_entry.GetFileSpec().GetFilename() == 'main.c', "Make sure we stopped on line 5 in main.c") - self.assertTrue(line_entry.GetLine() == 5, "Make sure we stopped on line 5 in main.c") + self.assertTrue( + line_entry.GetFileSpec().GetFilename() == 'main.c', + "Make sure we stopped on line 5 in main.c") + self.assertTrue( + line_entry.GetLine() == 5, + "Make sure we stopped on line 5 in main.c") - # Now single step thread 0x111111111 and make sure it does what we need it to + # Now single step thread 0x111111111 and make sure it does what we need + # it to thread.StepOver() - + frame = thread.GetFrameAtIndex(0) - self.assertTrue(frame.IsValid(), "Make sure we get a frame from thread 0x111111111") + self.assertTrue( + frame.IsValid(), + "Make sure we get a frame from thread 0x111111111") line_entry = frame.GetLineEntry() - - self.assertTrue(line_entry.GetFileSpec().GetFilename() == 'main.c', "Make sure we stepped from line 5 to line 6 in main.c") - self.assertTrue(line_entry.GetLine() == 6, "Make sure we stepped from line 5 to line 6 in main.c") + + self.assertTrue( + line_entry.GetFileSpec().GetFilename() == 'main.c', + "Make sure we stepped from line 5 to line 6 in main.c") + self.assertTrue(line_entry.GetLine() == 6, + "Make sure we stepped from line 5 to line 6 in main.c") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py index 536092e40b3..394c24b4a88 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py @@ -3,21 +3,22 @@ import lldb import struct + class OperatingSystemPlugIn(object): """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class""" - + def __init__(self, process): '''Initialization needs a valid.SBProcess object. - + This plug-in will get created after a live process is valid and has stopped for the first time.''' self.process = None self.registers = None self.threads = None - if type(process) is lldb.SBProcess and process.IsValid(): + if isinstance(process, lldb.SBProcess) and process.IsValid(): self.process = process - self.threads = None # Will be an dictionary containing info for each thread - + self.threads = None # Will be an dictionary containing info for each thread + def get_target(self): # NOTE: Don't use "lldb.target" when trying to get your target as the "lldb.target" # tracks the current target in the LLDB command interpreter which isn't the @@ -26,11 +27,16 @@ class OperatingSystemPlugIn(object): def create_thread(self, tid, context): if tid == 0x444444444: - thread_info = { 'tid' : tid, 'name' : 'four' , 'queue' : 'queue4', 'state' : 'stopped', 'stop_reason' : 'none' } + thread_info = { + 'tid': tid, + 'name': 'four', + 'queue': 'queue4', + 'state': 'stopped', + 'stop_reason': 'none'} self.threads.append(thread_info) return thread_info return None - + def get_thread_info(self): if not self.threads: # The sample dictionary below shows the values that can be returned for a thread @@ -48,43 +54,75 @@ class OperatingSystemPlugIn(object): # Specifying this key/value pair for a thread will avoid a call to get_register_data() # and can be used when your registers are in a thread context structure that is contiguous # in memory. Don't specify this if your register layout in memory doesn't match the layout - # described by the dictionary returned from a call to the get_register_info() method. - self.threads = [ - { 'tid' : 0x111111111, 'name' : 'one' , 'queue' : 'queue1', 'state' : 'stopped', 'stop_reason' : 'breakpoint'}, - { 'tid' : 0x222222222, 'name' : 'two' , 'queue' : 'queue2', 'state' : 'stopped', 'stop_reason' : 'none' }, - { 'tid' : 0x333333333, 'name' : 'three', 'queue' : 'queue3', 'state' : 'stopped', 'stop_reason' : 'trace' } - ] + # described by the dictionary returned from a call to the + # get_register_info() method. + self.threads = [{'tid': 0x111111111, + 'name': 'one', + 'queue': 'queue1', + 'state': 'stopped', + 'stop_reason': 'breakpoint'}, + {'tid': 0x222222222, + 'name': 'two', + 'queue': 'queue2', + 'state': 'stopped', + 'stop_reason': 'none'}, + {'tid': 0x333333333, + 'name': 'three', + 'queue': 'queue3', + 'state': 'stopped', + 'stop_reason': 'trace'}] return self.threads - + def get_register_info(self): - if self.registers == None: - self.registers = dict() + if self.registers is None: + self.registers = dict() self.registers['sets'] = ['GPR'] self.registers['registers'] = [ - { 'name':'rax' , 'bitsize' : 64, 'offset' : 0, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 0, 'dwarf' : 0}, - { 'name':'rbx' , 'bitsize' : 64, 'offset' : 8, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 3, 'dwarf' : 3}, - { 'name':'rcx' , 'bitsize' : 64, 'offset' : 16, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 2, 'dwarf' : 2, 'generic':'arg4', 'alt-name':'arg4', }, - { 'name':'rdx' , 'bitsize' : 64, 'offset' : 24, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 1, 'dwarf' : 1, 'generic':'arg3', 'alt-name':'arg3', }, - { 'name':'rdi' , 'bitsize' : 64, 'offset' : 32, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 5, 'dwarf' : 5, 'generic':'arg1', 'alt-name':'arg1', }, - { 'name':'rsi' , 'bitsize' : 64, 'offset' : 40, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 4, 'dwarf' : 4, 'generic':'arg2', 'alt-name':'arg2', }, - { 'name':'rbp' , 'bitsize' : 64, 'offset' : 48, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 6, 'dwarf' : 6, 'generic':'fp' , 'alt-name':'fp', }, - { 'name':'rsp' , 'bitsize' : 64, 'offset' : 56, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 7, 'dwarf' : 7, 'generic':'sp' , 'alt-name':'sp', }, - { 'name':'r8' , 'bitsize' : 64, 'offset' : 64, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 8, 'dwarf' : 8, 'generic':'arg5', 'alt-name':'arg5', }, - { 'name':'r9' , 'bitsize' : 64, 'offset' : 72, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 9, 'dwarf' : 9, 'generic':'arg6', 'alt-name':'arg6', }, - { 'name':'r10' , 'bitsize' : 64, 'offset' : 80, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 10, 'dwarf' : 10}, - { 'name':'r11' , 'bitsize' : 64, 'offset' : 88, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 11, 'dwarf' : 11}, - { 'name':'r12' , 'bitsize' : 64, 'offset' : 96, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 12, 'dwarf' : 12}, - { 'name':'r13' , 'bitsize' : 64, 'offset' : 104, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 13, 'dwarf' : 13}, - { 'name':'r14' , 'bitsize' : 64, 'offset' : 112, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 14, 'dwarf' : 14}, - { 'name':'r15' , 'bitsize' : 64, 'offset' : 120, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 15, 'dwarf' : 15}, - { 'name':'rip' , 'bitsize' : 64, 'offset' : 128, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 16, 'dwarf' : 16, 'generic':'pc', 'alt-name':'pc' }, - { 'name':'rflags' , 'bitsize' : 64, 'offset' : 136, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'generic':'flags', 'alt-name':'flags' }, - { 'name':'cs' , 'bitsize' : 64, 'offset' : 144, 'encoding':'uint' , 'format':'hex' , 'set': 0 }, - { 'name':'fs' , 'bitsize' : 64, 'offset' : 152, 'encoding':'uint' , 'format':'hex' , 'set': 0 }, - { 'name':'gs' , 'bitsize' : 64, 'offset' : 160, 'encoding':'uint' , 'format':'hex' , 'set': 0 }, - ] + {'name': 'rax', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0}, + {'name': 'rbx', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3}, + {'name': 'rcx', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg4', 'alt-name': 'arg4', }, + {'name': 'rdx', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg3', 'alt-name': 'arg3', }, + {'name': 'rdi', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg1', 'alt-name': 'arg1', }, + {'name': 'rsi', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg2', 'alt-name': 'arg2', }, + {'name': 'rbp', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'fp', 'alt-name': 'fp', }, + {'name': 'rsp', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'sp', 'alt-name': 'sp', }, + {'name': 'r8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8, 'generic': 'arg5', 'alt-name': 'arg5', }, + {'name': 'r9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9, 'generic': 'arg6', 'alt-name': 'arg6', }, + {'name': 'r10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10}, + {'name': 'r11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11}, + {'name': 'r12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12}, + {'name': 'r13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13}, + {'name': 'r14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14}, + {'name': 'r15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15}, + {'name': 'rip', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16, 'generic': 'pc', 'alt-name': 'pc'}, + {'name': 'rflags', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'generic': 'flags', 'alt-name': 'flags'}, + {'name': 'cs', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'fs', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'gs', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + ] return self.registers - + def get_register_data(self, tid): - return struct.pack('21Q',tid + 1,tid + 2,tid + 3,tid + 4,tid + 5,tid + 6,tid + 7,tid + 8,tid + 9,tid + 10,tid + 11,tid + 12,tid + 13,tid + 14,tid + 15,tid + 16,tid + 17,tid + 18,tid + 19,tid + 20,tid + 21); - + return struct.pack( + '21Q', + tid + 1, + tid + 2, + tid + 3, + tid + 4, + tid + 5, + tid + 6, + tid + 7, + tid + 8, + tid + 9, + tid + 10, + tid + 11, + tid + 12, + tid + 13, + tid + 14, + tid + 15, + tid + 16, + tid + 17, + tid + 18, + tid + 19, + tid + 20, + tid + 21) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py index 7a9435d44ed..438538ca922 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py @@ -3,21 +3,22 @@ import lldb import struct + class OperatingSystemPlugIn(object): """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class""" - + def __init__(self, process): '''Initialization needs a valid.SBProcess object. - + This plug-in will get created after a live process is valid and has stopped for the first time.''' self.process = None self.registers = None self.threads = None - if type(process) is lldb.SBProcess and process.IsValid(): + if isinstance(process, lldb.SBProcess) and process.IsValid(): self.process = process - self.threads = None # Will be an dictionary containing info for each thread - + self.threads = None # Will be an dictionary containing info for each thread + def get_target(self): # NOTE: Don't use "lldb.target" when trying to get your target as the "lldb.target" # tracks the current target in the LLDB command interpreter which isn't the @@ -26,11 +27,16 @@ class OperatingSystemPlugIn(object): def create_thread(self, tid, context): if tid == 0x444444444: - thread_info = { 'tid' : tid, 'name' : 'four' , 'queue' : 'queue4', 'state' : 'stopped', 'stop_reason' : 'none' } + thread_info = { + 'tid': tid, + 'name': 'four', + 'queue': 'queue4', + 'state': 'stopped', + 'stop_reason': 'none'} self.threads.append(thread_info) return thread_info return None - + def get_thread_info(self): if not self.threads: # The sample dictionary below shows the values that can be returned for a thread @@ -48,41 +54,63 @@ class OperatingSystemPlugIn(object): # Specifying this key/value pair for a thread will avoid a call to get_register_data() # and can be used when your registers are in a thread context structure that is contiguous # in memory. Don't specify this if your register layout in memory doesn't match the layout - # described by the dictionary returned from a call to the get_register_info() method. + # described by the dictionary returned from a call to the + # get_register_info() method. self.threads = [ - { 'tid' : 0x111111111, 'core' : 0 } - ] + {'tid': 0x111111111, 'core': 0} + ] return self.threads - + def get_register_info(self): - if self.registers == None: - self.registers = dict() + if self.registers is None: + self.registers = dict() self.registers['sets'] = ['GPR'] self.registers['registers'] = [ - { 'name':'rax' , 'bitsize' : 64, 'offset' : 0, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 0, 'dwarf' : 0}, - { 'name':'rbx' , 'bitsize' : 64, 'offset' : 8, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 3, 'dwarf' : 3}, - { 'name':'rcx' , 'bitsize' : 64, 'offset' : 16, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 2, 'dwarf' : 2, 'generic':'arg4', 'alt-name':'arg4', }, - { 'name':'rdx' , 'bitsize' : 64, 'offset' : 24, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 1, 'dwarf' : 1, 'generic':'arg3', 'alt-name':'arg3', }, - { 'name':'rdi' , 'bitsize' : 64, 'offset' : 32, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 5, 'dwarf' : 5, 'generic':'arg1', 'alt-name':'arg1', }, - { 'name':'rsi' , 'bitsize' : 64, 'offset' : 40, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 4, 'dwarf' : 4, 'generic':'arg2', 'alt-name':'arg2', }, - { 'name':'rbp' , 'bitsize' : 64, 'offset' : 48, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 6, 'dwarf' : 6, 'generic':'fp' , 'alt-name':'fp', }, - { 'name':'rsp' , 'bitsize' : 64, 'offset' : 56, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 7, 'dwarf' : 7, 'generic':'sp' , 'alt-name':'sp', }, - { 'name':'r8' , 'bitsize' : 64, 'offset' : 64, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 8, 'dwarf' : 8, 'generic':'arg5', 'alt-name':'arg5', }, - { 'name':'r9' , 'bitsize' : 64, 'offset' : 72, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 9, 'dwarf' : 9, 'generic':'arg6', 'alt-name':'arg6', }, - { 'name':'r10' , 'bitsize' : 64, 'offset' : 80, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 10, 'dwarf' : 10}, - { 'name':'r11' , 'bitsize' : 64, 'offset' : 88, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 11, 'dwarf' : 11}, - { 'name':'r12' , 'bitsize' : 64, 'offset' : 96, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 12, 'dwarf' : 12}, - { 'name':'r13' , 'bitsize' : 64, 'offset' : 104, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 13, 'dwarf' : 13}, - { 'name':'r14' , 'bitsize' : 64, 'offset' : 112, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 14, 'dwarf' : 14}, - { 'name':'r15' , 'bitsize' : 64, 'offset' : 120, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 15, 'dwarf' : 15}, - { 'name':'rip' , 'bitsize' : 64, 'offset' : 128, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 16, 'dwarf' : 16, 'generic':'pc', 'alt-name':'pc' }, - { 'name':'rflags' , 'bitsize' : 64, 'offset' : 136, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'generic':'flags', 'alt-name':'flags' }, - { 'name':'cs' , 'bitsize' : 64, 'offset' : 144, 'encoding':'uint' , 'format':'hex' , 'set': 0 }, - { 'name':'fs' , 'bitsize' : 64, 'offset' : 152, 'encoding':'uint' , 'format':'hex' , 'set': 0 }, - { 'name':'gs' , 'bitsize' : 64, 'offset' : 160, 'encoding':'uint' , 'format':'hex' , 'set': 0 }, - ] + {'name': 'rax', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0}, + {'name': 'rbx', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3}, + {'name': 'rcx', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg4', 'alt-name': 'arg4', }, + {'name': 'rdx', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg3', 'alt-name': 'arg3', }, + {'name': 'rdi', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg1', 'alt-name': 'arg1', }, + {'name': 'rsi', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg2', 'alt-name': 'arg2', }, + {'name': 'rbp', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'fp', 'alt-name': 'fp', }, + {'name': 'rsp', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'sp', 'alt-name': 'sp', }, + {'name': 'r8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8, 'generic': 'arg5', 'alt-name': 'arg5', }, + {'name': 'r9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9, 'generic': 'arg6', 'alt-name': 'arg6', }, + {'name': 'r10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10}, + {'name': 'r11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11}, + {'name': 'r12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12}, + {'name': 'r13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13}, + {'name': 'r14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14}, + {'name': 'r15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15}, + {'name': 'rip', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16, 'generic': 'pc', 'alt-name': 'pc'}, + {'name': 'rflags', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'generic': 'flags', 'alt-name': 'flags'}, + {'name': 'cs', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'fs', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'gs', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + ] return self.registers - + def get_register_data(self, tid): - return struct.pack('21Q',tid + 1,tid + 2,tid + 3,tid + 4,tid + 5,tid + 6,tid + 7,tid + 8,tid + 9,tid + 10,tid + 11,tid + 12,tid + 13,tid + 14,tid + 15,tid + 16,tid + 17,tid + 18,tid + 19,tid + 20,tid + 21); - + return struct.pack( + '21Q', + tid + 1, + tid + 2, + tid + 3, + tid + 4, + tid + 5, + tid + 6, + tid + 7, + tid + 8, + tid + 9, + tid + 10, + tid + 11, + tid + 12, + tid + 13, + tid + 14, + tid + 15, + tid + 16, + tid + 17, + tid + 18, + tid + 19, + tid + 20, + tid + 21) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/linux-core/TestLinuxCore.py b/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/linux-core/TestLinuxCore.py index 3c650639aeb..197a0378d99 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/linux-core/TestLinuxCore.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/linux-core/TestLinuxCore.py @@ -12,18 +12,19 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LinuxCoreTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True mydir = TestBase.compute_mydir(__file__) - _i386_pid = 32306 + _i386_pid = 32306 _x86_64_pid = 32259 - _s390x_pid = 1045 + _s390x_pid = 1045 - _i386_regions = 4 + _i386_regions = 4 _x86_64_regions = 5 - _s390x_regions = 2 + _s390x_regions = 2 def test_i386(self): """Test that lldb can read the process information from an i386 linux core file.""" @@ -33,8 +34,9 @@ class LinuxCoreTestCase(TestBase): """Test that lldb can read the process information from an x86_64 linux core file.""" self.do_test("x86_64", self._x86_64_pid, self._x86_64_regions) - # This seems to hang on non-s390x platforms for some reason. Disabling for now. - @skipIf(archs=no_match(['s390x'])) + # This seems to hang on non-s390x platforms for some reason. Disabling + # for now. + @skipIf(archs=no_match(['s390x'])) def test_s390x(self): """Test that lldb can read the process information from an s390x linux core file.""" self.do_test("s390x", self._s390x_pid, self._s390x_regions) @@ -43,7 +45,7 @@ class LinuxCoreTestCase(TestBase): """Test that we read the information from the core correctly even if we have a running process with the same PID around""" try: - shutil.copyfile("x86_64.out", "x86_64-pid.out") + shutil.copyfile("x86_64.out", "x86_64-pid.out") shutil.copyfile("x86_64.core", "x86_64-pid.core") with open("x86_64-pid.core", "r+b") as f: # These are offsets into the NT_PRSTATUS and NT_PRPSINFO structures in the note @@ -51,9 +53,14 @@ class LinuxCoreTestCase(TestBase): # as well. (Notes can be viewed with readelf --notes.) for pid_offset in [0x1c4, 0x320]: f.seek(pid_offset) - self.assertEqual(struct.unpack("<I", f.read(4))[0], self._x86_64_pid) - - # We insert our own pid, and make sure the test still works. + self.assertEqual( + struct.unpack( + "<I", + f.read(4))[0], + self._x86_64_pid) + + # We insert our own pid, and make sure the test still + # works. f.seek(pid_offset) f.write(struct.pack("<I", os.getpid())) self.do_test("x86_64-pid", os.getpid(), self._x86_64_regions) @@ -72,10 +79,15 @@ class LinuxCoreTestCase(TestBase): altframe = altprocess.GetSelectedThread().GetFrameAtIndex(0) self.assertEqual(altframe.GetFunctionName(), "_start") - self.assertEqual(altframe.GetLineEntry().GetLine(), line_number("altmain.c", "Frame _start")) + self.assertEqual( + altframe.GetLineEntry().GetLine(), + line_number( + "altmain.c", + "Frame _start")) error = lldb.SBError() - F = altprocess.ReadCStringFromMemory(altframe.FindVariable("F").GetValueAsUnsigned(), 256, error) + F = altprocess.ReadCStringFromMemory( + altframe.FindVariable("F").GetValueAsUnsigned(), 256, error) self.assertTrue(error.Success()) self.assertEqual(F, "_start") @@ -90,33 +102,40 @@ class LinuxCoreTestCase(TestBase): region = lldb.SBMemoryRegionInfo() # Check we have the right number of regions. - self.assertEqual(region_list.GetSize(), region_count); + self.assertEqual(region_list.GetSize(), region_count) # Check that getting a region beyond the last in the list fails. - self.assertFalse(region_list.GetMemoryRegionAtIndex(region_count, region)); + self.assertFalse( + region_list.GetMemoryRegionAtIndex( + region_count, region)) # Check each region is valid. for i in range(region_list.GetSize()): # Check we can actually get this region. self.assertTrue(region_list.GetMemoryRegionAtIndex(i, region)) - #Every region in the list should be mapped. + # Every region in the list should be mapped. self.assertTrue(region.IsMapped()) - # Test the address at the start of a region returns it's enclosing region. + # Test the address at the start of a region returns it's enclosing + # region. begin_address = region.GetRegionBase() region_at_begin = lldb.SBMemoryRegionInfo() error = process.GetMemoryRegionInfo(begin_address, region_at_begin) self.assertEqual(region, region_at_begin) - # Test an address in the middle of a region returns it's enclosing region. - middle_address = (region.GetRegionBase() + region.GetRegionEnd()) / 2l + # Test an address in the middle of a region returns it's enclosing + # region. + middle_address = (region.GetRegionBase() + + region.GetRegionEnd()) / 2 region_at_middle = lldb.SBMemoryRegionInfo() - error = process.GetMemoryRegionInfo(middle_address, region_at_middle) + error = process.GetMemoryRegionInfo( + middle_address, region_at_middle) self.assertEqual(region, region_at_middle) - # Test the address at the end of a region returns it's enclosing region. - end_address = region.GetRegionEnd() - 1l + # Test the address at the end of a region returns it's enclosing + # region. + end_address = region.GetRegionEnd() - 1 region_at_end = lldb.SBMemoryRegionInfo() error = process.GetMemoryRegionInfo(end_address, region_at_end) self.assertEqual(region, region_at_end) @@ -124,18 +143,24 @@ class LinuxCoreTestCase(TestBase): # Check that quering the end address does not return this region but # the next one. next_region = lldb.SBMemoryRegionInfo() - error = process.GetMemoryRegionInfo(region.GetRegionEnd(), next_region) + error = process.GetMemoryRegionInfo( + region.GetRegionEnd(), next_region) self.assertNotEqual(region, next_region) - self.assertEqual(region.GetRegionEnd(), next_region.GetRegionBase()) + self.assertEqual( + region.GetRegionEnd(), + next_region.GetRegionBase()) # Check that query beyond the last region returns an unmapped region # that ends at LLDB_INVALID_ADDRESS last_region = lldb.SBMemoryRegionInfo() region_list.GetMemoryRegionAtIndex(region_count - 1, last_region) end_region = lldb.SBMemoryRegionInfo() - error = process.GetMemoryRegionInfo(last_region.GetRegionEnd(), end_region) + error = process.GetMemoryRegionInfo( + last_region.GetRegionEnd(), end_region) self.assertFalse(end_region.IsMapped()) - self.assertEqual(last_region.GetRegionEnd(), end_region.GetRegionBase()) + self.assertEqual( + last_region.GetRegionEnd(), + end_region.GetRegionBase()) self.assertEqual(end_region.GetRegionEnd(), lldb.LLDB_INVALID_ADDRESS) def do_test(self, filename, pid, region_count): @@ -155,8 +180,10 @@ class LinuxCoreTestCase(TestBase): self.assertTrue(frame) self.assertEqual(frame.GetFunctionName(), backtrace[i]) self.assertEqual(frame.GetLineEntry().GetLine(), - line_number("main.c", "Frame " + backtrace[i])) - self.assertEqual(frame.FindVariable("F").GetValueAsUnsigned(), ord(backtrace[i][0])) + line_number("main.c", "Frame " + backtrace[i])) + self.assertEqual( + frame.FindVariable("F").GetValueAsUnsigned(), ord( + backtrace[i][0])) self.check_memory_regions(process, region_count) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py b/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py index 89d1974b670..8c375f7d862 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py @@ -11,6 +11,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiniDumpTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -35,12 +36,13 @@ class MiniDumpTestCase(TestBase): self.dbg.CreateTarget("") self.target = self.dbg.GetSelectedTarget() self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp") - # This process crashed due to an access violation (0xc0000005) in its one and only thread. + # This process crashed due to an access violation (0xc0000005) in its + # one and only thread. self.assertEqual(self.process.GetNumThreads(), 1) thread = self.process.GetThreadAtIndex(0) self.assertEqual(thread.GetStopReason(), lldb.eStopReasonException) - stop_description = thread.GetStopDescription(256); - self.assertTrue("0xc0000005" in stop_description); + stop_description = thread.GetStopDescription(256) + self.assertTrue("0xc0000005" in stop_description) @skipUnlessWindows # for now mini-dump debugging is limited to Windows hosts @no_debug_info_test @@ -72,7 +74,8 @@ class MiniDumpTestCase(TestBase): # Set a breakpoint and capture a mini dump. target = self.dbg.CreateTarget(exe) breakpoint = target.BreakpointCreateByName("bar") - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertEqual(process.GetState(), lldb.eStateStopped) self.assertTrue(process.SaveCore(core)) self.assertTrue(os.path.isfile(core)) @@ -83,7 +86,7 @@ class MiniDumpTestCase(TestBase): process = target.LoadCore(core) thread = process.GetThreadAtIndex(0) - expected_stack = { 0: 'bar', 1: 'foo', 2: 'main' } + expected_stack = {0: 'bar', 1: 'foo', 2: 'main'} self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack)) for index, name in iteritems(expected_stack): frame = thread.GetFrameAtIndex(index) @@ -108,7 +111,8 @@ class MiniDumpTestCase(TestBase): # Set a breakpoint and capture a mini dump. target = self.dbg.CreateTarget(exe) breakpoint = target.BreakpointCreateByName("bar") - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertEqual(process.GetState(), lldb.eStateStopped) self.assertTrue(process.SaveCore(core)) self.assertTrue(os.path.isfile(core)) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/TestWow64MiniDump.py b/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/TestWow64MiniDump.py index 08debab538f..d68871a34fb 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/TestWow64MiniDump.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/TestWow64MiniDump.py @@ -16,6 +16,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class Wow64MiniDumpTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -66,7 +67,8 @@ class Wow64MiniDumpTestCase(TestBase): # In the dump, none of the threads are stopped, so we cannot use # lldbutil.get_stopped_thread. thread = process.GetThreadAtIndex(0) - # The crash is in main, so there should be at least one frame on the stack. + # The crash is in main, so there should be at least one frame on the + # stack. self.assertGreaterEqual(thread.GetNumFrames(), 1) frame = thread.GetFrameAtIndex(0) self.assertTrue(frame.IsValid()) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py b/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py index e4eb302d83d..6a366b69d93 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py @@ -5,8 +5,8 @@ Test process attach. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -14,6 +14,7 @@ from lldbsuite.test import lldbutil exe_name = "ProcessAttach" # Must match Makefile + class ProcessAttachTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py b/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py index 3d1d7fdc790..071f5d57c78 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py @@ -5,7 +5,6 @@ Test denied process attach. from __future__ import print_function - import os import time import lldb @@ -15,6 +14,7 @@ from lldbsuite.test import lldbutil exe_name = 'AttachDenied' # Must match Makefile + class AttachDeniedTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -28,8 +28,11 @@ class AttachDeniedTestCase(TestBase): # Use a file as a synchronization point between test and inferior. pid_file_path = lldbutil.append_to_process_working_directory( - "pid_file_%d" % (int(time.time()))) - self.addTearDownHook(lambda: self.run_platform_command("rm %s" % (pid_file_path))) + "pid_file_%d" % (int(time.time()))) + self.addTearDownHook( + lambda: self.run_platform_command( + "rm %s" % + (pid_file_path))) # Spawn a new process popen = self.spawnSubprocess(exe, [pid_file_path]) @@ -38,5 +41,5 @@ class AttachDeniedTestCase(TestBase): pid = lldbutil.wait_for_file_on_target(self, pid_file_path) self.expect('process attach -p ' + pid, - startstr = 'error: attach failed:', - error = True) + startstr='error: attach failed:', + error=True) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py b/lldb/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py index c20d66aa3ab..00b4d415340 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py @@ -3,7 +3,6 @@ from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * @@ -21,8 +20,8 @@ class ChangeProcessGroupTestCase(TestBase): # Find the line number to break for main.c. self.line = line_number('main.c', '// Set breakpoint here') - @skipIfFreeBSD # Times out on FreeBSD llvm.org/pr23731 - @skipIfWindows # setpgid call does not exist on Windows + @skipIfFreeBSD # Times out on FreeBSD llvm.org/pr23731 + @skipIfWindows # setpgid call does not exist on Windows @expectedFailureAndroid("http://llvm.org/pr23762", api_levels=[16]) def test_setpgid(self): self.build() @@ -30,8 +29,11 @@ class ChangeProcessGroupTestCase(TestBase): # Use a file as a synchronization point between test and inferior. pid_file_path = lldbutil.append_to_process_working_directory( - "pid_file_%d" % (int(time.time()))) - self.addTearDownHook(lambda: self.run_platform_command("rm %s" % (pid_file_path))) + "pid_file_%d" % (int(time.time()))) + self.addTearDownHook( + lambda: self.run_platform_command( + "rm %s" % + (pid_file_path))) popen = self.spawnSubprocess(exe, [pid_file_path]) self.addTearDownHook(self.cleanupSubprocesses) @@ -57,19 +59,20 @@ class ChangeProcessGroupTestCase(TestBase): self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # set a breakpoint just before the setpgid() call - lldbutil.run_break_set_by_file_and_line(self, 'main.c', self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, 'main.c', self.line, num_expected_locations=-1) thread = process.GetSelectedThread() # release the child from its loop value = thread.GetSelectedFrame().EvaluateExpression("release_child_flag = 1") - self.assertTrue(value.IsValid() and value.GetValueAsUnsigned(0) == 1); + self.assertTrue(value.IsValid() and value.GetValueAsUnsigned(0) == 1) process.Continue() # make sure the child's process group id is different from its pid value = thread.GetSelectedFrame().EvaluateExpression("(int)getpgid(0)") self.assertTrue(value.IsValid()) - self.assertNotEqual(value.GetValueAsUnsigned(0), int(pid)); + self.assertNotEqual(value.GetValueAsUnsigned(0), int(pid)) # step over the setpgid() call thread.StepOver() @@ -79,7 +82,7 @@ class ChangeProcessGroupTestCase(TestBase): # this also checks that we are still in full control of the child value = thread.GetSelectedFrame().EvaluateExpression("(int)getpgid(0)") self.assertTrue(value.IsValid()) - self.assertEqual(value.GetValueAsUnsigned(0), int(pid)); + self.assertEqual(value.GetValueAsUnsigned(0), int(pid)) # run to completion process.Continue() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py b/lldb/packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py index 5998edb3c7e..5929a352b61 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py @@ -15,6 +15,7 @@ from lldbsuite.test import lldbutil import six + class ProcessLaunchTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,12 +30,12 @@ class ProcessLaunchTestCase(TestBase): TestBase.tearDown(self) @not_remote_testsuite_ready - def test_io (self): + def test_io(self): """Test that process launch I/O redirection flags work properly.""" - self.build () - exe = os.path.join (os.getcwd(), "a.out") + self.build() + exe = os.path.join(os.getcwd(), "a.out") self.expect("file " + exe, - patterns = [ "Current executable set to .*a.out" ]) + patterns=["Current executable set to .*a.out"]) in_file = "input-file.txt" out_file = "output-test.out" @@ -42,23 +43,24 @@ class ProcessLaunchTestCase(TestBase): # Make sure the output files do not exist before launching the process try: - os.remove (out_file) + os.remove(out_file) except OSError: pass try: - os.remove (err_file) + os.remove(err_file) except OSError: pass - launch_command = "process launch -i " + in_file + " -o " + out_file + " -e " + err_file + launch_command = "process launch -i " + \ + in_file + " -o " + out_file + " -e " + err_file if lldb.remote_platform: self.runCmd('platform put-file "{local}" "{remote}"'.format( local=in_file, remote=in_file)) - self.expect (launch_command, - patterns = [ "Process .* launched: .*a.out" ]) + self.expect(launch_command, + patterns=["Process .* launched: .*a.out"]) if lldb.remote_platform: self.runCmd('platform get-file "{remote}" "{local}"'.format( @@ -71,33 +73,33 @@ class ProcessLaunchTestCase(TestBase): # Check to see if the 'stdout' file was created try: - out_f = open (out_file) + out_f = open(out_file) except IOError: success = False err_msg = err_msg + " ERROR: stdout file was not created.\n" else: # Check to see if the 'stdout' file contains the right output - line = out_f.readline (); + line = out_f.readline() if line != "This should go to stdout.\n": success = False err_msg = err_msg + " ERROR: stdout file does not contain correct output.\n" - out_f.close(); + out_f.close() # Try to delete the 'stdout' file try: - os.remove (out_file) + os.remove(out_file) except OSError: pass # Check to see if the 'stderr' file was created try: - err_f = open (err_file) + err_f = open(err_file) except IOError: success = False err_msg = err_msg + " ERROR: stderr file was not created.\n" else: # Check to see if the 'stderr' file contains the right output - line = err_f.readline () + line = err_f.readline() if line != "This should go to stderr.\n": success = False err_msg = err_msg + " ERROR: stderr file does not contain correct output.\n\ @@ -106,23 +108,24 @@ class ProcessLaunchTestCase(TestBase): # Try to delete the 'stderr' file try: - os.remove (err_file) + os.remove(err_file) except OSError: pass if not success: - self.fail (err_msg) + self.fail(err_msg) # rdar://problem/9056462 - # The process launch flag '-w' for setting the current working directory not working? + # The process launch flag '-w' for setting the current working directory + # not working? @not_remote_testsuite_ready @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20265") - def test_set_working_dir (self): + def test_set_working_dir(self): """Test that '-w dir' sets the working dir when running the inferior.""" - d = {'CXX_SOURCES' : 'print_cwd.cpp'} + d = {'CXX_SOURCES': 'print_cwd.cpp'} self.build(dictionary=d) self.setTearDownCleanup(d) - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe) mywd = 'my_working_dir' @@ -135,26 +138,26 @@ class ProcessLaunchTestCase(TestBase): # Make sure the output files do not exist before launching the process try: - os.remove (out_file_path) - os.remove (err_file_path) + os.remove(out_file_path) + os.remove(err_file_path) except OSError: pass # Check that we get an error when we have a nonexisting path - launch_command = "process launch -w %s -o %s -e %s" % (my_working_dir_path + 'z', - out_file_path, - err_file_path) + launch_command = "process launch -w %s -o %s -e %s" % ( + my_working_dir_path + 'z', out_file_path, err_file_path) - self.expect(launch_command, error=True, - patterns = ["error:.* No such file or directory: %sz" % my_working_dir_path]) + self.expect( + launch_command, error=True, patterns=[ + "error:.* No such file or directory: %sz" % + my_working_dir_path]) # Really launch the process - launch_command = "process launch -w %s -o %s -e %s" % (my_working_dir_path, - out_file_path, - err_file_path) + launch_command = "process launch -w %s -o %s -e %s" % ( + my_working_dir_path, out_file_path, err_file_path) self.expect(launch_command, - patterns = [ "Process .* launched: .*a.out" ]) + patterns=["Process .* launched: .*a.out"]) success = True err_msg = "" @@ -167,13 +170,13 @@ class ProcessLaunchTestCase(TestBase): err_msg = err_msg + "ERROR: stdout file was not created.\n" else: # Check to see if the 'stdout' file contains the right output - line = out_f.readline(); + line = out_f.readline() if self.TraceOn(): print("line:", line) if not re.search(mywd, line): success = False err_msg = err_msg + "The current working directory was not set correctly.\n" - out_f.close(); + out_f.close() # Try to delete the 'stdout' and 'stderr' files try: @@ -186,24 +189,31 @@ class ProcessLaunchTestCase(TestBase): if not success: self.fail(err_msg) - def test_environment_with_special_char (self): + def test_environment_with_special_char(self): """Test that environment variables containing '*' and '}' are handled correctly by the inferior.""" source = 'print_env.cpp' - d = {'CXX_SOURCES' : source} + d = {'CXX_SOURCES': source} self.build(dictionary=d) self.setTearDownCleanup(d) - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") evil_var = 'INIT*MIDDLE}TAIL' target = self.dbg.CreateTarget(exe) main_source_spec = lldb.SBFileSpec(source) - breakpoint = target.BreakpointCreateBySourceRegex('// Set breakpoint here.', main_source_spec) - - process = target.LaunchSimple(None, ['EVIL=' + evil_var], self.get_process_working_directory()) - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) - - threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint) + breakpoint = target.BreakpointCreateBySourceRegex( + '// Set breakpoint here.', main_source_spec) + + process = target.LaunchSimple(None, + ['EVIL=' + evil_var], + self.get_process_working_directory()) + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) self.assertEqual(len(threads), 1) frame = threads[0].GetFrameAtIndex(0) sbvalue = frame.EvaluateExpression("evil") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py b/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py index 1c01e2138c2..ee1f82b14f7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py @@ -4,12 +4,14 @@ Test saving a core file (or mini dump). from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ProcessSaveCoreTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,7 +24,8 @@ class ProcessSaveCoreTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") core = os.path.join(os.getcwd(), "core.dmp") target = self.dbg.CreateTarget(exe) - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertNotEqual(process.GetState(), lldb.eStateStopped) error = process.SaveCore(core) self.assertTrue(error.Fail()) @@ -37,7 +40,8 @@ class ProcessSaveCoreTestCase(TestBase): try: target = self.dbg.CreateTarget(exe) breakpoint = target.BreakpointCreateByName("bar") - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertEqual(process.GetState(), lldb.eStateStopped) self.assertTrue(process.SaveCore(core)) self.assertTrue(os.path.isfile(core)) @@ -47,8 +51,13 @@ class ProcessSaveCoreTestCase(TestBase): # the executable in the module list. target = self.dbg.CreateTarget(None) process = target.LoadCore(core) - files = [target.GetModuleAtIndex(i).GetFileSpec() for i in range(0, target.GetNumModules())] - paths = [os.path.join(f.GetDirectory(), f.GetFilename()) for f in files] + files = [ + target.GetModuleAtIndex(i).GetFileSpec() for i in range( + 0, target.GetNumModules())] + paths = [ + os.path.join( + f.GetDirectory(), + f.GetFilename()) for f in files] self.assertTrue(exe in paths) finally: @@ -56,5 +65,3 @@ class ProcessSaveCoreTestCase(TestBase): self.assertTrue(self.dbg.DeleteTarget(target)) if (os.path.isfile(core)): os.unlink(core) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/TestPtrRefs.py b/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/TestPtrRefs.py index 81db42d8e3c..5085b8cce99 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/TestPtrRefs.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/TestPtrRefs.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestPtrRefs(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,24 +21,29 @@ class TestPtrRefs(TestBase): self.build() exe_name = 'a.out' exe = os.path.join(os.getcwd(), exe_name) - + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - main_file_spec = lldb.SBFileSpec ('main.c') - breakpoint = target.BreakpointCreateBySourceRegex('break', main_file_spec) + main_file_spec = lldb.SBFileSpec('main.c') + breakpoint = target.BreakpointCreateBySourceRegex( + 'break', main_file_spec) self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1 and the break condition should hold. - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") - frame = thread.GetFrameAtIndex(0) + frame = thread.GetFrameAtIndex(0) self.dbg.HandleCommand("script import lldb.macosx.heap") - self.expect("ptr_refs my_ptr", substrs=["malloc", "stack"]); + self.expect("ptr_refs my_ptr", substrs=["malloc", "stack"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py b/lldb/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py index fcb493bc9d9..5b72d383f14 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py @@ -5,12 +5,13 @@ Test lldb data formatter subsystem. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class ValueObjectRecursionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,14 +27,15 @@ class ValueObjectRecursionTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -47,13 +49,21 @@ class ValueObjectRecursionTestCase(TestBase): root = self.frame().FindVariable("root") child = root.GetChildAtIndex(1) if self.TraceOn(): - print(root) - print(child) - for i in range(0,15000): - child = child.GetChildAtIndex(1) + print(root) + print(child) + for i in range(0, 15000): + child = child.GetChildAtIndex(1) if self.TraceOn(): - print(child) - self.assertTrue(child.IsValid(),"could not retrieve the deep ValueObject") - self.assertTrue(child.GetChildAtIndex(0).IsValid(),"the deep ValueObject has no value") - self.assertTrue(child.GetChildAtIndex(0).GetValueAsUnsigned() != 0,"the deep ValueObject has a zero value") - self.assertTrue(child.GetChildAtIndex(1).GetValueAsUnsigned() != 0, "the deep ValueObject has no next") + print(child) + self.assertTrue( + child.IsValid(), + "could not retrieve the deep ValueObject") + self.assertTrue( + child.GetChildAtIndex(0).IsValid(), + "the deep ValueObject has no value") + self.assertTrue( + child.GetChildAtIndex(0).GetValueAsUnsigned() != 0, + "the deep ValueObject has a zero value") + self.assertTrue( + child.GetChildAtIndex(1).GetValueAsUnsigned() != 0, + "the deep ValueObject has no next") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py b/lldb/packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py index 21de3ab7cc3..3f9535a220c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py @@ -5,14 +5,16 @@ Test the 'register' command. from __future__ import print_function - -import os, sys, time +import os +import sys +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class RegisterCommandsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -36,19 +38,24 @@ class RegisterCommandsTestCase(TestBase): self.log_enable("registers") self.expect("register read -a", MISSING_EXPECTED_REGISTERS, - substrs = ['registers were unavailable'], matching = False) + substrs=['registers were unavailable'], matching=False) if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: self.runCmd("register read xmm0") - self.runCmd("register read ymm15") # may be available + self.runCmd("register read ymm15") # may be available elif self.getArchitecture() in ['arm']: self.runCmd("register read s0") - self.runCmd("register read q15") # may be available + self.runCmd("register read q15") # may be available - self.expect("register read -s 3", substrs = ['invalid register set index: 3'], error = True) + self.expect( + "register read -s 3", + substrs=['invalid register set index: 3'], + error=True) @skipIfiOSSimulator - @skipIfTargetAndroid(archs=["i386"]) # Writing of mxcsr register fails, presumably due to a kernel/hardware problem + # Writing of mxcsr register fails, presumably due to a kernel/hardware + # problem + @skipIfTargetAndroid(archs=["i386"]) @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) def test_fp_register_write(self): """Test commands that write to registers, in particular floating-point registers.""" @@ -56,8 +63,9 @@ class RegisterCommandsTestCase(TestBase): self.fp_register_write() @skipIfiOSSimulator - @expectedFailureAndroid(archs=["i386"]) # "register read fstat" always return 0xffff - @skipIfFreeBSD #llvm.org/pr25057 + # "register read fstat" always return 0xffff + @expectedFailureAndroid(archs=["i386"]) + @skipIfFreeBSD # llvm.org/pr25057 @skipIf(archs=no_match(['amd64', 'i386', 'x86_64'])) def test_fp_special_purpose_register_read(self): """Test commands that read fpu special purpose registers.""" @@ -78,12 +86,16 @@ class RegisterCommandsTestCase(TestBase): gpr = "r0" vector = "q0" - self.expect("expr/x $%s" % gpr, substrs = ['unsigned int', ' = 0x']) - self.expect("expr $%s" % vector, substrs = ['vector_type']) - self.expect("expr (unsigned int)$%s[0]" % vector, substrs = ['unsigned int']) + self.expect("expr/x $%s" % gpr, substrs=['unsigned int', ' = 0x']) + self.expect("expr $%s" % vector, substrs=['vector_type']) + self.expect( + "expr (unsigned int)$%s[0]" % + vector, substrs=['unsigned int']) if self.getArchitecture() in ['amd64', 'x86_64']: - self.expect("expr -- ($rax & 0xffffffff) == $eax", substrs = ['true']) + self.expect( + "expr -- ($rax & 0xffffffff) == $eax", + substrs=['true']) @skipIfiOSSimulator @skipIf(archs=no_match(['amd64', 'x86_64'])) @@ -112,13 +124,14 @@ class RegisterCommandsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break in main(). - lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=-1) + lldbutil.run_break_set_by_symbol( + self, "main", num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # platform specific logging of the specified category def log_enable(self, category): @@ -126,7 +139,7 @@ class RegisterCommandsTestCase(TestBase): # platform as logging is host side. self.platform = "" if sys.platform.startswith("darwin"): - self.platform = "" # TODO: add support for "log enable darwin registers" + self.platform = "" # TODO: add support for "log enable darwin registers" if sys.platform.startswith("freebsd"): self.platform = "freebsd" @@ -139,7 +152,14 @@ class RegisterCommandsTestCase(TestBase): if self.platform != "": self.log_file = os.path.join(os.getcwd(), 'TestRegisters.log') - self.runCmd("log enable " + self.platform + " " + str(category) + " registers -v -f " + self.log_file, RUN_SUCCEEDED) + self.runCmd( + "log enable " + + self.platform + + " " + + str(category) + + " registers -v -f " + + self.log_file, + RUN_SUCCEEDED) if not self.has_teardown: def remove_log(self): if os.path.exists(self.log_file): @@ -147,15 +167,24 @@ class RegisterCommandsTestCase(TestBase): self.has_teardown = True self.addTearDownHook(remove_log) - def write_and_read(self, frame, register, new_value, must_exist = True): + def write_and_read(self, frame, register, new_value, must_exist=True): value = frame.FindValue(register, lldb.eValueTypeRegister) if must_exist: - self.assertTrue(value.IsValid(), "finding a value for register " + register) + self.assertTrue( + value.IsValid(), + "finding a value for register " + + register) elif not value.IsValid(): - return # If register doesn't exist, skip this test + return # If register doesn't exist, skip this test self.runCmd("register write " + register + " \'" + new_value + "\'") - self.expect("register read " + register, substrs = [register + ' = ', new_value]) + self.expect( + "register read " + + register, + substrs=[ + register + + ' = ', + new_value]) def fp_special_purpose_register_read(self): exe = os.path.join(os.getcwd(), "a.out") @@ -165,12 +194,14 @@ class RegisterCommandsTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Launch the process and stop. - self.expect ("run", PROCESS_STOPPED, substrs = ['stopped']) + self.expect("run", PROCESS_STOPPED, substrs=['stopped']) # Check stop reason; Should be either signal SIGTRAP or EXC_BREAKPOINT output = self.res.GetOutput() matched = False - substrs = ['stop reason = EXC_BREAKPOINT', 'stop reason = signal SIGTRAP'] + substrs = [ + 'stop reason = EXC_BREAKPOINT', + 'stop reason = signal SIGTRAP'] for str1 in substrs: matched = output.find(str1) != -1 with recording(self, False) as sbuf: @@ -202,30 +233,39 @@ class RegisterCommandsTestCase(TestBase): reg_value_ftag_initial = value.GetValueAsUnsigned(error, 0) self.assertTrue(error.Success(), "reading a value for ftag") - fstat_top_pointer_initial = (reg_value_fstat_initial & 0x3800)>>11 + fstat_top_pointer_initial = (reg_value_fstat_initial & 0x3800) >> 11 # Execute 'si' aka 'thread step-inst' instruction 5 times and with # every execution verify the value of fstat and ftag registers - for x in range(0,5): - # step into the next instruction to push a value on 'st' register stack - self.runCmd ("si", RUN_SUCCEEDED) + for x in range(0, 5): + # step into the next instruction to push a value on 'st' register + # stack + self.runCmd("si", RUN_SUCCEEDED) - # Verify fstat and save it to be used for verification in next execution of 'si' command + # Verify fstat and save it to be used for verification in next + # execution of 'si' command if not (reg_value_fstat_initial & 0x3800): - self.expect("register read fstat", - substrs = ['fstat' + ' = ', str("0x%0.4x" %((reg_value_fstat_initial & ~(0x3800))| 0x3800))]) - reg_value_fstat_initial = ((reg_value_fstat_initial & ~(0x3800))| 0x3800) + self.expect("register read fstat", substrs=[ + 'fstat' + ' = ', str("0x%0.4x" % ((reg_value_fstat_initial & ~(0x3800)) | 0x3800))]) + reg_value_fstat_initial = ( + (reg_value_fstat_initial & ~(0x3800)) | 0x3800) fstat_top_pointer_initial = 7 - else : - self.expect("register read fstat", - substrs = ['fstat' + ' = ', str("0x%0.4x" % (reg_value_fstat_initial - 0x0800))]) + else: + self.expect("register read fstat", substrs=[ + 'fstat' + ' = ', str("0x%0.4x" % (reg_value_fstat_initial - 0x0800))]) reg_value_fstat_initial = (reg_value_fstat_initial - 0x0800) fstat_top_pointer_initial -= 1 - # Verify ftag and save it to be used for verification in next execution of 'si' command - self.expect("register read ftag", - substrs = ['ftag' + ' = ', str("0x%0.2x" % (reg_value_ftag_initial | (1<< fstat_top_pointer_initial)))]) - reg_value_ftag_initial = reg_value_ftag_initial | (1<< fstat_top_pointer_initial) + # Verify ftag and save it to be used for verification in next + # execution of 'si' command + self.expect( + "register read ftag", substrs=[ + 'ftag' + ' = ', str( + "0x%0.2x" % + (reg_value_ftag_initial | ( + 1 << fstat_top_pointer_initial)))]) + reg_value_ftag_initial = reg_value_ftag_initial | ( + 1 << fstat_top_pointer_initial) def fp_register_write(self): exe = os.path.join(os.getcwd(), "a.out") @@ -234,13 +274,17 @@ class RegisterCommandsTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=-1) + lldbutil.run_break_set_by_symbol( + self, "main", num_expected_locations=-1) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) process = target.GetProcess() - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) thread = process.GetThreadAtIndex(0) self.assertTrue(thread.IsValid(), "current thread is valid") @@ -251,12 +295,12 @@ class RegisterCommandsTestCase(TestBase): if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: reg_list = [ # reg value must-have - ("fcw", "0x0000ff0e", False), - ("fsw", "0x0000ff0e", False), - ("ftw", "0x0000ff0e", False), - ("ip", "0x0000ff0e", False), - ("dp", "0x0000ff0e", False), - ("mxcsr", "0x0000ff0e", False), + ("fcw", "0x0000ff0e", False), + ("fsw", "0x0000ff0e", False), + ("ftw", "0x0000ff0e", False), + ("ip", "0x0000ff0e", False), + ("dp", "0x0000ff0e", False), + ("mxcsr", "0x0000ff0e", False), ("mxcsrmask", "0x0000ff0e", False), ] @@ -266,31 +310,52 @@ class RegisterCommandsTestCase(TestBase): elif currentFrame.FindRegister("stmm0").IsValid(): st0regname = "stmm0" if st0regname is not None: - # reg value must-have - reg_list.append((st0regname, "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00}", True)) - reg_list.append(("xmm0", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True)) - reg_list.append(("xmm15", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", False)) + # reg value + # must-have + reg_list.append( + (st0regname, "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00}", True)) + reg_list.append( + ("xmm0", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", + True)) + reg_list.append( + ("xmm15", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False)) elif self.getArchitecture() in ['arm']: reg_list = [ - # reg value must-have - ("fpscr", "0xfbf79f9f", True), - ("s0", "1.25", True), - ("s31", "0.75", True), - ("d1", "123", True), - ("d17", "987", False), - ("q1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), - ("q14", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", False), + # reg value + # must-have + ("fpscr", "0xfbf79f9f", True), + ("s0", "1.25", True), + ("s31", "0.75", True), + ("d1", "123", True), + ("d17", "987", False), + ("q1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), + ("q14", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False), ] for (reg, val, must) in reg_list: self.write_and_read(currentFrame, reg, val, must) if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: - self.runCmd("register write " + st0regname + " \"{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00}\"") - self.expect("register read " + st0regname + " --format f", substrs = [st0regname + ' = 0']) - - has_avx = False - registerSets = currentFrame.GetRegisters() # Returns an SBValueList. + self.runCmd( + "register write " + + st0regname + + " \"{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00}\"") + self.expect( + "register read " + + st0regname + + " --format f", + substrs=[ + st0regname + + ' = 0']) + + has_avx = False + # Returns an SBValueList. + registerSets = currentFrame.GetRegisters() for registerSet in registerSets: if 'advanced vector extensions' in registerSet.GetName().lower(): has_avx = True @@ -300,7 +365,7 @@ class RegisterCommandsTestCase(TestBase): new_value = "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x0c 0x0d 0x0e 0x0f}" self.write_and_read(currentFrame, "ymm0", new_value) self.write_and_read(currentFrame, "ymm7", new_value) - self.expect("expr $ymm0", substrs = ['vector_type']) + self.expect("expr $ymm0", substrs=['vector_type']) else: self.runCmd("register read ymm0") @@ -308,22 +373,24 @@ class RegisterCommandsTestCase(TestBase): """Test convenience registers.""" self.common_setup() - # The command "register read -a" does output a derived register like eax... + # The command "register read -a" does output a derived register like + # eax... self.expect("register read -a", matching=True, - substrs = ['eax']) + substrs=['eax']) # ...however, the vanilla "register read" command should not output derived registers like eax. self.expect("register read", matching=False, - substrs = ['eax']) - + substrs=['eax']) + # Test reading of rax and eax. self.expect("register read rax eax", - substrs = ['rax = 0x', 'eax = 0x']) + substrs=['rax = 0x', 'eax = 0x']) - # Now write rax with a unique bit pattern and test that eax indeed represents the lower half of rax. + # Now write rax with a unique bit pattern and test that eax indeed + # represents the lower half of rax. self.runCmd("register write rax 0x1234567887654321") self.expect("register read rax 0x1234567887654321", - substrs = ['0x1234567887654321']) + substrs=['0x1234567887654321']) def convenience_registers_with_process_attach(self, test_16bit_regs): """Test convenience registers after a 'process attach'.""" @@ -343,8 +410,8 @@ class RegisterCommandsTestCase(TestBase): if self.getArchitecture() in ['amd64', 'x86_64']: self.expect("expr -- ($rax & 0xffffffff) == $eax", - substrs = ['true']) + substrs=['true']) if test_16bit_regs: self.expect("expr -- $ax == (($ah << 8) | $al)", - substrs = ['true']) + substrs=['true']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py b/lldb/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py index 8636abadd10..20d64b38f0c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py @@ -4,7 +4,6 @@ Test that argdumper is a viable launching strategy. from __future__ import print_function - import lldb import os import time @@ -12,45 +11,51 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestRerun(TestBase): mydir = TestBase.compute_mydir(__file__) - def test (self): + def test(self): self.build() - exe = os.path.join (os.getcwd(), "a.out") - + exe = os.path.join(os.getcwd(), "a.out") + self.runCmd("target create %s" % exe) - + # Create the target target = self.dbg.CreateTarget(exe) - + # Create any breakpoints we need - breakpoint = target.BreakpointCreateBySourceRegex ('break here', lldb.SBFileSpec ("main.cpp", False)) + breakpoint = target.BreakpointCreateBySourceRegex( + 'break here', lldb.SBFileSpec("main.cpp", False)) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("process launch 1 2 3") process = self.process() - thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, breakpoint) - self.assertIsNotNone(thread, "Process should be stopped at a breakpoint in main") + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + self.assertIsNotNone( + thread, "Process should be stopped at a breakpoint in main") self.assertTrue(thread.IsValid(), "Stopped thread is not valid") self.expect("frame variable argv[1]", substrs=['1']) self.expect("frame variable argv[2]", substrs=['2']) self.expect("frame variable argv[3]", substrs=['3']) - + # Let program exit self.runCmd("continue") - + # Re-run with no args and make sure we still run with 1 2 3 as arguments as # they should have been stored in "target.run-args" self.runCmd("process launch") process = self.process() - thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, breakpoint) + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) - self.assertIsNotNone(thread, "Process should be stopped at a breakpoint in main"); + self.assertIsNotNone( + thread, "Process should be stopped at a breakpoint in main") self.assertTrue(thread.IsValid(), "Stopped thread is not valid") self.expect("frame variable argv[1]", substrs=['1']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py b/lldb/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py index 81d93294b5a..71edcdfd95e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py @@ -5,21 +5,33 @@ Test getting return-values correctly when stepping out from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ReturnValueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["macosx","freebsd"], archs=["i386"]) - @expectedFailureAll(oslist=["linux"], compiler="clang", compiler_version=["<=", "3.6"], archs=["i386"]) - @expectedFailureAll(bugnumber="llvm.org/pr25785", hostoslist=["windows"], compiler="gcc", archs=["i386"], triple='.*-android') + @expectedFailureAll(oslist=["macosx", "freebsd"], archs=["i386"]) + @expectedFailureAll( + oslist=["linux"], + compiler="clang", + compiler_version=[ + "<=", + "3.6"], + archs=["i386"]) + @expectedFailureAll( + bugnumber="llvm.org/pr25785", + hostoslist=["windows"], + compiler="gcc", + archs=["i386"], + triple='.*-android') @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") @add_test_categories(['pyapi']) def test_with_python(self): @@ -35,7 +47,8 @@ class ReturnValueTestCase(TestBase): self.assertTrue(inner_sint_bkpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process, PROCESS_IS_VALID) @@ -44,168 +57,178 @@ class ReturnValueTestCase(TestBase): STOPPED_DUE_TO_BREAKPOINT) # Now finish, and make sure the return value is correct. - thread = lldbutil.get_stopped_thread (self.process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) # inner_sint returns the variable value, so capture that here: - in_int = thread.GetFrameAtIndex(0).FindVariable ("value").GetValueAsSigned(error) - self.assertTrue (error.Success()) + in_int = thread.GetFrameAtIndex(0).FindVariable( + "value").GetValueAsSigned(error) + self.assertTrue(error.Success()) - thread.StepOut(); + thread.StepOut() - self.assertTrue (self.process.GetState() == lldb.eStateStopped) - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete) + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) frame = thread.GetFrameAtIndex(0) fun_name = frame.GetFunctionName() - self.assertTrue (fun_name == "outer_sint") + self.assertTrue(fun_name == "outer_sint") return_value = thread.GetStopReturnValue() - self.assertTrue (return_value.IsValid()) + self.assertTrue(return_value.IsValid()) ret_int = return_value.GetValueAsSigned(error) - self.assertTrue (error.Success()) - self.assertTrue (in_int == ret_int) + self.assertTrue(error.Success()) + self.assertTrue(in_int == ret_int) - # Run again and we will stop in inner_sint the second time outer_sint is called. - #Then test stepping out two frames at once: + # Run again and we will stop in inner_sint the second time outer_sint is called. + # Then test stepping out two frames at once: self.process.Continue() - thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process, inner_sint_bkpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + self.process, inner_sint_bkpt) self.assertTrue(len(thread_list) == 1) thread = thread_list[0] # We are done with the inner_sint breakpoint: - self.target.BreakpointDelete (inner_sint_bkpt.GetID()) + self.target.BreakpointDelete(inner_sint_bkpt.GetID()) frame = thread.GetFrameAtIndex(1) - fun_name = frame.GetFunctionName () - self.assertTrue (fun_name == "outer_sint") - in_int = frame.FindVariable ("value").GetValueAsSigned(error) - self.assertTrue (error.Success()) + fun_name = frame.GetFunctionName() + self.assertTrue(fun_name == "outer_sint") + in_int = frame.FindVariable("value").GetValueAsSigned(error) + self.assertTrue(error.Success()) - thread.StepOutOfFrame (frame) + thread.StepOutOfFrame(frame) - self.assertTrue (self.process.GetState() == lldb.eStateStopped) - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete) + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) frame = thread.GetFrameAtIndex(0) fun_name = frame.GetFunctionName() - self.assertTrue (fun_name == "main") + self.assertTrue(fun_name == "main") ret_value = thread.GetStopReturnValue() - self.assertTrue (return_value.IsValid()) - ret_int = ret_value.GetValueAsSigned (error) - self.assertTrue (error.Success()) - self.assertTrue (2 * in_int == ret_int) - + self.assertTrue(return_value.IsValid()) + ret_int = ret_value.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(2 * in_int == ret_int) + # Now try some simple returns that have different types: - inner_float_bkpt = self.target.BreakpointCreateByName("inner_float", exe) + inner_float_bkpt = self.target.BreakpointCreateByName( + "inner_float", exe) self.assertTrue(inner_float_bkpt, VALID_BREAKPOINT) self.process.Continue() - thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process, inner_float_bkpt) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + self.process, inner_float_bkpt) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] - self.target.BreakpointDelete (inner_float_bkpt.GetID()) + self.target.BreakpointDelete(inner_float_bkpt.GetID()) frame = thread.GetFrameAtIndex(0) - in_value = frame.FindVariable ("value") - in_float = float (in_value.GetValue()) + in_value = frame.FindVariable("value") + in_float = float(in_value.GetValue()) thread.StepOut() - self.assertTrue (self.process.GetState() == lldb.eStateStopped) - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete) + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) frame = thread.GetFrameAtIndex(0) fun_name = frame.GetFunctionName() - self.assertTrue (fun_name == "outer_float") + self.assertTrue(fun_name == "outer_float") return_value = thread.GetStopReturnValue() - self.assertTrue (return_value.IsValid()) - return_float = float (return_value.GetValue()) + self.assertTrue(return_value.IsValid()) + return_float = float(return_value.GetValue()) self.assertTrue(in_float == return_float) - self.return_and_test_struct_value ("return_one_int") - self.return_and_test_struct_value ("return_two_int") - self.return_and_test_struct_value ("return_three_int") - self.return_and_test_struct_value ("return_four_int") - self.return_and_test_struct_value ("return_five_int") - - self.return_and_test_struct_value ("return_two_double") - self.return_and_test_struct_value ("return_one_double_two_float") - self.return_and_test_struct_value ("return_one_int_one_float_one_int") - - self.return_and_test_struct_value ("return_one_pointer") - self.return_and_test_struct_value ("return_two_pointer") - self.return_and_test_struct_value ("return_one_float_one_pointer") - self.return_and_test_struct_value ("return_one_int_one_pointer") - self.return_and_test_struct_value ("return_three_short_one_float") - - self.return_and_test_struct_value ("return_one_int_one_double") - self.return_and_test_struct_value ("return_one_int_one_double_one_int") - self.return_and_test_struct_value ("return_one_short_one_double_one_short") - self.return_and_test_struct_value ("return_one_float_one_int_one_float") - self.return_and_test_struct_value ("return_two_float") - # I am leaving out the packed test until we have a way to tell CLANG + self.return_and_test_struct_value("return_one_int") + self.return_and_test_struct_value("return_two_int") + self.return_and_test_struct_value("return_three_int") + self.return_and_test_struct_value("return_four_int") + self.return_and_test_struct_value("return_five_int") + + self.return_and_test_struct_value("return_two_double") + self.return_and_test_struct_value("return_one_double_two_float") + self.return_and_test_struct_value("return_one_int_one_float_one_int") + + self.return_and_test_struct_value("return_one_pointer") + self.return_and_test_struct_value("return_two_pointer") + self.return_and_test_struct_value("return_one_float_one_pointer") + self.return_and_test_struct_value("return_one_int_one_pointer") + self.return_and_test_struct_value("return_three_short_one_float") + + self.return_and_test_struct_value("return_one_int_one_double") + self.return_and_test_struct_value("return_one_int_one_double_one_int") + self.return_and_test_struct_value( + "return_one_short_one_double_one_short") + self.return_and_test_struct_value("return_one_float_one_int_one_float") + self.return_and_test_struct_value("return_two_float") + # I am leaving out the packed test until we have a way to tell CLANG # about alignment when reading DWARF for packed types. #self.return_and_test_struct_value ("return_one_int_one_double_packed") - self.return_and_test_struct_value ("return_one_int_one_long") + self.return_and_test_struct_value("return_one_int_one_long") # icc and gcc don't support this extension. if self.getCompiler().endswith('clang'): - self.return_and_test_struct_value ("return_vector_size_float32_8") - self.return_and_test_struct_value ("return_vector_size_float32_16") - self.return_and_test_struct_value ("return_vector_size_float32_32") - self.return_and_test_struct_value ("return_ext_vector_size_float32_2") - self.return_and_test_struct_value ("return_ext_vector_size_float32_4") - self.return_and_test_struct_value ("return_ext_vector_size_float32_8") - - def return_and_test_struct_value (self, func_name): + self.return_and_test_struct_value("return_vector_size_float32_8") + self.return_and_test_struct_value("return_vector_size_float32_16") + self.return_and_test_struct_value("return_vector_size_float32_32") + self.return_and_test_struct_value( + "return_ext_vector_size_float32_2") + self.return_and_test_struct_value( + "return_ext_vector_size_float32_4") + self.return_and_test_struct_value( + "return_ext_vector_size_float32_8") + + def return_and_test_struct_value(self, func_name): """Pass in the name of the function to return from - takes in value, returns value.""" - + # Set the breakpoint, run to it, finish out. - bkpt = self.target.BreakpointCreateByName (func_name) - self.assertTrue (bkpt.GetNumResolvedLocations() > 0) + bkpt = self.target.BreakpointCreateByName(func_name) + self.assertTrue(bkpt.GetNumResolvedLocations() > 0) - self.process.Continue () + self.process.Continue() - thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process, bkpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + self.process, bkpt) - self.assertTrue (len(thread_list) == 1) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] - self.target.BreakpointDelete (bkpt.GetID()) + self.target.BreakpointDelete(bkpt.GetID()) + + in_value = thread.GetFrameAtIndex(0).FindVariable("value") - in_value = thread.GetFrameAtIndex(0).FindVariable ("value") - - self.assertTrue (in_value.IsValid()) + self.assertTrue(in_value.IsValid()) num_in_children = in_value.GetNumChildren() # This is a little hokey, but if we don't get all the children now, then # once we've stepped we won't be able to get them? - + for idx in range(0, num_in_children): - in_child = in_value.GetChildAtIndex (idx) + in_child = in_value.GetChildAtIndex(idx) in_child_str = in_child.GetValue() thread.StepOut() - - self.assertTrue (self.process.GetState() == lldb.eStateStopped) - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete) + + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) # Assuming all these functions step out to main. Could figure out the caller dynamically # if that would add something to the test. frame = thread.GetFrameAtIndex(0) fun_name = frame.GetFunctionName() - self.assertTrue (fun_name == "main") + self.assertTrue(fun_name == "main") frame = thread.GetFrameAtIndex(0) ret_value = thread.GetStopReturnValue() - self.assertTrue (ret_value.IsValid()) + self.assertTrue(ret_value.IsValid()) num_ret_children = ret_value.GetNumChildren() - self.assertTrue (num_in_children == num_ret_children) + self.assertTrue(num_in_children == num_ret_children) for idx in range(0, num_ret_children): in_child = in_value.GetChildAtIndex(idx) ret_child = ret_value.GetChildAtIndex(idx) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py b/lldb/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py index 294aa672515..2fc31a4e78a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py @@ -5,13 +5,14 @@ Set the contents of variables and registers using raw data from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SetDataTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,41 +24,48 @@ class SetDataTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - self.runCmd("br s -p First"); - self.runCmd("br s -p Second"); + self.runCmd("br s -p First") + self.runCmd("br s -p Second") self.runCmd("run", RUN_SUCCEEDED) self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['2']) + substrs=['2']) process = self.dbg.GetSelectedTarget().GetProcess() frame = process.GetSelectedThread().GetFrameAtIndex(0) x = frame.FindVariable("myFoo").GetChildMemberWithName("x") - my_data = lldb.SBData.CreateDataFromSInt32Array(lldb.eByteOrderLittle, 8, [4]) + my_data = lldb.SBData.CreateDataFromSInt32Array( + lldb.eByteOrderLittle, 8, [4]) err = lldb.SBError() - self.assertTrue (x.SetData(my_data, err)) + self.assertTrue(x.SetData(my_data, err)) self.runCmd("continue") self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['4']) + substrs=['4']) frame = process.GetSelectedThread().GetFrameAtIndex(0) x = frame.FindVariable("string") if process.GetAddressByteSize() == 8: - my_data = lldb.SBData.CreateDataFromUInt64Array(process.GetByteOrder(), 8, [0]) + my_data = lldb.SBData.CreateDataFromUInt64Array( + process.GetByteOrder(), 8, [0]) else: - my_data = lldb.SBData.CreateDataFromUInt32Array(process.GetByteOrder(), 4, [0]) - + my_data = lldb.SBData.CreateDataFromUInt32Array( + process.GetByteOrder(), 4, [0]) + err = lldb.SBError() - self.assertTrue (x.SetData(my_data, err)) + self.assertTrue(x.SetData(my_data, err)) - self.expect("fr var -d run-target string", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['NSString *', 'nil']) + self.expect( + "fr var -d run-target string", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'NSString *', + 'nil']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py index 1da4d701a59..0a2756d87fb 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py @@ -3,8 +3,9 @@ from __future__ import print_function - -import os, time, signal +import os +import time +import signal import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -21,8 +22,10 @@ class SendSignalTestCase(TestBase): # Find the line number to break inside main(). self.line = line_number('main.c', 'Put breakpoint here') - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr23318: does not report running state") - @skipIfWindows # Windows does not support signals + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr23318: does not report running state") + @skipIfWindows # Windows does not support signals def test_with_run_command(self): """Test that lldb command 'process signal SIGUSR1' sends a signal to the inferior process.""" self.build() @@ -57,14 +60,17 @@ class SendSignalTestCase(TestBase): self.runCmd("process handle -n False -p True -s True SIGUSR1") - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid(), "We hit the first breakpoint.") # After resuming the process, send it a SIGUSR1 signal. self.setAsync(True) - self.assertTrue(process_listener.IsValid(), "Got a good process listener") + self.assertTrue( + process_listener.IsValid(), + "Got a good process listener") # Disable our breakpoint, we don't want to hit it anymore... breakpoint.SetEnabled(False) @@ -88,9 +94,12 @@ class SendSignalTestCase(TestBase): self.assertTrue(len(threads) == 1, "One thread stopped for a signal.") thread = threads[0] - self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.") - self.assertTrue(thread.GetStopReasonDataAtIndex(0) == lldbutil.get_signal_number('SIGUSR1'), - "The stop signal was SIGUSR1") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") + self.assertTrue( + thread.GetStopReasonDataAtIndex(0) == lldbutil.get_signal_number('SIGUSR1'), + "The stop signal was SIGUSR1") def match_state(self, process_listener, expected_state): num_seconds = 5 diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py b/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py index d8dbb7f6893..16681fdbcde 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py @@ -3,7 +3,6 @@ from __future__ import print_function - import os import re @@ -17,9 +16,11 @@ class HandleSegvTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows # signals do not exist on Windows + @skipIfWindows # signals do not exist on Windows @skipIfDarwin - @expectedFailureAll(oslist=['freebsd'], bugnumber="llvm.org/pr23699 SIGSEGV is reported as exception, not signal") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr23699 SIGSEGV is reported as exception, not signal") def test_inferior_handle_sigsegv(self): self.build() exe = os.path.join(os.getcwd(), "a.out") @@ -29,15 +30,21 @@ class HandleSegvTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # launch - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual(process.GetState(), lldb.eStateStopped) signo = process.GetUnixSignals().GetSignalNumberFromName("SIGSEGV") thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) - self.assertTrue(thread and thread.IsValid(), "Thread should be stopped due to a signal") - self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.") - self.assertEqual(thread.GetStopReasonDataAtIndex(0), signo, "The stop signal was SIGSEGV") + self.assertTrue( + thread and thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") + self.assertEqual(thread.GetStopReasonDataAtIndex(0), + signo, "The stop signal was SIGSEGV") # Continue until we exit. process.Continue() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py b/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py index 2c30f69d7b2..efadea51f66 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py @@ -3,7 +3,6 @@ from __future__ import print_function - import os import lldb import re @@ -13,7 +12,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -@skipIfWindows # signals do not exist on Windows +@skipIfWindows # signals do not exist on Windows class RaiseTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,9 +20,10 @@ class RaiseTestCase(TestBase): def test_sigstop(self): self.build() self.signal_test('SIGSTOP', False) - # passing of SIGSTOP is not correctly handled, so not testing that scenario: https://llvm.org/bugs/show_bug.cgi?id=23574 + # passing of SIGSTOP is not correctly handled, so not testing that + # scenario: https://llvm.org/bugs/show_bug.cgi?id=23574 - @skipIfDarwin # darwin does not support real time signals + @skipIfDarwin # darwin does not support real time signals @skipIfTargetAndroid() def test_sigsigrtmin(self): self.build() @@ -31,20 +31,25 @@ class RaiseTestCase(TestBase): def launch(self, target, signal): # launch the process, do not stop at entry point. - process = target.LaunchSimple([signal], None, self.get_process_working_directory()) + process = target.LaunchSimple( + [signal], None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual(process.GetState(), lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "Thread should be stopped due to a breakpoint") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "Thread should be stopped due to a breakpoint") return process def set_handle(self, signal, pass_signal, stop_at_signal, notify_signal): return_obj = lldb.SBCommandReturnObject() self.dbg.GetCommandInterpreter().HandleCommand( - "process handle %s -p %s -s %s -n %s" % (signal, pass_signal, stop_at_signal, notify_signal), - return_obj) - self.assertTrue (return_obj.Succeeded() == True, "Setting signal handling failed") - + "process handle %s -p %s -s %s -n %s" % + (signal, pass_signal, stop_at_signal, notify_signal), return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Setting signal handling failed") def signal_test(self, signal, test_passing): """Test that we handle inferior raising signals""" @@ -61,9 +66,12 @@ class RaiseTestCase(TestBase): # retrieve default signal disposition return_obj = lldb.SBCommandReturnObject() - self.dbg.GetCommandInterpreter().HandleCommand("process handle %s " % signal, return_obj) - match = re.match('NAME *PASS *STOP *NOTIFY.*(false|true) *(false|true) *(false|true)', - return_obj.GetOutput(), re.IGNORECASE | re.DOTALL) + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle %s " % signal, return_obj) + match = re.match( + 'NAME *PASS *STOP *NOTIFY.*(false|true) *(false|true) *(false|true)', + return_obj.GetOutput(), + re.IGNORECASE | re.DOTALL) if not match: self.fail('Unable to retrieve default signal disposition.') default_pass = match.group(1) @@ -75,10 +83,14 @@ class RaiseTestCase(TestBase): process.Continue() self.assertEqual(process.GetState(), lldb.eStateStopped) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) - self.assertTrue(thread.IsValid(), "Thread should be stopped due to a signal") - self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.") + self.assertTrue( + thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") self.assertEqual(thread.GetStopReasonDataAtIndex(0), signo, - "The stop signal was %s" % signal) + "The stop signal was %s" % signal) # Continue until we exit. process.Continue() @@ -88,18 +100,27 @@ class RaiseTestCase(TestBase): # launch again process = self.launch(target, signal) - # Make sure we do not stop at the signal. We should still get the notification. + # Make sure we do not stop at the signal. We should still get the + # notification. self.set_handle(signal, "false", "false", "true") - self.expect("process continue", substrs=["stopped and restarted", signal]) + self.expect( + "process continue", + substrs=[ + "stopped and restarted", + signal]) self.assertEqual(process.GetState(), lldb.eStateExited) self.assertEqual(process.GetExitStatus(), 0) # launch again process = self.launch(target, signal) - # Make sure we do not stop at the signal, and we do not get the notification. + # Make sure we do not stop at the signal, and we do not get the + # notification. self.set_handle(signal, "false", "false", "false") - self.expect("process continue", substrs=["stopped and restarted"], matching=False) + self.expect( + "process continue", + substrs=["stopped and restarted"], + matching=False) self.assertEqual(process.GetState(), lldb.eStateExited) self.assertEqual(process.GetExitStatus(), 0) @@ -116,11 +137,17 @@ class RaiseTestCase(TestBase): process.Continue() self.assertEqual(process.GetState(), lldb.eStateStopped) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) - self.assertTrue(thread.IsValid(), "Thread should be stopped due to a signal") - self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.") - self.assertEqual(thread.GetStopReasonDataAtIndex(0), - process.GetUnixSignals().GetSignalNumberFromName(signal), - "The stop signal was %s" % signal) + self.assertTrue( + thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") + self.assertEqual( + thread.GetStopReasonDataAtIndex(0), + process.GetUnixSignals().GetSignalNumberFromName(signal), + "The stop signal was %s" % + signal) # Continue until we exit. The process should receive the signal. process.Continue() @@ -133,7 +160,11 @@ class RaiseTestCase(TestBase): # Make sure we do not stop at the signal. We should still get the notification. Process # should receive the signal. self.set_handle(signal, "true", "false", "true") - self.expect("process continue", substrs=["stopped and restarted", signal]) + self.expect( + "process continue", + substrs=[ + "stopped and restarted", + signal]) self.assertEqual(process.GetState(), lldb.eStateExited) self.assertEqual(process.GetExitStatus(), signo) @@ -143,14 +174,20 @@ class RaiseTestCase(TestBase): # Make sure we do not stop at the signal, and we do not get the notification. Process # should receive the signal. self.set_handle(signal, "true", "false", "false") - self.expect("process continue", substrs=["stopped and restarted"], matching=False) + self.expect( + "process continue", + substrs=["stopped and restarted"], + matching=False) self.assertEqual(process.GetState(), lldb.eStateExited) self.assertEqual(process.GetExitStatus(), signo) # reset signal handling to default self.set_handle(signal, default_pass, default_stop, default_notify) - @expectedFailureAll(oslist=["linux"]+getDarwinOSTriples(), bugnumber="llvm.org/pr20231") + @expectedFailureAll( + oslist=["linux"] + + getDarwinOSTriples(), + bugnumber="llvm.org/pr20231") def test_restart_bug(self): """Test that we catch a signal in the edge case where the process receives it while we are about to interrupt it""" @@ -167,16 +204,16 @@ class RaiseTestCase(TestBase): self.dbg.SetAsync(True) error = lldb.SBError() listener = lldb.SBListener("my listener") - process = target.Launch (listener, - ["SIGSTOP"], # argv - None, # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working directory - 0, # launch flags - False, # Stop at entry - error) # error + process = target.Launch(listener, + ["SIGSTOP"], # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) @@ -187,12 +224,18 @@ class RaiseTestCase(TestBase): # The last WaitForEvent call will time out after 2 seconds. while listener.WaitForEvent(2, event): if self.TraceOn(): - print("Process changing state to:", self.dbg.StateAsCString(process.GetStateFromEvent(event))) + print( + "Process changing state to:", + self.dbg.StateAsCString( + process.GetStateFromEvent(event))) # now the process should be stopped - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) - self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint(process, bkpt)), 1, - "A thread should be stopped at breakpoint") + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint( + process, bkpt)), 1, "A thread should be stopped at breakpoint") # Remove all breakpoints. This makes sure we don't have to single-step over them when we # resume the process below @@ -200,23 +243,32 @@ class RaiseTestCase(TestBase): # resume the process and immediately try to set another breakpoint. When using the remote # stub, this will trigger a request to stop the process just as it is about to stop - # naturally due to a SIGSTOP signal it raises. Make sure we do not lose this signal. + # naturally due to a SIGSTOP signal it raises. Make sure we do not lose + # this signal. process.Continue() - self.assertTrue(target.BreakpointCreateByName("handler").IsValid(), VALID_BREAKPOINT) + self.assertTrue(target.BreakpointCreateByName( + "handler").IsValid(), VALID_BREAKPOINT) # Clear the events again while listener.WaitForEvent(2, event): if self.TraceOn(): - print("Process changing state to:", self.dbg.StateAsCString(process.GetStateFromEvent(event))) + print( + "Process changing state to:", + self.dbg.StateAsCString( + process.GetStateFromEvent(event))) # The process should be stopped due to a signal self.assertEqual(process.GetState(), lldb.eStateStopped) thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) - self.assertTrue(thread.IsValid(), "Thread should be stopped due to a signal") - self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.") + self.assertTrue( + thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") signo = process.GetUnixSignals().GetSignalNumberFromName("SIGSTOP") self.assertEqual(thread.GetStopReasonDataAtIndex(0), signo, - "The stop signal was %s" % signal) + "The stop signal was %s" % signal) # We are done process.Kill() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py b/lldb/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py index 6f5882636cb..ad08c6a9e95 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py @@ -5,13 +5,13 @@ Test the lldb command line takes a filename with single quote chars. from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SingleQuoteInCommandLineTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,7 +27,9 @@ class SingleQuoteInCommandLineTestCase(TestBase): except: pass - @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @no_debug_info_test def test_lldb_invocation_with_single_quote_in_filename(self): """Test that 'lldb my_file_name' works where my_file_name is a string with a single quote char in it.""" @@ -39,7 +41,9 @@ class SingleQuoteInCommandLineTestCase(TestBase): prompt = "(lldb) " # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s "%s"' % (lldbtest_config.lldbExec, self.lldbOption, self.myexe)) + self.child = pexpect.spawn( + '%s %s "%s"' % + (lldbtest_config.lldbExec, self.lldbOption, self.myexe)) child = self.child child.setecho(True) # Turn on logging for input/output to/from the child. @@ -58,7 +62,7 @@ class SingleQuoteInCommandLineTestCase(TestBase): # stop further logging. child.logfile_send = None child.logfile_read = None - + with open('child_send.txt', 'r') as fs: if self.TraceOn(): print("\n\nContents of child_send.txt:") @@ -70,4 +74,4 @@ class SingleQuoteInCommandLineTestCase(TestBase): print(from_child) self.expect(from_child, exe=False, - substrs = ["Current executable set to"]) + substrs=["Current executable set to"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py b/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py index 8b9c91217de..b0b2e609ba6 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py @@ -5,7 +5,6 @@ Test thread step-in, step-over and step-out work with the "Avoid no debug" optio from __future__ import print_function - import os import re import sys @@ -15,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ReturnValueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,8 +27,15 @@ class ReturnValueTestCase(TestBase): self.do_step_out_past_nodebug() @add_test_categories(['pyapi']) - @decorators.expectedFailureAll(compiler="gcc", bugnumber="llvm.org/pr28549") - @decorators.expectedFailureAll(compiler="clang", compiler_version=[">=", "3.9"], archs=["i386"], bugnumber="llvm.org/pr28549") + @decorators.expectedFailureAll( + compiler="gcc", bugnumber="llvm.org/pr28549") + @decorators.expectedFailureAll( + compiler="clang", + compiler_version=[ + ">=", + "3.9"], + archs=["i386"], + bugnumber="llvm.org/pr28549") def test_step_over_with_python(self): """Test stepping over using avoid-no-debug with dwarf.""" self.build() @@ -36,82 +43,111 @@ class ReturnValueTestCase(TestBase): self.do_step_over_past_nodebug() @add_test_categories(['pyapi']) - @decorators.expectedFailureAll(compiler="gcc", bugnumber="llvm.org/pr28549") - @decorators.expectedFailureAll(compiler="clang", compiler_version=[">=", "3.9"], archs=["i386"], bugnumber="llvm.org/pr28549") + @decorators.expectedFailureAll( + compiler="gcc", bugnumber="llvm.org/pr28549") + @decorators.expectedFailureAll( + compiler="clang", + compiler_version=[ + ">=", + "3.9"], + archs=["i386"], + bugnumber="llvm.org/pr28549") def test_step_in_with_python(self): """Test stepping in using avoid-no-debug with dwarf.""" self.build() self.get_to_starting_point() self.do_step_in_past_nodebug() - def setUp (self): + def setUp(self): TestBase.setUp(self) self.main_source = "with-debug.c" self.main_source_spec = lldb.SBFileSpec("with-debug.c") - self.dbg.HandleCommand ("settings set target.process.thread.step-out-avoid-nodebug true") + self.dbg.HandleCommand( + "settings set target.process.thread.step-out-avoid-nodebug true") - def tearDown (self): - self.dbg.HandleCommand ("settings set target.process.thread.step-out-avoid-nodebug false") + def tearDown(self): + self.dbg.HandleCommand( + "settings set target.process.thread.step-out-avoid-nodebug false") TestBase.tearDown(self) - def hit_correct_line (self, pattern): - target_line = line_number (self.main_source, pattern) - self.assertTrue (target_line != 0, "Could not find source pattern " + pattern) + def hit_correct_line(self, pattern): + target_line = line_number(self.main_source, pattern) + self.assertTrue( + target_line != 0, + "Could not find source pattern " + + pattern) cur_line = self.thread.frames[0].GetLineEntry().GetLine() - self.assertTrue (cur_line == target_line, "Stepped to line %d instead of expected %d with pattern '%s'."%(cur_line, target_line, pattern)) - - def hit_correct_function (self, pattern): + self.assertTrue( + cur_line == target_line, + "Stepped to line %d instead of expected %d with pattern '%s'." % + (cur_line, + target_line, + pattern)) + + def hit_correct_function(self, pattern): name = self.thread.frames[0].GetFunctionName() - self.assertTrue (pattern in name, "Got to '%s' not the expected function '%s'."%(name, pattern)) + self.assertTrue( + pattern in name, "Got to '%s' not the expected function '%s'." % + (name, pattern)) - def get_to_starting_point (self): + def get_to_starting_point(self): exe = os.path.join(os.getcwd(), "a.out") error = lldb.SBError() self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - inner_bkpt = self.target.BreakpointCreateBySourceRegex("Stop here and step out of me", self.main_source_spec) + inner_bkpt = self.target.BreakpointCreateBySourceRegex( + "Stop here and step out of me", self.main_source_spec) self.assertTrue(inner_bkpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process, PROCESS_IS_VALID) # Now finish, and make sure the return value is correct. - threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, inner_bkpt) + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, inner_bkpt) self.assertTrue(len(threads) == 1, "Stopped at inner breakpoint.") self.thread = threads[0] def do_step_out_past_nodebug(self): # The first step out takes us to the called_from_nodebug frame, just to make sure setting - # step-out-avoid-nodebug doesn't change the behavior in frames with debug info. + # step-out-avoid-nodebug doesn't change the behavior in frames with + # debug info. self.thread.StepOut() - self.hit_correct_line ("intermediate_return_value = called_from_nodebug_actual(some_value)") + self.hit_correct_line( + "intermediate_return_value = called_from_nodebug_actual(some_value)") self.thread.StepOut() - self.hit_correct_line ("int return_value = no_debug_caller(5, called_from_nodebug)") + self.hit_correct_line( + "int return_value = no_debug_caller(5, called_from_nodebug)") - def do_step_over_past_nodebug (self): + def do_step_over_past_nodebug(self): self.thread.StepOver() - self.hit_correct_line ("intermediate_return_value = called_from_nodebug_actual(some_value)") + self.hit_correct_line( + "intermediate_return_value = called_from_nodebug_actual(some_value)") self.thread.StepOver() - self.hit_correct_line ("return intermediate_return_value") + self.hit_correct_line("return intermediate_return_value") self.thread.StepOver() # Note, lldb doesn't follow gdb's distinction between "step-out" and "step-over/step-in" # when exiting a frame. In all cases we leave the pc at the point where we exited the # frame. In gdb, step-over/step-in move to the end of the line they stepped out to. # If we ever change this we will need to fix this test. - self.hit_correct_line ("int return_value = no_debug_caller(5, called_from_nodebug)") + self.hit_correct_line( + "int return_value = no_debug_caller(5, called_from_nodebug)") - def do_step_in_past_nodebug (self): + def do_step_in_past_nodebug(self): self.thread.StepInto() - self.hit_correct_line ("intermediate_return_value = called_from_nodebug_actual(some_value)") + self.hit_correct_line( + "intermediate_return_value = called_from_nodebug_actual(some_value)") self.thread.StepInto() - self.hit_correct_line ("return intermediate_return_value") + self.hit_correct_line("return intermediate_return_value") self.thread.StepInto() # Note, lldb doesn't follow gdb's distinction between "step-out" and "step-over/step-in" # when exiting a frame. In all cases we leave the pc at the point where we exited the # frame. In gdb, step-over/step-in move to the end of the line they stepped out to. # If we ever change this we will need to fix this test. - self.hit_correct_line ("int return_value = no_debug_caller(5, called_from_nodebug)") + self.hit_correct_line( + "int return_value = no_debug_caller(5, called_from_nodebug)") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py b/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py index 93f846a0687..3d23f644554 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py @@ -5,13 +5,13 @@ Test lldb target stop-hook command. from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StopHookCmdTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,9 +20,15 @@ class StopHookCmdTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line numbers inside main.cpp. - self.begl = line_number('main.cpp', '// Set breakpoint here to test target stop-hook.') - self.endl = line_number('main.cpp', '// End of the line range for which stop-hook is to be run.') - self.line = line_number('main.cpp', '// Another breakpoint which is outside of the stop-hook range.') + self.begl = line_number( + 'main.cpp', + '// Set breakpoint here to test target stop-hook.') + self.endl = line_number( + 'main.cpp', + '// End of the line range for which stop-hook is to be run.') + self.line = line_number( + 'main.cpp', + '// Another breakpoint which is outside of the stop-hook range.') @no_debug_info_test def test_not_crashing_if_no_target(self): @@ -35,32 +41,37 @@ class StopHookCmdTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.begl, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.begl, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) - self.runCmd("target stop-hook add -f main.cpp -l %d -e %d -o 'expr ptr'" % (self.begl, self.endl)) + self.runCmd( + "target stop-hook add -f main.cpp -l %d -e %d -o 'expr ptr'" % + (self.begl, self.endl)) self.expect('target stop-hook list', 'Stop Hook added successfully', - substrs = ['State: enabled', - 'expr ptr']) + substrs=['State: enabled', + 'expr ptr']) self.runCmd('target stop-hook disable') self.expect('target stop-hook list', 'Stop Hook disabled successfully', - substrs = ['State: disabled', - 'expr ptr']) + substrs=['State: disabled', + 'expr ptr']) self.runCmd('target stop-hook enable') self.expect('target stop-hook list', 'Stop Hook enabled successfully', - substrs = ['State: enabled', - 'expr ptr']) + substrs=['State: enabled', + 'expr ptr']) self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) self.runCmd('target stop-hook delete') self.expect('target stop-hook list', 'Stop Hook deleted successfully', - substrs = ['No stop hooks.']) + substrs=['No stop hooks.']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py b/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py index c42c1e56388..fa5c6de0565 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py @@ -5,7 +5,6 @@ Test lldb target stop-hook mechanism to see whether it fires off correctly . from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * @@ -13,6 +12,7 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import configuration from lldbsuite.test import lldbutil + class StopHookMechanismTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,14 +21,24 @@ class StopHookMechanismTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line numbers inside main.cpp. - self.begl = line_number('main.cpp', '// Set breakpoint here to test target stop-hook.') - self.endl = line_number('main.cpp', '// End of the line range for which stop-hook is to be run.') - self.correct_step_line = line_number ('main.cpp', '// We should stop here after stepping.') - self.line = line_number('main.cpp', '// Another breakpoint which is outside of the stop-hook range.') + self.begl = line_number( + 'main.cpp', + '// Set breakpoint here to test target stop-hook.') + self.endl = line_number( + 'main.cpp', + '// End of the line range for which stop-hook is to be run.') + self.correct_step_line = line_number( + 'main.cpp', '// We should stop here after stepping.') + self.line = line_number( + 'main.cpp', + '// Another breakpoint which is outside of the stop-hook range.') - @skipIfFreeBSD # llvm.org/pr15037 - @expectedFlakeyLinux('llvm.org/pr15037') # stop-hooks sometimes fail to fire on Linux - @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr15037 + # stop-hooks sometimes fail to fire on Linux + @expectedFlakeyLinux('llvm.org/pr15037') + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test(self): """Test the stop-hook mechanism.""" self.build() @@ -40,7 +50,8 @@ class StopHookMechanismTestCase(TestBase): add_prompt1 = "> " # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption)) + self.child = pexpect.spawn('%s %s' % + (lldbtest_config.lldbExec, self.lldbOption)) child = self.child # Turn on logging for what the child sends back. if self.TraceOn(): @@ -48,11 +59,17 @@ class StopHookMechanismTestCase(TestBase): if lldb.remote_platform: child.expect_exact(prompt) - child.sendline('platform select %s' % lldb.remote_platform.GetName()) + child.sendline( + 'platform select %s' % + lldb.remote_platform.GetName()) child.expect_exact(prompt) - child.sendline('platform connect %s' % configuration.lldb_platform_url) + child.sendline( + 'platform connect %s' % + configuration.lldb_platform_url) child.expect_exact(prompt) - child.sendline('platform settings -w %s' % configuration.lldb_platform_working_dir) + child.sendline( + 'platform settings -w %s' % + configuration.lldb_platform_working_dir) child.expect_exact(prompt) child.sendline('target create %s' % exe) @@ -63,7 +80,9 @@ class StopHookMechanismTestCase(TestBase): child.expect_exact(prompt) child.sendline('breakpoint set -f main.cpp -l %d' % self.line) child.expect_exact(prompt) - child.sendline('target stop-hook add -f main.cpp -l %d -e %d' % (self.begl, self.endl)) + child.sendline( + 'target stop-hook add -f main.cpp -l %d -e %d' % + (self.begl, self.endl)) child.expect_exact(add_prompt) child.expect_exact(add_prompt1) child.sendline('expr ptr') @@ -72,10 +91,12 @@ class StopHookMechanismTestCase(TestBase): child.expect_exact(prompt) child.sendline('target stop-hook list') - # Now run the program, expect to stop at the first breakpoint which is within the stop-hook range. + # Now run the program, expect to stop at the first breakpoint which is + # within the stop-hook range. child.expect_exact(prompt) child.sendline('run') - # Make sure we see the stop hook text from the stop of the process from the run hitting the first breakpoint + # Make sure we see the stop hook text from the stop of the process from + # the run hitting the first breakpoint child.expect_exact('(void *) $') child.expect_exact(prompt) child.sendline('thread step-over') @@ -91,13 +112,16 @@ class StopHookMechanismTestCase(TestBase): print('expecting "%s"' % at_line) child.expect_exact(at_line) - # Now continue the inferior, we'll stop at another breakpoint which is outside the stop-hook range. + # Now continue the inferior, we'll stop at another breakpoint which is + # outside the stop-hook range. child.sendline('process continue') - child.expect_exact('// Another breakpoint which is outside of the stop-hook range.') - #self.DebugPExpect(child) + child.expect_exact( + '// Another breakpoint which is outside of the stop-hook range.') + # self.DebugPExpect(child) child.sendline('thread step-over') - child.expect_exact('// Another breakpoint which is outside of the stop-hook range.') - #self.DebugPExpect(child) + child.expect_exact( + '// Another breakpoint which is outside of the stop-hook range.') + # self.DebugPExpect(child) # Verify that the 'Stop Hooks' mechanism is NOT BEING fired off. self.expect(child.before, exe=False, matching=False, - substrs = ['(void *) $']) + substrs=['(void *) $']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py b/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py index 57395832dc2..3a18877ef2d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py @@ -5,14 +5,15 @@ Test that lldb stop-hook works for multiple threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import configuration from lldbsuite.test import lldbutil + class StopHookForMultipleThreadsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,15 +24,22 @@ class StopHookForMultipleThreadsTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.first_stop = line_number(self.source, '// Set break point at this line, and add a stop-hook.') - self.thread_function = line_number(self.source, '// Break here to test that the stop-hook mechanism works for multiple threads.') - # Build dictionary to have unique executable names for each test method. + self.first_stop = line_number( + self.source, '// Set break point at this line, and add a stop-hook.') + self.thread_function = line_number( + self.source, + '// Break here to test that the stop-hook mechanism works for multiple threads.') + # Build dictionary to have unique executable names for each test + # method. self.exe_name = self.testMethodName self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} @expectedFlakeyFreeBSD("llvm.org/pr15037") - @expectedFlakeyLinux("llvm.org/pr15037") # stop hooks sometimes fail to fire on Linux - @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + # stop hooks sometimes fail to fire on Linux + @expectedFlakeyLinux("llvm.org/pr15037") + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") def test_stop_hook_multiple_threads(self): """Test that lldb stop-hook works for multiple threads.""" self.build(dictionary=self.d) @@ -42,7 +50,8 @@ class StopHookForMultipleThreadsTestCase(TestBase): prompt = "(lldb) " # So that the child gets torn down after the test. - self.child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption)) + self.child = pexpect.spawn('%s %s' % + (lldbtest_config.lldbExec, self.lldbOption)) child = self.child # Turn on logging for what the child sends back. if self.TraceOn(): @@ -50,11 +59,17 @@ class StopHookForMultipleThreadsTestCase(TestBase): if lldb.remote_platform: child.expect_exact(prompt) - child.sendline('platform select %s' % lldb.remote_platform.GetName()) + child.sendline( + 'platform select %s' % + lldb.remote_platform.GetName()) child.expect_exact(prompt) - child.sendline('platform connect %s' % configuration.lldb_platform_url) + child.sendline( + 'platform connect %s' % + configuration.lldb_platform_url) child.expect_exact(prompt) - child.sendline('platform settings -w %s' % configuration.lldb_platform_working_dir) + child.sendline( + 'platform settings -w %s' % + configuration.lldb_platform_working_dir) child.expect_exact(prompt) child.sendline('target create %s' % exe) @@ -63,17 +78,23 @@ class StopHookForMultipleThreadsTestCase(TestBase): child.expect_exact(prompt) child.sendline('breakpoint set -f main.cpp -l %d' % self.first_stop) child.expect_exact(prompt) - child.sendline('breakpoint set -f main.cpp -l %d' % self.thread_function) + child.sendline( + 'breakpoint set -f main.cpp -l %d' % + self.thread_function) child.expect_exact(prompt) - # Now run the program, expect to stop at the first breakpoint which is within the stop-hook range. + # Now run the program, expect to stop at the first breakpoint which is + # within the stop-hook range. child.sendline('run') - child.expect_exact("Process") # 'Process 2415 launched', 'Process 2415 stopped' + # 'Process 2415 launched', 'Process 2415 stopped' + child.expect_exact("Process") child.expect_exact(prompt) - child.sendline('target stop-hook add -o "frame variable --show-globals g_val"') - child.expect_exact("Stop hook") # 'Stop hook #1 added.' + child.sendline( + 'target stop-hook add -o "frame variable --show-globals g_val"') + child.expect_exact("Stop hook") # 'Stop hook #1 added.' child.expect_exact(prompt) - # Continue and expect to find the output emitted by the firing of our stop hook. + # Continue and expect to find the output emitted by the firing of our + # stop hook. child.sendline('continue') child.expect_exact('(uint32_t) ::g_val = ') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py b/lldb/packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py index 126f6e4dab8..7d2900d6171 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py @@ -5,13 +5,13 @@ Test some target commands: create, list, select, variable. from __future__ import print_function - import lldb import sys from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class targetCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -80,17 +80,19 @@ class targetCommandTestCase(TestBase): # We will start from (index + 1) .... base = int(match.group(1), 10) + 1 #print("base is:", base) - break; + break self.runCmd("target create " + exe_a, CURRENT_EXECUTABLE_SET) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("target create " + exe_b, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, 'b.c', self.line_b, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, 'b.c', self.line_b, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("target create " + exe_c, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, 'c.c', self.line_c, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, 'c.c', self.line_c, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.runCmd("target list") @@ -100,13 +102,13 @@ class targetCommandTestCase(TestBase): self.runCmd("target select %d" % (base + 2)) self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['c.c:%d' % self.line_c, - 'stop reason = breakpoint']) + substrs=['c.c:%d' % self.line_c, + 'stop reason = breakpoint']) self.runCmd("target select %d" % (base + 1)) self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['b.c:%d' % self.line_b, - 'stop reason = breakpoint']) + substrs=['b.c:%d' % self.line_b, + 'stop reason = breakpoint']) self.runCmd("target list") @@ -114,89 +116,160 @@ class targetCommandTestCase(TestBase): """Exercise 'target variable' command before and after starting the inferior.""" self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET) - self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["my_global_char", "'X'"]) - self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_global_str', '"abc"']) - self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_static_int', '228']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) self.expect("target variable my_global_str_ptr", matching=False, - substrs = ['"abc"']) + substrs=['"abc"']) self.expect("target variable *my_global_str_ptr", matching=True, - substrs = ['"abc"']) - self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['a']) + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) self.runCmd("b main") self.runCmd("run") - - self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_global_str', '"abc"']) - self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_static_int', '228']) + + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) self.expect("target variable my_global_str_ptr", matching=False, - substrs = ['"abc"']) + substrs=['"abc"']) self.expect("target variable *my_global_str_ptr", matching=True, - substrs = ['"abc"']) - self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['a']) - self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["my_global_char", "'X'"]) + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) self.runCmd("c") # rdar://problem/9763907 # 'target variable' command fails if the target program has been run - self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_global_str', '"abc"']) - self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_static_int', '228']) + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) self.expect("target variable my_global_str_ptr", matching=False, - substrs = ['"abc"']) + substrs=['"abc"']) self.expect("target variable *my_global_str_ptr", matching=True, - substrs = ['"abc"']) - self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['a']) - self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["my_global_char", "'X'"]) + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) def do_target_variable_command_no_fail(self, exe_name): """Exercise 'target variable' command before and after starting the inferior.""" self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET) - self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["my_global_char", "'X'"]) - self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_global_str', '"abc"']) - self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_static_int', '228']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) self.expect("target variable my_global_str_ptr", matching=False, - substrs = ['"abc"']) + substrs=['"abc"']) self.expect("target variable *my_global_str_ptr", matching=True, - substrs = ['"abc"']) - self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['a']) + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) self.runCmd("b main") self.runCmd("run") - + # New feature: you don't need to specify the variable(s) to 'target vaiable'. - # It will find all the global and static variables in the current compile unit. + # It will find all the global and static variables in the current + # compile unit. self.expect("target variable", - substrs = ['my_global_char', - 'my_global_str', - 'my_global_str_ptr', - 'my_static_int']) - - self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_global_str', '"abc"']) - self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['my_static_int', '228']) + substrs=['my_global_char', + 'my_global_str', + 'my_global_str_ptr', + 'my_static_int']) + + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) self.expect("target variable my_global_str_ptr", matching=False, - substrs = ['"abc"']) + substrs=['"abc"']) self.expect("target variable *my_global_str_ptr", matching=True, - substrs = ['"abc"']) - self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['a']) - self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["my_global_char", "'X'"]) + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py index 8184ddcfbf4..094c8670596 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py @@ -5,12 +5,13 @@ Test number of threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class NumberOfThreadsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -28,18 +29,23 @@ class NumberOfThreadsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint with 1 location. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1) # The breakpoint list should show 3 locations. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.line]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.line]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Stopped once. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) + substrs=["stop reason = breakpoint 1."]) # Get the target process target = self.dbg.GetSelectedTarget() @@ -50,4 +56,6 @@ class NumberOfThreadsTestCase(TestBase): # Using std::thread may involve extra threads, so we assert that there are # at least 4 rather than exactly 4. - self.assertTrue(num_threads >= 4, 'Number of expected threads and actual threads do not match.') + self.assertTrue( + num_threads >= 4, + 'Number of expected threads and actual threads do not match.') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py index 902adacb2ab..ba5094f6de3 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py @@ -2,13 +2,15 @@ Test regression for Bug 25251. """ -import os, time +import os +import time import unittest2 import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BreakpointAfterJoinTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -17,11 +19,13 @@ class BreakpointAfterJoinTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number for our breakpoint. - self.breakpoint = line_number('ParallelTask.cpp', '// Set breakpoint here') - - @skipIfTargetAndroid(archs=["arm"]) # The android-arm compiler can't compile the inferior - # because of an issue around std::future. - # TODO: Change the test to don't depend on std::future<T> + self.breakpoint = line_number( + 'ParallelTask.cpp', '// Set breakpoint here') + + # The android-arm compiler can't compile the inferior + @skipIfTargetAndroid(archs=["arm"]) + # because of an issue around std::future. + # TODO: Change the test to don't depend on std::future<T> def test(self): """Test breakpoint handling after a thread join.""" self.build(dictionary=self.getBuildFlags()) @@ -30,23 +34,28 @@ class BreakpointAfterJoinTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint - lldbutil.run_break_set_by_file_and_line (self, "ParallelTask.cpp", self.breakpoint, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "ParallelTask.cpp", self.breakpoint, num_expected_locations=-1) # The breakpoint list should show 1 location. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'ParallelTask.cpp', line = %d, exact_match = 0" % self.breakpoint]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'ParallelTask.cpp', line = %d, exact_match = 0" % + self.breakpoint]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This should not result in a segmentation fault self.expect("thread backtrace all", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint 1."]) + substrs=["stop reason = breakpoint 1."]) # Run to completion self.runCmd("continue") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py index 8ef0fb0a000..34634c37a7f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py @@ -5,13 +5,14 @@ Test number of threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BreakpointAfterJoinTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,9 +23,15 @@ class BreakpointAfterJoinTestCase(TestBase): # Find the line number for our breakpoint. self.breakpoint = line_number('main.cpp', '// Set breakpoint here') - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") def test(self): """Test breakpoint handling after a thread join.""" self.build(dictionary=self.getBuildFlags()) @@ -33,19 +40,24 @@ class BreakpointAfterJoinTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) # The breakpoint list should show 1 location. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.breakpoint]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.breakpoint]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Get the target process target = self.dbg.GetSelectedTarget() @@ -59,12 +71,15 @@ class BreakpointAfterJoinTestCase(TestBase): num_threads = process.GetNumThreads() # Make sure we see at least six threads - self.assertTrue(num_threads >= 6, 'Number of expected threads and actual threads do not match.') + self.assertTrue( + num_threads >= 6, + 'Number of expected threads and actual threads do not match.') # Make sure all threads are stopped for i in range(0, num_threads): - self.assertTrue(process.GetThreadAtIndex(i).IsStopped(), - "Thread {0} didn't stop during breakpoint.".format(i)) + self.assertTrue( + process.GetThreadAtIndex(i).IsStopped(), + "Thread {0} didn't stop during breakpoint.".format(i)) # Run to completion self.runCmd("continue") @@ -75,4 +90,6 @@ class BreakpointAfterJoinTestCase(TestBase): self.runCmd("process status") # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_delay_breakpoint_one_signal/TestConcurrentBreakpointDelayBreakpointOneSignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_delay_breakpoint_one_signal/TestConcurrentBreakpointDelayBreakpointOneSignal.py index bafff4c63f0..d470e1a46bd 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_delay_breakpoint_one_signal/TestConcurrentBreakpointDelayBreakpointOneSignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_delay_breakpoint_one_signal/TestConcurrentBreakpointDelayBreakpointOneSignal.py @@ -12,13 +12,12 @@ class ConcurrentBreakpointDelayBreakpointOneSignal(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_breakpoint_delay_breakpoint_one_signal(self): """Test two threads that trigger a breakpoint (one with a 1 second delay) and one signal thread. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_breakpoint_threads=1, num_delay_breakpoint_threads=1, num_signal_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_one_delay_breakpoint_threads/TestConcurrentBreakpointOneDelayBreakpointThreads.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_one_delay_breakpoint_threads/TestConcurrentBreakpointOneDelayBreakpointThreads.py index 5d31f9a402f..5b88f7e38c8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_one_delay_breakpoint_threads/TestConcurrentBreakpointOneDelayBreakpointThreads.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoint_one_delay_breakpoint_threads/TestConcurrentBreakpointOneDelayBreakpointThreads.py @@ -12,12 +12,11 @@ class ConcurrentBreakpointOneDelayBreakpointThreads(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_breakpoint_one_delay_breakpoint_threads(self): """Test threads that trigger a breakpoint where one thread has a 1 second delay. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_breakpoint_threads=1, num_delay_breakpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoints_delayed_breakpoint_one_watchpoint/TestConcurrentBreakpointsDelayedBreakpointOneWatchpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoints_delayed_breakpoint_one_watchpoint/TestConcurrentBreakpointsDelayedBreakpointOneWatchpoint.py index 8cba670d6b9..b48ff4bf04a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoints_delayed_breakpoint_one_watchpoint/TestConcurrentBreakpointsDelayedBreakpointOneWatchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/breakpoints_delayed_breakpoint_one_watchpoint/TestConcurrentBreakpointsDelayedBreakpointOneWatchpoint.py @@ -8,18 +8,18 @@ from lldbsuite.test.lldbtest import TestBase @skipIfWindows -class ConcurrentBreakpointsDelayedBreakpointOneWatchpoint(ConcurrentEventsBase): +class ConcurrentBreakpointsDelayedBreakpointOneWatchpoint( + ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_breakpoints_delayed_breakpoint_one_watchpoint(self): """Test a breakpoint, a delayed breakpoint, and one watchpoint thread. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_breakpoint_threads=1, num_delay_breakpoint_threads=1, num_watchpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_break/TestConcurrentCrashWithBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_break/TestConcurrentCrashWithBreak.py index a24399347ae..827a5dcd343 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_break/TestConcurrentCrashWithBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_break/TestConcurrentCrashWithBreak.py @@ -12,11 +12,10 @@ class ConcurrentCrashWithBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_crash_with_break(self): """ Test a thread that crashes while another thread hits a breakpoint.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_crash_threads=1, num_breakpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_signal/TestConcurrentCrashWithSignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_signal/TestConcurrentCrashWithSignal.py index a6da4a8b001..4d9d758f323 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_signal/TestConcurrentCrashWithSignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_signal/TestConcurrentCrashWithSignal.py @@ -12,11 +12,10 @@ class ConcurrentCrashWithSignal(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_crash_with_signal(self): """ Test a thread that crashes while another thread generates a signal.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_crash_threads=1, num_signal_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint/TestConcurrentCrashWithWatchpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint/TestConcurrentCrashWithWatchpoint.py index 9c45f9592e8..db7b40ea454 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint/TestConcurrentCrashWithWatchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint/TestConcurrentCrashWithWatchpoint.py @@ -12,12 +12,11 @@ class ConcurrentCrashWithWatchpoint(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_crash_with_watchpoint(self): """ Test a thread that crashes while another thread hits a watchpoint.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_crash_threads=1, num_watchpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint_breakpoint_signal/TestConcurrentCrashWithWatchpointBreakpointSignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint_breakpoint_signal/TestConcurrentCrashWithWatchpointBreakpointSignal.py index 093eb156297..44faf408760 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint_breakpoint_signal/TestConcurrentCrashWithWatchpointBreakpointSignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/crash_with_watchpoint_breakpoint_signal/TestConcurrentCrashWithWatchpointBreakpointSignal.py @@ -12,9 +12,10 @@ class ConcurrentCrashWithWatchpointBreakpointSignal(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_crash_with_watchpoint_breakpoint_signal(self): """ Test a thread that crashes while other threads generate a signal and hit a watchpoint and breakpoint. """ self.build(dictionary=self.getBuildFlags()) @@ -22,5 +23,3 @@ class ConcurrentCrashWithWatchpointBreakpointSignal(ConcurrentEventsBase): num_breakpoint_threads=1, num_signal_threads=1, num_watchpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_break/TestConcurrentDelaySignalBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_break/TestConcurrentDelaySignalBreak.py index 37d8f24de0d..5f69e5615eb 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_break/TestConcurrentDelaySignalBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_break/TestConcurrentDelaySignalBreak.py @@ -12,11 +12,12 @@ class ConcurrentDelaySignalBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_delay_signal_break(self): """Test (1-second delay) signal and a breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_breakpoint_threads=1, num_delay_signal_threads=1) - - + self.do_thread_actions( + num_breakpoint_threads=1, + num_delay_signal_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_watch/TestConcurrentDelaySignalWatch.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_watch/TestConcurrentDelaySignalWatch.py index 1d52d6a6df9..0118f584c1b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_watch/TestConcurrentDelaySignalWatch.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_signal_watch/TestConcurrentDelaySignalWatch.py @@ -12,12 +12,13 @@ class ConcurrentDelaySignalWatch(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_delay_signal_watch(self): """Test a watchpoint and a (1 second delay) signal in multiple threads.""" self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_delay_signal_threads=1, num_watchpoint_threads=1) - - + self.do_thread_actions( + num_delay_signal_threads=1, + num_watchpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_watch_break/TestConcurrentDelayWatchBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_watch_break/TestConcurrentDelayWatchBreak.py index 9f7b91c7fa4..79d04d1ca63 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_watch_break/TestConcurrentDelayWatchBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delay_watch_break/TestConcurrentDelayWatchBreak.py @@ -12,12 +12,13 @@ class ConcurrentDelayWatchBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_delay_watch_break(self): """Test (1-second delay) watchpoint and a breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_breakpoint_threads=1, num_delay_watchpoint_threads=1) - - + self.do_thread_actions( + num_breakpoint_threads=1, + num_delay_watchpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_signal/TestConcurrentDelayedCrashWithBreakpointSignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_signal/TestConcurrentDelayedCrashWithBreakpointSignal.py index 0d36ce663db..8018ee30748 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_signal/TestConcurrentDelayedCrashWithBreakpointSignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_signal/TestConcurrentDelayedCrashWithBreakpointSignal.py @@ -12,13 +12,12 @@ class ConcurrentDelayedCrashWithBreakpointSignal(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_delayed_crash_with_breakpoint_signal(self): """ Test a thread with a delayed crash while other threads generate a signal and hit a breakpoint. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_delay_crash_threads=1, num_breakpoint_threads=1, num_signal_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_watchpoint/TestConcurrentDelayedCrashWithBreakpointWatchpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_watchpoint/TestConcurrentDelayedCrashWithBreakpointWatchpoint.py index 2397c4117f0..552e9424bad 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_watchpoint/TestConcurrentDelayedCrashWithBreakpointWatchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/delayed_crash_with_breakpoint_watchpoint/TestConcurrentDelayedCrashWithBreakpointWatchpoint.py @@ -12,14 +12,13 @@ class ConcurrentDelayedCrashWithBreakpointWatchpoint(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_delayed_crash_with_breakpoint_watchpoint(self): """ Test a thread with a delayed crash while other threads hit a watchpoint and a breakpoint. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_delay_crash_threads=1, num_breakpoint_threads=1, num_watchpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_breakpoints/TestConcurrentManyBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_breakpoints/TestConcurrentManyBreakpoints.py index af55e0b067b..3f221b19752 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_breakpoints/TestConcurrentManyBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_breakpoints/TestConcurrentManyBreakpoints.py @@ -12,11 +12,12 @@ class ConcurrentManyBreakpoints(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @unittest2.skipIf( + TestBase.skipLongRunningTest(), + "Skip this long running test") + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_many_breakpoints(self): """Test 100 breakpoints from 100 threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_breakpoint_threads=100) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_crash/TestConcurrentManyCrash.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_crash/TestConcurrentManyCrash.py index 89b494d489b..a6c4a0082f3 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_crash/TestConcurrentManyCrash.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_crash/TestConcurrentManyCrash.py @@ -12,12 +12,12 @@ class ConcurrentManyCrash(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @unittest2.skipIf( + TestBase.skipLongRunningTest(), + "Skip this long running test") + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_many_crash(self): """Test 100 threads that cause a segfault.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_crash_threads=100) - - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_signals/TestConcurrentManySignals.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_signals/TestConcurrentManySignals.py index 1c07a12de60..5dcf52178b7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_signals/TestConcurrentManySignals.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_signals/TestConcurrentManySignals.py @@ -12,11 +12,12 @@ class ConcurrentManySignals(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @unittest2.skipIf( + TestBase.skipLongRunningTest(), + "Skip this long running test") + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_many_signals(self): """Test 100 signals from 100 threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_signal_threads=100) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_watchpoints/TestConcurrentManyWatchpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_watchpoints/TestConcurrentManyWatchpoints.py index 48fddac5e93..9d2d0ffc2a6 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_watchpoints/TestConcurrentManyWatchpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/many_watchpoints/TestConcurrentManyWatchpoints.py @@ -12,11 +12,12 @@ class ConcurrentManyWatchpoints(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @unittest2.skipIf( + TestBase.skipLongRunningTest(), + "Skip this long running test") + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_many_watchpoints(self): """Test 100 watchpoints from 100 threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_watchpoint_threads=100) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/n_watch_n_break/TestConcurrentNWatchNBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/n_watch_n_break/TestConcurrentNWatchNBreak.py index 79926feb7cf..a538c1b5243 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/n_watch_n_break/TestConcurrentNWatchNBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/n_watch_n_break/TestConcurrentNWatchNBreak.py @@ -12,14 +12,12 @@ class ConcurrentNWatchNBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_n_watch_n_break(self): """Test with 5 watchpoint and breakpoint threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_watchpoint_threads=5, num_breakpoint_threads=5) - - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_break/TestConcurrentSignalBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_break/TestConcurrentSignalBreak.py index 8d863ef131d..7937126cbbf 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_break/TestConcurrentSignalBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_break/TestConcurrentSignalBreak.py @@ -12,11 +12,10 @@ class ConcurrentSignalBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_signal_break(self): """Test signal and a breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_breakpoint_threads=1, num_signal_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_break/TestConcurrentSignalDelayBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_break/TestConcurrentSignalDelayBreak.py index 442b52f0311..33ebcc97520 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_break/TestConcurrentSignalDelayBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_break/TestConcurrentSignalDelayBreak.py @@ -12,12 +12,12 @@ class ConcurrentSignalDelayBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_signal_delay_break(self): """Test signal and a (1 second delay) breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_delay_breakpoint_threads=1, num_signal_threads=1) - - - + self.do_thread_actions( + num_delay_breakpoint_threads=1, + num_signal_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_watch/TestConcurrentSignalDelayWatch.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_watch/TestConcurrentSignalDelayWatch.py index 92d40c1fe3b..4f797730b00 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_watch/TestConcurrentSignalDelayWatch.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_delay_watch/TestConcurrentSignalDelayWatch.py @@ -12,13 +12,13 @@ class ConcurrentSignalDelayWatch(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_signal_delay_watch(self): """Test a (1 second delay) watchpoint and a signal in multiple threads.""" self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_signal_threads=1, num_delay_watchpoint_threads=1) - - - + self.do_thread_actions( + num_signal_threads=1, + num_delay_watchpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_n_watch_n_break/TestConcurrentSignalNWatchNBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_n_watch_n_break/TestConcurrentSignalNWatchNBreak.py index 4c3aaba2943..861273a1701 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_n_watch_n_break/TestConcurrentSignalNWatchNBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_n_watch_n_break/TestConcurrentSignalNWatchNBreak.py @@ -12,14 +12,13 @@ class ConcurrentSignalNWatchNBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_signal_n_watch_n_break(self): """Test one signal thread with 5 watchpoint and breakpoint threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_signal_threads=1, num_watchpoint_threads=5, num_breakpoint_threads=5) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch/TestConcurrentSignalWatch.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch/TestConcurrentSignalWatch.py index bc019e29bd0..8aadd318e9b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch/TestConcurrentSignalWatch.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch/TestConcurrentSignalWatch.py @@ -12,12 +12,11 @@ class ConcurrentSignalWatch(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_signal_watch(self): """Test a watchpoint and a signal in multiple threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_signal_threads=1, num_watchpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch_break/TestConcurrentSignalWatchBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch_break/TestConcurrentSignalWatchBreak.py index a0bf925f564..025e10bf931 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch_break/TestConcurrentSignalWatchBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/signal_watch_break/TestConcurrentSignalWatchBreak.py @@ -12,14 +12,13 @@ class ConcurrentSignalWatchBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_signal_watch_break(self): """Test a signal/watchpoint/breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_signal_threads=1, num_watchpoint_threads=1, num_breakpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoint_threads/TestConcurrentTwoBreakpointThreads.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoint_threads/TestConcurrentTwoBreakpointThreads.py index ecd8061cca2..24012365b8d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoint_threads/TestConcurrentTwoBreakpointThreads.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoint_threads/TestConcurrentTwoBreakpointThreads.py @@ -12,11 +12,10 @@ class ConcurrentTwoBreakpointThreads(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_breakpoint_threads(self): """Test two threads that trigger a breakpoint. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_breakpoint_threads=2) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_delay_signal/TestConcurrentTwoBreakpointsOneDelaySignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_delay_signal/TestConcurrentTwoBreakpointsOneDelaySignal.py index 2814cab1362..56435026253 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_delay_signal/TestConcurrentTwoBreakpointsOneDelaySignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_delay_signal/TestConcurrentTwoBreakpointsOneDelaySignal.py @@ -12,11 +12,12 @@ class ConcurrentTwoBreakpointsOneDelaySignal(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_breakpoints_one_delay_signal(self): """Test two threads that trigger a breakpoint and one (1 second delay) signal thread. """ self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_breakpoint_threads=2, num_delay_signal_threads=1) - - + self.do_thread_actions( + num_breakpoint_threads=2, + num_delay_signal_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_signal/TestConcurrentTwoBreakpointsOneSignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_signal/TestConcurrentTwoBreakpointsOneSignal.py index 2513e61fd4e..bd9f5cd4ca7 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_signal/TestConcurrentTwoBreakpointsOneSignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_signal/TestConcurrentTwoBreakpointsOneSignal.py @@ -12,11 +12,10 @@ class ConcurrentTwoBreakpointsOneSignal(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_breakpoints_one_signal(self): """Test two threads that trigger a breakpoint and one signal thread. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_breakpoint_threads=2, num_signal_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_watchpoint/TestConcurrentTwoBreakpointsOneWatchpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_watchpoint/TestConcurrentTwoBreakpointsOneWatchpoint.py index c3444459109..6d2c8ef6cbc 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_watchpoint/TestConcurrentTwoBreakpointsOneWatchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_breakpoints_one_watchpoint/TestConcurrentTwoBreakpointsOneWatchpoint.py @@ -12,12 +12,13 @@ class ConcurrentTwoBreakpointsOneWatchpoint(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_breakpoints_one_watchpoint(self): """Test two threads that trigger a breakpoint and one watchpoint thread. """ self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_breakpoint_threads=2, num_watchpoint_threads=1) - - + self.do_thread_actions( + num_breakpoint_threads=2, + num_watchpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoint_threads/TestConcurrentTwoWatchpointThreads.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoint_threads/TestConcurrentTwoWatchpointThreads.py index 60b538d43cf..7742f00aeed 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoint_threads/TestConcurrentTwoWatchpointThreads.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoint_threads/TestConcurrentTwoWatchpointThreads.py @@ -12,12 +12,11 @@ class ConcurrentTwoWatchpointThreads(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_watchpoint_threads(self): """Test two threads that trigger a watchpoint. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_watchpoint_threads=2) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_breakpoint/TestConcurrentTwoWatchpointsOneBreakpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_breakpoint/TestConcurrentTwoWatchpointsOneBreakpoint.py index 9e448d607d6..d1be67cad31 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_breakpoint/TestConcurrentTwoWatchpointsOneBreakpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_breakpoint/TestConcurrentTwoWatchpointsOneBreakpoint.py @@ -12,12 +12,13 @@ class ConcurrentTwoWatchpointsOneBreakpoint(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_watchpoints_one_breakpoint(self): """Test two threads that trigger a watchpoint and one breakpoint thread. """ self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_watchpoint_threads=2, num_breakpoint_threads=1) - - + self.do_thread_actions( + num_watchpoint_threads=2, + num_breakpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_delay_breakpoint/TestConcurrentTwoWatchpointsOneDelayBreakpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_delay_breakpoint/TestConcurrentTwoWatchpointsOneDelayBreakpoint.py index 60faf1bbb3f..b1b6fbc82f2 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_delay_breakpoint/TestConcurrentTwoWatchpointsOneDelayBreakpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_delay_breakpoint/TestConcurrentTwoWatchpointsOneDelayBreakpoint.py @@ -12,12 +12,13 @@ class ConcurrentTwoWatchpointsOneDelayBreakpoint(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_watchpoints_one_delay_breakpoint(self): """Test two threads that trigger a watchpoint and one (1 second delay) breakpoint thread. """ self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_watchpoint_threads=2, num_delay_breakpoint_threads=1) - - + self.do_thread_actions( + num_watchpoint_threads=2, + num_delay_breakpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_signal/TestConcurrentTwoWatchpointsOneSignal.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_signal/TestConcurrentTwoWatchpointsOneSignal.py index 070fd64e583..39e77a2052a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_signal/TestConcurrentTwoWatchpointsOneSignal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/two_watchpoints_one_signal/TestConcurrentTwoWatchpointsOneSignal.py @@ -12,12 +12,11 @@ class ConcurrentTwoWatchpointsOneSignal(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_two_watchpoints_one_signal(self): """Test two threads that trigger a watchpoint and one signal thread. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_watchpoint_threads=2, num_signal_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break/TestConcurrentWatchBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break/TestConcurrentWatchBreak.py index c678e0053cb..7537490eaa4 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break/TestConcurrentWatchBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break/TestConcurrentWatchBreak.py @@ -12,12 +12,13 @@ class ConcurrentWatchBreak(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_watch_break(self): """Test watchpoint and a breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_breakpoint_threads=1, num_watchpoint_threads=1) - - + self.do_thread_actions( + num_breakpoint_threads=1, + num_watchpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break_delay/TestConcurrentWatchBreakDelay.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break_delay/TestConcurrentWatchBreakDelay.py index 909ba7a78af..d5af2ce4770 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break_delay/TestConcurrentWatchBreakDelay.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watch_break_delay/TestConcurrentWatchBreakDelay.py @@ -12,12 +12,13 @@ class ConcurrentWatchBreakDelay(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_watch_break_delay(self): """Test watchpoint and a (1 second delay) breakpoint in multiple threads.""" self.build(dictionary=self.getBuildFlags()) - self.do_thread_actions(num_delay_breakpoint_threads=1, num_watchpoint_threads=1) - - + self.do_thread_actions( + num_delay_breakpoint_threads=1, + num_watchpoint_threads=1) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_delay_watchpoint_one_breakpoint/TestConcurrentWatchpointDelayWatchpointOneBreakpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_delay_watchpoint_one_breakpoint/TestConcurrentWatchpointDelayWatchpointOneBreakpoint.py index 52c55244f43..79fc70f888f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_delay_watchpoint_one_breakpoint/TestConcurrentWatchpointDelayWatchpointOneBreakpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_delay_watchpoint_one_breakpoint/TestConcurrentWatchpointDelayWatchpointOneBreakpoint.py @@ -12,14 +12,13 @@ class ConcurrentWatchpointDelayWatchpointOneBreakpoint(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_watchpoint_delay_watchpoint_one_breakpoint(self): """Test two threads that trigger a watchpoint (one with a 1 second delay) and one breakpoint thread. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_watchpoint_threads=1, num_delay_watchpoint_threads=1, num_breakpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_with_delay_watchpoint_threads/TestConcurrentWatchpointWithDelayWatchpointThreads.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_with_delay_watchpoint_threads/TestConcurrentWatchpointWithDelayWatchpointThreads.py index 71ebcc1e509..2b3d422c066 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_with_delay_watchpoint_threads/TestConcurrentWatchpointWithDelayWatchpointThreads.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/watchpoint_with_delay_watchpoint_threads/TestConcurrentWatchpointWithDelayWatchpointThreads.py @@ -12,13 +12,12 @@ class ConcurrentWatchpointWithDelayWatchpointThreads(ConcurrentEventsBase): mydir = ConcurrentEventsBase.compute_mydir(__file__) - @skipIfFreeBSD # timing out on buildbot + @skipIfFreeBSD # timing out on buildbot @skipIfRemoteDueToDeadlock - @expectedFailureAll(triple = '^mips') # Atomic sequences are not supported yet for MIPS in LLDB. + # Atomic sequences are not supported yet for MIPS in LLDB. + @expectedFailureAll(triple='^mips') def test_watchpoint_with_delay_watchpoint_threads(self): """Test two threads that trigger a watchpoint where one thread has a 1 second delay. """ self.build(dictionary=self.getBuildFlags()) self.do_thread_actions(num_watchpoint_threads=1, num_delay_watchpoint_threads=1) - - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py index edd1e885ca9..a9a8aa31e37 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py @@ -5,13 +5,13 @@ Test that step-inst over a crash behaves correctly. from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CreateDuringStepTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,8 +22,12 @@ class CreateDuringStepTestCase(TestBase): @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") @expectedFailureAndroid("llvm.org/pr24497", archs=['arm', 'aarch64']) - @expectedFailureAll(oslist=["linux"], archs=["arm"], bugnumber="llvm.org/pr24497") - @expectedFailureAll(triple = re.compile('^mips')) # IO error due to breakpoint at invalid address + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr24497") + # IO error due to breakpoint at invalid address + @expectedFailureAll(triple=re.compile('^mips')) def test_step_inst_with(self): """Test thread creation during step-inst handling.""" self.build(dictionary=self.getBuildFlags()) @@ -32,21 +36,34 @@ class CreateDuringStepTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target and target.IsValid(), "Target is valid") - self.bp_num = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1) + self.bp_num = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) # Run the program. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) # The stop reason should be breakpoint. - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid(), STOPPED_DUE_TO_BREAKPOINT) # Keep stepping until the inferior crashes while process.GetState() == lldb.eStateStopped and not lldbutil.is_thread_crashed(self, thread): thread.StepInstruction(False) - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) - self.assertTrue(lldbutil.is_thread_crashed(self, thread), "Thread has crashed") + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + self.assertTrue( + lldbutil.is_thread_crashed( + self, + thread), + "Thread has crashed") process.Kill() diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py index 1cb97355395..fb6208a0d3e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py @@ -5,31 +5,33 @@ Test thread creation after process attach. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CreateAfterAttachTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfFreeBSD # Hangs. May be the same as Linux issue llvm.org/pr16229 but - # not yet investigated. Revisit once required functionality - # is implemented for FreeBSD. - @skipIfWindows # Occasionally hangs on Windows, may be same as other issues. + @skipIfFreeBSD # Hangs. May be the same as Linux issue llvm.org/pr16229 but + # not yet investigated. Revisit once required functionality + # is implemented for FreeBSD. + # Occasionally hangs on Windows, may be same as other issues. + @skipIfWindows @skipIfiOSSimulator def test_create_after_attach_with_popen(self): """Test thread creation after process attach.""" self.build(dictionary=self.getBuildFlags(use_cpp11=False)) self.create_after_attach(use_fork=False) - @skipIfFreeBSD # Hangs. Revisit once required functionality is implemented - # for FreeBSD. + @skipIfFreeBSD # Hangs. Revisit once required functionality is implemented + # for FreeBSD. @skipIfRemote - @skipIfWindows # Windows doesn't have fork. + @skipIfWindows # Windows doesn't have fork. @skipIfiOSSimulator def test_create_after_attach_with_fork(self): """Test thread creation after process attach.""" @@ -66,13 +68,16 @@ class CreateAfterAttachTestCase(TestBase): self.assertTrue(process, PROCESS_IS_VALID) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) # This should create a breakpoint in the second child thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) # This should create a breakpoint in the first child thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_3, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_3, num_expected_locations=1) # Note: With std::thread, we cannot rely on particular thread numbers. Using # std::thread may cause the program to spin up a thread pool (and it does on @@ -83,10 +88,10 @@ class CreateAfterAttachTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - '* thread #', - 'main', - 'stop reason = breakpoint']) + substrs=['stopped', + '* thread #', + 'main', + 'stop reason = breakpoint']) # Change a variable to escape the loop self.runCmd("expression main_thread_continue = 1") @@ -96,10 +101,10 @@ class CreateAfterAttachTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - '* thread #', - 'thread_2_func', - 'stop reason = breakpoint']) + substrs=['stopped', + '* thread #', + 'thread_2_func', + 'stop reason = breakpoint']) # Change a variable to escape the loop self.runCmd("expression child_thread_continue = 1") @@ -110,13 +115,15 @@ class CreateAfterAttachTestCase(TestBase): # The stop reason of the thread should be breakpoint. # Thread 3 may or may not have already exited. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - '* thread #', - 'thread_1_func', - 'stop reason = breakpoint']) + substrs=['stopped', + '* thread #', + 'thread_1_func', + 'stop reason = breakpoint']) # Run to completion self.runCmd("continue") # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py index 9401826e304..02f6a1aca41 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py @@ -5,43 +5,74 @@ Test number of threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CreateDuringStepTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18190 thread states not properly maintained") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") def test_step_inst(self): """Test thread creation during step-inst handling.""" self.build(dictionary=self.getBuildFlags()) - self.create_during_step_base("thread step-inst -m all-threads", 'stop reason = instruction step') - - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18190 thread states not properly maintained") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + self.create_during_step_base( + "thread step-inst -m all-threads", + 'stop reason = instruction step') + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") def test_step_over(self): """Test thread creation during step-over handling.""" self.build(dictionary=self.getBuildFlags()) - self.create_during_step_base("thread step-over -m all-threads", 'stop reason = step over') - - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18190 thread states not properly maintained") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + self.create_during_step_base( + "thread step-over -m all-threads", + 'stop reason = step over') + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") def test_step_in(self): """Test thread creation during step-in handling.""" self.build(dictionary=self.getBuildFlags()) - self.create_during_step_base("thread step-in -m all-threads", 'stop reason = step in') + self.create_during_step_base( + "thread step-in -m all-threads", + 'stop reason = step in') def setUp(self): # Call super's setUp(). @@ -56,19 +87,24 @@ class CreateDuringStepTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the stepping thread. - self.bp_num = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1) + self.bp_num = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) # The breakpoint list should show 1 location. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, locations = 1" % self.breakpoint]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, locations = 1" % + self.breakpoint]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Get the target process target = self.dbg.GetSelectedTarget() @@ -78,15 +114,21 @@ class CreateDuringStepTestCase(TestBase): num_threads = process.GetNumThreads() # Make sure we see only two threads - self.assertTrue(num_threads == 2, 'Number of expected threads and actual threads do not match.') + self.assertTrue( + num_threads == 2, + 'Number of expected threads and actual threads do not match.') # Get the thread objects thread1 = process.GetThreadAtIndex(0) thread2 = process.GetThreadAtIndex(1) # Make sure both threads are stopped - self.assertTrue(thread1.IsStopped(), "Thread 1 didn't stop during breakpoint") - self.assertTrue(thread2.IsStopped(), "Thread 2 didn't stop during breakpoint") + self.assertTrue( + thread1.IsStopped(), + "Thread 1 didn't stop during breakpoint") + self.assertTrue( + thread2.IsStopped(), + "Thread 2 didn't stop during breakpoint") # Find the thread that is stopped at the breakpoint stepping_thread = None @@ -95,7 +137,10 @@ class CreateDuringStepTestCase(TestBase): if expected_bp_desc in thread.GetStopDescription(100): stepping_thread = thread break - self.assertTrue(stepping_thread != None, "unable to find thread stopped at %s" % expected_bp_desc) + self.assertTrue( + stepping_thread is not None, + "unable to find thread stopped at %s" % + expected_bp_desc) current_line = self.breakpoint # Keep stepping until we've reached our designated continue point while current_line != self.continuepoint: @@ -108,21 +153,31 @@ class CreateDuringStepTestCase(TestBase): current_line = frame.GetLineEntry().GetLine() # Make sure we're still where we thought we were - self.assertTrue(current_line >= self.breakpoint, "Stepped to unexpected line, " + str(current_line)) - self.assertTrue(current_line <= self.continuepoint, "Stepped to unexpected line, " + str(current_line)) + self.assertTrue( + current_line >= self.breakpoint, + "Stepped to unexpected line, " + + str(current_line)) + self.assertTrue( + current_line <= self.continuepoint, + "Stepped to unexpected line, " + + str(current_line)) # Update the number of threads num_threads = process.GetNumThreads() # Check to see that we increased the number of threads as expected - self.assertTrue(num_threads == 3, 'Number of expected threads and actual threads do not match after thread exit.') + self.assertTrue( + num_threads == 3, + 'Number of expected threads and actual threads do not match after thread exit.') self.expect("thread list", 'Process state is stopped due to step', - substrs = ['stopped', - step_stop_reason]) + substrs=['stopped', + step_stop_reason]) # Run to completion self.runCmd("process continue") # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py index 2c394263d36..3b0d102c6cb 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py @@ -5,13 +5,14 @@ Test number of threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExitDuringBreakpointTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,10 +23,18 @@ class ExitDuringBreakpointTestCase(TestBase): # Find the line number for our breakpoint. self.breakpoint = line_number('main.cpp', '// Set breakpoint here') - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18190 thread states not properly maintained") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") def test(self): """Test thread exit during breakpoint handling.""" self.build(dictionary=self.getBuildFlags()) @@ -33,19 +42,24 @@ class ExitDuringBreakpointTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) # The breakpoint list should show 1 location. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, locations = 1" % self.breakpoint]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, locations = 1" % + self.breakpoint]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Get the target process target = self.dbg.GetSelectedTarget() @@ -59,7 +73,9 @@ class ExitDuringBreakpointTestCase(TestBase): num_threads = process.GetNumThreads() # Make sure we see at least five threads - self.assertTrue(num_threads >= 5, 'Number of expected threads and actual threads do not match.') + self.assertTrue( + num_threads >= 5, + 'Number of expected threads and actual threads do not match.') # Get the thread objects thread1 = process.GetThreadAtIndex(0) @@ -69,14 +85,26 @@ class ExitDuringBreakpointTestCase(TestBase): thread5 = process.GetThreadAtIndex(4) # Make sure all threads are stopped - self.assertTrue(thread1.IsStopped(), "Thread 1 didn't stop during breakpoint") - self.assertTrue(thread2.IsStopped(), "Thread 2 didn't stop during breakpoint") - self.assertTrue(thread3.IsStopped(), "Thread 3 didn't stop during breakpoint") - self.assertTrue(thread4.IsStopped(), "Thread 4 didn't stop during breakpoint") - self.assertTrue(thread5.IsStopped(), "Thread 5 didn't stop during breakpoint") + self.assertTrue( + thread1.IsStopped(), + "Thread 1 didn't stop during breakpoint") + self.assertTrue( + thread2.IsStopped(), + "Thread 2 didn't stop during breakpoint") + self.assertTrue( + thread3.IsStopped(), + "Thread 3 didn't stop during breakpoint") + self.assertTrue( + thread4.IsStopped(), + "Thread 4 didn't stop during breakpoint") + self.assertTrue( + thread5.IsStopped(), + "Thread 5 didn't stop during breakpoint") # Run to completion self.runCmd("continue") # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py index af4a022ed0c..c27bd2d3e4d 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py @@ -5,34 +5,41 @@ Test number of threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ExitDuringStepTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfFreeBSD # llvm.org/pr21411: test is hanging + @skipIfFreeBSD # llvm.org/pr21411: test is hanging def test(self): """Test thread exit during step handling.""" self.build(dictionary=self.getBuildFlags()) - self.exit_during_step_base("thread step-inst -m all-threads", 'stop reason = instruction step') + self.exit_during_step_base( + "thread step-inst -m all-threads", + 'stop reason = instruction step') - @skipIfFreeBSD # llvm.org/pr21411: test is hanging + @skipIfFreeBSD # llvm.org/pr21411: test is hanging def test_step_over(self): """Test thread exit during step-over handling.""" self.build(dictionary=self.getBuildFlags()) - self.exit_during_step_base("thread step-over -m all-threads", 'stop reason = step over') + self.exit_during_step_base( + "thread step-over -m all-threads", + 'stop reason = step over') - @skipIfFreeBSD # llvm.org/pr21411: test is hanging + @skipIfFreeBSD # llvm.org/pr21411: test is hanging def test_step_in(self): """Test thread exit during step-in handling.""" self.build(dictionary=self.getBuildFlags()) - self.exit_during_step_base("thread step-in -m all-threads", 'stop reason = step in') + self.exit_during_step_base( + "thread step-in -m all-threads", + 'stop reason = step in') def setUp(self): # Call super's setUp(). @@ -47,19 +54,24 @@ class ExitDuringStepTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - self.bp_num = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1) + self.bp_num = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) # The breakpoint list should show 1 location. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.breakpoint]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.breakpoint]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Get the target process target = self.dbg.GetSelectedTarget() @@ -67,14 +79,23 @@ class ExitDuringStepTestCase(TestBase): num_threads = process.GetNumThreads() # Make sure we see all three threads - self.assertGreaterEqual(num_threads, 3, 'Number of expected threads and actual threads do not match.') + self.assertGreaterEqual( + num_threads, + 3, + 'Number of expected threads and actual threads do not match.') - stepping_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id(process, self.bp_num) - self.assertIsNotNone(stepping_thread, "Could not find a thread stopped at the breakpoint") + stepping_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, self.bp_num) + self.assertIsNotNone( + stepping_thread, + "Could not find a thread stopped at the breakpoint") current_line = self.breakpoint stepping_frame = stepping_thread.GetFrameAtIndex(0) - self.assertEqual(current_line, stepping_frame.GetLineEntry().GetLine(), "Starting line for stepping doesn't match breakpoint line.") + self.assertEqual( + current_line, + stepping_frame.GetLineEntry().GetLine(), + "Starting line for stepping doesn't match breakpoint line.") # Keep stepping until we've reached our designated continue point while current_line != self.continuepoint: @@ -90,8 +111,16 @@ class ExitDuringStepTestCase(TestBase): current_line = frame.GetLineEntry().GetLine() - self.assertGreaterEqual(current_line, self.breakpoint, "Stepped to unexpected line, " + str(current_line)) - self.assertLessEqual(current_line, self.continuepoint, "Stepped to unexpected line, " + str(current_line)) + self.assertGreaterEqual( + current_line, + self.breakpoint, + "Stepped to unexpected line, " + + str(current_line)) + self.assertLessEqual( + current_line, + self.continuepoint, + "Stepped to unexpected line, " + + str(current_line)) self.runCmd("thread list") @@ -99,11 +128,14 @@ class ExitDuringStepTestCase(TestBase): new_num_threads = process.GetNumThreads() # Check to see that we reduced the number of threads as expected - self.assertEqual(new_num_threads, num_threads-1, 'Number of threads did not reduce by 1 after thread exit.') + self.assertEqual( + new_num_threads, + num_threads - 1, + 'Number of threads did not reduce by 1 after thread exit.') self.expect("thread list", 'Process state is stopped due to step', - substrs = ['stopped', - step_stop_reason]) + substrs=['stopped', + step_stop_reason]) # Run to completion self.runCmd("continue") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py index 4c55bcd982a..26ee5d4084e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py @@ -5,13 +5,14 @@ Test jumping to different places. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ThreadJumpTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,31 +30,50 @@ class ThreadJumpTestCase(TestBase): self.mark4 = line_number('main.cpp', '// 4th marker') self.mark5 = line_number('other.cpp', '// other marker') - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.mark3, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.mark3, num_expected_locations=1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint 1. - self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT + " 1", - substrs=['stopped', 'main.cpp:{}'.format(self.mark3), 'stop reason = breakpoint 1']) + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT + " 1", + substrs=[ + 'stopped', + 'main.cpp:{}'.format( + self.mark3), + 'stop reason = breakpoint 1']) - self.do_min_test(self.mark3, self.mark1, "i", "4"); # Try the int path, force it to return 'a' - self.do_min_test(self.mark3, self.mark2, "i", "5"); # Try the int path, force it to return 'b' - self.do_min_test(self.mark4, self.mark1, "j", "7"); # Try the double path, force it to return 'a' - self.do_min_test(self.mark4, self.mark2, "j", "8"); # Try the double path, force it to return 'b' + # Try the int path, force it to return 'a' + self.do_min_test(self.mark3, self.mark1, "i", "4") + # Try the int path, force it to return 'b' + self.do_min_test(self.mark3, self.mark2, "i", "5") + # Try the double path, force it to return 'a' + self.do_min_test(self.mark4, self.mark1, "j", "7") + # Try the double path, force it to return 'b' + self.do_min_test(self.mark4, self.mark2, "j", "8") # Try jumping to another function in a different file. - self.runCmd("thread jump --file other.cpp --line %i --force" % self.mark5) + self.runCmd( + "thread jump --file other.cpp --line %i --force" % + self.mark5) self.expect("process status", - substrs = ["at other.cpp:%i" % self.mark5]) + substrs=["at other.cpp:%i" % self.mark5]) # Try jumping to another function (without forcing) - self.expect("j main.cpp:%i" % self.mark1, COMMAND_FAILED_AS_EXPECTED, error = True, - substrs = ["error"]) - + self.expect( + "j main.cpp:%i" % + self.mark1, + COMMAND_FAILED_AS_EXPECTED, + error=True, + substrs=["error"]) + def do_min_test(self, start, jump, var, value): - self.runCmd("j %i" % start) # jump to the start marker + # jump to the start marker + self.runCmd("j %i" % start) self.runCmd("thread step-in") # step into the min fn - self.runCmd("j %i" % jump) # jump to the branch we're interested in + # jump to the branch we're interested in + self.runCmd("j %i" % jump) self.runCmd("thread step-out") # return out self.runCmd("thread step-over") # assign to the global - self.expect("expr %s" % var, substrs = [value]) # check it + self.expect("expr %s" % var, substrs=[value]) # check it diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py index d4b1eb32a9a..7f542d442ac 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py @@ -5,13 +5,14 @@ Test number of threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MultipleBreakpointTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,10 +23,18 @@ class MultipleBreakpointTestCase(TestBase): # Find the line number for our breakpoint. self.breakpoint = line_number('main.cpp', '// Set breakpoint here') - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18190 thread states not properly maintained") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") def test(self): """Test simultaneous breakpoints in multiple threads.""" self.build(dictionary=self.getBuildFlags()) @@ -33,11 +42,16 @@ class MultipleBreakpointTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) # The breakpoint list should show 1 location. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, locations = 1" % self.breakpoint]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, locations = 1" % + self.breakpoint]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -45,8 +59,8 @@ class MultipleBreakpointTestCase(TestBase): # The stop reason of the thread should be breakpoint. # The breakpoint may be hit in either thread 2 or thread 3. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Get the target process target = self.dbg.GetSelectedTarget() @@ -56,7 +70,9 @@ class MultipleBreakpointTestCase(TestBase): num_threads = process.GetNumThreads() # Make sure we see all three threads - self.assertTrue(num_threads >= 3, 'Number of expected threads and actual threads do not match.') + self.assertTrue( + num_threads >= 3, + 'Number of expected threads and actual threads do not match.') # Get the thread objects thread1 = process.GetThreadAtIndex(0) @@ -64,9 +80,15 @@ class MultipleBreakpointTestCase(TestBase): thread3 = process.GetThreadAtIndex(2) # Make sure both threads are stopped - self.assertTrue(thread1.IsStopped(), "Primary thread didn't stop during breakpoint") - self.assertTrue(thread2.IsStopped(), "Secondary thread didn't stop during breakpoint") - self.assertTrue(thread3.IsStopped(), "Tertiary thread didn't stop during breakpoint") + self.assertTrue( + thread1.IsStopped(), + "Primary thread didn't stop during breakpoint") + self.assertTrue( + thread2.IsStopped(), + "Secondary thread didn't stop during breakpoint") + self.assertTrue( + thread3.IsStopped(), + "Tertiary thread didn't stop during breakpoint") # Delete the first breakpoint then continue self.runCmd("breakpoint delete 1") @@ -75,4 +97,6 @@ class MultipleBreakpointTestCase(TestBase): self.runCmd("continue") # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py index 5afb57bf4ba..c3604783d89 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py @@ -5,28 +5,37 @@ Test thread states. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ThreadStateTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr15824 thread states not properly maintained") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") def test_state_after_breakpoint(self): """Test thread state after breakpoint.""" self.build(dictionary=self.getBuildFlags(use_cpp11=False)) self.thread_state_after_breakpoint_test() - @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly - @expectedFailureAll(oslist=lldbplatformutil.getDarwinOSTriples(), bugnumber="llvm.org/pr23669") + @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr23669") @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr15824") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24660") def test_state_after_continue(self): @@ -34,24 +43,31 @@ class ThreadStateTestCase(TestBase): self.build(dictionary=self.getBuildFlags(use_cpp11=False)) self.thread_state_after_continue_test() - @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly + @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly @expectedFailureDarwin('llvm.org/pr23669') @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24660") - @unittest2.expectedFailure("llvm.org/pr16712") # thread states not properly maintained + # thread states not properly maintained + @unittest2.expectedFailure("llvm.org/pr16712") def test_state_after_expression(self): """Test thread state after expression.""" self.build(dictionary=self.getBuildFlags(use_cpp11=False)) self.thread_state_after_expression_test() - @unittest2.expectedFailure("llvm.org/pr16712") # thread states not properly maintained - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + # thread states not properly maintained + @unittest2.expectedFailure("llvm.org/pr16712") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") def test_process_interrupt(self): """Test process interrupt.""" self.build(dictionary=self.getBuildFlags(use_cpp11=False)) self.process_interrupt_test() - @unittest2.expectedFailure("llvm.org/pr15824") # thread states not properly maintained - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + # thread states not properly maintained + @unittest2.expectedFailure("llvm.org/pr15824") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") def test_process_state(self): """Test thread states (comprehensive).""" self.build(dictionary=self.getBuildFlags(use_cpp11=False)) @@ -70,7 +86,8 @@ class ThreadStateTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - bp = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1) + bp = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -79,12 +96,16 @@ class ThreadStateTestCase(TestBase): target = self.dbg.GetSelectedTarget() process = target.GetProcess() - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # Make sure the thread is in the stopped state. - self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' during breakpoint 1.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' during breakpoint 1.") + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' during breakpoint 1.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' during breakpoint 1.") # Kill the process self.runCmd("process kill") @@ -92,8 +113,12 @@ class ThreadStateTestCase(TestBase): def wait_for_running_event(self, process): listener = self.dbg.GetListener() if lldb.remote_platform: - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateConnected]) - lldbutil.expect_state_changes(self, listener, process, [lldb.eStateRunning]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateConnected]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) def thread_state_after_continue_test(self): """Test thread state after continue.""" @@ -101,8 +126,10 @@ class ThreadStateTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -111,17 +138,23 @@ class ThreadStateTestCase(TestBase): target = self.dbg.GetSelectedTarget() process = target.GetProcess() - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) - # Continue, the inferior will go into an infinite loop waiting for 'g_test' to change. + # Continue, the inferior will go into an infinite loop waiting for + # 'g_test' to change. self.dbg.SetAsync(True) self.runCmd("continue") self.wait_for_running_event(process) # Check the thread state. It should be running. - self.assertFalse(thread.IsStopped(), "Thread state is \'stopped\' when it should be running.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' when it should be running.") + self.assertFalse( + thread.IsStopped(), + "Thread state is \'stopped\' when it should be running.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' when it should be running.") # Go back to synchronous interactions self.dbg.SetAsync(False) @@ -135,8 +168,10 @@ class ThreadStateTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -145,27 +180,32 @@ class ThreadStateTestCase(TestBase): target = self.dbg.GetSelectedTarget() process = target.GetProcess() - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # Get the inferior out of its loop self.runCmd("expression g_test = 1") # Check the thread state - self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' after expression evaluation.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' after expression evaluation.") + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' after expression evaluation.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' after expression evaluation.") # Let the process run to completion self.runCmd("process continue") - def process_interrupt_test(self): """Test process interrupt and continue.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -174,10 +214,12 @@ class ThreadStateTestCase(TestBase): target = self.dbg.GetSelectedTarget() process = target.GetProcess() - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) - # Continue, the inferior will go into an infinite loop waiting for 'g_test' to change. + # Continue, the inferior will go into an infinite loop waiting for + # 'g_test' to change. self.dbg.SetAsync(True) self.runCmd("continue") self.wait_for_running_event(process) @@ -202,8 +244,10 @@ class ThreadStateTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -211,21 +255,30 @@ class ThreadStateTestCase(TestBase): # Get the target process target = self.dbg.GetSelectedTarget() process = target.GetProcess() - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # Make sure the thread is in the stopped state. - self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' during breakpoint 1.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' during breakpoint 1.") - - # Continue, the inferior will go into an infinite loop waiting for 'g_test' to change. + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' during breakpoint 1.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' during breakpoint 1.") + + # Continue, the inferior will go into an infinite loop waiting for + # 'g_test' to change. self.dbg.SetAsync(True) self.runCmd("continue") self.wait_for_running_event(process) # Check the thread state. It should be running. - self.assertFalse(thread.IsStopped(), "Thread state is \'stopped\' when it should be running.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' when it should be running.") + self.assertFalse( + thread.IsStopped(), + "Thread state is \'stopped\' when it should be running.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' when it should be running.") # Go back to synchronous interactions self.dbg.SetAsync(False) @@ -236,15 +289,22 @@ class ThreadStateTestCase(TestBase): self.assertEqual(thread.GetState(), lldb.eStopReasonSignal) # Check the thread state - self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' after process stop.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' after process stop.") + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' after process stop.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' after process stop.") # Get the inferior out of its loop self.runCmd("expression g_test = 1") # Check the thread state - self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' after expression evaluation.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' after expression evaluation.") + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' after expression evaluation.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' after expression evaluation.") self.assertEqual(thread.GetState(), lldb.eStopReasonSignal) @@ -254,8 +314,11 @@ class ThreadStateTestCase(TestBase): self.assertEqual(thread.GetState(), lldb.eStopReasonBreakpoint) # Make sure both threads are stopped - self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' during breakpoint 2.") - self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' during breakpoint 2.") + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' during breakpoint 2.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' during breakpoint 2.") # Run to completion self.runCmd("continue") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py index 735ee80d624..f043013b90c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py @@ -5,38 +5,54 @@ Test stepping out from a function in a multi-threaded program. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ThreadStepOutTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfLinux # Test occasionally times out on the Linux build bot - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr18066 inferior does not exit") + # Test occasionally times out on the Linux build bot + @skipIfLinux + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18066 inferior does not exit") @expectedFailureAll(oslist=["windows"]) def test_step_single_thread(self): """Test thread step out on one thread via command interpreter. """ self.build(dictionary=self.getBuildFlags()) self.step_out_test(self.step_out_single_thread_with_cmd) - @skipIfLinux # Test occasionally times out on the Linux build bot - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr19347 2nd thread stops at breakpoint") + # Test occasionally times out on the Linux build bot + @skipIfLinux + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr19347 2nd thread stops at breakpoint") @expectedFailureAll(oslist=["windows"]) def test_step_all_threads(self): """Test thread step out on all threads via command interpreter. """ self.build(dictionary=self.getBuildFlags()) self.step_out_test(self.step_out_all_threads_with_cmd) - @skipIfLinux # Test occasionally times out on the Linux build bot - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr19347 2nd thread stops at breakpoint") + # Test occasionally times out on the Linux build bot + @skipIfLinux + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr19347 2nd thread stops at breakpoint") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24681") def test_python(self): """Test thread step out on one thread via Python API (dwarf).""" @@ -48,43 +64,63 @@ class ThreadStepOutTestCase(TestBase): TestBase.setUp(self) # Find the line number for our breakpoint. self.breakpoint = line_number('main.cpp', '// Set breakpoint here') - if "gcc" in self.getCompiler() or self.isIntelCompiler(): - self.step_out_destination = line_number('main.cpp', '// Expect to stop here after step-out (icc and gcc)') + if "gcc" in self.getCompiler() or self.isIntelCompiler(): + self.step_out_destination = line_number( + 'main.cpp', '// Expect to stop here after step-out (icc and gcc)') else: - self.step_out_destination = line_number('main.cpp', '// Expect to stop here after step-out (clang)') + self.step_out_destination = line_number( + 'main.cpp', '// Expect to stop here after step-out (clang)') def step_out_single_thread_with_cmd(self): self.step_out_with_cmd("this-thread") - self.expect("thread backtrace all", "Thread location after step out is correct", - substrs = ["main.cpp:%d" % self.step_out_destination, - "main.cpp:%d" % self.breakpoint]) + self.expect( + "thread backtrace all", + "Thread location after step out is correct", + substrs=[ + "main.cpp:%d" % + self.step_out_destination, + "main.cpp:%d" % + self.breakpoint]) def step_out_all_threads_with_cmd(self): self.step_out_with_cmd("all-threads") - self.expect("thread backtrace all", "Thread location after step out is correct", - substrs = ["main.cpp:%d" % self.step_out_destination]) + self.expect( + "thread backtrace all", + "Thread location after step out is correct", + substrs=[ + "main.cpp:%d" % + self.step_out_destination]) def step_out_with_cmd(self, run_mode): self.runCmd("thread select %d" % self.step_out_thread.GetIndexID()) self.runCmd("thread step-out -m %s" % run_mode) self.expect("process status", "Expected stop reason to be step-out", - substrs = ["stop reason = step out"]) + substrs=["stop reason = step out"]) - self.expect("thread list", "Selected thread did not change during step-out", - substrs = ["* thread #%d" % self.step_out_thread.GetIndexID()]) + self.expect( + "thread list", + "Selected thread did not change during step-out", + substrs=[ + "* thread #%d" % + self.step_out_thread.GetIndexID()]) def step_out_with_python(self): self.step_out_thread.StepOut() reason = self.step_out_thread.GetStopReason() - self.assertEqual(lldb.eStopReasonPlanComplete, reason, - "Expected thread stop reason 'plancomplete', but got '%s'" % lldbutil.stop_reason_to_str(reason)) + self.assertEqual( + lldb.eStopReasonPlanComplete, + reason, + "Expected thread stop reason 'plancomplete', but got '%s'" % + lldbutil.stop_reason_to_str(reason)) # Verify location after stepping out frame = self.step_out_thread.GetFrameAtIndex(0) desc = lldbutil.get_description(frame.GetLineEntry()) expect = "main.cpp:%d" % self.step_out_destination - self.assertTrue(expect in desc, "Expected %s but thread stopped at %s" % (expect, desc)) + self.assertTrue( + expect in desc, "Expected %s but thread stopped at %s" % + (expect, desc)) def step_out_test(self, step_out_func): """Test single thread step out of a function.""" @@ -92,11 +128,16 @@ class ThreadStepOutTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint in the main thread. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) # The breakpoint list should show 1 location. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.breakpoint]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.breakpoint]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -107,7 +148,10 @@ class ThreadStepOutTestCase(TestBase): # Get the number of threads, ensure we see all three. num_threads = self.inferior_process.GetNumThreads() - self.assertEqual(num_threads, 3, 'Number of expected threads and actual threads do not match.') + self.assertEqual( + num_threads, + 3, + 'Number of expected threads and actual threads do not match.') (breakpoint_threads, other_threads) = ([], []) lldbutil.sort_stopped_threads(self.inferior_process, @@ -115,10 +159,12 @@ class ThreadStepOutTestCase(TestBase): other_threads=other_threads) while len(breakpoint_threads) < 2: - self.runCmd("thread continue %s" % " ".join([str(x.GetIndexID()) for x in other_threads])) - lldbutil.sort_stopped_threads(self.inferior_process, - breakpoint_threads=breakpoint_threads, - other_threads=other_threads) + self.runCmd("thread continue %s" % + " ".join([str(x.GetIndexID()) for x in other_threads])) + lldbutil.sort_stopped_threads( + self.inferior_process, + breakpoint_threads=breakpoint_threads, + other_threads=other_threads) self.step_out_thread = breakpoint_threads[0] @@ -129,4 +175,5 @@ class ThreadStepOutTestCase(TestBase): self.runCmd("continue") # At this point, the inferior process should have exited. - self.assertTrue(self.inferior_process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue(self.inferior_process.GetState() == + lldb.eStateExited, PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py index 2ba6f2e57f2..deedc4b7507 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py @@ -5,12 +5,13 @@ Test number of threads. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class ThreadExitTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -31,17 +32,28 @@ class ThreadExitTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # This should create a breakpoint with 1 location. - bp1_id = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1) - bp2_id = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1) - bp3_id = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_3, num_expected_locations=1) - bp4_id = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_4, num_expected_locations=1) + bp1_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + bp2_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) + bp3_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_3, num_expected_locations=1) + bp4_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_4, num_expected_locations=1) # The breakpoint list should show 1 locations. - self.expect("breakpoint list -f", "Breakpoint location shown correctly", - substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_1, - "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_2, - "3: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_3, - "4: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_4]) + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_1, + "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_2, + "3: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_3, + "4: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_4]) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -49,39 +61,59 @@ class ThreadExitTestCase(TestBase): target = self.dbg.GetSelectedTarget() process = target.GetProcess() - stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id(process, bp1_id) - self.assertIsNotNone(stopped_thread, "Process is not stopped at breakpoint 1") + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp1_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 1") # Get the number of threads num_threads = process.GetNumThreads() - self.assertGreaterEqual(num_threads, 2, 'Number of expected threads and actual threads do not match at breakpoint 1.') + self.assertGreaterEqual( + num_threads, + 2, + 'Number of expected threads and actual threads do not match at breakpoint 1.') # Run to the second breakpoint self.runCmd("continue") - stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id(process, bp2_id) - self.assertIsNotNone(stopped_thread, "Process is not stopped at breakpoint 2") + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp2_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 2") # Update the number of threads new_num_threads = process.GetNumThreads() - self.assertEqual(new_num_threads, num_threads+1, 'Number of expected threads did not increase by 1 at bp 2.') + self.assertEqual( + new_num_threads, + num_threads + 1, + 'Number of expected threads did not increase by 1 at bp 2.') # Run to the third breakpoint self.runCmd("continue") - stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id(process, bp3_id) - self.assertIsNotNone(stopped_thread, "Process is not stopped at breakpoint 3") + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp3_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 3") # Update the number of threads new_num_threads = process.GetNumThreads() - self.assertEqual(new_num_threads, num_threads, 'Number of expected threads is not equal to original number of threads at bp 3.') + self.assertEqual( + new_num_threads, + num_threads, + 'Number of expected threads is not equal to original number of threads at bp 3.') # Run to the fourth breakpoint self.runCmd("continue") - stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id(process, bp4_id) - self.assertIsNotNone(stopped_thread, "Process is not stopped at breakpoint 4") + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp4_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 4") # Update the number of threads new_num_threads = process.GetNumThreads() - self.assertEqual(new_num_threads, num_threads-1, 'Number of expected threads did not decrease by 1 at bp 4.') + self.assertEqual( + new_num_threads, + num_threads - 1, + 'Number of expected threads did not decrease by 1 at bp 4.') # Run to completion self.runCmd("continue") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py index 12bacabd0d7..0377b0c0a80 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py @@ -5,14 +5,15 @@ Test that we obey thread conditioned breakpoints. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ThreadSpecificBreakTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,24 +31,42 @@ class ThreadSpecificBreakTestCase(TestBase): # This test works by setting a breakpoint in a function conditioned to stop only on # the main thread, and then calling this function on a secondary thread, joining, # and then calling again on the main thread. If the thread specific breakpoint works - # then it should not be hit on the secondary thread, only on the main thread. - - main_source_spec = lldb.SBFileSpec ("main.cpp") - - main_breakpoint = target.BreakpointCreateBySourceRegex("Set main breakpoint here", main_source_spec); - thread_breakpoint = target.BreakpointCreateBySourceRegex("Set thread-specific breakpoint here", main_source_spec) - - self.assertTrue(main_breakpoint.IsValid(), "Failed to set main breakpoint.") - self.assertGreater(main_breakpoint.GetNumLocations(), 0, "main breakpoint has no locations associated with it.") - self.assertTrue(thread_breakpoint.IsValid(), "Failed to set thread breakpoint.") - self.assertGreater(thread_breakpoint.GetNumLocations(), 0, "thread breakpoint has no locations associated with it.") - - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + # then it should not be hit on the secondary thread, only on the main + # thread. + + main_source_spec = lldb.SBFileSpec("main.cpp") + + main_breakpoint = target.BreakpointCreateBySourceRegex( + "Set main breakpoint here", main_source_spec) + thread_breakpoint = target.BreakpointCreateBySourceRegex( + "Set thread-specific breakpoint here", main_source_spec) + + self.assertTrue( + main_breakpoint.IsValid(), + "Failed to set main breakpoint.") + self.assertGreater( + main_breakpoint.GetNumLocations(), + 0, + "main breakpoint has no locations associated with it.") + self.assertTrue( + thread_breakpoint.IsValid(), + "Failed to set thread breakpoint.") + self.assertGreater( + thread_breakpoint.GetNumLocations(), + 0, + "thread breakpoint has no locations associated with it.") + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - stopped_threads = lldbutil.get_threads_stopped_at_breakpoint(process, main_breakpoint) - self.assertEqual(len(stopped_threads), 1, "main breakpoint stopped at unexpected number of threads") + stopped_threads = lldbutil.get_threads_stopped_at_breakpoint( + process, main_breakpoint) + self.assertEqual( + len(stopped_threads), + 1, + "main breakpoint stopped at unexpected number of threads") main_thread = stopped_threads[0] main_thread_id = main_thread.GetThreadID() @@ -58,7 +77,17 @@ class ThreadSpecificBreakTestCase(TestBase): process.Continue() next_stop_state = process.GetState() - self.assertEqual(next_stop_state, lldb.eStateStopped, "We should have stopped at the thread breakpoint.") - stopped_threads = lldbutil.get_threads_stopped_at_breakpoint(process, thread_breakpoint) - self.assertEqual(len(stopped_threads), 1, "thread breakpoint stopped at unexpected number of threads") - self.assertEqual(stopped_threads[0].GetThreadID(), main_thread_id, "thread breakpoint stopped at the wrong thread") + self.assertEqual( + next_stop_state, + lldb.eStateStopped, + "We should have stopped at the thread breakpoint.") + stopped_threads = lldbutil.get_threads_stopped_at_breakpoint( + process, thread_breakpoint) + self.assertEqual( + len(stopped_threads), + 1, + "thread breakpoint stopped at unexpected number of threads") + self.assertEqual( + stopped_threads[0].GetThreadID(), + main_thread_id, + "thread breakpoint stopped at the wrong thread") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py b/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py index ec5719d730d..da9ba59f992 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py @@ -6,20 +6,23 @@ conditioned breakpoints simultaneously from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ThreadSpecificBreakPlusConditionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIf(oslist=['windows', 'freebsd']) # test frequently times out or hangs - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr18522') # hits break in another thread in testrun + # test frequently times out or hangs + @skipIf(oslist=['windows', 'freebsd']) + # hits break in another thread in testrun + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr18522') @add_test_categories(['pyapi']) def test_python(self): """Test that we obey thread conditioned breakpoints.""" @@ -29,18 +32,24 @@ class ThreadSpecificBreakPlusConditionTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - main_source_spec = lldb.SBFileSpec ("main.cpp") + main_source_spec = lldb.SBFileSpec("main.cpp") - # Set a breakpoint in the thread body, and make it active for only the first thread. - break_thread_body = target.BreakpointCreateBySourceRegex ("Break here in thread body.", main_source_spec) - self.assertTrue (break_thread_body.IsValid() and break_thread_body.GetNumLocations() > 0, "Failed to set thread body breakpoint.") + # Set a breakpoint in the thread body, and make it active for only the + # first thread. + break_thread_body = target.BreakpointCreateBySourceRegex( + "Break here in thread body.", main_source_spec) + self.assertTrue( + break_thread_body.IsValid() and break_thread_body.GetNumLocations() > 0, + "Failed to set thread body breakpoint.") - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_thread_body) - + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_thread_body) + victim_thread = threads[0] # Pick one of the threads, and change the breakpoint so it ONLY stops for this thread, @@ -51,14 +60,18 @@ class ThreadSpecificBreakPlusConditionTestCase(TestBase): frame = victim_thread.GetFrameAtIndex(0) value = frame.FindVariable("my_value").GetValueAsSigned(0) - self.assertTrue (value > 0 and value < 11, "Got a reasonable value for my_value.") + self.assertTrue( + value > 0 and value < 11, + "Got a reasonable value for my_value.") - cond_string = "my_value != %d"%(value) + cond_string = "my_value != %d" % (value) break_thread_body.SetThreadID(victim_thread.GetThreadID()) - break_thread_body.SetCondition (cond_string) + break_thread_body.SetCondition(cond_string) process.Continue() next_stop_state = process.GetState() - self.assertTrue (next_stop_state == lldb.eStateExited, "We should have not hit the breakpoint again.") + self.assertTrue( + next_stop_state == lldb.eStateExited, + "We should have not hit the breakpoint again.") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py index 44fa9cedc86..241c49897ef 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py @@ -2,25 +2,29 @@ Tests basic ThreadSanitizer support (detecting a data race). """ -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import json + class TsanBasicTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt @skipUnlessThreadSanitizer - def test (self): - self.build () - self.tsan_tests () + def test(self): + self.build() + self.tsan_tests() def setUp(self): # Call super's setUp(). @@ -29,26 +33,33 @@ class TsanBasicTestCase(TestBase): self.line_thread1 = line_number('main.c', '// thread1 line') self.line_thread2 = line_number('main.c', '// thread2 line') - def tsan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def tsan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") # the stop reason of the thread should be breakpoint. self.expect("thread list", "A data race should be detected", - substrs = ['stopped', 'stop reason = Data race detected']) + substrs=['stopped', 'stop reason = Data race detected']) - self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation) + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) # test that the TSan dylib is present - self.expect("image lookup -n __tsan_get_current_report", "__tsan_get_current_report should be present", - substrs = ['1 match found']) + self.expect( + "image lookup -n __tsan_get_current_report", + "__tsan_get_current_report should be present", + substrs=['1 match found']) # We should be stopped in __tsan_on_report process = self.dbg.GetSelectedTarget().process @@ -56,7 +67,8 @@ class TsanBasicTestCase(TestBase): frame = thread.GetSelectedFrame() self.assertTrue("__tsan_on_report" in frame.GetFunctionName()) - # The stopped thread backtrace should contain either line1 or line2 from main.c. + # The stopped thread backtrace should contain either line1 or line2 + # from main.c. found = False for i in range(0, thread.GetNumFrames()): frame = thread.GetFrameAtIndex(i) @@ -67,8 +79,13 @@ class TsanBasicTestCase(TestBase): found = True self.assertTrue(found) - self.expect("thread info -s", "The extended stop info should contain the TSan provided fields", - substrs = ["instrumentation_class", "description", "mops"]) + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) output_lines = self.res.GetOutput().split('\n') json_line = '\n'.join(output_lines[2:]) @@ -77,10 +94,12 @@ class TsanBasicTestCase(TestBase): self.assertEqual(data["issue_type"], "data-race") self.assertEqual(len(data["mops"]), 2) - backtraces = thread.GetStopReasonExtendedBacktraces(lldb.eInstrumentationRuntimeTypeAddressSanitizer) + backtraces = thread.GetStopReasonExtendedBacktraces( + lldb.eInstrumentationRuntimeTypeAddressSanitizer) self.assertEqual(backtraces.GetSize(), 0) - backtraces = thread.GetStopReasonExtendedBacktraces(lldb.eInstrumentationRuntimeTypeThreadSanitizer) + backtraces = thread.GetStopReasonExtendedBacktraces( + lldb.eInstrumentationRuntimeTypeThreadSanitizer) self.assertTrue(backtraces.GetSize() >= 2) # First backtrace is a memory operation @@ -111,8 +130,8 @@ class TsanBasicTestCase(TestBase): # the stop reason of the thread should be a SIGABRT. self.expect("thread list", "We should be stopped due a SIGABRT", - substrs = ['stopped', 'stop reason = signal SIGABRT']) + substrs=['stopped', 'stop reason = signal SIGABRT']) # test that we're in pthread_kill now (TSan abort the process) self.expect("thread list", "We should be stopped in pthread_kill", - substrs = ['pthread_kill']) + substrs=['pthread_kill']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/TestTsanCPPGlobalLocation.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/TestTsanCPPGlobalLocation.py index 230ff982da0..8aa75d22e97 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/TestTsanCPPGlobalLocation.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/TestTsanCPPGlobalLocation.py @@ -2,47 +2,59 @@ Tests that TSan correctly reports the filename and line number of a racy global C++ variable. """ -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import json + class TsanCPPGlobalLocationTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt @skipUnlessThreadSanitizer - def test (self): - self.build () - self.tsan_tests () + def test(self): + self.build() + self.tsan_tests() def setUp(self): # Call super's setUp(). TestBase.setUp(self) - def tsan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def tsan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") # the stop reason of the thread should be breakpoint. self.expect("thread list", "A data race should be detected", - substrs = ['stopped', 'stop reason = Data race detected']) + substrs=['stopped', 'stop reason = Data race detected']) - self.expect("thread info -s", "The extended stop info should contain the TSan provided fields", - substrs = ["instrumentation_class", "description", "mops"]) + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) output_lines = self.res.GetOutput().split('\n') json_line = '\n'.join(output_lines[2:]) @@ -51,4 +63,8 @@ class TsanCPPGlobalLocationTestCase(TestBase): self.assertEqual(data["issue_type"], "data-race") self.assertTrue(data["location_filename"].endswith("/main.cpp")) - self.assertEqual(data["location_line"], line_number('main.cpp', '// global variable')) + self.assertEqual( + data["location_line"], + line_number( + 'main.cpp', + '// global variable')) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/TestTsanGlobalLocation.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/TestTsanGlobalLocation.py index b268c46fead..cec74eeaf44 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/TestTsanGlobalLocation.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/TestTsanGlobalLocation.py @@ -2,53 +2,69 @@ Tests that TSan correctly reports the filename and line number of a racy global variable. """ -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import json + class TsanGlobalLocationTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt @skipUnlessThreadSanitizer - def test (self): - self.build () - self.tsan_tests () + def test(self): + self.build() + self.tsan_tests() def setUp(self): # Call super's setUp(). TestBase.setUp(self) - def tsan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def tsan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") # the stop reason of the thread should be breakpoint. self.expect("thread list", "A data race should be detected", - substrs = ['stopped', 'stop reason = Data race detected']) + substrs=['stopped', 'stop reason = Data race detected']) - self.expect("thread info -s", "The extended stop info should contain the TSan provided fields", - substrs = ["instrumentation_class", "description", "mops"]) + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) output_lines = self.res.GetOutput().split('\n') json_line = '\n'.join(output_lines[2:]) data = json.loads(json_line) self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") self.assertEqual(data["issue_type"], "data-race") - + self.assertTrue(data["location_filename"].endswith("/main.c")) - self.assertEqual(data["location_line"], line_number('main.c', '// global variable')) + self.assertEqual( + data["location_line"], + line_number( + 'main.c', + '// global variable')) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/TestTsanMultiple.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/TestTsanMultiple.py index c22501141cc..b9baaf89b05 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/TestTsanMultiple.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/TestTsanMultiple.py @@ -2,33 +2,39 @@ Test ThreadSanitizer when multiple different issues are found. """ -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import json + class TsanMultipleTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt @skipUnlessThreadSanitizer - def test (self): - self.build () - self.tsan_tests () + def test(self): + self.build() + self.tsan_tests() def setUp(self): # Call super's setUp(). TestBase.setUp(self) - def tsan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def tsan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("env TSAN_OPTIONS=abort_on_error=0") @@ -36,34 +42,46 @@ class TsanMultipleTestCase(TestBase): stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") report_count = 0 - while self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() == lldb.eStopReasonInstrumentation: + while self.dbg.GetSelectedTarget().process.GetSelectedThread( + ).GetStopReason() == lldb.eStopReasonInstrumentation: report_count += 1 - stop_description = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopDescription(100) + stop_description = self.dbg.GetSelectedTarget( + ).process.GetSelectedThread().GetStopDescription(100) self.assertTrue( - (stop_description == "Data race detected") or - (stop_description == "Use of deallocated memory detected") or - (stop_description == "Thread leak detected") or - (stop_description == "Use of an uninitialized or destroyed mutex detected") or - (stop_description == "Unlock of an unlocked mutex (or by a wrong thread) detected") + (stop_description == "Data race detected") or + (stop_description == "Use of deallocated memory detected") or + (stop_description == "Thread leak detected") or + (stop_description == "Use of an uninitialized or destroyed mutex detected") or + (stop_description == "Unlock of an unlocked mutex (or by a wrong thread) detected") ) - self.expect("thread info -s", "The extended stop info should contain the TSan provided fields", - substrs = ["instrumentation_class", "description", "mops"]) + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) output_lines = self.res.GetOutput().split('\n') json_line = '\n'.join(output_lines[2:]) data = json.loads(json_line) self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") - backtraces = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReasonExtendedBacktraces(lldb.eInstrumentationRuntimeTypeThreadSanitizer) + backtraces = self.dbg.GetSelectedTarget().process.GetSelectedThread( + ).GetStopReasonExtendedBacktraces(lldb.eInstrumentationRuntimeTypeThreadSanitizer) self.assertTrue(backtraces.GetSize() >= 1) self.runCmd("continue") - self.assertEqual(self.dbg.GetSelectedTarget().process.GetState(), lldb.eStateExited, PROCESS_EXITED) + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetState(), + lldb.eStateExited, + PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py index ed620093c1f..45e5dbf9b30 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py @@ -2,39 +2,48 @@ Tests ThreadSanitizer's support to detect a leaked thread. """ -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import json + class TsanThreadLeakTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt @skipUnlessThreadSanitizer - def test (self): - self.build () - self.tsan_tests () + def test(self): + self.build() + self.tsan_tests() - def tsan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def tsan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") # the stop reason of the thread should be breakpoint. self.expect("thread list", "A thread leak should be detected", - substrs = ['stopped', 'stop reason = Thread leak detected']) + substrs=['stopped', 'stop reason = Thread leak detected']) - self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation) + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/TestTsanThreadNumbers.py b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/TestTsanThreadNumbers.py index c7905bcb1c1..abcf1f4eca0 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/TestTsanThreadNumbers.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/TestTsanThreadNumbers.py @@ -2,51 +2,66 @@ Tests that TSan and LLDB have correct thread numbers. """ -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import json + class TsanThreadNumbersTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["linux"], bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") - @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default @skipIfRemote @skipUnlessCompilerRt @skipUnlessThreadSanitizer - def test (self): - self.build () - self.tsan_tests () + def test(self): + self.build() + self.tsan_tests() def setUp(self): # Call super's setUp(). TestBase.setUp(self) - def tsan_tests (self): - exe = os.path.join (os.getcwd(), "a.out") - self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ]) + def tsan_tests(self): + exe = os.path.join(os.getcwd(), "a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) self.runCmd("run") stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() if stop_reason == lldb.eStopReasonExec: - # On OS X 10.10 and older, we need to re-exec to enable interceptors. + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. self.runCmd("continue") # the stop reason of the thread should be breakpoint. self.expect("thread list", "A data race should be detected", - substrs = ['stopped', 'stop reason = Data race detected']) + substrs=['stopped', 'stop reason = Data race detected']) - self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation) + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) - report_thread_id = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetIndexID() + report_thread_id = self.dbg.GetSelectedTarget( + ).process.GetSelectedThread().GetIndexID() - self.expect("thread info -s", "The extended stop info should contain the TSan provided fields", - substrs = ["instrumentation_class", "description", "mops"]) + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) output_lines = self.res.GetOutput().split('\n') json_line = '\n'.join(output_lines[2:]) @@ -59,10 +74,15 @@ class TsanThreadNumbersTestCase(TestBase): other_thread_id = data["mops"][1]["thread_id"] self.assertTrue(other_thread_id != report_thread_id) - other_thread = self.dbg.GetSelectedTarget().process.GetThreadByIndexID(other_thread_id) + other_thread = self.dbg.GetSelectedTarget( + ).process.GetThreadByIndexID(other_thread_id) self.assertTrue(other_thread.IsValid()) self.runCmd("thread select %d" % other_thread_id) - self.expect("thread backtrace", "The other thread should be stopped in f1 or f2", - substrs = ["a.out", "main.c"]) + self.expect( + "thread backtrace", + "The other thread should be stopped in f1 or f2", + substrs=[ + "a.out", + "main.c"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py b/lldb/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py index cebba1b4c57..f4268f5bfa9 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py @@ -5,14 +5,15 @@ Test lldb command aliases. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LaunchInTerminalTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,18 +25,26 @@ class LaunchInTerminalTestCase(TestBase): @expectedFailureDarwin("llvm.org/pr25484") # If the test is being run under sudo, the spawned terminal won't retain that elevated # privilege so it can't open the socket to talk back to the test case - @unittest2.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, "test cannot be run as root") + @unittest2.skipIf(hasattr(os, 'geteuid') and os.geteuid() + == 0, "test cannot be run as root") # Do we need to disable this test if the testsuite is being run on a remote system? - # This env var is only defined when the shell is running in a local mac terminal window - @unittest2.skipUnless('TERM_PROGRAM' in os.environ, "test must be run on local system") + # This env var is only defined when the shell is running in a local mac + # terminal window + @unittest2.skipUnless( + 'TERM_PROGRAM' in os.environ, + "test must be run on local system") @no_debug_info_test - def test_launch_in_terminal (self): + def test_launch_in_terminal(self): exe = "/bin/ls" target = self.dbg.CreateTarget(exe) launch_info = lldb.SBLaunchInfo(["-lAF", "/tmp/"]) - launch_info.SetLaunchFlags(lldb.eLaunchFlagLaunchInTTY | lldb.eLaunchFlagCloseTTYOnExit) + launch_info.SetLaunchFlags( + lldb.eLaunchFlagLaunchInTTY | lldb.eLaunchFlagCloseTTYOnExit) error = lldb.SBError() - process = target.Launch (launch_info, error) - self.assertTrue(error.Success(), "Make sure launch happened successfully in a terminal window") - # Running in synchronous mode our process should have run and already exited by the time target.Launch() returns + process = target.Launch(launch_info, error) + self.assertTrue( + error.Success(), + "Make sure launch happened successfully in a terminal window") + # Running in synchronous mode our process should have run and already + # exited by the time target.Launch() returns self.assertTrue(process.GetState() == lldb.eStateExited) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py b/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py index 2bf10204ea6..8d6311e42b9 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py @@ -5,32 +5,37 @@ Check that types only get completed when necessary. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TypeCompletionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(compiler="icc", bugnumber="often fails with 'NameAndAddress should be valid.") - # Fails with gcc 4.8.1 with llvm.org/pr15301 LLDB prints incorrect sizes of STL containers + @expectedFailureAll( + compiler="icc", + bugnumber="often fails with 'NameAndAddress should be valid.") + # Fails with gcc 4.8.1 with llvm.org/pr15301 LLDB prints incorrect sizes + # of STL containers def test_with_run_command(self): """Check that types only get completed when necessary.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp (self, "// Set break point at this line.") + lldbutil.run_break_set_by_source_regexp( + self, "// Set break point at this line.") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -42,68 +47,112 @@ class TypeCompletionTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') p_type = p_vector.GetType() - self.assertFalse(p_type.IsTypeComplete(), 'vector<T> complete but it should not be') + self.assertFalse( + p_type.IsTypeComplete(), + 'vector<T> complete but it should not be') self.runCmd("continue") - p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') p_type = p_vector.GetType() - self.assertFalse(p_type.IsTypeComplete(), 'vector<T> complete but it should not be') + self.assertFalse( + p_type.IsTypeComplete(), + 'vector<T> complete but it should not be') self.runCmd("continue") self.runCmd("frame variable p --show-types") - p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') p_type = p_vector.GetType() - self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete') + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') name_address_type = p_type.GetTemplateArgumentType(0) - self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid') - self.assertFalse(name_address_type.IsTypeComplete(), 'NameAndAddress complete but it should not be') + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertFalse( + name_address_type.IsTypeComplete(), + 'NameAndAddress complete but it should not be') self.runCmd("continue") self.runCmd("frame variable guy --show-types") - p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') p_type = p_vector.GetType() - self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete') + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') name_address_type = p_type.GetTemplateArgumentType(0) - self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid') - self.assertTrue(name_address_type.IsTypeComplete(), 'NameAndAddress should now be complete') + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertTrue( + name_address_type.IsTypeComplete(), + 'NameAndAddress should now be complete') field0 = name_address_type.GetFieldAtIndex(0) - self.assertTrue(field0.IsValid(), 'NameAndAddress::m_name should be valid') + self.assertTrue( + field0.IsValid(), + 'NameAndAddress::m_name should be valid') string = field0.GetType().GetPointeeType() self.assertTrue(string.IsValid(), 'CustomString should be valid') - self.assertFalse(string.IsTypeComplete(), 'CustomString complete but it should not be') + self.assertFalse(string.IsTypeComplete(), + 'CustomString complete but it should not be') self.runCmd("continue") - p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') p_type = p_vector.GetType() - self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete') + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') name_address_type = p_type.GetTemplateArgumentType(0) - self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid') - self.assertTrue(name_address_type.IsTypeComplete(), 'NameAndAddress should now be complete') + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertTrue( + name_address_type.IsTypeComplete(), + 'NameAndAddress should now be complete') field0 = name_address_type.GetFieldAtIndex(0) - self.assertTrue(field0.IsValid(), 'NameAndAddress::m_name should be valid') + self.assertTrue( + field0.IsValid(), + 'NameAndAddress::m_name should be valid') string = field0.GetType().GetPointeeType() self.assertTrue(string.IsValid(), 'CustomString should be valid') - self.assertFalse(string.IsTypeComplete(), 'CustomString complete but it should not be') + self.assertFalse(string.IsTypeComplete(), + 'CustomString complete but it should not be') self.runCmd('type category enable -l c++', check=False) self.runCmd('frame variable guy --show-types --ptr-depth=1') - p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') p_type = p_vector.GetType() - self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete') + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') name_address_type = p_type.GetTemplateArgumentType(0) - self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid') - self.assertTrue(name_address_type.IsTypeComplete(), 'NameAndAddress should now be complete') + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertTrue( + name_address_type.IsTypeComplete(), + 'NameAndAddress should now be complete') field0 = name_address_type.GetFieldAtIndex(0) - self.assertTrue(field0.IsValid(), 'NameAndAddress::m_name should be valid') + self.assertTrue( + field0.IsValid(), + 'NameAndAddress::m_name should be valid') string = field0.GetType().GetPointeeType() self.assertTrue(string.IsValid(), 'CustomString should be valid') - self.assertTrue(string.IsTypeComplete(), 'CustomString should now be complete') + self.assertTrue( + string.IsTypeComplete(), + 'CustomString should now be complete') diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py b/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py index 774eb437b78..0c415480de8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py @@ -5,14 +5,15 @@ Test type lookup command. from __future__ import print_function - import datetime -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TypeLookupTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,17 +30,22 @@ class TypeLookupTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - - self.expect('type lookup NoSuchType', substrs=['@interface'], matching=False) + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect( + 'type lookup NoSuchType', + substrs=['@interface'], + matching=False) self.expect('type lookup NSURL', substrs=['NSURL']) self.expect('type lookup NSArray', substrs=['NSArray']) self.expect('type lookup NSObject', substrs=['NSObject', 'isa']) - self.expect('type lookup PleaseDontBeARealTypeThatExists', substrs=["no type was found matching 'PleaseDontBeARealTypeThatExists'"]) + self.expect('type lookup PleaseDontBeARealTypeThatExists', substrs=[ + "no type was found matching 'PleaseDontBeARealTypeThatExists'"]) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/TestEhFrameUnwind.py b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/TestEhFrameUnwind.py index e17d5d36d39..a855be7536c 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/TestEhFrameUnwind.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/TestEhFrameUnwind.py @@ -5,20 +5,20 @@ Test that we can backtrace correctly from Non ABI functions on the stack from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class EHFrameBasedUnwind(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipUnlessPlatform(['linux']) @skipIf(archs=["aarch64", "arm", "i386", "i686"]) - def test (self): + def test(self): """Test that we can backtrace correctly from Non ABI functions on the stack""" self.build() self.setTearDownCleanup() @@ -28,9 +28,10 @@ class EHFrameBasedUnwind(TestBase): self.assertTrue(target, VALID_TARGET) - lldbutil.run_break_set_by_symbol (self, "func") + lldbutil.run_break_set_by_symbol(self, "func") - process = target.LaunchSimple (["abc", "xyz"], None, self.get_process_working_directory()) + process = target.LaunchSimple( + ["abc", "xyz"], None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") @@ -42,10 +43,10 @@ class EHFrameBasedUnwind(TestBase): stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, - substrs = ['(int)argc=3']) + substrs=['(int)argc=3']) self.runCmd("thread step-inst") stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, - substrs = ['(int)argc=3']) + substrs=['(int)argc=3']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py index 62c6c16080a..e5c9c907727 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py @@ -5,18 +5,19 @@ Test that we can backtrace correctly with 'noreturn' functions on the stack from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NoreturnUnwind(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows # clang-cl does not support gcc style attributes. - def test (self): + @skipIfWindows # clang-cl does not support gcc style attributes. + def test(self): """Test that we can backtrace correctly with 'noreturn' functions on the stack""" self.build() self.setTearDownCleanup() @@ -25,7 +26,8 @@ class NoreturnUnwind(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") @@ -55,22 +57,27 @@ class NoreturnUnwind(TestBase): self.fail("Unable to find abort() in backtrace.") func_c_frame_number = abort_frame_number + 1 - if thread.GetFrameAtIndex (func_c_frame_number).GetFunctionName() != "func_c": + if thread.GetFrameAtIndex( + func_c_frame_number).GetFunctionName() != "func_c": self.fail("Did not find func_c() above abort().") # This depends on whether we see the func_b inlined function in the backtrace # or not. I'm not interested in testing that aspect of the backtrace here # right now. - if thread.GetFrameAtIndex (func_c_frame_number + 1).GetFunctionName() == "func_b": + if thread.GetFrameAtIndex( + func_c_frame_number + + 1).GetFunctionName() == "func_b": func_a_frame_number = func_c_frame_number + 2 else: func_a_frame_number = func_c_frame_number + 1 - if thread.GetFrameAtIndex (func_a_frame_number).GetFunctionName() != "func_a": + if thread.GetFrameAtIndex( + func_a_frame_number).GetFunctionName() != "func_a": self.fail("Did not find func_a() above func_c().") main_frame_number = func_a_frame_number + 1 - if thread.GetFrameAtIndex (main_frame_number).GetFunctionName() != "main": + if thread.GetFrameAtIndex( + main_frame_number).GetFunctionName() != "main": self.fail("Did not find main() above func_a().") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py index d2b36412f1f..e35bb966c91 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py @@ -5,20 +5,21 @@ Test that we can backtrace correctly with 'sigtramp' functions on the stack from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SigtrampUnwind(TestBase): mydir = TestBase.compute_mydir(__file__) # On different platforms the "_sigtramp" and "__kill" frames are likely to be different. # This test could probably be adapted to run on linux/*bsd easily enough. @skipUnlessDarwin - def test (self): + def test(self): """Test that we can backtrace correctly with _sigtramp on the stack""" self.build() self.setTearDownCleanup() @@ -27,10 +28,11 @@ class SigtrampUnwind(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) + lldbutil.run_break_set_by_file_and_line(self, "main.c", line_number( + 'main.c', '// Set breakpoint here'), num_expected_locations=1) - lldbutil.run_break_set_by_file_and_line (self, "main.c", line_number('main.c', '// Set breakpoint here'), num_expected_locations=1) - - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") @@ -40,10 +42,20 @@ class SigtrampUnwind(TestBase): "instead the actual state is: '%s'" % lldbutil.state_type_to_str(process.GetState())) - self.expect("pro handle -n false -p true -s false SIGUSR1", "Have lldb pass SIGUSR1 signals", - substrs = ["SIGUSR1", "true", "false", "false"]) - - lldbutil.run_break_set_by_symbol (self, "handler", num_expected_locations=1, module_name="a.out") + self.expect( + "pro handle -n false -p true -s false SIGUSR1", + "Have lldb pass SIGUSR1 signals", + substrs=[ + "SIGUSR1", + "true", + "false", + "false"]) + + lldbutil.run_break_set_by_symbol( + self, + "handler", + num_expected_locations=1, + module_name="a.out") self.runCmd("continue") @@ -69,14 +81,14 @@ class SigtrampUnwind(TestBase): for f in thread.frames: print(" %d %s" % (f.GetFrameID(), f.GetFunctionName())) - if found_handler == False: + if not found_handler: self.fail("Unable to find handler() in backtrace.") - if found_sigtramp == False: + if not found_sigtramp: self.fail("Unable to find _sigtramp() in backtrace.") - if found_kill == False: + if not found_kill: self.fail("Unable to find kill() in backtrace.") - if found_main == False: + if not found_main: self.fail("Unable to find main() in backtrace.") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py index 20532c6fc67..2416128d2ef 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py @@ -13,9 +13,9 @@ after escaping some special characters). from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -23,10 +23,11 @@ from lldbsuite.test import lldbutil test_source_dirs = ["."] + class StandardUnwindTest(TestBase): mydir = TestBase.compute_mydir(__file__) - def standard_unwind_tests (self): + def standard_unwind_tests(self): # The following variables have to be defined for each architecture and OS we testing for: # base_function_names: List of function names where we accept that the stack unwinding is # correct if they are on the stack. It should include the bottom most @@ -36,20 +37,27 @@ class StandardUnwindTest(TestBase): # instruction by instruction for any reason. (A valid reason is if # it is impossible to step through a function instruction by # instruction because it is special for some reason.) For these - # functions we will immediately do a step-out when we hit them. + # functions we will immediately do a step-out when we hit them. triple = self.dbg.GetSelectedPlatform().GetTriple() if re.match("arm-.*-.*-android", triple): base_function_names = [ "_start", # Base function on the stack "__memcpy_base", # Function reached by a fall through from the previous function - "__memcpy_base_aligned", # Function reached by a fall through from the previous function + "__memcpy_base_aligned", + # Function reached by a fall through from the previous function ] no_step_function_names = [ - "__sync_fetch_and_add_4", # Calls into a special SO where we can't set a breakpoint - "pthread_mutex_lock", # Uses ldrex and strex what interferes with the software single stepping - "pthread_mutex_unlock", # Uses ldrex and strex what interferes with the software single stepping - "pthread_once", # Uses ldrex and strex what interferes with the software single stepping + "__sync_fetch_and_add_4", # Calls into a special SO where we can't set a breakpoint + "pthread_mutex_lock", + # Uses ldrex and strex what interferes with the software single + # stepping + "pthread_mutex_unlock", + # Uses ldrex and strex what interferes with the software single + # stepping + "pthread_once", + # Uses ldrex and strex what interferes with the software single + # stepping ] elif re.match("aarch64-.*-.*-android", triple): base_function_names = [ @@ -57,11 +65,21 @@ class StandardUnwindTest(TestBase): ] no_step_function_names = [ None, - "__cxa_guard_acquire", # Uses ldxr and stxr what interferes with the software single stepping - "__cxa_guard_release", # Uses ldxr and stxr what interferes with the software single stepping - "pthread_mutex_lock", # Uses ldxr and stxr what interferes with the software single stepping - "pthread_mutex_unlock", # Uses ldxr and stxr what interferes with the software single stepping - "pthread_once", # Uses ldxr and stxr what interferes with the software single stepping + "__cxa_guard_acquire", + # Uses ldxr and stxr what interferes with the software single + # stepping + "__cxa_guard_release", + # Uses ldxr and stxr what interferes with the software single + # stepping + "pthread_mutex_lock", + # Uses ldxr and stxr what interferes with the software single + # stepping + "pthread_mutex_unlock", + # Uses ldxr and stxr what interferes with the software single + # stepping + "pthread_once", + # Uses ldxr and stxr what interferes with the software single + # stepping ] else: self.skipTest("No expectations for the current architecture") @@ -72,17 +90,23 @@ class StandardUnwindTest(TestBase): target.BreakpointCreateByName("main") - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process is not None, "SBTarget.Launch() failed") - self.assertEqual(process.GetState(), lldb.eStateStopped, "The process didn't hit main") + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + "The process didn't hit main") index = 0 while process.GetState() == lldb.eStateStopped: index += 1 if process.GetNumThreads() > 1: # In case of a multi threaded inferior if one of the thread is stopped in a blocking - # syscall and we try to step it then SBThread::StepInstruction() will block forever - self.skipTest("Multi threaded inferiors are not supported by this test") + # syscall and we try to step it then + # SBThread::StepInstruction() will block forever + self.skipTest( + "Multi threaded inferiors are not supported by this test") thread = process.GetThreadAtIndex(0) @@ -97,9 +121,11 @@ class StandardUnwindTest(TestBase): if f.GetFunctionName() in base_function_names: found_main = True break - self.assertTrue(found_main, "Main function isn't found on the backtrace") + self.assertTrue(found_main, + "Main function isn't found on the backtrace") - if thread.GetFrameAtIndex(0).GetFunctionName() in no_step_function_names: + if thread.GetFrameAtIndex( + 0).GetFunctionName() in no_step_function_names: thread.StepOut() else: thread.StepInstruction(False) @@ -113,13 +139,16 @@ for d in test_source_dirs: dirname = os.path.join(os.path.dirname(__file__), d) for root, _, files in os.walk(dirname): - test_source_files = test_source_files | set(os.path.abspath(os.path.join(root, f)) for f in files) + test_source_files = test_source_files | set( + os.path.abspath(os.path.join(root, f)) for f in files) # Generate test cases based on the collected source files for f in test_source_files: if f.endswith(".cpp") or f.endswith(".c"): @add_test_categories(["dwarf"]) - @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") + @unittest2.skipIf( + TestBase.skipLongRunningTest(), + "Skip this long running test") def test_function_dwarf(self, f=f): if f.endswith(".cpp"): d = {'CXX_SOURCES': f} @@ -143,4 +172,7 @@ for f in test_source_files: test_name = test_name.replace(c, '_') test_function_dwarf.__name__ = test_name - setattr(StandardUnwindTest, test_function_dwarf.__name__, test_function_dwarf) + setattr( + StandardUnwindTest, + test_function_dwarf.__name__, + test_function_dwarf) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py b/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py index cbea7d22cc4..8e3ab853e27 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py @@ -5,13 +5,14 @@ Verify that the hash computing logic for ValueObject's values can't crash us. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ValueMD5CrashTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -28,26 +29,27 @@ class ValueMD5CrashTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) value = self.frame().FindVariable("a") value.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) - + v = value.GetValue() type_name = value.GetTypeName() self.assertTrue(type_name == "B *", "a is a B*") - + self.runCmd("next") self.runCmd("process kill") - + # now the process is dead, and value needs updating v = value.GetValue() - + # if we are here, instead of crashed, the test succeeded diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py index 933f21a90bb..6a68730e08e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py @@ -5,14 +5,15 @@ Test lldb watchpoint that uses '-s size' to watch a pointed location with size. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class HelloWatchLocationTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,18 +24,31 @@ class HelloWatchLocationTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # This is for verifying that watch location works. - self.violating_func = "do_bad_thing_with_location"; - # Build dictionary to have unique executable names for each test method. + self.violating_func = "do_bad_thing_with_location" + # Build dictionary to have unique executable names for each test + # method. self.exe_name = self.testMethodName self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(triple = re.compile('^mips')) # Most of the MIPS boards provide only one H/W watchpoints, and S/W watchpoints are not supported yet - @expectedFailureAll(archs=['s390x']) # SystemZ also currently supports only one H/W watchpoint - @expectedFailureAll(oslist=["linux"], archs=["arm", "aarch64"], bugnumber="llvm.org/pr27795") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Most of the MIPS boards provide only one H/W watchpoints, and S/W + # watchpoints are not supported yet + @expectedFailureAll(triple=re.compile('^mips')) + # SystemZ also currently supports only one H/W watchpoint + @expectedFailureAll(archs=['s390x']) + @expectedFailureAll( + oslist=["linux"], + archs=[ + "arm", + "aarch64"], + bugnumber="llvm.org/pr27795") @skipIfDarwin def test_hello_watchlocation(self): """Test watching a location with '-s size' option.""" @@ -44,7 +58,8 @@ class HelloWatchLocationTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1, loc_exact=False) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -52,48 +67,56 @@ class HelloWatchLocationTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint pointed to by 'g_char_ptr'. - self.expect("watchpoint set expression -w write -s 1 -- g_char_ptr", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 1', 'type = w']) + self.expect( + "watchpoint set expression -w write -s 1 -- g_char_ptr", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 1', + 'type = w']) # Get a hold of the watchpoint id just created, it is used later on to # match the watchpoint id which is expected to be fired. - match = re.match("Watchpoint created: Watchpoint (.*):", self.res.GetOutput().splitlines()[0]) + match = re.match( + "Watchpoint created: Watchpoint (.*):", + self.res.GetOutput().splitlines()[0]) if match: expected_wp_id = int(match.group(1), 0) else: - self.fail("Grokking watchpoint id faailed!") + self.fail("Grokking watchpoint id faailed!") self.runCmd("expr unsigned val = *g_char_ptr; val") self.expect(self.res.GetOutput().splitlines()[0], exe=False, - endstr = ' = 0') + endstr=' = 0') self.runCmd("watchpoint set expression -w write -s 4 -- &threads[0]") # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stopped', - 'stop reason = watchpoint %d' % expected_wp_id]) + substrs=['stopped', + 'stop reason = watchpoint %d' % expected_wp_id]) - # Switch to the thread stopped due to watchpoint and issue some commands. + # Switch to the thread stopped due to watchpoint and issue some + # commands. self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint) self.runCmd("thread backtrace") self.expect("frame info", - substrs = [self.violating_func]) + substrs=[self.violating_func]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. self.expect("watchpoint list -v", - substrs = ['hit_count = 1']) + substrs=['hit_count = 1']) self.runCmd("thread backtrace all") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py index 5214c7f5e08..c74452fd375 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py @@ -5,16 +5,17 @@ Test my first lldb watchpoint. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class HelloWatchpointTestCase(TestBase): - def getCategories (self): + def getCategories(self): return ['basic_process'] mydir = TestBase.compute_mydir(__file__) @@ -25,14 +26,19 @@ class HelloWatchpointTestCase(TestBase): # Our simple source filename. self.source = 'main.c' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, '// Watchpoint variable declaration.') + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') self.exe_name = 'a.out' self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_hello_watchpoint_using_watchpoint_set(self): """Test a simple sequence of watchpoint creation and watchpoint hit.""" self.build(dictionary=self.d) @@ -42,7 +48,8 @@ class HelloWatchpointTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -50,36 +57,45 @@ class HelloWatchpointTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for 'global'. # There should be only one watchpoint hit (see main.c). - self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stopped', - 'stop reason = watchpoint']) + substrs=['stopped', + 'stop reason = watchpoint']) self.runCmd("process continue") # Don't expect the read of 'global' to trigger a stop exception. process = self.dbg.GetSelectedTarget().GetProcess() if process.GetState() == lldb.eStateStopped: - self.assertFalse(lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)) + self.assertFalse( + lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint)) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. self.expect("watchpoint list -v", - substrs = ['hit_count = 1']) + substrs=['hit_count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py index af8306c9a20..78273d6ec69 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py @@ -5,28 +5,35 @@ Test that lldb watchpoint works for multiple threads. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointForMultipleThreadsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watchpoint_multiple_threads(self): """Test that lldb watchpoint works for multiple threads.""" self.build() self.setTearDownCleanup() self.hello_multiple_threads() - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watchpoint_multiple_threads_wp_set_and_then_delete(self): """Test that lldb watchpoint works for multiple threads, and after the watchpoint is deleted, the watchpoint event should no longer fires.""" self.build() @@ -39,14 +46,21 @@ class WatchpointForMultipleThreadsTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.first_stop = line_number(self.source, '// Set break point at this line') + self.first_stop = line_number( + self.source, '// Set break point at this line') def hello_multiple_threads(self): """Test that lldb watchpoint works for multiple threads.""" - self.runCmd("file %s" % os.path.join(os.getcwd(), 'a.out'), CURRENT_EXECUTABLE_SET) + self.runCmd( + "file %s" % + os.path.join( + os.getcwd(), + 'a.out'), + CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.first_stop, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.first_stop, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -54,17 +68,22 @@ class WatchpointForMultipleThreadsTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for variable 'g_val'. - self.expect("watchpoint set variable -w write g_val", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w']) + self.expect( + "watchpoint set variable -w write g_val", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) while True: self.runCmd("process continue") @@ -80,14 +99,20 @@ class WatchpointForMultipleThreadsTestCase(TestBase): # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. self.expect("watchpoint list -v", - substrs = ['hit_count = 1']) + substrs=['hit_count = 1']) def hello_multiple_threads_wp_set_and_then_delete(self): """Test that lldb watchpoint works for multiple threads, and after the watchpoint is deleted, the watchpoint event should no longer fires.""" - self.runCmd("file %s" % os.path.join(os.getcwd(), 'a.out'), CURRENT_EXECUTABLE_SET) + self.runCmd( + "file %s" % + os.path.join( + os.getcwd(), + 'a.out'), + CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.first_stop, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.first_stop, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -95,17 +120,22 @@ class WatchpointForMultipleThreadsTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for variable 'g_val'. - self.expect("watchpoint set variable -w write g_val", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w']) + self.expect( + "watchpoint set variable -w write g_val", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) watchpoint_stops = 0 while True: @@ -120,13 +150,17 @@ class WatchpointForMultipleThreadsTestCase(TestBase): self.runCmd("thread backtrace all") watchpoint_stops += 1 if watchpoint_stops > 1: - self.fail("Watchpoint hits not supposed to exceed 1 by design!") - # Good, we verified that the watchpoint works! Now delete the watchpoint. + self.fail( + "Watchpoint hits not supposed to exceed 1 by design!") + # Good, we verified that the watchpoint works! Now delete the + # watchpoint. if self.TraceOn(): - print("watchpoint_stops=%d at the moment we delete the watchpoint" % watchpoint_stops) + print( + "watchpoint_stops=%d at the moment we delete the watchpoint" % + watchpoint_stops) self.runCmd("watchpoint delete 1") self.expect("watchpoint list -v", - substrs = ['No watchpoints currently set.']) + substrs=['No watchpoints currently set.']) continue else: self.fail("The stop reason should be either break or watchpoint") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py index 22011f11352..f1d7acfcc5e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py @@ -3,7 +3,6 @@ from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -17,10 +16,19 @@ class TestStepOverWatchpoint(TestBase): def getCategories(self): return ['basic_process'] - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=['aarch64', 'arm'], bugnumber="llvm.org/pr26031") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=[ + 'aarch64', + 'arm'], + bugnumber="llvm.org/pr26031") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test(self): """Test stepping over watchpoints.""" self.build() @@ -73,9 +81,10 @@ class TestStepOverWatchpoint(TestBase): lldb.eValueTypeVariableGlobal) self.assertTrue(write_value, "Failed to find write value.") - # Most of the MIPS boards provide only one H/W watchpoints, and S/W watchpoints are not supported yet + # Most of the MIPS boards provide only one H/W watchpoints, and S/W + # watchpoints are not supported yet arch = self.getArchitecture() - if re.match("^mips",arch): + if re.match("^mips", arch): self.runCmd("watchpoint delete 1") # resolve_location=True, read=False, write=True diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py index 21f1fb68426..d3074149763 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py @@ -5,13 +5,14 @@ Test that a variable watchpoint should only hit when in scope. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class WatchedVariableHitWhenInScopeTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,7 +21,7 @@ class WatchedVariableHitWhenInScopeTestCase(TestBase): # This test depends on not tracking watchpoint expression hits if we have # left the watchpoint scope. We will provide such an ability at some point # but the way this was done was incorrect, and it is unclear that for the - # most part that's not what folks mostly want, so we have to provide a + # most part that's not what folks mostly want, so we have to provide a # clearer API to express this. # @@ -42,7 +43,8 @@ class WatchedVariableHitWhenInScopeTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped in main. - lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=-1) + lldbutil.run_break_set_by_symbol( + self, "main", num_expected_locations=-1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -50,34 +52,34 @@ class WatchedVariableHitWhenInScopeTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a watchpoint for 'c.a'. # There should be only one watchpoint hit (see main.c). self.expect("watchpoint set variable c.a", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w']) + substrs=['Watchpoint created', 'size = 4', 'type = w']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stopped', - 'stop reason = watchpoint']) + substrs=['stopped', + 'stop reason = watchpoint']) self.runCmd("process continue") # Don't expect the read of 'global' to trigger a stop exception. # The process status should be 'exited'. self.expect("process status", - substrs = ['exited']) + substrs=['exited']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. self.expect("watchpoint list -v", - substrs = ['hit_count = 1']) + substrs=['hit_count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py index 4ce05af96e2..7a9904c53f8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py @@ -5,13 +5,14 @@ Test watchpoint list, enable, disable, and delete commands. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointCommandsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,27 +23,37 @@ class WatchpointCommandsTestCase(TestBase): # Our simple source filename. self.source = 'main.c' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') - self.line2 = line_number(self.source, '// Set 2nd break point for disable_then_enable test case.') + self.line = line_number( + self.source, '// Set break point at this line.') + self.line2 = line_number( + self.source, + '// Set 2nd break point for disable_then_enable test case.') # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, '// Watchpoint variable declaration.') - # Build dictionary to have unique executable names for each test method. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. self.exe_name = self.testMethodName self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_rw_watchpoint(self): """Test read_write watchpoint and expect to stop two times.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) - + exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -50,60 +61,72 @@ class WatchpointCommandsTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). - self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = rw', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['Number of supported hardware watchpoints:', - 'hit_count = 0']) + substrs=['Number of supported hardware watchpoints:', + 'hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. self.expect("process status", - substrs = ['exited']) + substrs=['exited']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 2. self.expect("watchpoint list -v", - substrs = ['hit_count = 2']) - - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + substrs=['hit_count = 2']) + + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_rw_watchpoint_delete(self): """Test delete watchpoint and expect not to stop for watchpoint.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) - + exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -111,19 +134,27 @@ class WatchpointCommandsTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). - self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = rw', - '%s:%d' % (self.source, self.decl)]) - - # Delete the watchpoint immediately, but set auto-confirm to true first. + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) + + # Delete the watchpoint immediately, but set auto-confirm to true + # first. self.runCmd("settings set auto-confirm true") self.expect("watchpoint delete", - substrs = ['All watchpoints removed.']) + substrs=['All watchpoints removed.']) # Restore the original setting of auto-confirm. self.runCmd("settings clear auto-confirm") @@ -135,21 +166,26 @@ class WatchpointCommandsTestCase(TestBase): # There should be no more watchpoint hit and the process status should # be 'exited'. self.expect("process status", - substrs = ['exited']) - - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + substrs=['exited']) + + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_rw_watchpoint_set_ignore_count(self): """Test watchpoint ignore count and expect to not to stop at all.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) - + exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -157,49 +193,61 @@ class WatchpointCommandsTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). - self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = rw', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) # Set the ignore count of the watchpoint immediately. self.expect("watchpoint ignore -i 2", - substrs = ['All watchpoints ignored.']) + substrs=['All watchpoints ignored.']) # Use the '-v' option to do verbose listing of the watchpoint. # Expect to find an ignore_count of 2. self.expect("watchpoint list -v", - substrs = ['hit_count = 0', 'ignore_count = 2']) + substrs=['hit_count = 0', 'ignore_count = 2']) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. self.expect("process status", - substrs = ['exited']) + substrs=['exited']) # Use the '-v' option to do verbose listing of the watchpoint. # Expect to find a hit_count of 2 as well. self.expect("watchpoint list -v", - substrs = ['hit_count = 2', 'ignore_count = 2']) - - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + substrs=['hit_count = 2', 'ignore_count = 2']) + + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_rw_disable_after_first_stop(self): """Test read_write watchpoint but disable it after the first stop.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) - + exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -207,49 +255,60 @@ class WatchpointCommandsTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). - self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = rw', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['state = enabled', 'hit_count = 0']) + substrs=['state = enabled', 'hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) # Before continuing, we'll disable the watchpoint, which means we won't # stop again after this. self.runCmd("watchpoint disable") self.expect("watchpoint list -v", - substrs = ['state = disabled', 'hit_count = 1']) + substrs=['state = disabled', 'hit_count = 1']) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. self.expect("process status", - substrs = ['exited']) + substrs=['exited']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 1. self.expect("watchpoint list -v", - substrs = ['hit_count = 1']) - - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + substrs=['hit_count = 1']) + + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_rw_disable_then_enable(self): """Test read_write watchpoint, disable initially, then enable it.""" self.build(dictionary=self.d) @@ -259,8 +318,10 @@ class WatchpointCommandsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) - lldbutil.run_break_set_by_file_and_line (self, None, self.line2, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line2, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -268,14 +329,21 @@ class WatchpointCommandsTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a read_write-type watchpoint for 'global'. # There should be two watchpoint hits (see main.c). - self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = rw', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) # Immediately, we disable the watchpoint. We won't be stopping due to a # watchpoint after this. @@ -284,36 +352,36 @@ class WatchpointCommandsTestCase(TestBase): # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['state = disabled', 'hit_count = 0']) + substrs=['state = disabled', 'hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the breakpoint. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stop reason = breakpoint']) + substrs=['stop reason = breakpoint']) # Before continuing, we'll enable the watchpoint, which means we will # stop again after this. self.runCmd("watchpoint enable") self.expect("watchpoint list -v", - substrs = ['state = enabled', 'hit_count = 0']) + substrs=['state = enabled', 'hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (read_write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. self.expect("process status", - substrs = ['exited']) + substrs=['exited']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 1. self.expect("watchpoint list -v", - substrs = ['hit_count = 1']) + substrs=['hit_count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py index ee276dd5687..5b89f14dd85 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py @@ -5,13 +5,14 @@ Test 'watchpoint command'. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointLLDBCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,26 +23,36 @@ class WatchpointLLDBCommandTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, '// Watchpoint variable declaration.') - # Build dictionary to have unique executable names for each test method. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. self.exe_name = 'a%d.out' % self.test_number self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=["aarch64"], bugnumber="llvm.org/pr27710") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=["aarch64"], + bugnumber="llvm.org/pr27710") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watchpoint_command(self): """Test 'watchpoint command'.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) - + exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -49,44 +60,58 @@ class WatchpointLLDBCommandTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for 'global'. - self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) self.runCmd('watchpoint command add 1 -o "expr -- cookie = 777"') # List the watchpoint command we just added. self.expect("watchpoint command list 1", - substrs = ['expr -- cookie = 777']) + substrs=['expr -- cookie = 777']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) # Check that the watchpoint snapshoting mechanism is working. self.expect("watchpoint list -v", - substrs = ['old value:', ' = 0', - 'new value:', ' = 1']) + substrs=['old value:', ' = 0', + 'new value:', ' = 1']) - # The watchpoint command "forced" our global variable 'cookie' to become 777. + # The watchpoint command "forced" our global variable 'cookie' to + # become 777. self.expect("frame variable --show-globals cookie", - substrs = ['(int32_t)', 'cookie = 777']) - - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=["aarch64"], bugnumber="llvm.org/pr27710") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + substrs=['(int32_t)', 'cookie = 777']) + + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=["aarch64"], + bugnumber="llvm.org/pr27710") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watchpoint_command_can_disable_a_watchpoint(self): """Test that 'watchpoint command' action can disable a watchpoint after it is triggered.""" self.build(dictionary=self.d) @@ -96,7 +121,8 @@ class WatchpointLLDBCommandTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -104,39 +130,46 @@ class WatchpointLLDBCommandTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for 'global'. - self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) self.runCmd('watchpoint command add 1 -o "watchpoint disable 1"') # List the watchpoint command we just added. self.expect("watchpoint command list 1", - substrs = ['watchpoint disable 1']) + substrs=['watchpoint disable 1']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) # Check that the watchpoint has been disabled. self.expect("watchpoint list -v", - substrs = ['disabled']) + substrs=['disabled']) self.runCmd("process continue") # There should be no more watchpoint hit and the process status should # be 'exited'. self.expect("process status", - substrs = ['exited']) + substrs=['exited']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py index f6ea4fc1686..494ea2e4a54 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py @@ -5,13 +5,14 @@ Test 'watchpoint command'. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointPythonCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,17 +23,26 @@ class WatchpointPythonCommandTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, '// Watchpoint variable declaration.') - # Build dictionary to have unique executable names for each test method. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. self.exe_name = self.testMethodName self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=["aarch64"], bugnumber="llvm.org/pr27710") + @skipIfFreeBSD # timing out on buildbot + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=["aarch64"], + bugnumber="llvm.org/pr27710") def test_watchpoint_command(self): """Test 'watchpoint command'.""" self.build(dictionary=self.d) @@ -42,7 +52,8 @@ class WatchpointPythonCommandTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # self.expect("breakpoint set -l %d" % self.line, BREAKPOINT_CREATED, # startstr = "Breakpoint created: 1: file ='%s', line = %d, locations = 1" % # (self.source, self.line))# @@ -53,46 +64,62 @@ class WatchpointPythonCommandTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for 'global'. - self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w', - '%s:%d' % (self.source, self.decl)]) - - self.runCmd('watchpoint command add -s python 1 -o \'frame.EvaluateExpression("cookie = 777")\'') + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) + + self.runCmd( + 'watchpoint command add -s python 1 -o \'frame.EvaluateExpression("cookie = 777")\'') # List the watchpoint command we just added. self.expect("watchpoint command list 1", - substrs = ['frame.EvaluateExpression', 'cookie = 777']) + substrs=['frame.EvaluateExpression', 'cookie = 777']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) # Check that the watchpoint snapshoting mechanism is working. self.expect("watchpoint list -v", - substrs = ['old value:', ' = 0', - 'new value:', ' = 1']) + substrs=['old value:', ' = 0', + 'new value:', ' = 1']) - # The watchpoint command "forced" our global variable 'cookie' to become 777. + # The watchpoint command "forced" our global variable 'cookie' to + # become 777. self.expect("frame variable --show-globals cookie", - substrs = ['(int32_t)', 'cookie = 777']) - - @skipIfFreeBSD # timing out on buildbot - @expectedFailureAll(bugnumber="llvm.org/pr28055: continue in watchpoint commands disables the watchpoint") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=["aarch64"], bugnumber="llvm.org/pr27710") + substrs=['(int32_t)', 'cookie = 777']) + + @skipIfFreeBSD # timing out on buildbot + @expectedFailureAll( + bugnumber="llvm.org/pr28055: continue in watchpoint commands disables the watchpoint") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=["aarch64"], + bugnumber="llvm.org/pr27710") def test_continue_in_watchpoint_command(self): """Test continue in a watchpoint command.""" self.build(dictionary=self.d) @@ -102,7 +129,8 @@ class WatchpointPythonCommandTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # self.expect("breakpoint set -l %d" % self.line, BREAKPOINT_CREATED, # startstr = "Breakpoint created: 1: file ='%s', line = %d, locations = 1" % # (self.source, self.line))# @@ -113,31 +141,39 @@ class WatchpointPythonCommandTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for 'global'. - self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) cmd_script_file = os.path.join(os.getcwd(), "watchpoint_command.py") - self.runCmd("command script import '%s'"%(cmd_script_file)) + self.runCmd("command script import '%s'" % (cmd_script_file)) - self.runCmd('watchpoint command add -F watchpoint_command.watchpoint_command') + self.runCmd( + 'watchpoint command add -F watchpoint_command.watchpoint_command') # List the watchpoint command we just added. self.expect("watchpoint command list 1", - substrs = ['watchpoint_command.watchpoint_command']) + substrs=['watchpoint_command.watchpoint_command']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) # We should have hit the watchpoint once, set cookie to 888, then continued to the # second hit and set it to 999 self.expect("frame variable --show-globals cookie", - substrs = ['(int32_t)', 'cookie = 999']) + substrs=['(int32_t)', 'cookie = 999']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/watchpoint_command.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/watchpoint_command.py index 575a5160d21..ae5913a500e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/watchpoint_command.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/watchpoint_command.py @@ -1,7 +1,9 @@ import lldb num_hits = 0 -def watchpoint_command (frame, wp, dict): + + +def watchpoint_command(frame, wp, dict): global num_hits if num_hits == 0: print ("I stopped the first time") @@ -9,6 +11,5 @@ def watchpoint_command (frame, wp, dict): num_hits += 1 frame.thread.process.Continue() else: - print ("I stopped the %d time"%(num_hits)) + print ("I stopped the %d time" % (num_hits)) frame.EvaluateExpression("cookie = 999") - diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py index 64e01e5cb93..5a16856149b 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py @@ -5,13 +5,14 @@ Test watchpoint modify command to set condition on a watchpoint. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointConditionCmdTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,16 +23,25 @@ class WatchpointConditionCmdTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, '// Watchpoint variable declaration.') - # Build dictionary to have unique executable names for each test method. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. self.exe_name = self.testMethodName self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=["aarch64"], bugnumber="llvm.org/pr27710") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=["aarch64"], + bugnumber="llvm.org/pr27710") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watchpoint_cond(self): """Test watchpoint condition.""" self.build(dictionary=self.d) @@ -41,7 +51,8 @@ class WatchpointConditionCmdTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -49,32 +60,39 @@ class WatchpointConditionCmdTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint for 'global'. # With a condition of 'global==5'. - self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 4', 'type = w', - '%s:%d' % (self.source, self.decl)]) + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) self.runCmd("watchpoint modify -c 'global==5'") # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0', 'global==5']) + substrs=['hit_count = 0', 'global==5']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type). # The stop reason of the thread should be watchpoint. self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stop reason = watchpoint']) + substrs=['stop reason = watchpoint']) self.expect("frame variable --show-globals global", - substrs = ['(int32_t)', 'global = 5']) + substrs=['(int32_t)', 'global = 5']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 2. self.expect("watchpoint list -v", - substrs = ['hit_count = 5']) + substrs=['hit_count = 5']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py index f8435befae5..02180a127a8 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestWatchpointEvents (TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,51 +22,65 @@ class TestWatchpointEvents (TestBase): self.main_source = "main.c" @add_test_categories(['pyapi']) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=["aarch64"], bugnumber="llvm.org/pr27710") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=["aarch64"], + bugnumber="llvm.org/pr27710") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_with_python_api(self): """Test that adding, deleting and modifying watchpoints sends the appropriate events.""" self.build() - + exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) - break_in_main = target.BreakpointCreateBySourceRegex ('// Put a breakpoint here.', self.main_source_spec) + break_in_main = target.BreakpointCreateBySourceRegex( + '// Put a breakpoint here.', self.main_source_spec) self.assertTrue(break_in_main, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_main) if len(threads) != 1: - self.fail ("Failed to stop at first breakpoint in main.") + self.fail("Failed to stop at first breakpoint in main.") thread = threads[0] frame = thread.GetFrameAtIndex(0) - local_var = frame.FindVariable ("local_var") - self.assertTrue (local_var.IsValid()) + local_var = frame.FindVariable("local_var") + self.assertTrue(local_var.IsValid()) self.listener = lldb.SBListener("com.lldb.testsuite_listener") self.target_bcast = target.GetBroadcaster() - self.target_bcast.AddListener (self.listener, lldb.SBTarget.eBroadcastBitWatchpointChanged) - self.listener.StartListeningForEvents (self.target_bcast, lldb.SBTarget.eBroadcastBitWatchpointChanged) + self.target_bcast.AddListener( + self.listener, lldb.SBTarget.eBroadcastBitWatchpointChanged) + self.listener.StartListeningForEvents( + self.target_bcast, lldb.SBTarget.eBroadcastBitWatchpointChanged) error = lldb.SBError() local_watch = local_var.Watch(True, False, True, error) if not error.Success(): - self.fail ("Failed to make watchpoint for local_var: %s"%(error.GetCString())) + self.fail( + "Failed to make watchpoint for local_var: %s" % + (error.GetCString())) self.GetWatchpointEvent(lldb.eWatchpointEventTypeAdded) - # Now change some of the features of this watchpoint and make sure we get events: + # Now change some of the features of this watchpoint and make sure we + # get events: local_watch.SetEnabled(False) self.GetWatchpointEvent(lldb.eWatchpointEventTypeDisabled) @@ -79,19 +94,27 @@ class TestWatchpointEvents (TestBase): local_watch.SetCondition(condition) self.GetWatchpointEvent(lldb.eWatchpointEventTypeConditionChanged) - self.assertTrue(local_watch.GetCondition() == condition, 'make sure watchpoint condition is "' + condition + '"'); - - def GetWatchpointEvent (self, event_type): + self.assertTrue(local_watch.GetCondition() == condition, + 'make sure watchpoint condition is "' + condition + '"') + + def GetWatchpointEvent(self, event_type): # We added a watchpoint so we should get a watchpoint added event. event = lldb.SBEvent() - success = self.listener.WaitForEvent (1, event) - self.assertTrue(success == True, "Successfully got watchpoint event") - self.assertTrue (lldb.SBWatchpoint.EventIsWatchpointEvent(event), "Event is a watchpoint event.") - found_type = lldb.SBWatchpoint.GetWatchpointEventTypeFromEvent (event) - self.assertTrue (found_type == event_type, "Event is not correct type, expected: %d, found: %d"%(event_type, found_type)) + success = self.listener.WaitForEvent(1, event) + self.assertTrue(success, "Successfully got watchpoint event") + self.assertTrue( + lldb.SBWatchpoint.EventIsWatchpointEvent(event), + "Event is a watchpoint event.") + found_type = lldb.SBWatchpoint.GetWatchpointEventTypeFromEvent(event) + self.assertTrue( + found_type == event_type, + "Event is not correct type, expected: %d, found: %d" % + (event_type, + found_type)) # There shouldn't be another event waiting around: - found_event = self.listener.PeekAtNextEventForBroadcasterWithType (self.target_bcast, lldb.SBTarget.eBroadcastBitBreakpointChanged, event) + found_event = self.listener.PeekAtNextEventForBroadcasterWithType( + self.target_bcast, lldb.SBTarget.eBroadcastBitBreakpointChanged, event) if found_event: print("Found an event I didn't expect: ", event) - self.assertTrue (not found_event, "Only one event per change.") + self.assertTrue(not found_event, "Only one event per change.") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py index c66ddb51288..3f301fd9f1a 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py @@ -5,25 +5,29 @@ Test displayed value of a vector variable while doing watchpoint operations from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestValueOfVectorVariableTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_value_of_vector_variable_using_watchpoint_set(self): """Test verify displayed value of vector variable.""" self.build(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) self.value_of_vector_variable_with_watchpoint_set() - + def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -39,10 +43,12 @@ class TestValueOfVectorVariableTestCase(TestBase): # Set break to get a frame self.runCmd("b main") - + # Run the program. self.runCmd("run", RUN_SUCCEEDED) # Value of a vector variable should be displayed correctly - self.expect("watchpoint set variable global_vector", WATCHPOINT_CREATED, - substrs = ['new value: (1, 2, 3, 4)']) + self.expect( + "watchpoint set variable global_vector", + WATCHPOINT_CREATED, + substrs=['new value: (1, 2, 3, 4)']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py index 735a5678c4f..1a94276c58e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py @@ -5,13 +5,14 @@ Test lldb watchpoint that uses 'watchpoint set -w write -s size' to watch a poin from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchLocationUsingWatchpointSetTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,14 +23,24 @@ class WatchLocationUsingWatchpointSetTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # This is for verifying that watch location works. - self.violating_func = "do_bad_thing_with_location"; - # Build dictionary to have unique executable names for each test method. - - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=['aarch64', 'arm'], bugnumber="llvm.org/pr26031") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + self.violating_func = "do_bad_thing_with_location" + # Build dictionary to have unique executable names for each test + # method. + + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=[ + 'aarch64', + 'arm'], + bugnumber="llvm.org/pr26031") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watchlocation_using_watchpoint_set(self): """Test watching a location with 'watchpoint set expression -w write -s size' option.""" self.build() @@ -39,7 +50,8 @@ class WatchLocationUsingWatchpointSetTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -47,45 +59,52 @@ class WatchLocationUsingWatchpointSetTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Now let's set a write-type watchpoint pointed to by 'g_char_ptr' and # with offset as 7. # The main.cpp, by design, misbehaves by not following the agreed upon # protocol of only accessing the allowable index range of [0, 6]. - self.expect("watchpoint set expression -w write -s 1 -- g_char_ptr + 7", WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = 1', 'type = w']) + self.expect( + "watchpoint set expression -w write -s 1 -- g_char_ptr + 7", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 1', + 'type = w']) self.runCmd("expr unsigned val = g_char_ptr[7]; val") self.expect(self.res.GetOutput().splitlines()[0], exe=False, - endstr = ' = 0') + endstr=' = 0') # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. self.expect("watchpoint list -v", - substrs = ['hit_count = 0']) + substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped again due to the watchpoint (write type), but # only once. The stop reason of the thread should be watchpoint. self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stopped', - 'stop reason = watchpoint', - self.violating_func]) + substrs=['stopped', + 'stop reason = watchpoint', + self.violating_func]) - # Switch to the thread stopped due to watchpoint and issue some commands. + # Switch to the thread stopped due to watchpoint and issue some + # commands. self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint) self.runCmd("thread backtrace") self.runCmd("expr unsigned val = g_char_ptr[7]; val") self.expect(self.res.GetOutput().splitlines()[0], exe=False, - endstr = ' = 99') + endstr=' = 99') # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be the same as the number of threads that # stopped on a watchpoint. - threads = lldbutil.get_stopped_threads(self.process(), lldb.eStopReasonWatchpoint) + threads = lldbutil.get_stopped_threads( + self.process(), lldb.eStopReasonWatchpoint) self.expect("watchpoint list -v", - substrs = ['hit_count = %d' % len(threads)]) + substrs=['hit_count = %d' % len(threads)]) self.runCmd("thread backtrace all") diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py index 43597ec28f5..269b7c9b44e 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py @@ -5,13 +5,14 @@ Test error cases for the 'watchpoint set' command to make sure it errors out whe from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class WatchpointSetErrorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,8 +23,10 @@ class WatchpointSetErrorTestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') - # Build dictionary to have unique executable names for each test method. + self.line = line_number( + self.source, '// Set break point at this line.') + # Build dictionary to have unique executable names for each test + # method. @expectedFailureAll(oslist=["windows"]) def test_error_cases_with_watchpoint_set(self): @@ -35,7 +38,8 @@ class WatchpointSetErrorTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Add a breakpoint to set a watchpoint when stopped on the breakpoint. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -43,27 +47,29 @@ class WatchpointSetErrorTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Try some error conditions: # 'watchpoint set' is now a multiword command. self.expect("watchpoint set", - substrs = ['The following subcommands are supported:', - 'expression', - 'variable']) + substrs=['The following subcommands are supported:', + 'expression', + 'variable']) self.runCmd("watchpoint set variable -w read_write", check=False) # 'watchpoint set expression' with '-w' or '-s' specified now needs # an option terminator and a raw expression after that. self.expect("watchpoint set expression -w write --", error=True, - startstr = 'error: ') + startstr='error: ') # It's an error if the expression did not evaluate to an address. - self.expect("watchpoint set expression MyAggregateDataType", error=True, - startstr = 'error: expression did not evaluate to an address') + self.expect( + "watchpoint set expression MyAggregateDataType", + error=True, + startstr='error: expression did not evaluate to an address') # Wrong size parameter is an error. self.expect("watchpoint set variable -s -128", error=True, - substrs = ['invalid enumeration value']) + substrs=['invalid enumeration value']) diff --git a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_size/TestWatchpointSizes.py b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_size/TestWatchpointSizes.py index 55e36649ce1..e342e34667f 100644 --- a/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_size/TestWatchpointSizes.py +++ b/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_size/TestWatchpointSizes.py @@ -7,12 +7,14 @@ when they are packed in a 8-byte region. from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointSizeTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True @@ -29,23 +31,35 @@ class WatchpointSizeTestCase(TestBase): self.exe_name = 'a.out' self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_byte_size_watchpoints_with_byte_selection(self): """Test to selectively watch different bytes in a 8-byte array.""" self.run_watchpoint_size_test('byteArray', 8, '1') - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_two_byte_watchpoints_with_word_selection(self): """Test to selectively watch different words in an 8-byte word array.""" self.run_watchpoint_size_test('wordArray', 4, '2') - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_four_byte_watchpoints_with_dword_selection(self): """Test to selectively watch two double words in an 8-byte dword array.""" self.run_watchpoint_size_test('dwordArray', 2, '4') @@ -61,8 +75,8 @@ class WatchpointSizeTestCase(TestBase): loc_line = line_number('main.c', '// About to write ' + arrayName) # Set a breakpoint on the line detected above. - lldbutil.run_break_set_by_file_and_line (self, "main.c",loc_line, - num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", loc_line, num_expected_locations=1, loc_exact=True) # Run the program. self.runCmd("run", RUN_SUCCEEDED) @@ -71,46 +85,55 @@ class WatchpointSizeTestCase(TestBase): # We should be stopped again due to the breakpoint. # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # Set a read_write type watchpoint arrayName - watch_loc=arrayName+"[" + str(i) + "]" - self.expect("watchpoint set variable -w read_write " + watch_loc, + watch_loc = arrayName + "[" + str(i) + "]" + self.expect( + "watchpoint set variable -w read_write " + + watch_loc, WATCHPOINT_CREATED, - substrs = ['Watchpoint created', 'size = ' + watchsize, 'type = rw']) + substrs=[ + 'Watchpoint created', + 'size = ' + + watchsize, + 'type = rw']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should be 0 initially. - self.expect("watchpoint list -v", substrs = ['hit_count = 0']) + self.expect("watchpoint list -v", substrs=['hit_count = 0']) self.runCmd("process continue") # We should be stopped due to the watchpoint. # The stop reason of the thread should be watchpoint. self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stopped', 'stop reason = watchpoint']) + substrs=['stopped', 'stop reason = watchpoint']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. self.expect("watchpoint list -v", - substrs = ['hit_count = 1']) + substrs=['hit_count = 1']) self.runCmd("process continue") # We should be stopped due to the watchpoint. # The stop reason of the thread should be watchpoint. self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, - substrs = ['stopped', 'stop reason = watchpoint']) + substrs=['stopped', 'stop reason = watchpoint']) # Use the '-v' option to do verbose listing of the watchpoint. # The hit count should now be 1. # Verify hit_count has been updated after value has been read. self.expect("watchpoint list -v", - substrs = ['hit_count = 2']) + substrs=['hit_count = 2']) - # Delete the watchpoint immediately, but set auto-confirm to true first. + # Delete the watchpoint immediately, but set auto-confirm to true + # first. self.runCmd("settings set auto-confirm true") - self.expect("watchpoint delete", substrs = ['All watchpoints removed.']) + self.expect( + "watchpoint delete", + substrs=['All watchpoints removed.']) # Restore the original setting of auto-confirm. self.runCmd("settings clear auto-confirm") diff --git a/lldb/packages/Python/lldbsuite/test/help/TestApropos.py b/lldb/packages/Python/lldbsuite/test/help/TestApropos.py index 7b2e69938a0..8bf75ab6880 100644 --- a/lldb/packages/Python/lldbsuite/test/help/TestApropos.py +++ b/lldb/packages/Python/lldbsuite/test/help/TestApropos.py @@ -5,13 +5,14 @@ Test some lldb apropos commands. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class AproposCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,4 +20,9 @@ class AproposCommandTestCase(TestBase): @no_debug_info_test def test_apropos_variable(self): """Test that 'apropos variable' prints the fully qualified command name""" - self.expect('apropos variable', substrs=['frame variable', 'target variable', 'watchpoint set variable']) + self.expect( + 'apropos variable', + substrs=[ + 'frame variable', + 'target variable', + 'watchpoint set variable']) diff --git a/lldb/packages/Python/lldbsuite/test/help/TestHelp.py b/lldb/packages/Python/lldbsuite/test/help/TestHelp.py index f4e9faff0ed..9bcac6b398d 100644 --- a/lldb/packages/Python/lldbsuite/test/help/TestHelp.py +++ b/lldb/packages/Python/lldbsuite/test/help/TestHelp.py @@ -7,13 +7,14 @@ See also CommandInterpreter::OutputFormattedHelpText(). from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class HelpCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,25 +23,28 @@ class HelpCommandTestCase(TestBase): def test_simplehelp(self): """A simple test of 'help' command and its output.""" self.expect("help", - startstr = 'Debugger commands:') + startstr='Debugger commands:') self.expect("help -a", matching=False, - substrs = ['next']) - + substrs=['next']) + self.expect("help", matching=True, - substrs = ['next']) - + substrs=['next']) + @no_debug_info_test def test_help_on_help(self): """Testing the help on the help facility.""" self.expect("help help", matching=True, - substrs = ['--hide-aliases', - '--hide-user-commands']) + substrs=['--hide-aliases', + '--hide-user-commands']) @no_debug_info_test def version_number_string(self): """Helper function to find the version number string of lldb.""" - plist = os.path.join(os.environ["LLDB_SRC"], "resources", "LLDB-Info.plist") + plist = os.path.join( + os.environ["LLDB_SRC"], + "resources", + "LLDB-Info.plist") try: CFBundleVersionSegFound = False with open(plist, 'r') as f: @@ -53,13 +57,14 @@ class HelpCommandTestCase(TestBase): version = m.group(1) return version else: - # Unsuccessful, let's juts break out of the for loop. + # Unsuccessful, let's juts break out of the for + # loop. break if line.find("<key>CFBundleVersion</key>") != -1: # Found our match. The next line contains our version # string, for example: - # + # # <string>38</string> CFBundleVersionSegFound = True @@ -76,13 +81,13 @@ class HelpCommandTestCase(TestBase): def test_help_arch(self): """Test 'help arch' which should list of supported architectures.""" self.expect("help arch", - substrs = ['arm', 'x86_64', 'i386']) + substrs=['arm', 'x86_64', 'i386']) @no_debug_info_test def test_help_version(self): """Test 'help version' and 'version' commands.""" self.expect("help version", - substrs = ['Show the LLDB debugger version.']) + substrs=['Show the LLDB debugger version.']) version_str = self.version_number_string() import re match = re.match('[0-9]+', version_str) @@ -92,7 +97,7 @@ class HelpCommandTestCase(TestBase): search_regexp = ['lldb version (\d|\.)+.*$'] self.expect("version", - patterns = search_regexp) + patterns=search_regexp) @no_debug_info_test def test_help_should_not_crash_lldb(self): @@ -103,101 +108,112 @@ class HelpCommandTestCase(TestBase): @no_debug_info_test def test_help_should_not_hang_emacsshell(self): """Command 'settings set term-width 0' should not hang the help command.""" - self.expect("settings set term-width 0", - COMMAND_FAILED_AS_EXPECTED, error=True, - substrs = ['error: 0 is out of range, valid values must be between']) + self.expect( + "settings set term-width 0", + COMMAND_FAILED_AS_EXPECTED, + error=True, + substrs=['error: 0 is out of range, valid values must be between']) # self.runCmd("settings set term-width 0") self.expect("help", - startstr = 'Debugger commands:') + startstr='Debugger commands:') @no_debug_info_test def test_help_breakpoint_set(self): """Test that 'help breakpoint set' does not print out redundant lines of: 'breakpoint set [-s <shlib-name>] ...'.""" self.expect("help breakpoint set", matching=False, - substrs = ['breakpoint set [-s <shlib-name>]']) + substrs=['breakpoint set [-s <shlib-name>]']) @no_debug_info_test def test_help_image_dump_symtab_should_not_crash(self): """Command 'help image dump symtab' should not crash lldb.""" # 'image' is an alias for 'target modules'. self.expect("help image dump symtab", - substrs = ['dump symtab', - 'sort-order']) + substrs=['dump symtab', + 'sort-order']) @no_debug_info_test def test_help_image_du_sym_is_ambiguous(self): """Command 'help image du sym' is ambiguous and spits out the list of candidates.""" self.expect("help image du sym", COMMAND_FAILED_AS_EXPECTED, error=True, - substrs = ['error: ambiguous command image du sym', - 'symfile', - 'symtab']) + substrs=['error: ambiguous command image du sym', + 'symfile', + 'symtab']) @no_debug_info_test def test_help_image_du_line_should_work(self): """Command 'help image du line-table' is not ambiguous and should work.""" # 'image' is an alias for 'target modules'. - self.expect("help image du line", - substrs = ['Dump the line table for one or more compilation units']) + self.expect("help image du line", substrs=[ + 'Dump the line table for one or more compilation units']) @no_debug_info_test def test_help_target_variable_syntax(self): """Command 'help target variable' should display <variable-name> ...""" self.expect("help target variable", - substrs = ['<variable-name> [<variable-name> [...]]']) + substrs=['<variable-name> [<variable-name> [...]]']) @no_debug_info_test def test_help_watchpoint_and_its_args(self): """Command 'help watchpoint', 'help watchpt-id', and 'help watchpt-id-list' should work.""" self.expect("help watchpoint", - substrs = ['delete', 'disable', 'enable', 'list']) + substrs=['delete', 'disable', 'enable', 'list']) self.expect("help watchpt-id", - substrs = ['<watchpt-id>']) + substrs=['<watchpt-id>']) self.expect("help watchpt-id-list", - substrs = ['<watchpt-id-list>']) + substrs=['<watchpt-id-list>']) @no_debug_info_test def test_help_watchpoint_set(self): """Test that 'help watchpoint set' prints out 'expression' and 'variable' as the possible subcommands.""" self.expect("help watchpoint set", - substrs = ['The following subcommands are supported:'], - patterns = ['expression +--', - 'variable +--']) + substrs=['The following subcommands are supported:'], + patterns=['expression +--', + 'variable +--']) @no_debug_info_test def test_help_po_hides_options(self): """Test that 'help po' does not show all the options for expression""" - self.expect("help po", - substrs = ['--show-all-children', '--object-description'], matching=False) + self.expect( + "help po", + substrs=[ + '--show-all-children', + '--object-description'], + matching=False) @no_debug_info_test def test_help_run_hides_options(self): """Test that 'help run' does not show all the options for process launch""" self.expect("help run", - substrs = ['--arch', '--environment'], matching=False) + substrs=['--arch', '--environment'], matching=False) @no_debug_info_test def test_help_next_shows_options(self): """Test that 'help next' shows all the options for thread step-over""" self.expect("help next", - substrs = ['--python-class','--run-mode'], matching=True) + substrs=['--python-class', '--run-mode'], matching=True) @no_debug_info_test def test_help_provides_alternatives(self): """Test that help on commands that don't exist provides information on additional help avenues""" - self.expect("help thisisnotadebuggercommand", - substrs = ["'thisisnotadebuggercommand' is not a known command.", - "Try 'help' to see a current list of commands.", - "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", - "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."], error=True) - - self.expect("help process thisisnotadebuggercommand", - substrs = ["'process thisisnotadebuggercommand' is not a known command.", - "Try 'help' to see a current list of commands.", - "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", - "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."]) + self.expect( + "help thisisnotadebuggercommand", + substrs=[ + "'thisisnotadebuggercommand' is not a known command.", + "Try 'help' to see a current list of commands.", + "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", + "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."], + error=True) + + self.expect( + "help process thisisnotadebuggercommand", + substrs=[ + "'process thisisnotadebuggercommand' is not a known command.", + "Try 'help' to see a current list of commands.", + "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", + "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."]) @no_debug_info_test def test_custom_help_alias(self): @@ -205,9 +221,15 @@ class HelpCommandTestCase(TestBase): def cleanup(): self.runCmd('command unalias afriendlyalias', check=False) self.runCmd('command unalias averyfriendlyalias', check=False) - + self.addTearDownHook(cleanup) - self.runCmd('command alias --help "I am a friendly alias" -- afriendlyalias help') - self.expect("help afriendlyalias", matching=True, substrs = ['I am a friendly alias']) - self.runCmd('command alias --long-help "I am a very friendly alias" -- averyfriendlyalias help') - self.expect("help averyfriendlyalias", matching=True, substrs = ['I am a very friendly alias']) + self.runCmd( + 'command alias --help "I am a friendly alias" -- afriendlyalias help') + self.expect( + "help afriendlyalias", + matching=True, + substrs=['I am a friendly alias']) + self.runCmd( + 'command alias --long-help "I am a very friendly alias" -- averyfriendlyalias help') + self.expect("help averyfriendlyalias", matching=True, + substrs=['I am a very friendly alias']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py b/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py index e6f1092c702..6d5f61ebb8b 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py @@ -3,28 +3,31 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class AnonymousTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIf(compiler="icc", bugnumber="llvm.org/pr15036: LLDB generates an incorrect AST layout for an anonymous struct when DWARF is generated by ICC") + @skipIf( + compiler="icc", + bugnumber="llvm.org/pr15036: LLDB generates an incorrect AST layout for an anonymous struct when DWARF is generated by ICC") def test_expr_nest(self): self.build() self.common_setup(self.line0) # These should display correctly. self.expect("expression n->foo.d", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 4"]) - + substrs=["= 4"]) + self.expect("expression n->b", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 2"]) + substrs=["= 2"]) def test_expr_child(self): self.build() @@ -32,35 +35,40 @@ class AnonymousTestCase(TestBase): # These should display correctly. self.expect("expression c->foo.d", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 4"]) - - self.expect("expression c->grandchild.b", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 2"]) + substrs=["= 4"]) - @skipIf(compiler="icc", bugnumber="llvm.org/pr15036: This particular regression was introduced by r181498") + self.expect( + "expression c->grandchild.b", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 2"]) + + @skipIf( + compiler="icc", + bugnumber="llvm.org/pr15036: This particular regression was introduced by r181498") def test_expr_grandchild(self): self.build() self.common_setup(self.line2) # These should display correctly. self.expect("expression g.child.foo.d", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 4"]) - + substrs=["= 4"]) + self.expect("expression g.child.b", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 2"]) + substrs=["= 2"]) def test_expr_parent(self): self.build() if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): - self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") self.common_setup(self.line2) # These should display correctly. self.expect("expression pz", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(type_z *) $", " = 0x0000"]) + substrs=["(type_z *) $", " = 0x0000"]) self.expect("expression z.y", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(type_y) $", "dummy = 2"]) + substrs=["(type_y) $", "dummy = 2"]) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21550") def test_expr_null(self): @@ -69,48 +77,52 @@ class AnonymousTestCase(TestBase): # This should fail because pz is 0, but it succeeds on OS/X. # This fails on Linux with an upstream error "Couldn't dematerialize struct", as does "p *n" with "int *n = 0". - # Note that this can also trigger llvm.org/pr15036 when run interactively at the lldb command prompt. - self.expect("expression *(type_z *)pz", error = True) + # Note that this can also trigger llvm.org/pr15036 when run + # interactively at the lldb command prompt. + self.expect("expression *(type_z *)pz", error=True) def test_child_by_name(self): self.build() - + # Set debugger into synchronous mode self.dbg.SetAsync(False) # Create a target - exe = os.path.join (os.getcwd(), "a.out") + exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - break_in_main = target.BreakpointCreateBySourceRegex ('// Set breakpoint 2 here.', lldb.SBFileSpec(self.source)) + break_in_main = target.BreakpointCreateBySourceRegex( + '// Set breakpoint 2 here.', lldb.SBFileSpec(self.source)) self.assertTrue(break_in_main, VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) - self.assertTrue (process, PROCESS_IS_VALID) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_main) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint in main.") + self.fail("Failed to stop at breakpoint in main.") thread = threads[0] frame = thread.frames[0] if not frame.IsValid(): - self.fail ("Failed to get frame 0.") + self.fail("Failed to get frame 0.") var_n = frame.FindVariable("n") if not var_n.IsValid(): - self.fail ("Failed to get the variable 'n'") + self.fail("Failed to get the variable 'n'") elem_a = var_n.GetChildMemberWithName("a") if not elem_a.IsValid(): - self.fail ("Failed to get the element a in n") + self.fail("Failed to get the element a in n") error = lldb.SBError() value = elem_a.GetValueAsSigned(error, 1000) if not error.Success() or value != 0: - self.fail ("failed to get the correct value for element a in n") + self.fail("failed to get the correct value for element a in n") def test_nest_flat(self): self.build() @@ -118,10 +130,10 @@ class AnonymousTestCase(TestBase): # These should display correctly. self.expect('frame variable n --flat', - substrs = ['n.a = 0', - 'n.b = 2', - 'n.foo.c = 0', - 'n.foo.d = 4']) + substrs=['n.a = 0', + 'n.b = 2', + 'n.foo.c = 0', + 'n.foo.d = 4']) def setUp(self): # Call super's setUp(). @@ -133,7 +145,7 @@ class AnonymousTestCase(TestBase): self.line2 = line_number(self.source, '// Set breakpoint 2 here.') def common_setup(self, line): - + # Set debugger into synchronous mode self.dbg.SetAsync(False) @@ -142,18 +154,21 @@ class AnonymousTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - # Set breakpoints inside and outside methods that take pointers to the containing struct. - lldbutil.run_break_set_by_file_and_line (self, self.source, line, num_expected_locations=1, loc_exact=True) + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. + lldbutil.run_break_set_by_file_and_line( + self, self.source, line, num_expected_locations=1, loc_exact=True) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py b/lldb/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py index 5a490746568..d4716de907c 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ArrayTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,7 +27,8 @@ class ArrayTypesTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=False) self.runCmd("run", RUN_SUCCEEDED) @@ -39,35 +41,45 @@ class ArrayTypesTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = ['resolved, hit count = 1']) + substrs=['resolved, hit count = 1']) # Issue 'variable list' command on several array-type variables. - self.expect("frame variable --show-types strings", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(char *[4])', - substrs = ['(char *) [0]', - '(char *) [1]', - '(char *) [2]', - '(char *) [3]', - 'Hello', - 'Hola', - 'Bonjour', - 'Guten Tag']) - - self.expect("frame variable --show-types --raw -- char_16", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(char) [0]', - '(char) [15]']) - - self.expect("frame variable --show-types ushort_matrix", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(unsigned short [2][3])') - - self.expect("frame variable --show-types long_6", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(long [6])') + self.expect( + "frame variable --show-types strings", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(char *[4])', + substrs=[ + '(char *) [0]', + '(char *) [1]', + '(char *) [2]', + '(char *) [3]', + 'Hello', + 'Hola', + 'Bonjour', + 'Guten Tag']) + + self.expect( + "frame variable --show-types --raw -- char_16", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(char) [0]', + '(char) [15]']) + + self.expect( + "frame variable --show-types ushort_matrix", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(unsigned short [2][3])') + + self.expect( + "frame variable --show-types long_6", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(long [6])') @add_test_categories(['pyapi']) def test_and_python_api(self): @@ -84,24 +96,30 @@ class ArrayTypesTestCase(TestBase): # Sanity check the print representation of breakpoint. bp = str(breakpoint) self.expect(bp, msg="Breakpoint looks good", exe=False, - substrs = ["file = 'main.c'", - "line = %d" % self.line, - "locations = 1"]) - self.expect(bp, msg="Breakpoint is not resolved as yet", exe=False, matching=False, - substrs = ["resolved = 1"]) + substrs=["file = 'main.c'", + "line = %d" % self.line, + "locations = 1"]) + self.expect( + bp, + msg="Breakpoint is not resolved as yet", + exe=False, + matching=False, + substrs=["resolved = 1"]) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Sanity check the print representation of process. proc = str(process) self.expect(proc, msg="Process looks good", exe=False, - substrs = ["state = stopped", - "executable = a.out"]) + substrs=["state = stopped", + "executable = a.out"]) # The stop reason of the thread should be breakpoint. - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # Sanity check the print representation of thread. @@ -114,8 +132,11 @@ class ArrayTypesTestCase(TestBase): tidstr = "tid = %u" % thread.GetThreadID() else: tidstr = "tid = 0x%4.4x" % thread.GetThreadID() - self.expect(thr, "Thread looks good with stop reason = breakpoint", exe=False, - substrs = [tidstr]) + self.expect( + thr, + "Thread looks good with stop reason = breakpoint", + exe=False, + substrs=[tidstr]) # The breakpoint should have a hit count of 1. self.assertEqual(breakpoint.GetHitCount(), 1, BREAKPOINT_HIT_ONCE) @@ -123,24 +144,33 @@ class ArrayTypesTestCase(TestBase): # The breakpoint should be resolved by now. bp = str(breakpoint) self.expect(bp, "Breakpoint looks good and is resolved", exe=False, - substrs = ["file = 'main.c'", - "line = %d" % self.line, - "locations = 1"]) + substrs=["file = 'main.c'", + "line = %d" % self.line, + "locations = 1"]) # Sanity check the print representation of frame. frame = thread.GetFrameAtIndex(0) frm = str(frame) - self.expect(frm, - "Frame looks good with correct index %d" % frame.GetFrameID(), - exe=False, - substrs = ["#%d" % frame.GetFrameID()]) + self.expect( + frm, + "Frame looks good with correct index %d" % + frame.GetFrameID(), + exe=False, + substrs=[ + "#%d" % + frame.GetFrameID()]) # Lookup the "strings" string array variable and sanity check its print # representation. variable = frame.FindVariable("strings") var = str(variable) - self.expect(var, "Variable for 'strings' looks good with correct name", exe=False, - substrs = ["%s" % variable.GetName()]) + self.expect( + var, + "Variable for 'strings' looks good with correct name", + exe=False, + substrs=[ + "%s" % + variable.GetName()]) self.DebugSBValue(variable) self.assertTrue(variable.GetNumChildren() == 4, "Variable 'strings' should have 4 children") @@ -186,9 +216,11 @@ class ArrayTypesTestCase(TestBase): # Last, check that "long_6" has a value type of eValueTypeVariableLocal # and "argc" has eValueTypeVariableArgument. from lldbsuite.test.lldbutil import value_type_to_str - self.assertTrue(variable.GetValueType() == lldb.eValueTypeVariableLocal, - "Variable 'long_6' should have '%s' value type." % - value_type_to_str(lldb.eValueTypeVariableLocal)) + self.assertTrue( + variable.GetValueType() == lldb.eValueTypeVariableLocal, + "Variable 'long_6' should have '%s' value type." % + value_type_to_str( + lldb.eValueTypeVariableLocal)) argc = frame.FindVariable("argc") self.DebugSBValue(argc) self.assertTrue(argc.GetValueType() == lldb.eValueTypeVariableArgument, diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py b/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py index 30175c5e1c1..0c6f5373fc5 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py @@ -3,24 +3,27 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BitfieldsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - + def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') - @skipIfWindows # BitFields exhibit crashes in record layout on Windows (http://llvm.org/pr21800) + # BitFields exhibit crashes in record layout on Windows + # (http://llvm.org/pr21800) + @skipIfWindows def test_and_run_command(self): """Test 'frame variable ...' on a variable with bitfields.""" self.build() @@ -28,85 +31,102 @@ class BitfieldsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # This should display correctly. - self.expect("frame variable --show-types bits", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(uint32_t:1) b1 = 1', - '(uint32_t:2) b2 = 3', - '(uint32_t:3) b3 = 7', - '(uint32_t) b4 = 15', - '(uint32_t:5) b5 = 31', - '(uint32_t:6) b6 = 63', - '(uint32_t:7) b7 = 127', - '(uint32_t:4) four = 15']) + self.expect( + "frame variable --show-types bits", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(uint32_t:1) b1 = 1', + '(uint32_t:2) b2 = 3', + '(uint32_t:3) b3 = 7', + '(uint32_t) b4 = 15', + '(uint32_t:5) b5 = 31', + '(uint32_t:6) b6 = 63', + '(uint32_t:7) b7 = 127', + '(uint32_t:4) four = 15']) # And so should this. # rdar://problem/8348251 - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(uint32_t:1) b1 = 1', - '(uint32_t:2) b2 = 3', - '(uint32_t:3) b3 = 7', - '(uint32_t) b4 = 15', - '(uint32_t:5) b5 = 31', - '(uint32_t:6) b6 = 63', - '(uint32_t:7) b7 = 127', - '(uint32_t:4) four = 15']) + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(uint32_t:1) b1 = 1', + '(uint32_t:2) b2 = 3', + '(uint32_t:3) b3 = 7', + '(uint32_t) b4 = 15', + '(uint32_t:5) b5 = 31', + '(uint32_t:6) b6 = 63', + '(uint32_t:7) b7 = 127', + '(uint32_t:4) four = 15']) self.expect("expr (bits.b1)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '1']) + substrs=['uint32_t', '1']) self.expect("expr (bits.b2)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '3']) + substrs=['uint32_t', '3']) self.expect("expr (bits.b3)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '7']) + substrs=['uint32_t', '7']) self.expect("expr (bits.b4)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '15']) + substrs=['uint32_t', '15']) self.expect("expr (bits.b5)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '31']) + substrs=['uint32_t', '31']) self.expect("expr (bits.b6)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '63']) + substrs=['uint32_t', '63']) self.expect("expr (bits.b7)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '127']) + substrs=['uint32_t', '127']) self.expect("expr (bits.four)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '15']) + substrs=['uint32_t', '15']) - self.expect("frame variable --show-types more_bits", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(uint32_t:3) a = 3', - '(uint8_t:1) b = \'\\0\'', - '(uint8_t:1) c = \'\\x01\'', - '(uint8_t:1) d = \'\\0\'']) + self.expect( + "frame variable --show-types more_bits", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(uint32_t:3) a = 3', + '(uint8_t:1) b = \'\\0\'', + '(uint8_t:1) c = \'\\x01\'', + '(uint8_t:1) d = \'\\0\'']) self.expect("expr (more_bits.a)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', '3']) + substrs=['uint32_t', '3']) self.expect("expr (more_bits.b)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint8_t', '\\0']) + substrs=['uint8_t', '\\0']) self.expect("expr (more_bits.c)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint8_t', '\\x01']) + substrs=['uint8_t', '\\x01']) self.expect("expr (more_bits.d)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint8_t', '\\0']) - - self.expect("expr (packed.a)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['char', "'a'"]) - self.expect("expr (packed.b)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', "10"]) - self.expect("expr/x (packed.c)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['uint32_t', "7112233"]) + substrs=['uint8_t', '\\0']) + self.expect("expr (packed.a)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['char', "'a'"]) + self.expect("expr (packed.b)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', "10"]) + self.expect("expr/x (packed.c)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', "7112233"]) @add_test_categories(['pyapi']) - @skipIfWindows # BitFields exhibit crashes in record layout on Windows (http://llvm.org/pr21800) - @expectedFailureAll("llvm.org/pr27510", oslist=["linux"], compiler="clang", compiler_version=[">=", "3.9"]) + # BitFields exhibit crashes in record layout on Windows + # (http://llvm.org/pr21800) + @skipIfWindows + @expectedFailureAll( + "llvm.org/pr27510", + oslist=["linux"], + compiler="clang", + compiler_version=[ + ">=", + "3.9"]) def test_and_python_api(self): """Use Python APIs to inspect a bitfields variable.""" self.build() @@ -118,11 +138,13 @@ class BitfieldsTestCase(TestBase): breakpoint = target.BreakpointCreateByLocation("main.c", self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # The breakpoint should have a hit count of 1. @@ -132,10 +154,14 @@ class BitfieldsTestCase(TestBase): frame = thread.GetFrameAtIndex(0) bits = frame.FindVariable("bits") self.DebugSBValue(bits) - self.assertTrue(bits.GetTypeName() == 'Bits', "bits.GetTypeName() == 'Bits'"); - self.assertTrue(bits.GetNumChildren() == 10, "bits.GetNumChildren() == 10"); + self.assertTrue( + bits.GetTypeName() == 'Bits', + "bits.GetTypeName() == 'Bits'") + self.assertTrue( + bits.GetNumChildren() == 10, + "bits.GetNumChildren() == 10") test_compiler = self.getCompiler() - self.assertTrue(bits.GetByteSize() == 32, "bits.GetByteSize() == 32"); + self.assertTrue(bits.GetByteSize() == 32, "bits.GetByteSize() == 32") # Notice the pattern of int(b1.GetValue(), 0). We pass a base of 0 # so that the proper radix is determined based on the contents of the diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py b/lldb/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py index e31b56c06fb..4025635eec6 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py @@ -3,14 +3,15 @@ from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil + class BlocksTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -32,38 +33,46 @@ class BlocksTestCase(TestBase): # Break inside the foo function which takes a bar_ptr argument. for line in self.lines: - lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) self.wait_for_breakpoint() - + @skipUnlessDarwin def test_expr(self): self.launch_common() self.expect("expression a + b", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 7"]) + substrs=["= 7"]) self.expect("expression c", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 1"]) + substrs=["= 1"]) self.wait_for_breakpoint() # This should display correctly. self.expect("expression (int)neg (-12)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 12"]) + substrs=["= 12"]) @skipUnlessDarwin def test_define(self): self.launch_common() - self.runCmd("expression int (^$add)(int, int) = ^int(int a, int b) { return a + b; };") - self.expect("expression $add(2,3)", VARIABLES_DISPLAYED_CORRECTLY, substrs = [" = 5"]) + self.runCmd( + "expression int (^$add)(int, int) = ^int(int a, int b) { return a + b; };") + self.expect( + "expression $add(2,3)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[" = 5"]) self.runCmd("expression int $a = 3") - self.expect("expression int (^$addA)(int) = ^int(int b) { return $a + b; };", "Proper error is reported on capture", error=True) - + self.expect( + "expression int (^$addA)(int) = ^int(int b) { return $a + b; };", + "Proper error is reported on capture", + error=True) + def wait_for_breakpoint(self): - if self.is_started == False: + if not self.is_started: self.is_started = True self.runCmd("process launch", RUN_SUCCEEDED) else: @@ -71,5 +80,5 @@ class BlocksTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py b/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py index 99544c7bd80..d54435a4c67 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ConstVariableTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,8 +26,15 @@ class ConstVariableTestCase(TestBase): compiler="clang", compiler_version=["=", "3.8"]) @expectedFailureAll(oslist=["freebsd", "linux"], compiler="icc") @expectedFailureAll(archs=['mips', 'mipsel', 'mips64', 'mips64el']) - @expectedFailureAll(oslist=["linux"], archs=['arm', 'aarch64'], bugnumber="llvm.org/pr27883") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=[ + 'arm', + 'aarch64'], + bugnumber="llvm.org/pr27883") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_and_run_command(self): """Test interpreted and JITted expressions on constant values.""" self.build() @@ -34,32 +42,35 @@ class ConstVariableTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=1) + lldbutil.run_break_set_by_symbol( + self, "main", num_expected_locations=1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) self.runCmd("next") self.runCmd("next") # Try frame variable. self.expect("frame variable index", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(int32_t) index = 512']) + substrs=['(int32_t) index = 512']) # Try an interpreted expression. self.expect("expr (index + 512)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['1024']) + substrs=['1024']) # Try a JITted expression. - self.expect("expr (int)getpid(); (index - 256)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['256']) + self.expect( + "expr (int)getpid(); (index - 256)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['256']) self.runCmd("kill") diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py b/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py index 044accf14f6..55e0f70f279 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.decorators import * + class EnumTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,7 +21,8 @@ class EnumTypesTestCase(TestBase): # Find the line number to break inside main(). self.line = line_number('main.c', '// Set break point at this line.') - @expectedFailureAll(oslist=['windows']) # derefing the null pointer "works" on Windows + # derefing the null pointer "works" on Windows + @expectedFailureAll(oslist=['windows']) def test(self): """Test 'image lookup -t days' and check for correct display and enum value printing.""" self.build() @@ -28,23 +30,35 @@ class EnumTypesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - bkpt_id = lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + bkpt_id = lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Look up information about the 'days' enum type. # Check for correct display. self.expect("image lookup -t days", DATA_TYPES_DISPLAYED_CORRECTLY, - substrs = ['enum days {', + substrs=['enum days {', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + 'kNumDays', + '}']) + + enum_values = ['-4', 'Monday', 'Tuesday', 'Wednesday', @@ -53,28 +67,41 @@ class EnumTypesTestCase(TestBase): 'Saturday', 'Sunday', 'kNumDays', - '}']) - - enum_values = [ '-4', - 'Monday', - 'Tuesday', - 'Wednesday', - 'Thursday', - 'Friday', - 'Saturday', - 'Sunday', - 'kNumDays', - '5']; + '5'] # Make sure a pointer to an anonymous enum type does crash LLDB and displays correctly using # frame variable and expression commands - self.expect('frame variable f.op', DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['ops *', 'f.op'], patterns = ['0x0+$']) - self.expect('frame variable *f.op', DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['ops', '*f.op', '<parent is NULL>']) - self.expect('expr f.op', DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['ops *', '$'], patterns = ['0x0+$']) - self.expect('expr *f.op', DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['error:'], error = True) + self.expect( + 'frame variable f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=[ + 'ops *', + 'f.op'], + patterns=['0x0+$']) + self.expect( + 'frame variable *f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=[ + 'ops', + '*f.op', + '<parent is NULL>']) + self.expect( + 'expr f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=[ + 'ops *', + '$'], + patterns=['0x0+$']) + self.expect( + 'expr *f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=['error:'], + error=True) bkpt = self.target().FindBreakpointByID(bkpt_id) for enum_value in enum_values: - self.expect("frame variable day", 'check for valid enumeration value', - substrs = [enum_value]) - lldbutil.continue_to_breakpoint (self.process(), bkpt) + self.expect( + "frame variable day", + 'check for valid enumeration value', + substrs=[enum_value]) + lldbutil.continue_to_breakpoint(self.process(), bkpt) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py b/lldb/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py index 33c0de2d72d..60e7073f146 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py @@ -3,12 +3,13 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class ForwardDeclarationTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,28 +21,35 @@ class ForwardDeclarationTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_symbol (self, "foo", num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, "foo", num_expected_locations=1, sym_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # This should display correctly. # Note that the member fields of a = 1 and b = 2 is by design. - self.expect("frame variable --show-types *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(bar) *bar_ptr = ', - '(int) a = 1', - '(int) b = 2']) + self.expect( + "frame variable --show-types *bar_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(bar) *bar_ptr = ', + '(int) a = 1', + '(int) b = 2']) # And so should this. - self.expect("expression --show-types -- *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(bar)', - '(int) a = 1', - '(int) b = 2']) + self.expect( + "expression --show-types -- *bar_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(bar)', + '(int) a = 1', + '(int) b = 2']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py b/lldb/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py index 67ccb1aa3fa..35e902e5bdc 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class FunctionTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,18 +27,24 @@ class FunctionTypesTestCase(TestBase): self.runToBreakpoint() # Check that the 'callback' variable display properly. - self.expect("frame variable --show-types callback", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int (*)(const char *)) callback =') + self.expect( + "frame variable --show-types callback", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int (*)(const char *)) callback =') # And that we can break on the callback function. - lldbutil.run_break_set_by_symbol (self, "string_not_empty", num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + "string_not_empty", + num_expected_locations=1, + sym_exact=True) self.runCmd("continue") # Check that we do indeed stop on the string_not_empty function. self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['a.out`string_not_empty', - 'stop reason = breakpoint']) - + substrs=['a.out`string_not_empty', + 'stop reason = breakpoint']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") def test_pointers(self): """Test that a function pointer to 'printf' works and can be called.""" @@ -45,33 +52,34 @@ class FunctionTypesTestCase(TestBase): self.runToBreakpoint() self.expect("expr string_not_empty", - substrs = ['(int (*)(const char *)) $0 = ', '(a.out`']) + substrs=['(int (*)(const char *)) $0 = ', '(a.out`']) if self.platformIsDarwin(): regexps = ['lib.*\.dylib`printf'] else: regexps = ['printf'] self.expect("expr (int (*)(const char*, ...))printf", - substrs = ['(int (*)(const char *, ...)) $1 = '], - patterns = regexps) + substrs=['(int (*)(const char *, ...)) $1 = '], + patterns=regexps) self.expect("expr $1(\"Hello world\\n\")", - startstr = '(int) $2 = 12') + startstr='(int) $2 = 12') def runToBreakpoint(self): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - + # Break inside the main. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) - + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + self.runCmd("run", RUN_SUCCEEDED) - + # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py b/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py index 87160f5252b..28a8b36543e 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py @@ -7,6 +7,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class GlobalVariablesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -16,11 +17,17 @@ class GlobalVariablesTestCase(TestBase): TestBase.setUp(self) # Find the line number to break inside main(). self.source = 'main.c' - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') self.shlib_names = ["a"] @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") - @expectedFailureAll("llvm.org/pr25872", oslist=["macosx"], debug_info=["dwarf", "gmodules"]) + @expectedFailureAll( + "llvm.org/pr25872", + oslist=["macosx"], + debug_info=[ + "dwarf", + "gmodules"]) def test_c_global_variables(self): """Test 'frame variable --scope --no-args' which omits args and shows scopes.""" self.build() @@ -30,48 +37,67 @@ class GlobalVariablesTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Break inside the main. - lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) - # Register our shared libraries for remote targets so they get automatically uploaded - environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names) + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Check that GLOBAL scopes are indicated for the variables. - self.expect("frame variable --show-types --scope --show-globals --no-args", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['GLOBAL: (int) g_file_global_int = 42', - 'STATIC: (const int) g_file_static_int = 2', - 'GLOBAL: (const char *) g_file_global_cstr', - '"g_file_global_cstr"', - 'STATIC: (const char *) g_file_static_cstr', - '"g_file_static_cstr"', - 'GLOBAL: (int) g_common_1 = 21']) + self.expect( + "frame variable --show-types --scope --show-globals --no-args", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'GLOBAL: (int) g_file_global_int = 42', + 'STATIC: (const int) g_file_static_int = 2', + 'GLOBAL: (const char *) g_file_global_cstr', + '"g_file_global_cstr"', + 'STATIC: (const char *) g_file_static_cstr', + '"g_file_static_cstr"', + 'GLOBAL: (int) g_common_1 = 21']) # 'frame variable' should support address-of operator. self.runCmd("frame variable &g_file_global_int") - # Exercise the 'target variable' command to display globals in a.c file. + # Exercise the 'target variable' command to display globals in a.c + # file. self.expect("target variable g_a", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['g_a', '123']) - self.expect("target variable g_marked_spot.x", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['g_marked_spot.x', '20']) + substrs=['g_a', '123']) + self.expect( + "target variable g_marked_spot.x", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'g_marked_spot.x', + '20']) # rdar://problem/9747668 # runCmd: target variable g_marked_spot.y # output: (int) g_marked_spot.y = <a.o[0x214] can't be resolved, in not currently loaded. # > - self.expect("target variable g_marked_spot.y", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['g_marked_spot.y', '21']) - self.expect("target variable g_marked_spot.y", VARIABLES_DISPLAYED_CORRECTLY, matching=False, - substrs = ["can't be resolved"]) + self.expect( + "target variable g_marked_spot.y", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'g_marked_spot.y', + '21']) + self.expect( + "target variable g_marked_spot.y", + VARIABLES_DISPLAYED_CORRECTLY, + matching=False, + substrs=["can't be resolved"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/inlines/TestRedefinitionsInInlines.py b/lldb/packages/Python/lldbsuite/test/lang/c/inlines/TestRedefinitionsInInlines.py index d6fbf42b757..576e9ecd52a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/inlines/TestRedefinitionsInInlines.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/inlines/TestRedefinitionsInInlines.py @@ -1,5 +1,11 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr27845"), - decorators.expectedFailureAll(compiler="clang", compiler_version=["<", "3.5"], bugnumber="llvm.org/pr27845")]) +lldbinline.MakeInlineTest(__file__, + globals(), + [decorators.expectedFailureAll(oslist=["windows"], + bugnumber="llvm.org/pr27845"), + decorators.expectedFailureAll(compiler="clang", + compiler_version=["<", + "3.5"], + bugnumber="llvm.org/pr27845")]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py b/lldb/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py index 5a940e2e5ef..850b760577b 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py @@ -3,9 +3,9 @@ from __future__ import print_function - from distutils.version import StrictVersion -import os, time +import os +import time import platform import lldb @@ -13,13 +13,18 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CModulesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIfFreeBSD - @expectedFailureAll(oslist=["linux"], bugnumber="http://llvm.org/pr23456 'fopen' has unknown return type") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["linux"], + bugnumber="http://llvm.org/pr23456 'fopen' has unknown return type") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_expr(self): if platform.system() == "Darwin" and platform.release() < StrictVersion('12.0.0'): self.skipTest() @@ -29,33 +34,46 @@ class CModulesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) - - self.expect("expr -l objc++ -- @import Darwin; 3", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["int", "3"]) - - self.expect("expr *fopen(\"/dev/zero\", \"w\")", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["FILE", "_close"]) + substrs=[' resolved, hit count = 1']) + + self.expect( + "expr -l objc++ -- @import Darwin; 3", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "int", + "3"]) + + self.expect( + "expr *fopen(\"/dev/zero\", \"w\")", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "FILE", + "_close"]) self.expect("expr *myFile", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["a", "5", "b", "9"]) + substrs=["a", "5", "b", "9"]) - self.expect("expr MIN((uint64_t)2, (uint64_t)3)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["uint64_t", "2"]) + self.expect( + "expr MIN((uint64_t)2, (uint64_t)3)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "uint64_t", + "2"]) self.expect("expr stdin", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(FILE *)", "0x"]) + substrs=["(FILE *)", "0x"]) def setUp(self): # Call super's setUp(). diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py b/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py index 6b2dc6a9b12..733340eda65 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py @@ -2,7 +2,8 @@ from __future__ import print_function -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * @@ -15,6 +16,8 @@ from lldbsuite.test import lldbutil # Return: # True if the value has a readable value and is in a register # False otherwise + + def is_variable_in_register(frame, var_name): # Ensure we can lookup the variable. var = frame.FindVariable(var_name) @@ -90,9 +93,11 @@ class RegisterVariableTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(compiler="clang", compiler_version=['<', '3.5']) - @expectedFailureAll(compiler="gcc", compiler_version=['>=', '4.8.2'], archs=["i386", "x86_64"]) + @expectedFailureAll( + compiler="gcc", compiler_version=[ + '>=', '4.8.2'], archs=[ + "i386", "x86_64"]) def test_and_run_command(self): """Test expressions on register values.""" @@ -108,7 +113,8 @@ class RegisterVariableTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - lldbutil.run_break_set_by_source_regexp(self, "break", num_expected_locations=3) + lldbutil.run_break_set_by_source_regexp( + self, "break", num_expected_locations=3) #################### # First breakpoint @@ -117,24 +123,25 @@ class RegisterVariableTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Try some variables that should be visible - frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() if is_variable_in_register(frame, 'a'): register_variables_count += 1 self.expect("expr a", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [re_expr_equals('int', 2)]) + patterns=[re_expr_equals('int', 2)]) if is_struct_pointer_in_register(frame, 'b'): register_variables_count += 1 self.expect("expr b->m1", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [re_expr_equals('int', 3)]) + patterns=[re_expr_equals('int', 3)]) ##################### # Second breakpoint @@ -143,24 +150,25 @@ class RegisterVariableTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Try some variables that should be visible - frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() if is_struct_pointer_in_register(frame, 'b'): register_variables_count += 1 self.expect("expr b->m2", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [re_expr_equals('int', 5)]) + patterns=[re_expr_equals('int', 5)]) if is_variable_in_register(frame, 'c'): register_variables_count += 1 self.expect("expr c", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [re_expr_equals('int', 5)]) + patterns=[re_expr_equals('int', 5)]) ##################### # Third breakpoint @@ -169,22 +177,25 @@ class RegisterVariableTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Try some variables that should be visible - frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() if is_variable_in_register(frame, 'f'): register_variables_count += 1 self.expect("expr f", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [re_expr_equals('float', '3.1')]) + patterns=[re_expr_equals('float', '3.1')]) # Validate that we verified at least one register variable - self.assertTrue(register_variables_count > 0, "expected to verify at least one variable in a register") + self.assertTrue( + register_variables_count > 0, + "expected to verify at least one variable in a register") # print("executed {} expressions with values in registers".format(register_variables_count)) self.runCmd("kill") diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py b/lldb/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py index 12e20dd42d4..bb94f1c4182 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SetValuesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -31,81 +32,111 @@ class SetValuesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Set breakpoints on several places to set program variables. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line1, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line1, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line2, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line2, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line3, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line3, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line4, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line4, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line5, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line5, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # main.c:15 - # Check that 'frame variable --show-types' displays the correct data type and value. - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(char) i = 'a'") + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(char) i = 'a'") # Now set variable 'i' and check that it is correctly displayed. self.runCmd("expression i = 'b'") - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(char) i = 'b'") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(char) i = 'b'") self.runCmd("continue") # main.c:36 - # Check that 'frame variable --show-types' displays the correct data type and value. - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ["\((short unsigned int|unsigned short)\) i = 33"]) + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\((short unsigned int|unsigned short)\) i = 33"]) # Now set variable 'i' and check that it is correctly displayed. self.runCmd("expression i = 333") - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ["\((short unsigned int|unsigned short)\) i = 333"]) + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\((short unsigned int|unsigned short)\) i = 333"]) self.runCmd("continue") # main.c:57 - # Check that 'frame variable --show-types' displays the correct data type and value. - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(long) i = 33") + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long) i = 33") # Now set variable 'i' and check that it is correctly displayed. self.runCmd("expression i = 33333") - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(long) i = 33333") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long) i = 33333") self.runCmd("continue") # main.c:78 - # Check that 'frame variable --show-types' displays the correct data type and value. - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(double) i = 2.25") + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(double) i = 2.25") # Now set variable 'i' and check that it is correctly displayed. self.runCmd("expression i = 1.5") - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(double) i = 1.5") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(double) i = 1.5") self.runCmd("continue") # main.c:85 - # Check that 'frame variable --show-types' displays the correct data type and value. - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(long double) i = 2.25") + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long double) i = 2.25") # Now set variable 'i' and check that it is correctly displayed. self.runCmd("expression i = 1.5") - self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(long double) i = 1.5") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long double) i = 1.5") diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py b/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py index 954d1bac636..61a67dc1398 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py @@ -3,12 +3,12 @@ from __future__ import print_function - import unittest2 import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class SharedLibTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -16,14 +16,20 @@ class SharedLibTestCase(TestBase): def test_expr(self): """Test that types work when defined in a shared library and forward-declared in the main executable""" if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): - self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") self.build() self.common_setup() # This should display correctly. - self.expect("expression --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(foo)", "(sub_foo)", "other_element = 3"]) + self.expect( + "expression --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) @unittest2.expectedFailure("rdar://problem/10704639") def test_frame_variable(self): @@ -32,8 +38,13 @@ class SharedLibTestCase(TestBase): self.common_setup() # This should display correctly. - self.expect("frame variable --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(foo)", "(sub_foo)", "other_element = 3"]) + self.expect( + "frame variable --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) def setUp(self): # Call super's setUp(). @@ -42,7 +53,7 @@ class SharedLibTestCase(TestBase): self.source = 'main.c' self.line = line_number(self.source, '// Set breakpoint 0 here.') self.shlib_names = ["foo"] - + def common_setup(self): # Run in synchronous mode self.dbg.SetAsync(False) @@ -52,20 +63,24 @@ class SharedLibTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) - # Register our shared libraries for remote targets so they get automatically uploaded - environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names) + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py b/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py index 011e4d1f22a..7b371a2a9a9 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py @@ -3,13 +3,13 @@ from __future__ import print_function - import unittest2 import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SharedLibStrippedTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -18,14 +18,20 @@ class SharedLibStrippedTestCase(TestBase): def test_expr(self): """Test that types work when defined in a shared library and forward-declared in the main executable""" if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): - self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") self.build() self.common_setup() # This should display correctly. - self.expect("expression --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(foo)", "(sub_foo)", "other_element = 3"]) + self.expect( + "expression --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) @expectedFailureAll(oslist=["windows"]) @unittest2.expectedFailure("rdar://problem/10381325") @@ -35,8 +41,13 @@ class SharedLibStrippedTestCase(TestBase): self.common_setup() # This should display correctly. - self.expect("frame variable --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(foo)", "(sub_foo)", "other_element = 3"]) + self.expect( + "frame variable --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) def setUp(self): # Call super's setUp(). @@ -55,20 +66,24 @@ class SharedLibStrippedTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) - # Register our shared libraries for remote targets so they get automatically uploaded - environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names) + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/step-target/TestStepTarget.py b/lldb/packages/Python/lldbsuite/test/lang/c/step-target/TestStepTarget.py index 2bd72434d39..b1aa98c50ba 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/step-target/TestStepTarget.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/step-target/TestStepTarget.py @@ -2,12 +2,14 @@ from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestStepTarget(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,30 +25,32 @@ class TestStepTarget(TestBase): self.end_line = line_number(self.main_source, "All done") @add_test_categories(['pyapi']) - - def get_to_start (self): + def get_to_start(self): self.build() exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) - break_in_main = target.BreakpointCreateBySourceRegex ('Break here to try targetted stepping', self.main_source_spec) + break_in_main = target.BreakpointCreateBySourceRegex( + 'Break here to try targetted stepping', self.main_source_spec) self.assertTrue(break_in_main, VALID_BREAKPOINT) - self.assertTrue(break_in_main.GetNumLocations() > 0,"Has locations.") + self.assertTrue(break_in_main.GetNumLocations() > 0, "Has locations.") # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_main) if len(threads) != 1: - self.fail ("Failed to stop at first breakpoint in main.") + self.fail("Failed to stop at first breakpoint in main.") thread = threads[0] return thread @@ -60,7 +64,7 @@ class TestStepTarget(TestBase): thread.StepInto("lotsOfArgs", self.end_line, error) frame = thread.frames[0] - self.assertTrue (frame.name == "lotsOfArgs", "Stepped to lotsOfArgs.") + self.assertTrue(frame.name == "lotsOfArgs", "Stepped to lotsOfArgs.") def test_with_end_line_bad_name(self): """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" @@ -70,7 +74,9 @@ class TestStepTarget(TestBase): error = lldb.SBError() thread.StepInto("lotsOfArgssss", self.end_line, error) frame = thread.frames[0] - self.assertTrue (frame.line_entry.line == self.end_line, "Stepped to the block end.") + self.assertTrue( + frame.line_entry.line == self.end_line, + "Stepped to the block end.") def test_with_end_line_deeper(self): """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" @@ -80,7 +86,7 @@ class TestStepTarget(TestBase): error = lldb.SBError() thread.StepInto("modifyInt", self.end_line, error) frame = thread.frames[0] - self.assertTrue (frame.name == "modifyInt", "Stepped to modifyInt.") + self.assertTrue(frame.name == "modifyInt", "Stepped to modifyInt.") def test_with_command_and_block(self): """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" @@ -88,11 +94,14 @@ class TestStepTarget(TestBase): thread = self.get_to_start() result = lldb.SBCommandReturnObject() - self.dbg.GetCommandInterpreter().HandleCommand('thread step-in -t "lotsOfArgs" -e block', result) - self.assertTrue(result.Succeeded(), "thread step-in command succeeded.") + self.dbg.GetCommandInterpreter().HandleCommand( + 'thread step-in -t "lotsOfArgs" -e block', result) + self.assertTrue( + result.Succeeded(), + "thread step-in command succeeded.") frame = thread.frames[0] - self.assertTrue (frame.name == "lotsOfArgs", "Stepped to lotsOfArgs.") + self.assertTrue(frame.name == "lotsOfArgs", "Stepped to lotsOfArgs.") def test_with_command_and_block_and_bad_name(self): """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" @@ -100,14 +109,17 @@ class TestStepTarget(TestBase): thread = self.get_to_start() result = lldb.SBCommandReturnObject() - self.dbg.GetCommandInterpreter().HandleCommand('thread step-in -t "lotsOfArgsssss" -e block', result) - self.assertTrue(result.Succeeded(), "thread step-in command succeeded.") + self.dbg.GetCommandInterpreter().HandleCommand( + 'thread step-in -t "lotsOfArgsssss" -e block', result) + self.assertTrue( + result.Succeeded(), + "thread step-in command succeeded.") frame = thread.frames[0] - self.assertTrue (frame.name == "main", "Stepped back out to main.") - # end_line is set to the line after the containing block. Check that we got there: - self.assertTrue(frame.line_entry.line == self.end_line, "Got out of the block") - - - + self.assertTrue(frame.name == "main", "Stepped back out to main.") + # end_line is set to the line after the containing block. Check that + # we got there: + self.assertTrue( + frame.line_entry.line == self.end_line, + "Got out of the block") diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py b/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py index cfaff91daa4..d693e1dada5 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCStepping(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -35,36 +36,43 @@ class TestCStepping(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) breakpoints_to_disable = [] - break_1_in_main = target.BreakpointCreateBySourceRegex ('// frame select 2, thread step-out while stopped at .c.1..', self.main_source_spec) + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// frame select 2, thread step-out while stopped at .c.1..', + self.main_source_spec) self.assertTrue(break_1_in_main, VALID_BREAKPOINT) - breakpoints_to_disable.append (break_1_in_main) + breakpoints_to_disable.append(break_1_in_main) - break_in_a = target.BreakpointCreateBySourceRegex ('// break here to stop in a before calling b', self.main_source_spec) + break_in_a = target.BreakpointCreateBySourceRegex( + '// break here to stop in a before calling b', self.main_source_spec) self.assertTrue(break_in_a, VALID_BREAKPOINT) - breakpoints_to_disable.append (break_in_a) + breakpoints_to_disable.append(break_in_a) - break_in_b = target.BreakpointCreateBySourceRegex ('// thread step-out while stopped at .c.2..', self.main_source_spec) + break_in_b = target.BreakpointCreateBySourceRegex( + '// thread step-out while stopped at .c.2..', self.main_source_spec) self.assertTrue(break_in_b, VALID_BREAKPOINT) - breakpoints_to_disable.append (break_in_b) + breakpoints_to_disable.append(break_in_b) - break_in_c = target.BreakpointCreateBySourceRegex ('// Find the line number of function .c. here.', self.main_source_spec) + break_in_c = target.BreakpointCreateBySourceRegex( + '// Find the line number of function .c. here.', self.main_source_spec) self.assertTrue(break_in_c, VALID_BREAKPOINT) - breakpoints_to_disable.append (break_in_c) + breakpoints_to_disable.append(break_in_c) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_1_in_main) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_1_in_main) if len(threads) != 1: - self.fail ("Failed to stop at first breakpoint in main.") + self.fail("Failed to stop at first breakpoint in main.") thread = threads[0] @@ -75,22 +83,26 @@ class TestCStepping(TestBase): thread.StepOver() # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_a) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_a) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint in a.") + self.fail("Failed to stop at breakpoint in a.") # Check that the stop ID increases: new_stop_id = process.GetStopID() - self.assertTrue(new_stop_id > old_stop_id, "Stop ID increases monotonically.") + self.assertTrue( + new_stop_id > old_stop_id, + "Stop ID increases monotonically.") thread = threads[0] # Step over, and we should hit the breakpoint in b: thread.StepOver() - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_b) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_b) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint in b.") + self.fail("Failed to stop at breakpoint in b.") thread = threads[0] # Now try running some function, and make sure that we still end up in the same place @@ -105,32 +117,51 @@ class TestCStepping(TestBase): stop_id_before_expression = process.GetStopID() stop_id_before_including_expressions = process.GetStopID(True) - frame.EvaluateExpression ("(int) printf (print_string)") + frame.EvaluateExpression("(int) printf (print_string)") frame = thread.GetFrameAtIndex(0) - self.assertTrue (current_line == frame.GetLineEntry().GetLine(), "The line stayed the same after expression.") - self.assertTrue (current_file == frame.GetLineEntry().GetFileSpec(), "The file stayed the same after expression.") - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonBreakpoint, "We still say we stopped for a breakpoint.") - self.assertTrue (thread.GetStopReasonDataAtIndex(0) == current_bp[0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.") - + self.assertTrue( + current_line == frame.GetLineEntry().GetLine(), + "The line stayed the same after expression.") + self.assertTrue( + current_file == frame.GetLineEntry().GetFileSpec(), + "The file stayed the same after expression.") + self.assertTrue( + thread.GetStopReason() == lldb.eStopReasonBreakpoint, + "We still say we stopped for a breakpoint.") + self.assertTrue(thread.GetStopReasonDataAtIndex(0) == current_bp[ + 0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.") + # Also make sure running the expression didn't change the public stop id # but did change if we are asking for expression stops as well. stop_id_after_expression = process.GetStopID() stop_id_after_including_expressions = process.GetStopID(True) - self.assertTrue (stop_id_before_expression == stop_id_after_expression, "Expression calling doesn't change stop ID") + self.assertTrue( + stop_id_before_expression == stop_id_after_expression, + "Expression calling doesn't change stop ID") - self.assertTrue (stop_id_after_including_expressions > stop_id_before_including_expressions, "Stop ID including expressions increments over expression call.") + self.assertTrue( + stop_id_after_including_expressions > stop_id_before_including_expressions, + "Stop ID including expressions increments over expression call.") - # Do the same thing with an expression that's going to crash, and make sure we are still unchanged. + # Do the same thing with an expression that's going to crash, and make + # sure we are still unchanged. - frame.EvaluateExpression ("((char *) 0)[0] = 'a'") + frame.EvaluateExpression("((char *) 0)[0] = 'a'") frame = thread.GetFrameAtIndex(0) - self.assertTrue (current_line == frame.GetLineEntry().GetLine(), "The line stayed the same after expression.") - self.assertTrue (current_file == frame.GetLineEntry().GetFileSpec(), "The file stayed the same after expression.") - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonBreakpoint, "We still say we stopped for a breakpoint.") - self.assertTrue (thread.GetStopReasonDataAtIndex(0) == current_bp[0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.") + self.assertTrue( + current_line == frame.GetLineEntry().GetLine(), + "The line stayed the same after expression.") + self.assertTrue( + current_file == frame.GetLineEntry().GetFileSpec(), + "The file stayed the same after expression.") + self.assertTrue( + thread.GetStopReason() == lldb.eStopReasonBreakpoint, + "We still say we stopped for a breakpoint.") + self.assertTrue(thread.GetStopReasonDataAtIndex(0) == current_bp[ + 0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.") # Now continue and make sure we just complete the step: # Disable all our breakpoints first - sometimes the compiler puts two line table entries in for the @@ -140,16 +171,17 @@ class TestCStepping(TestBase): process.Continue() - self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "a") - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete) + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "a") + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) # And one more time should get us back to main: process.Continue() - self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "main") - self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete) + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "main") + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) - # Now make sure we can call a function, break in the called function, then have "continue" get us back out again: + # Now make sure we can call a function, break in the called function, + # then have "continue" get us back out again: frame = thread.GetFrameAtIndex(0) frame = thread.GetFrameAtIndex(0) current_line = frame.GetLineEntry().GetLine() @@ -160,12 +192,13 @@ class TestCStepping(TestBase): options.SetIgnoreBreakpoints(False) options.SetFetchDynamicValue(False) options.SetUnwindOnError(False) - frame.EvaluateExpression ("b (4)", options) + frame.EvaluateExpression("b (4)", options) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_b) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_b) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint in b when calling b.") + self.fail("Failed to stop at breakpoint in b when calling b.") thread = threads[0] # So do a step over here to make sure we can still do that: @@ -174,75 +207,95 @@ class TestCStepping(TestBase): # See that we are still in b: func_name = thread.GetFrameAtIndex(0).GetFunctionName() - self.assertTrue (func_name == "b", "Should be in 'b', were in %s"%(func_name)) + self.assertTrue( + func_name == "b", + "Should be in 'b', were in %s" % + (func_name)) - # Okay, now if we continue, we will finish off our function call and we should end up back in "a" as if nothing had happened: - process.Continue () + # Okay, now if we continue, we will finish off our function call and we + # should end up back in "a" as if nothing had happened: + process.Continue() - self.assertTrue (thread.GetFrameAtIndex(0).GetLineEntry().GetLine() == current_line) - self.assertTrue (thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec() == current_file) + self.assertTrue(thread.GetFrameAtIndex( + 0).GetLineEntry().GetLine() == current_line) + self.assertTrue(thread.GetFrameAtIndex( + 0).GetLineEntry().GetFileSpec() == current_file) # Now we are going to test step in targeting a function: - break_in_b.SetEnabled (False) + break_in_b.SetEnabled(False) - break_before_complex_1 = target.BreakpointCreateBySourceRegex ('// Stop here to try step in targeting b.', self.main_source_spec) + break_before_complex_1 = target.BreakpointCreateBySourceRegex( + '// Stop here to try step in targeting b.', self.main_source_spec) self.assertTrue(break_before_complex_1, VALID_BREAKPOINT) - break_before_complex_2 = target.BreakpointCreateBySourceRegex ('// Stop here to try step in targeting complex.', self.main_source_spec) + break_before_complex_2 = target.BreakpointCreateBySourceRegex( + '// Stop here to try step in targeting complex.', self.main_source_spec) self.assertTrue(break_before_complex_2, VALID_BREAKPOINT) - break_before_complex_3 = target.BreakpointCreateBySourceRegex ('// Stop here to step targeting b and hitting breakpoint.', self.main_source_spec) + break_before_complex_3 = target.BreakpointCreateBySourceRegex( + '// Stop here to step targeting b and hitting breakpoint.', self.main_source_spec) self.assertTrue(break_before_complex_3, VALID_BREAKPOINT) - break_before_complex_4 = target.BreakpointCreateBySourceRegex ('// Stop here to make sure bogus target steps over.', self.main_source_spec) + break_before_complex_4 = target.BreakpointCreateBySourceRegex( + '// Stop here to make sure bogus target steps over.', self.main_source_spec) self.assertTrue(break_before_complex_4, VALID_BREAKPOINT) - threads = lldbutil.continue_to_breakpoint(process, break_before_complex_1) - self.assertTrue (len(threads) == 1) + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_1) + self.assertTrue(len(threads) == 1) thread = threads[0] break_before_complex_1.SetEnabled(False) - thread.StepInto ("b") - self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "b") + thread.StepInto("b") + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "b") - # Now continue out and stop at the next call to complex. This time step all the way into complex: - threads = lldbutil.continue_to_breakpoint (process, break_before_complex_2) - self.assertTrue (len(threads) == 1) + # Now continue out and stop at the next call to complex. This time + # step all the way into complex: + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_2) + self.assertTrue(len(threads) == 1) thread = threads[0] break_before_complex_2.SetEnabled(False) - thread.StepInto ("complex") - self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "complex") - - # Now continue out and stop at the next call to complex. This time enable breakpoints in a and c and then step targeting b: - threads = lldbutil.continue_to_breakpoint (process, break_before_complex_3) - self.assertTrue (len(threads) == 1) + thread.StepInto("complex") + self.assertTrue(thread.GetFrameAtIndex( + 0).GetFunctionName() == "complex") + + # Now continue out and stop at the next call to complex. This time + # enable breakpoints in a and c and then step targeting b: + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_3) + self.assertTrue(len(threads) == 1) thread = threads[0] break_before_complex_3.SetEnabled(False) - break_at_start_of_a = target.BreakpointCreateByName ('a') - break_at_start_of_c = target.BreakpointCreateByName ('c') + break_at_start_of_a = target.BreakpointCreateByName('a') + break_at_start_of_c = target.BreakpointCreateByName('c') - thread.StepInto ("b") - threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonBreakpoint); + thread.StepInto("b") + threads = lldbutil.get_stopped_threads( + process, lldb.eStopReasonBreakpoint) - self.assertTrue (len(threads) == 1) + self.assertTrue(len(threads) == 1) thread = threads[0] stop_break_id = thread.GetStopReasonDataAtIndex(0) - self.assertTrue(stop_break_id == break_at_start_of_a.GetID() or stop_break_id == break_at_start_of_c.GetID()) + self.assertTrue(stop_break_id == break_at_start_of_a.GetID() + or stop_break_id == break_at_start_of_c.GetID()) break_at_start_of_a.SetEnabled(False) break_at_start_of_c.SetEnabled(False) process.Continue() - self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "b") - - # Now continue out and stop at the next call to complex. This time enable breakpoints in a and c and then step targeting b: - threads = lldbutil.continue_to_breakpoint (process, break_before_complex_4) - self.assertTrue (len(threads) == 1) + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "b") + + # Now continue out and stop at the next call to complex. This time + # enable breakpoints in a and c and then step targeting b: + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_4) + self.assertTrue(len(threads) == 1) thread = threads[0] break_before_complex_4.SetEnabled(False) thread.StepInto("NoSuchFunction") - self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "main") + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "main") diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py b/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py index c3ed3f933ab..c436000d882 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py @@ -5,14 +5,15 @@ Test thread stepping features in combination with frame select. from __future__ import print_function - -import os, time +import os +import time import re import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class ThreadSteppingTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,10 +22,14 @@ class ThreadSteppingTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line1 = line_number('main.c', '// Find the line number of function "c" here.') - self.line2 = line_number('main.c', '// frame select 2, thread step-out while stopped at "c(1)"') - self.line3 = line_number('main.c', '// thread step-out while stopped at "c(2)"') - self.line4 = line_number('main.c', '// frame select 1, thread step-out while stopped at "c(3)"') + self.line1 = line_number( + 'main.c', '// Find the line number of function "c" here.') + self.line2 = line_number( + 'main.c', '// frame select 2, thread step-out while stopped at "c(1)"') + self.line3 = line_number( + 'main.c', '// thread step-out while stopped at "c(2)"') + self.line4 = line_number( + 'main.c', '// frame select 1, thread step-out while stopped at "c(3)"') def test_step_out_with_run_command(self): """Exercise thread step-out and frame select followed by thread step-out.""" @@ -33,49 +38,50 @@ class ThreadSteppingTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Create a breakpoint inside function 'c'. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line1, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line1, num_expected_locations=1, loc_exact=True) # Now run the program. self.runCmd("run", RUN_SUCCEEDED) # The process should be stopped at this point. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* stopped']) + patterns=['Process .* stopped']) # The frame #0 should correspond to main.c:32, the executable statement # in function name 'c'. And frame #3 should point to main.c:37. self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint"], - patterns = ["frame #0.*main.c:%d" % self.line1, - "frame #3.*main.c:%d" % self.line2]) + substrs=["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #3.*main.c:%d" % self.line2]) # We want to move the pc to frame #3. This can be accomplished by # 'frame select 2', followed by 'thread step-out'. self.runCmd("frame select 2") self.runCmd("thread step-out") self.expect("thread backtrace", STEP_OUT_SUCCEEDED, - substrs = ["stop reason = step out"], - patterns = ["frame #0.*main.c:%d" % self.line2]) + substrs=["stop reason = step out"], + patterns=["frame #0.*main.c:%d" % self.line2]) # Let's move on to a single step-out case. self.runCmd("process continue") # The process should be stopped at this point. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* stopped']) + patterns=['Process .* stopped']) self.runCmd("thread step-out") self.expect("thread backtrace", STEP_OUT_SUCCEEDED, - substrs = ["stop reason = step out"], - patterns = ["frame #0.*main.c:%d" % self.line3]) + substrs=["stop reason = step out"], + patterns=["frame #0.*main.c:%d" % self.line3]) # Do another frame selct, followed by thread step-out. self.runCmd("process continue") # The process should be stopped at this point. self.expect("process status", PROCESS_STOPPED, - patterns = ['Process .* stopped']) + patterns=['Process .* stopped']) self.runCmd("frame select 1") self.runCmd("thread step-out") self.expect("thread backtrace", STEP_OUT_SUCCEEDED, - substrs = ["stop reason = step out"], - patterns = ["frame #0.*main.c:%d" % self.line4]) + substrs=["stop reason = step out"], + patterns=["frame #0.*main.c:%d" % self.line4]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py b/lldb/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py index a9f49c30d10..27821845e28 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py @@ -6,10 +6,11 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CStringsTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") def test_with_run_command(self): """Tests that C strings work as expected in expressions""" @@ -17,39 +18,40 @@ class CStringsTestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) line = line_number('main.c', '// breakpoint 1') - lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) self.runCmd("process launch", RUN_SUCCEEDED) self.expect("expression -- a[2]", - patterns = ["\((const )?char\) \$0 = 'c'"]) + patterns=["\((const )?char\) \$0 = 'c'"]) self.expect("expression -- z[2]", - startstr = "(const char) $1 = 'x'") + startstr="(const char) $1 = 'x'") # On Linux, the expression below will test GNU indirect function calls. self.expect("expression -- (int)strlen(\"hello\")", - startstr = "(int) $2 = 5") + startstr="(int) $2 = 5") self.expect("expression -- \"world\"[2]", - startstr = "(const char) $3 = 'r'") + startstr="(const char) $3 = 'r'") self.expect("expression -- \"\"[0]", - startstr = "(const char) $4 = '\\0'") + startstr="(const char) $4 = '\\0'") self.expect("expr --raw -- \"hello\"", - substrs = ['[0] = \'h\'', - '[5] = \'\\0\'']) + substrs=['[0] = \'h\'', + '[5] = \'\\0\'']) self.expect("p \"hello\"", - substrs = ['[6]) $', 'hello']) + substrs=['[6]) $', 'hello']) self.expect("p (char*)\"hello\"", - substrs = ['(char *) $', ' = 0x', - 'hello']) + substrs=['(char *) $', ' = 0x', + 'hello']) self.expect("p (int)strlen(\"\")", - substrs = ['(int) $', ' = 0']) + substrs=['(int) $', ' = 0']) self.expect("expression !z", - substrs = ['false']) + substrs=['false']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py b/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py index 2249a8c9b16..af362f5be5d 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py @@ -1,4 +1,7 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764")] ) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + oslist=["windows"], bugnumber="llvm.org/pr24764")]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py b/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py index 0ca9923c89a..c6952d4d904 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py @@ -3,14 +3,15 @@ from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TlsGlobalTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,15 +20,31 @@ class TlsGlobalTestCase(TestBase): TestBase.setUp(self) if self.getPlatform() == "freebsd" or self.getPlatform() == "linux": - # LD_LIBRARY_PATH must be set so the shared libraries are found on startup + # LD_LIBRARY_PATH must be set so the shared libraries are found on + # startup if "LD_LIBRARY_PATH" in os.environ: - self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + os.environ["LD_LIBRARY_PATH"] + ":" + os.getcwd()) + self.runCmd( + "settings set target.env-vars " + + self.dylibPath + + "=" + + os.environ["LD_LIBRARY_PATH"] + + ":" + + os.getcwd()) else: - self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + os.getcwd()) - self.addTearDownHook(lambda: self.runCmd("settings remove target.env-vars " + self.dylibPath)) - - @skipIfWindows # TLS works differently on Windows, this would need to be implemented separately. - @expectedFailureAll(bugnumber="llvm.org/pr28392", oslist=no_match(lldbplatformutil.getDarwinOSTriples())) + self.runCmd("settings set target.env-vars " + + self.dylibPath + "=" + os.getcwd()) + self.addTearDownHook( + lambda: self.runCmd( + "settings remove target.env-vars " + + self.dylibPath)) + + # TLS works differently on Windows, this would need to be implemented + # separately. + @skipIfWindows + @expectedFailureAll( + bugnumber="llvm.org/pr28392", + oslist=no_match( + lldbplatformutil.getDarwinOSTriples())) def test(self): """Test thread-local storage.""" self.build() @@ -35,14 +52,15 @@ class TlsGlobalTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) line1 = line_number('main.c', '// thread breakpoint') - lldbutil.run_break_set_by_file_and_line (self, "main.c", line1, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line1, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.runCmd("process status", "Get process status") self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # BUG: sometimes lldb doesn't change threads to the stopped thread. # (unrelated to this test). @@ -50,20 +68,21 @@ class TlsGlobalTestCase(TestBase): # Check that TLS evaluates correctly within the thread. self.expect("expr var_static", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ["\(int\) \$.* = 88"]) + patterns=["\(int\) \$.* = 88"]) self.expect("expr var_shared", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ["\(int\) \$.* = 66"]) + patterns=["\(int\) \$.* = 66"]) # Continue on the main thread line2 = line_number('main.c', '// main breakpoint') - lldbutil.run_break_set_by_file_and_line (self, "main.c", line2, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line2, num_expected_locations=1, loc_exact=True) self.runCmd("continue", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.runCmd("process status", "Get process status") self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # BUG: sometimes lldb doesn't change threads to the stopped thread. # (unrelated to this test). @@ -71,6 +90,6 @@ class TlsGlobalTestCase(TestBase): # Check that TLS evaluates correctly within the main thread. self.expect("expr var_static", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ["\(int\) \$.* = 44"]) + patterns=["\(int\) \$.* = 44"]) self.expect("expr var_shared", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ["\(int\) \$.* = 33"]) + patterns=["\(int\) \$.* = 33"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py b/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py index 232a86a2cde..71d00c5a9a6 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py @@ -3,19 +3,22 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TypedefTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @expectedFailureAll(compiler="clang", bugnumber="llvm.org/pr19238") - @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr25626 expectedFailureClang fails on FreeBSD") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr25626 expectedFailureClang fails on FreeBSD") def test_typedef(self): """Test 'image lookup -t a' and check for correct display at different scopes.""" self.build() @@ -25,17 +28,28 @@ class TypedefTestCase(TestBase): """Test 'image lookup -t a' at different scopes and check for correct display.""" exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - typearray = ("float", "float", "char", "double *", "float", "int", "double", "float", "float") - arraylen = len(typearray)+1 - for i in range(1,arraylen): - loc_line = line_number('main.c', '// Set break point ' + str(i) + '.') - lldbutil.run_break_set_by_file_and_line (self, "main.c",loc_line, num_expected_locations=1, loc_exact=True) + typearray = ( + "float", + "float", + "char", + "double *", + "float", + "int", + "double", + "float", + "float") + arraylen = len(typearray) + 1 + for i in range(1, arraylen): + loc_line = line_number( + 'main.c', '// Set break point ' + str(i) + '.') + lldbutil.run_break_set_by_file_and_line( + self, "main.c", loc_line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) for t in typearray: self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) self.expect("image lookup -t a", DATA_TYPES_DISPLAYED_CORRECTLY, - substrs = ['name = "' + t + '"']) + substrs=['name = "' + t + '"']) self.runCmd("continue") diff --git a/lldb/packages/Python/lldbsuite/test/lang/c/unions/TestUnionMembers.py b/lldb/packages/Python/lldbsuite/test/lang/c/unions/TestUnionMembers.py index 114be3ade01..496398b1d0a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/c/unions/TestUnionMembers.py +++ b/lldb/packages/Python/lldbsuite/test/lang/c/unions/TestUnionMembers.py @@ -2,6 +2,7 @@ import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class TestUnionMembers(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -10,22 +11,29 @@ class TestUnionMembers(TestBase): self._load_exe() # Set breakpoints - bp = self.target.BreakpointCreateBySourceRegex("Break here", self.src_file_spec) - self.assertTrue(bp.IsValid() and bp.GetNumLocations() >= 1, VALID_BREAKPOINT) + bp = self.target.BreakpointCreateBySourceRegex( + "Break here", self.src_file_spec) + self.assertTrue( + bp.IsValid() and bp.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process - self.process = self.target.LaunchSimple(None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process.IsValid(), PROCESS_IS_VALID) - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("u"); + val = frame.EvaluateExpression("u") self.assertTrue(val.IsValid()) - val = frame.EvaluateExpression("u.s"); + val = frame.EvaluateExpression("u.s") self.assertTrue(val.IsValid()) self.assertEqual(val.GetNumChildren(), 2) @@ -39,7 +47,7 @@ class TestUnionMembers(TestBase): self.assertTrue(self.src_file_spec.IsValid(), "breakpoint file") # Get the path of the executable - exe_path = os.path.join(cwd, 'a.out') + exe_path = os.path.join(cwd, 'a.out') # Load the executable self.target = self.dbg.CreateTarget(exe_path) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py index ea210a1e9ea..1fb7a521749 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py @@ -6,11 +6,14 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CPPAutoTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(compiler="gcc", bugnumber="GCC generates incomplete debug info") + @expectedFailureAll( + compiler="gcc", + bugnumber="GCC generates incomplete debug info") @expectedFailureAll(oslist=['windows'], bugnumber="llvm.org/pr26339") def test_with_run_command(self): """Test that auto types work in the expression parser""" @@ -18,10 +21,20 @@ class CPPAutoTestCase(TestBase): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) line = line_number('main.cpp', '// break here') - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) self.runCmd("process launch", RUN_SUCCEEDED) self.expect('expr auto f = 123456; f', substrs=['int', '123456']) - self.expect('expr struct Test { int x; int y; Test() : x(123), y(456) {} }; auto t = Test(); t', substrs=['Test', '123', '456']) - self.expect('expr auto s = helloworld; s', substrs=['string', 'hello world']) + self.expect( + 'expr struct Test { int x; int y; Test() : x(123), y(456) {} }; auto t = Test(); t', + substrs=[ + 'Test', + '123', + '456']) + self.expect( + 'expr auto s = helloworld; s', + substrs=[ + 'string', + 'hello world']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py index ef7135cfaa0..01f8cbacc36 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py @@ -5,22 +5,24 @@ import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class CPPBoolTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def test_with_run_command(self): """Test that bool types work in the expression parser""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) line = line_number('main.cpp', '// breakpoint 1') - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) self.runCmd("process launch", RUN_SUCCEEDED) self.expect("expression -- bool second_bool = my_bool; second_bool", - startstr = "(bool) $0 = false") + startstr="(bool) $0 = false") self.expect("expression -- my_bool = true", - startstr = "(bool) $1 = true") + startstr="(bool) $1 = true") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py index c8442bcb37e..eda0bf051cc 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py @@ -5,28 +5,31 @@ Test lldb breakpoint command for CPP methods & functions in a namespace. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CPPBreakpointCommandsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @expectedFailureAll(oslist=["windows"]) - def make_breakpoint(self, name, type, expected_num_locations): - bkpt = self.target.BreakpointCreateByName (name, - type, - self.a_out_module, - self.nested_comp_unit) + bkpt = self.target.BreakpointCreateByName(name, + type, + self.a_out_module, + self.nested_comp_unit) num_locations = bkpt.GetNumLocations() - self.assertTrue (num_locations == expected_num_locations, - "Wrong number of locations for '%s', expected: %d got: %d"%( - name, expected_num_locations, num_locations)) + self.assertTrue( + num_locations == expected_num_locations, + "Wrong number of locations for '%s', expected: %d got: %d" % + (name, + expected_num_locations, + num_locations)) return bkpt def test_cpp_breakpoint_cmds(self): @@ -37,48 +40,48 @@ class CPPBreakpointCommandsTestCase(TestBase): # Create a target from the debugger. - self.target = self.dbg.CreateTarget (exe) + self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) self.a_out_module = lldb.SBFileSpecList() self.a_out_module.Append(lldb.SBFileSpec(exe)) self.nested_comp_unit = lldb.SBFileSpecList() - self.nested_comp_unit.Append (lldb.SBFileSpec("nested.cpp")) + self.nested_comp_unit.Append(lldb.SBFileSpec("nested.cpp")) # First provide ONLY the method name. This should get everybody... self.make_breakpoint("Function", - lldb.eFunctionNameTypeAuto, - 5) + lldb.eFunctionNameTypeAuto, + 5) # Now add the Baz class specifier. This should get the version contained in Bar, # AND the one contained in :: self.make_breakpoint("Baz::Function", - lldb.eFunctionNameTypeAuto, - 2) + lldb.eFunctionNameTypeAuto, + 2) - # Then add the Bar::Baz specifier. This should get the version contained in Bar only + # Then add the Bar::Baz specifier. This should get the version + # contained in Bar only self.make_breakpoint("Bar::Baz::Function", - lldb.eFunctionNameTypeAuto, - 1) + lldb.eFunctionNameTypeAuto, + 1) - self.make_breakpoint("Function", + self.make_breakpoint("Function", lldb.eFunctionNameTypeMethod, - 3) + 3) - self.make_breakpoint("Baz::Function", - lldb.eFunctionNameTypeMethod, - 2) + self.make_breakpoint("Baz::Function", + lldb.eFunctionNameTypeMethod, + 2) - self.make_breakpoint("Bar::Baz::Function", + self.make_breakpoint("Bar::Baz::Function", lldb.eFunctionNameTypeMethod, 1) - self.make_breakpoint("Function", + self.make_breakpoint("Function", lldb.eFunctionNameTypeBase, 2) - self.make_breakpoint("Bar::Function", + self.make_breakpoint("Bar::Function", lldb.eFunctionNameTypeBase, 1) - diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py index 260dd763c00..b86cd2ac9c7 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py @@ -7,28 +7,32 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CallCPPFunctionTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def setUp(self): TestBase.setUp(self) self.line = line_number('main.cpp', '// breakpoint') - - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_with_run_command(self): """Test calling a function by basename""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("process launch", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) self.expect("expression -- a_function_to_call()", - startstr = "(int) $0 = 0") + startstr="(int) $0 = 0") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py index 140c4a832fd..0145bee3fc5 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py @@ -3,6 +3,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCppChainedCalls(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -17,58 +18,85 @@ class TestCppChainedCalls(TestBase): self.assertTrue(src_file_spec.IsValid(), "Main source file") # Get the path of the executable - cwd = os.getcwd() + cwd = os.getcwd() exe_file = "a.out" - exe_path = os.path.join(cwd, exe_file) + exe_path = os.path.join(cwd, exe_file) # Load the executable target = self.dbg.CreateTarget(exe_path) self.assertTrue(target.IsValid(), VALID_TARGET) # Break on main function - main_breakpoint = target.BreakpointCreateBySourceRegex("break here", src_file_spec) - self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT) + main_breakpoint = target.BreakpointCreateBySourceRegex( + "break here", src_file_spec) + self.assertTrue( + main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process args = None env = None - process = target.LaunchSimple(args, env, self.get_process_working_directory()) + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) # Get frame for current thread frame = thread.GetSelectedFrame() # Test chained calls test_result = frame.EvaluateExpression("get(set(true))") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "get(set(true)) = true") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "get(set(true)) = true") test_result = frame.EvaluateExpression("get(set(false))") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(set(false)) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(set(false)) = false") test_result = frame.EvaluateExpression("get(t & f)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(t & f) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(t & f) = false") test_result = frame.EvaluateExpression("get(f & t)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f & t) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f & t) = false") test_result = frame.EvaluateExpression("get(t & t)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "get(t & t) = true") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "get(t & t) = true") test_result = frame.EvaluateExpression("get(f & f)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f & f) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f & f) = false") test_result = frame.EvaluateExpression("get(t & f)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(t & f) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(t & f) = false") test_result = frame.EvaluateExpression("get(f) && get(t)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f) && get(t) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f) && get(t) = false") test_result = frame.EvaluateExpression("get(f) && get(f)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f) && get(t) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f) && get(t) = false") test_result = frame.EvaluateExpression("get(t) && get(t)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "get(t) && get(t) = true") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "get(t) && get(t) = true") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py index d4400d3a488..bf8605106ad 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py @@ -6,13 +6,14 @@ Test that the C++11 support for char16_t and char32_t works correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class Char1632TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,10 +23,12 @@ class Char1632TestCase(TestBase): TestBase.setUp(self) # Find the line number to break for main.cpp. self.source = 'main.cpp' - self.lines = [ line_number(self.source, '// breakpoint1'), - line_number(self.source, '// breakpoint2') ] + self.lines = [line_number(self.source, '// breakpoint1'), + line_number(self.source, '// breakpoint2')] - @expectedFailureAll(compiler="icc", bugnumber="ICC (13.1) does not emit the DW_TAG_base_type for char16_t and char32_t.") + @expectedFailureAll( + compiler="icc", + bugnumber="ICC (13.1) does not emit the DW_TAG_base_type for char16_t and char32_t.") def test(self): """Test that the C++11 support for char16_t and char32_t works correctly.""" self.build() @@ -37,54 +40,83 @@ class Char1632TestCase(TestBase): # Set breakpoints for line in self.lines: - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line) + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", line) - # Now launch the process, and do not stop at entry point and stop at breakpoint1 - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + # Now launch the process, and do not stop at entry point and stop at + # breakpoint1 + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") if self.TraceOn(): - self.runCmd("frame variable") + self.runCmd("frame variable") # Check that we correctly report the const types - self.expect("frame variable cs16 cs32", - substrs = ['(const char16_t *) cs16 = ','(const char32_t *) cs32 = ','u"hello world ྒྙྐ"','U"hello world ྒྙྐ"']) + self.expect( + "frame variable cs16 cs32", + substrs=[ + '(const char16_t *) cs16 = ', + '(const char32_t *) cs32 = ', + 'u"hello world ྒྙྐ"', + 'U"hello world ྒྙྐ"']) # Check that we correctly report the non-const types - self.expect("frame variable s16 s32", - substrs = ['(char16_t *) s16 = ','(char32_t *) s32 = ','u"ﺸﺵۻ"','U"ЕЙРГЖО"']) + self.expect( + "frame variable s16 s32", + substrs=[ + '(char16_t *) s16 = ', + '(char32_t *) s32 = ', + 'u"ﺸﺵۻ"', + 'U"ЕЙРГЖО"']) # Check that we correctly report the array types - self.expect("frame variable as16 as32", - patterns = ['\(char16_t \[[0-9]+\]\) as16 = ', '\(char32_t \[[0-9]+\]\) as32 = '], - substrs = ['u"ﺸﺵۻ"','U"ЕЙРГЖО"']) + self.expect( + "frame variable as16 as32", + patterns=[ + '\(char16_t \[[0-9]+\]\) as16 = ', + '\(char32_t \[[0-9]+\]\) as32 = '], + substrs=[ + 'u"ﺸﺵۻ"', + 'U"ЕЙРГЖО"']) - self.runCmd("next") # step to after the string is nullified + self.runCmd("next") # step to after the string is nullified # check that we don't crash on NULL self.expect("frame variable s32", - substrs = ['(char32_t *) s32 = 0x00000000']) + substrs=['(char32_t *) s32 = 0x00000000']) # continue and hit breakpoint2 self.runCmd("continue") # check that the new strings show - self.expect("frame variable s16 s32", - substrs = ['(char16_t *) s16 = 0x','(char32_t *) s32 = ','"色ハ匂ヘト散リヌルヲ"','"෴"']) + self.expect( + "frame variable s16 s32", + substrs=[ + '(char16_t *) s16 = 0x', + '(char32_t *) s32 = ', + '"色ハ匂ヘト散リヌルヲ"', + '"෴"']) # check the same as above for arrays - self.expect("frame variable as16 as32", - patterns = ['\(char16_t \[[0-9]+\]\) as16 = ', '\(char32_t \[[0-9]+\]\) as32 = '], - substrs = ['"色ハ匂ヘト散リヌルヲ"','"෴"']) + self.expect( + "frame variable as16 as32", + patterns=[ + '\(char16_t \[[0-9]+\]\) as16 = ', + '\(char32_t \[[0-9]+\]\) as32 = '], + substrs=[ + '"色ハ匂ヘト散リヌルヲ"', + '"෴"']) # check that zero values are properly handles self.expect('frame variable cs16_zero', substrs=["U+0000 u'\\0'"]) - self.expect('frame variable cs32_zero', substrs=["U+0x00000000 U'\\0'"]) + self.expect( + 'frame variable cs32_zero', + substrs=["U+0x00000000 U'\\0'"]) self.expect('expression cs16_zero', substrs=["U+0000 u'\\0'"]) self.expect('expression cs32_zero', substrs=["U+0x00000000 U'\\0'"]) # Check that we can run expressions that return charN_t - self.expect("expression u'a'",substrs = ['(char16_t) $',"61 u'a'"]) - self.expect("expression U'a'",substrs = ['(char32_t) $',"61 U'a'"]) + self.expect("expression u'a'", substrs=['(char16_t) $', "61 u'a'"]) + self.expect("expression U'a'", substrs=['(char32_t) $', "61 U'a'"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py index acce769bf94..328766b89e7 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py @@ -5,13 +5,14 @@ Test display and Python APIs on file and class static variables. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class StaticVariableTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -28,30 +29,42 @@ class StaticVariableTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - - # global variables are no longer displayed with the "frame variable" command. - self.expect('target variable A::g_points', VARIABLES_DISPLAYED_CORRECTLY, + substrs=['stopped', + 'stop reason = breakpoint']) + + # global variables are no longer displayed with the "frame variable" + # command. + self.expect( + 'target variable A::g_points', + VARIABLES_DISPLAYED_CORRECTLY, patterns=['\(PointType \[[1-9]*\]\) A::g_points = {.*}']) self.expect('target variable g_points', VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['(PointType [2]) g_points']) + substrs=['(PointType [2]) g_points']) # On Mac OS X, gcc 4.2 emits the wrong debug info for A::g_points. # A::g_points is an array of two elements. if self.platformIsDarwin() or self.getPlatform() == "linux": - self.expect("target variable A::g_points[1].x", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(int) A::g_points[1].x = 11") + self.expect( + "target variable A::g_points[1].x", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(int) A::g_points[1].x = 11") @expectedFailureDarwin(9980907) - @expectedFailureAll(compiler=["clang", "gcc"], bugnumber="Compiler emits incomplete debug info") - @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr20550 failing on FreeBSD-11') + @expectedFailureAll( + compiler=[ + "clang", + "gcc"], + bugnumber="Compiler emits incomplete debug info") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber='llvm.org/pr20550 failing on FreeBSD-11') @add_test_categories(['pyapi']) def test_with_python_api(self): """Test Python APIs on file and class static variables.""" @@ -65,11 +78,13 @@ class StaticVariableTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # Get the SBValue of 'A::g_points' and 'g_points'. @@ -86,10 +101,12 @@ class StaticVariableTestCase(TestBase): name = val.GetName() self.assertTrue(name in ['g_points', 'A::g_points']) if name == 'g_points': - self.assertTrue(val.GetValueType() == lldb.eValueTypeVariableStatic) + self.assertTrue( + val.GetValueType() == lldb.eValueTypeVariableStatic) self.assertTrue(val.GetNumChildren() == 2) elif name == 'A::g_points': - self.assertTrue(val.GetValueType() == lldb.eValueTypeVariableGlobal) + self.assertTrue( + val.GetValueType() == lldb.eValueTypeVariableGlobal) self.assertTrue(val.GetNumChildren() == 2) child1 = val.GetChildAtIndex(1) self.DebugSBValue(child1) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py index fe10120d497..c915e4b32fa 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ClassTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -27,7 +28,8 @@ class ClassTypesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on the ctor function of class C. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) @@ -40,17 +42,20 @@ class ClassTypesTestCase(TestBase): # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # We should be stopped on the ctor function of class C. - self.expect("frame variable --show-types this", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['C *', - ' this = ']) + self.expect( + "frame variable --show-types this", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'C *', + ' this = ']) @add_test_categories(['pyapi']) def test_with_python_api(self): @@ -77,11 +82,12 @@ class ClassTypesTestCase(TestBase): # Verify the breakpoint just created. self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False, - substrs = ['main.cpp', - str(self.line)]) + substrs=['main.cpp', + str(self.line)]) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") @@ -92,7 +98,8 @@ class ClassTypesTestCase(TestBase): lldbutil.state_type_to_str(process.GetState())) # The stop reason of the thread should be breakpoint. - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # The filename of frame #0 should be 'main.cpp' and the line number @@ -100,9 +107,9 @@ class ClassTypesTestCase(TestBase): self.expect("%s:%d" % (lldbutil.get_filenames(thread)[0], lldbutil.get_line_numbers(thread)[0]), "Break correctly at main.cpp:%d" % self.line, exe=False, - startstr = "main.cpp:") - ### clang compiled code reported main.cpp:94? - ### startstr = "main.cpp:93") + startstr="main.cpp:") + # clang compiled code reported main.cpp:94? + # startstr = "main.cpp:93") # We should be stopped on the breakpoint with a hit count of 1. self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE) @@ -119,49 +126,54 @@ class ClassTypesTestCase(TestBase): # Is this a case of clang (116.1) generating bad debug info? # # Break on the ctor function of class C. - #self.expect("breakpoint set -M C", BREAKPOINT_CREATED, + # self.expect("breakpoint set -M C", BREAKPOINT_CREATED, # startstr = "Breakpoint created: 1: name = 'C'") - # Make the test case more robust by using line number to break, instead. - lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=-1) + # Make the test case more robust by using line number to break, + # instead. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Continue on inside the ctor() body... self.runCmd("register read pc") self.runCmd("thread step-over") # Verify that 'frame variable this' gets the data type correct. - self.expect("frame variable this",VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['C *']) + self.expect("frame variable this", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['C *']) - # Verify that frame variable --show-types this->m_c_int behaves correctly. + # Verify that frame variable --show-types this->m_c_int behaves + # correctly. self.runCmd("register read pc") self.runCmd("expr m_c_int") - self.expect("frame variable --show-types this->m_c_int", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int) this->m_c_int = 66') + self.expect( + "frame variable --show-types this->m_c_int", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) this->m_c_int = 66') # Verify that 'expression this' gets the data type correct. self.expect("expression this", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['C *']) + substrs=['C *']) # rdar://problem/8430916 # expr this->m_c_int returns an incorrect value # # Verify that expr this->m_c_int behaves correctly. self.expect("expression this->m_c_int", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ['\(int\) \$[0-9]+ = 66']) + patterns=['\(int\) \$[0-9]+ = 66']) - def test_with_constructor_name (self): + def test_with_constructor_name(self): """Test 'frame variable this' and 'expr this' when stopped inside a constructor.""" self.build() exe = os.path.join(os.getcwd(), "a.out") @@ -185,11 +197,12 @@ class ClassTypesTestCase(TestBase): # Verify the breakpoint just created. self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False, - substrs = ['main.cpp', - str(self.line)]) + substrs=['main.cpp', + str(self.line)]) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") @@ -200,10 +213,12 @@ class ClassTypesTestCase(TestBase): lldbutil.state_type_to_str(process.GetState())) # The stop reason of the thread should be breakpoint. - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) frame = thread.frames[0] - self.assertTrue (frame.IsValid(), "Got a valid frame.") + self.assertTrue(frame.IsValid(), "Got a valid frame.") - self.assertTrue ("C::C" in frame.name, "Constructor name includes class name.") + self.assertTrue("C::C" in frame.name, + "Constructor name includes class name.") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py index 6413b3e056f..bc85ba5181e 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py @@ -5,13 +5,14 @@ Test the lldb disassemble command on each call frame when stopped on C's ctor. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class IterateFrameAndDisassembleTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -47,7 +48,8 @@ class IterateFrameAndDisassembleTestCase(TestBase): # disassemble it. target = self.dbg.GetSelectedTarget() process = target.GetProcess() - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) depth = thread.GetNumFrames() for i in range(depth - 1): @@ -62,7 +64,8 @@ class IterateFrameAndDisassembleTestCase(TestBase): insts = function.GetInstructions(target) for inst in insts: # We could simply do 'print inst' to print out the disassembly. - # But we want to print to stdout only if self.TraceOn() is True. + # But we want to print to stdout only if self.TraceOn() is + # True. disasm = str(inst) if self.TraceOn(): print(disasm) @@ -79,14 +82,15 @@ class IterateFrameAndDisassembleTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break on the ctor function of class C. - bpno = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1) + bpno = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint %d.'%(bpno)]) + substrs=['stopped', + 'stop reason = breakpoint %d.' % (bpno)]) # This test was failing because we fail to put the C:: in front of constructore. # We should maybe make another testcase to cover that specifically, but we shouldn't diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/TestConstThis.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/TestConstThis.py index a08af5d091e..f08c0dcbda9 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/TestConstThis.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/TestConstThis.py @@ -1,4 +1,4 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [] ) +lldbinline.MakeInlineTest(__file__, globals(), []) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py index d525e12b31e..c6f9d85cd2c 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py @@ -5,22 +5,25 @@ import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class CPPTestDiamondInheritance(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def test_with_run_command(self): """Test that virtual base classes work in when SBValue objects are used to explore the variable value""" self.build() exe = os.path.join(os.getcwd(), "a.out") - + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) self.set_breakpoint(line_number('main.cpp', '// breakpoint 1')) self.set_breakpoint(line_number('main.cpp', '// breakpoint 2')) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) frame = thread.GetFrameAtIndex(0) j1 = frame.FindVariable("j1") @@ -30,13 +33,19 @@ class CPPTestDiamondInheritance(TestBase): j1_Derived2_VBase = j1_Derived2.GetChildAtIndex(0) j1_Derived1_VBase_m_value = j1_Derived1_VBase.GetChildAtIndex(0) j1_Derived2_VBase_m_value = j1_Derived2_VBase.GetChildAtIndex(0) - self.assertTrue(j1_Derived1_VBase.GetLoadAddress() == j1_Derived2_VBase.GetLoadAddress(), "ensure virtual base class is the same between Derived1 and Derived2") - self.assertTrue(j1_Derived1_VBase_m_value.GetValueAsUnsigned(1) == j1_Derived2_VBase_m_value.GetValueAsUnsigned(2), "ensure m_value in VBase is the same") - self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex(0).GetValueAsUnsigned(0) == 12345, "ensure Derived2 from j1 is correct"); + self.assertTrue( + j1_Derived1_VBase.GetLoadAddress() == j1_Derived2_VBase.GetLoadAddress(), + "ensure virtual base class is the same between Derived1 and Derived2") + self.assertTrue(j1_Derived1_VBase_m_value.GetValueAsUnsigned( + 1) == j1_Derived2_VBase_m_value.GetValueAsUnsigned(2), "ensure m_value in VBase is the same") + self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex( + 0).GetValueAsUnsigned(0) == 12345, "ensure Derived2 from j1 is correct") thread.StepOver() - self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex(0).GetValueAsUnsigned(0) == 12346, "ensure Derived2 from j2 is correct"); - + self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex( + 0).GetValueAsUnsigned(0) == 12346, "ensure Derived2 from j2 is correct") + def set_breakpoint(self, line): # Some compilers (for example GCC 4.4.7 and 4.6.1) emit multiple locations for the statement with the ternary # operator in the test program, while others emit only 1. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py index b456de450a8..74b94517fa0 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py @@ -5,20 +5,22 @@ Test lldb Python API SBValue::Cast(SBType) for C++ types. from __future__ import print_function - import unittest2 -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CppValueCastTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @unittest2.expectedFailure("rdar://problem/10808472 SBValue::Cast test case is failing (virtual inheritance)") + @unittest2.expectedFailure( + "rdar://problem/10808472 SBValue::Cast test case is failing (virtual inheritance)") @add_test_categories(['pyapi']) def test_value_cast_with_virtual_inheritance(self): """Test SBValue::Cast(SBType) API for C++ types with virtual inheritance.""" @@ -34,23 +36,26 @@ class CppValueCastTestCase(TestBase): self.do_sbvalue_cast(self.exe_name) def setUp(self): - # Call super's setUp(). + # Call super's setUp(). TestBase.setUp(self) - # Find the line number to break for main.c. - self.source = 'sbvalue-cast.cpp'; + # Find the line number to break for main.c. + self.source = 'sbvalue-cast.cpp' self.line = line_number(self.source, '// Set breakpoint here.') self.exe_name = self.testMethodName - self.d_virtual = {'CXX_SOURCES': self.source, 'EXE': self.exe_name, 'CFLAGS_EXTRAS': '-DDO_VIRTUAL_INHERITANCE'} + self.d_virtual = { + 'CXX_SOURCES': self.source, + 'EXE': self.exe_name, + 'CFLAGS_EXTRAS': '-DDO_VIRTUAL_INHERITANCE'} self.d_regular = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} - def do_sbvalue_cast (self, exe_name): + def do_sbvalue_cast(self, exe_name): """Test SBValue::Cast(SBType) API for C++ types.""" exe = os.path.join(os.getcwd(), exe_name) # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoints: @@ -59,7 +64,8 @@ class CppValueCastTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) @@ -74,14 +80,16 @@ class CppValueCastTestCase(TestBase): error = lldb.SBError() # First stop is for DerivedA instance. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue (len(threads) == 1) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1) thread = threads[0] frame0 = thread.GetFrameAtIndex(0) tellerA = frame0.FindVariable('teller', lldb.eNoDynamicValues) self.DebugSBValue(tellerA) - self.assertTrue(tellerA.GetChildMemberWithName('m_base_val').GetValueAsUnsigned(error, 0) == 20) + self.assertTrue(tellerA.GetChildMemberWithName( + 'm_base_val').GetValueAsUnsigned(error, 0) == 20) if self.TraceOn(): for child in tellerA: @@ -102,14 +110,15 @@ class CppValueCastTestCase(TestBase): self.assertTrue(a_member_val.GetValueAsUnsigned(error, 0) == 10) # Second stop is for DerivedB instance. - threads = lldbutil.continue_to_breakpoint (process, breakpoint) - self.assertTrue (len(threads) == 1) + threads = lldbutil.continue_to_breakpoint(process, breakpoint) + self.assertTrue(len(threads) == 1) thread = threads[0] frame0 = thread.GetFrameAtIndex(0) tellerB = frame0.FindVariable('teller', lldb.eNoDynamicValues) self.DebugSBValue(tellerB) - self.assertTrue(tellerB.GetChildMemberWithName('m_base_val').GetValueAsUnsigned(error, 0) == 12) + self.assertTrue(tellerB.GetChildMemberWithName( + 'm_base_val').GetValueAsUnsigned(error, 0) == 12) if self.TraceOn(): for child in tellerB: diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py index 98e6ef92665..42db14f21e0 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py @@ -5,29 +5,32 @@ Use lldb Python API to test dynamic values in C++ from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DynamicValueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): - # Call super's setUp(). + # Call super's setUp(). TestBase.setUp(self) - # Find the line number to break for main.c. + # Find the line number to break for main.c. - self.do_something_line = line_number('pass-to-base.cpp', '// Break here in doSomething.') - self.main_first_call_line = line_number('pass-to-base.cpp', - '// Break here and get real addresses of myB and otherB.') - self.main_second_call_line = line_number('pass-to-base.cpp', - '// Break here and get real address of reallyA.') + self.do_something_line = line_number( + 'pass-to-base.cpp', '// Break here in doSomething.') + self.main_first_call_line = line_number( + 'pass-to-base.cpp', + '// Break here and get real addresses of myB and otherB.') + self.main_second_call_line = line_number( + 'pass-to-base.cpp', '// Break here and get real address of reallyA.') @add_test_categories(['pyapi']) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663") @@ -38,31 +41,36 @@ class DynamicValueTestCase(TestBase): # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoints: - do_something_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.do_something_line) + do_something_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.do_something_line) self.assertTrue(do_something_bpt, VALID_BREAKPOINT) - first_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_first_call_line) + first_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_first_call_line) self.assertTrue(first_call_bpt, VALID_BREAKPOINT) - second_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_second_call_line) + second_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_second_call_line) self.assertTrue(second_call_bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, first_call_bpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, first_call_bpt) + self.assertTrue(len(threads) == 1) thread = threads[0] frame = thread.GetFrameAtIndex(0) @@ -71,153 +79,175 @@ class DynamicValueTestCase(TestBase): # with the dynamic values we get in doSomething: use_dynamic = lldb.eDynamicCanRunTarget - no_dynamic = lldb.eNoDynamicValues + no_dynamic = lldb.eNoDynamicValues - myB = frame.FindVariable ('myB', no_dynamic); - self.assertTrue (myB) - myB_loc = int (myB.GetLocation(), 16) + myB = frame.FindVariable('myB', no_dynamic) + self.assertTrue(myB) + myB_loc = int(myB.GetLocation(), 16) otherB = frame.FindVariable('otherB', no_dynamic) - self.assertTrue (otherB) - otherB_loc = int (otherB.GetLocation(), 16) + self.assertTrue(otherB) + otherB_loc = int(otherB.GetLocation(), 16) # Okay now run to doSomething: - threads = lldbutil.continue_to_breakpoint (process, do_something_bpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.continue_to_breakpoint(process, do_something_bpt) + self.assertTrue(len(threads) == 1) thread = threads[0] frame = thread.GetFrameAtIndex(0) # Get "this" using FindVariable: - this_static = frame.FindVariable ('this', no_dynamic) - this_dynamic = frame.FindVariable ('this', use_dynamic) - self.examine_value_object_of_this_ptr (this_static, this_dynamic, myB_loc) - + this_static = frame.FindVariable('this', no_dynamic) + this_dynamic = frame.FindVariable('this', use_dynamic) + self.examine_value_object_of_this_ptr( + this_static, this_dynamic, myB_loc) + # Now make sure that the "GetDynamicValue" works: - # This doesn't work currently because we can't get dynamic values from ConstResult objects. + # This doesn't work currently because we can't get dynamic values from + # ConstResult objects. fetched_dynamic_value = this_static.GetDynamicValue(use_dynamic) - self.examine_value_object_of_this_ptr (this_static, fetched_dynamic_value, myB_loc) + self.examine_value_object_of_this_ptr( + this_static, fetched_dynamic_value, myB_loc) # And conversely that the GetDynamicValue() interface also works: fetched_static_value = this_dynamic.GetStaticValue() - self.examine_value_object_of_this_ptr (fetched_static_value, this_dynamic, myB_loc) + self.examine_value_object_of_this_ptr( + fetched_static_value, this_dynamic, myB_loc) # Get "this" using FindValue, make sure that works too: - this_static = frame.FindValue ('this', lldb.eValueTypeVariableArgument, no_dynamic) - this_dynamic = frame.FindValue ('this', lldb.eValueTypeVariableArgument, use_dynamic) - self.examine_value_object_of_this_ptr (this_static, this_dynamic, myB_loc) + this_static = frame.FindValue( + 'this', lldb.eValueTypeVariableArgument, no_dynamic) + this_dynamic = frame.FindValue( + 'this', lldb.eValueTypeVariableArgument, use_dynamic) + self.examine_value_object_of_this_ptr( + this_static, this_dynamic, myB_loc) # Get "this" using the EvaluateExpression: - this_static = frame.EvaluateExpression ('this', False) - this_dynamic = frame.EvaluateExpression ('this', True) - self.examine_value_object_of_this_ptr (this_static, this_dynamic, myB_loc) - + this_static = frame.EvaluateExpression('this', False) + this_dynamic = frame.EvaluateExpression('this', True) + self.examine_value_object_of_this_ptr( + this_static, this_dynamic, myB_loc) + # The "frame var" code uses another path to get into children, so let's # make sure that works as well: - self.expect('frame var -d run-target --ptr-depth=2 --show-types anotherA.m_client_A', 'frame var finds its way into a child member', - patterns = ['\(B \*\)']) + self.expect( + 'frame var -d run-target --ptr-depth=2 --show-types anotherA.m_client_A', + 'frame var finds its way into a child member', + patterns=['\(B \*\)']) # Now make sure we also get it right for a reference as well: - anotherA_static = frame.FindVariable ('anotherA', False) - self.assertTrue (anotherA_static) - anotherA_static_addr = int (anotherA_static.GetValue(), 16) + anotherA_static = frame.FindVariable('anotherA', False) + self.assertTrue(anotherA_static) + anotherA_static_addr = int(anotherA_static.GetValue(), 16) - anotherA_dynamic = frame.FindVariable ('anotherA', True) - self.assertTrue (anotherA_dynamic) - anotherA_dynamic_addr = int (anotherA_dynamic.GetValue(), 16) + anotherA_dynamic = frame.FindVariable('anotherA', True) + self.assertTrue(anotherA_dynamic) + anotherA_dynamic_addr = int(anotherA_dynamic.GetValue(), 16) anotherA_dynamic_typename = anotherA_dynamic.GetTypeName() - self.assertTrue (anotherA_dynamic_typename.find('B') != -1) + self.assertTrue(anotherA_dynamic_typename.find('B') != -1) self.assertTrue(anotherA_dynamic_addr < anotherA_static_addr) - anotherA_m_b_value_dynamic = anotherA_dynamic.GetChildMemberWithName('m_b_value', True) - self.assertTrue (anotherA_m_b_value_dynamic) - anotherA_m_b_val = int (anotherA_m_b_value_dynamic.GetValue(), 10) - self.assertTrue (anotherA_m_b_val == 300) + anotherA_m_b_value_dynamic = anotherA_dynamic.GetChildMemberWithName( + 'm_b_value', True) + self.assertTrue(anotherA_m_b_value_dynamic) + anotherA_m_b_val = int(anotherA_m_b_value_dynamic.GetValue(), 10) + self.assertTrue(anotherA_m_b_val == 300) - anotherA_m_b_value_static = anotherA_static.GetChildMemberWithName('m_b_value', True) - self.assertFalse (anotherA_m_b_value_static) + anotherA_m_b_value_static = anotherA_static.GetChildMemberWithName( + 'm_b_value', True) + self.assertFalse(anotherA_m_b_value_static) - # Okay, now continue again, and when we hit the second breakpoint in main + # Okay, now continue again, and when we hit the second breakpoint in + # main - threads = lldbutil.continue_to_breakpoint (process, second_call_bpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.continue_to_breakpoint(process, second_call_bpt) + self.assertTrue(len(threads) == 1) thread = threads[0] frame = thread.GetFrameAtIndex(0) - reallyA_value = frame.FindVariable ('reallyA', False) + reallyA_value = frame.FindVariable('reallyA', False) self.assertTrue(reallyA_value) - reallyA_loc = int (reallyA_value.GetLocation(), 16) - + reallyA_loc = int(reallyA_value.GetLocation(), 16) + # Finally continue to doSomething again, and make sure we get the right value for anotherA, # which this time around is just an "A". - threads = lldbutil.continue_to_breakpoint (process, do_something_bpt) + threads = lldbutil.continue_to_breakpoint(process, do_something_bpt) self.assertTrue(len(threads) == 1) thread = threads[0] frame = thread.GetFrameAtIndex(0) - anotherA_value = frame.FindVariable ('anotherA', True) + anotherA_value = frame.FindVariable('anotherA', True) self.assertTrue(anotherA_value) - anotherA_loc = int (anotherA_value.GetValue(), 16) - self.assertTrue (anotherA_loc == reallyA_loc) - self.assertTrue (anotherA_value.GetTypeName().find ('B') == -1) + anotherA_loc = int(anotherA_value.GetValue(), 16) + self.assertTrue(anotherA_loc == reallyA_loc) + self.assertTrue(anotherA_value.GetTypeName().find('B') == -1) - def examine_value_object_of_this_ptr (self, this_static, this_dynamic, dynamic_location): + def examine_value_object_of_this_ptr( + self, this_static, this_dynamic, dynamic_location): # Get "this" as its static value - self.assertTrue (this_static) - this_static_loc = int (this_static.GetValue(), 16) - + self.assertTrue(this_static) + this_static_loc = int(this_static.GetValue(), 16) + # Get "this" as its dynamic value - - self.assertTrue (this_dynamic) + + self.assertTrue(this_dynamic) this_dynamic_typename = this_dynamic.GetTypeName() - self.assertTrue (this_dynamic_typename.find('B') != -1) - this_dynamic_loc = int (this_dynamic.GetValue(), 16) - + self.assertTrue(this_dynamic_typename.find('B') != -1) + this_dynamic_loc = int(this_dynamic.GetValue(), 16) + # Make sure we got the right address for "this" - - self.assertTrue (this_dynamic_loc == dynamic_location) + + self.assertTrue(this_dynamic_loc == dynamic_location) # And that the static address is greater than the dynamic one - self.assertTrue (this_static_loc > this_dynamic_loc) - + self.assertTrue(this_static_loc > this_dynamic_loc) + # Now read m_b_value which is only in the dynamic value: use_dynamic = lldb.eDynamicCanRunTarget - no_dynamic = lldb.eNoDynamicValues - - this_dynamic_m_b_value = this_dynamic.GetChildMemberWithName('m_b_value', use_dynamic) - self.assertTrue (this_dynamic_m_b_value) - - m_b_value = int (this_dynamic_m_b_value.GetValue(), 0) - self.assertTrue (m_b_value == 10) - + no_dynamic = lldb.eNoDynamicValues + + this_dynamic_m_b_value = this_dynamic.GetChildMemberWithName( + 'm_b_value', use_dynamic) + self.assertTrue(this_dynamic_m_b_value) + + m_b_value = int(this_dynamic_m_b_value.GetValue(), 0) + self.assertTrue(m_b_value == 10) + # Make sure it is not in the static version - this_static_m_b_value = this_static.GetChildMemberWithName('m_b_value', no_dynamic) - self.assertFalse (this_static_m_b_value) + this_static_m_b_value = this_static.GetChildMemberWithName( + 'm_b_value', no_dynamic) + self.assertFalse(this_static_m_b_value) - # Okay, now let's make sure that we can get the dynamic type of a child element: + # Okay, now let's make sure that we can get the dynamic type of a child + # element: - contained_auto_ptr = this_dynamic.GetChildMemberWithName ('m_client_A', use_dynamic) - self.assertTrue (contained_auto_ptr) - contained_b = contained_auto_ptr.GetChildMemberWithName ('_M_ptr', use_dynamic) + contained_auto_ptr = this_dynamic.GetChildMemberWithName( + 'm_client_A', use_dynamic) + self.assertTrue(contained_auto_ptr) + contained_b = contained_auto_ptr.GetChildMemberWithName( + '_M_ptr', use_dynamic) if not contained_b: - contained_b = contained_auto_ptr.GetChildMemberWithName ('__ptr_', use_dynamic) - self.assertTrue (contained_b) - - contained_b_static = contained_auto_ptr.GetChildMemberWithName ('_M_ptr', no_dynamic) + contained_b = contained_auto_ptr.GetChildMemberWithName( + '__ptr_', use_dynamic) + self.assertTrue(contained_b) + + contained_b_static = contained_auto_ptr.GetChildMemberWithName( + '_M_ptr', no_dynamic) if not contained_b_static: - contained_b_static = contained_auto_ptr.GetChildMemberWithName ('__ptr_', no_dynamic) - self.assertTrue (contained_b_static) - - contained_b_addr = int (contained_b.GetValue(), 16) - contained_b_static_addr = int (contained_b_static.GetValue(), 16) - - self.assertTrue (contained_b_addr < contained_b_static_addr) + contained_b_static = contained_auto_ptr.GetChildMemberWithName( + '__ptr_', no_dynamic) + self.assertTrue(contained_b_static) + + contained_b_addr = int(contained_b.GetValue(), 16) + contained_b_static_addr = int(contained_b_static.GetValue(), 16) + + self.assertTrue(contained_b_addr < contained_b_static_addr) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py index 51c145c7b7c..e8d3284f609 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py @@ -3,54 +3,71 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class CPP11EnumTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def test_int8_t(self): """Test C++11 enumeration class types as int8_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int8_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int8_t"'}) self.image_lookup_for_enum_type() def test_int16_t(self): """Test C++11 enumeration class types as int16_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int16_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int16_t"'}) self.image_lookup_for_enum_type() def test_int32_t(self): """Test C++11 enumeration class types as int32_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int32_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int32_t"'}) self.image_lookup_for_enum_type() def test_int64_t(self): """Test C++11 enumeration class types as int64_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int64_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int64_t"'}) self.image_lookup_for_enum_type() def test_uint8_t(self): """Test C++11 enumeration class types as uint8_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint8_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint8_t"'}) self.image_lookup_for_enum_type() def test_uint16_t(self): """Test C++11 enumeration class types as uint16_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint16_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint16_t"'}) self.image_lookup_for_enum_type() def test_uint32_t(self): """Test C++11 enumeration class types as uint32_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint32_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint32_t"'}) self.image_lookup_for_enum_type() def test_uint64_t(self): """Test C++11 enumeration class types as uint64_t types.""" - self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint64_t"'}) + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint64_t"'}) self.image_lookup_for_enum_type() def setUp(self): @@ -65,23 +82,35 @@ class CPP11EnumTypesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - bkpt_id = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + bkpt_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Look up information about the 'DayType' enum type. # Check for correct display. self.expect("image lookup -t DayType", DATA_TYPES_DISPLAYED_CORRECTLY, - substrs = ['enum DayType {', + substrs=['enum DayType {', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + 'kNumDays', + '}']) + + enum_values = ['-4', 'Monday', 'Tuesday', 'Wednesday', @@ -90,21 +119,12 @@ class CPP11EnumTypesTestCase(TestBase): 'Saturday', 'Sunday', 'kNumDays', - '}']) - - enum_values = [ '-4', - 'Monday', - 'Tuesday', - 'Wednesday', - 'Thursday', - 'Friday', - 'Saturday', - 'Sunday', - 'kNumDays', - '5']; + '5'] bkpt = self.target().FindBreakpointByID(bkpt_id) for enum_value in enum_values: - self.expect("frame variable day", 'check for valid enumeration value', - substrs = [enum_value]) - lldbutil.continue_to_breakpoint (self.process(), bkpt) + self.expect( + "frame variable day", + 'check for valid enumeration value', + substrs=[enum_value]) + lldbutil.continue_to_breakpoint(self.process(), bkpt) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py index 4ca4cb8b79e..4bc33205319 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py @@ -5,13 +5,14 @@ Test lldb exception breakpoint command for CPP. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CPPBreakpointTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,9 +21,12 @@ class CPPBreakpointTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) self.source = 'exceptions.cpp' - self.catch_line = line_number(self.source, '// This is the line you should stop at for catch') + self.catch_line = line_number( + self.source, '// This is the line you should stop at for catch') - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24538, clang-cl does not support throw or catch") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24538, clang-cl does not support throw or catch") def test(self): """Test lldb exception breakpoint command for CPP.""" self.build() @@ -30,37 +34,51 @@ class CPPBreakpointTestCase(TestBase): # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - exception_bkpt = target.BreakpointCreateForException (lldb.eLanguageTypeC_plus_plus, True, True) - self.assertTrue (exception_bkpt, "Made an exception breakpoint") + exception_bkpt = target.BreakpointCreateForException( + lldb.eLanguageTypeC_plus_plus, True, True) + self.assertTrue(exception_bkpt, "Made an exception breakpoint") # Now run, and make sure we hit our breakpoint: - process = target.LaunchSimple (None, None, self.get_process_working_directory()) - self.assertTrue (process, "Got a valid process") - + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Got a valid process") + stopped_threads = [] - stopped_threads = lldbutil.get_threads_stopped_at_breakpoint (process, exception_bkpt) - self.assertTrue (len(stopped_threads) == 1, "Stopped at our exception breakpoint.") + stopped_threads = lldbutil.get_threads_stopped_at_breakpoint( + process, exception_bkpt) + self.assertTrue( + len(stopped_threads) == 1, + "Stopped at our exception breakpoint.") thread = stopped_threads[0] # Make sure our throw function is still above us on the stack: frame_functions = lldbutil.get_function_names(thread) - self.assertTrue (frame_functions.count ("throws_exception_on_even(int)") == 1, "Our throw function is still on the stack.") + self.assertTrue( + frame_functions.count("throws_exception_on_even(int)") == 1, + "Our throw function is still on the stack.") # Okay we hit our exception throw breakpoint, now make sure we get our catch breakpoint. # One potential complication is that we might hit a couple of the exception breakpoints in getting out of the throw. # so loop till we don't see the throws function on the stack. We should stop one more time for our exception breakpoint # and that should be the catch... - while frame_functions.count ("throws_exception_on_even(int)") == 1: - stopped_threads = lldbutil.continue_to_breakpoint (process, exception_bkpt) - self.assertTrue (len(stopped_threads) == 1) - + while frame_functions.count("throws_exception_on_even(int)") == 1: + stopped_threads = lldbutil.continue_to_breakpoint( + process, exception_bkpt) + self.assertTrue(len(stopped_threads) == 1) + thread = stopped_threads[0] frame_functions = lldbutil.get_function_names(thread) - self.assertTrue (frame_functions.count ("throws_exception_on_even(int)") == 0, "At catch our throw function is off the stack") - self.assertTrue (frame_functions.count ("intervening_function(int)") == 0, "At catch our intervening function is off the stack") - self.assertTrue (frame_functions.count ("catches_exception(int)") == 1, "At catch our catch function is on the stack") + self.assertTrue( + frame_functions.count("throws_exception_on_even(int)") == 0, + "At catch our throw function is off the stack") + self.assertTrue( + frame_functions.count("intervening_function(int)") == 0, + "At catch our intervening function is off the stack") + self.assertTrue( + frame_functions.count("catches_exception(int)") == 1, + "At catch our catch function is on the stack") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py index d5d53638822..c37107e898c 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py @@ -5,17 +5,19 @@ import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class FrameVariableAnonymousUnionsTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def test_with_run_command(self): """Tests that frame variable looks into anonymous unions""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) line = line_number('main.cpp', '// break here') - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) self.runCmd("process launch", RUN_SUCCEEDED) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py index 50f25485216..629d2bbce97 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py @@ -6,10 +6,11 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCppGlobalOperators(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def prepare_executable_and_get_frame(self): self.build() @@ -17,29 +18,36 @@ class TestCppGlobalOperators(TestBase): src_file = "main.cpp" src_file_spec = lldb.SBFileSpec(src_file) self.assertTrue(src_file_spec.IsValid(), "Main source file") - + # Get the path of the executable cwd = os.getcwd() exe_file = "a.out" - exe_path = os.path.join(cwd, exe_file) - + exe_path = os.path.join(cwd, exe_file) + # Load the executable target = self.dbg.CreateTarget(exe_path) self.assertTrue(target.IsValid(), VALID_TARGET) # Break on main function - main_breakpoint = target.BreakpointCreateBySourceRegex("// break here", src_file_spec) - self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT) + main_breakpoint = target.BreakpointCreateBySourceRegex( + "// break here", src_file_spec) + self.assertTrue( + main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process args = None env = None - process = target.LaunchSimple(args, env, self.get_process_working_directory()) + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) return thread.GetSelectedFrame() @@ -48,18 +56,25 @@ class TestCppGlobalOperators(TestBase): frame = self.prepare_executable_and_get_frame() test_result = frame.EvaluateExpression("operator==(s1, s2)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "operator==(s1, s2) = false") - + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "operator==(s1, s2) = false") + test_result = frame.EvaluateExpression("operator==(s1, s3)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "operator==(s1, s3) = true") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "operator==(s1, s3) = true") test_result = frame.EvaluateExpression("operator==(s2, s3)") - self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "operator==(s2, s3) = false") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "operator==(s2, s3) = false") def do_new_test(self, frame, expr, expected_value_name): """Evaluate a new expression, and check its result""" - expected_value = frame.FindValue(expected_value_name, lldb.eValueTypeVariableGlobal) + expected_value = frame.FindValue( + expected_value_name, lldb.eValueTypeVariableGlobal) self.assertTrue(expected_value.IsValid()) expected_value_addr = expected_value.AddressOf() @@ -67,7 +82,9 @@ class TestCppGlobalOperators(TestBase): got = frame.EvaluateExpression(expr) self.assertTrue(got.IsValid()) - self.assertEqual(got.GetValueAsUnsigned(), expected_value_addr.GetValueAsUnsigned()) + self.assertEqual( + got.GetValueAsUnsigned(), + expected_value_addr.GetValueAsUnsigned()) got_type = got.GetType() self.assertTrue(got_type.IsPointerType()) self.assertEqual(got_type.GetPointeeType().GetName(), "Struct") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/TestWithModuleDebugging.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/TestWithModuleDebugging.py index 942149f6173..ca5b3754a24 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/TestWithModuleDebugging.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/TestWithModuleDebugging.py @@ -1,8 +1,10 @@ -import lldb, os +import lldb +import os from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestWithGmodulesDebugInfo(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -18,33 +20,53 @@ class TestWithGmodulesDebugInfo(TestBase): self.assertTrue(src_file_spec.IsValid(), "breakpoint file") # Get the path of the executable - exe_path = os.path.join(cwd, 'a.out') + exe_path = os.path.join(cwd, 'a.out') # Load the executable target = self.dbg.CreateTarget(exe_path) self.assertTrue(target.IsValid(), VALID_TARGET) # Break on interesting line - breakpoint = target.BreakpointCreateBySourceRegex("break here", src_file_spec) - self.assertTrue(breakpoint.IsValid() and breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT) + breakpoint = target.BreakpointCreateBySourceRegex( + "break here", src_file_spec) + self.assertTrue( + breakpoint.IsValid() and breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") # Get frame for current thread frame = thread.frames[0] testValue = frame.EvaluateExpression("test") - self.assertTrue(testValue.GetError().Success(), "Test expression value invalid: %s" % (testValue.GetError().GetCString())) - self.assertTrue(testValue.GetTypeName() == "IntContainer", "Test expression type incorrect") + self.assertTrue( + testValue.GetError().Success(), + "Test expression value invalid: %s" % + (testValue.GetError().GetCString())) + self.assertTrue( + testValue.GetTypeName() == "IntContainer", + "Test expression type incorrect") memberValue = testValue.GetChildMemberWithName("storage") - self.assertTrue(memberValue.GetError().Success(), "Member value missing or invalid: %s" % (testValue.GetError().GetCString())) - self.assertTrue(memberValue.GetTypeName() == "int", "Member type incorrect") - self.assertEqual(42, memberValue.GetValueAsSigned(), "Member value incorrect") + self.assertTrue( + memberValue.GetError().Success(), + "Member value missing or invalid: %s" % + (testValue.GetError().GetCString())) + self.assertTrue( + memberValue.GetTypeName() == "int", + "Member type incorrect") + self.assertEqual( + 42, + memberValue.GetValueAsSigned(), + "Member value incorrect") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py index 1e3359ecde4..505a27a0a67 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py @@ -3,6 +3,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCppIncompleteTypes(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -13,25 +14,34 @@ class TestCppIncompleteTypes(TestBase): frame = self.get_test_frame('limit') value_f = frame.EvaluateExpression("f") - self.assertTrue(value_f.IsValid(), "'expr f' results in a valid SBValue object") + self.assertTrue( + value_f.IsValid(), + "'expr f' results in a valid SBValue object") self.assertTrue(value_f.GetError().Success(), "'expr f' is successful") value_a = frame.EvaluateExpression("a") - self.assertTrue(value_a.IsValid(), "'expr a' results in a valid SBValue object") + self.assertTrue( + value_a.IsValid(), + "'expr a' results in a valid SBValue object") self.assertTrue(value_a.GetError().Success(), "'expr a' is successful") @skipIf(compiler="gcc") - @skipIfWindows # Clang on Windows asserts in external record layout in this case. + # Clang on Windows asserts in external record layout in this case. + @skipIfWindows def test_partial_limit_debug_info(self): self.build() frame = self.get_test_frame('nolimit') value_f = frame.EvaluateExpression("f") - self.assertTrue(value_f.IsValid(), "'expr f' results in a valid SBValue object") + self.assertTrue( + value_f.IsValid(), + "'expr f' results in a valid SBValue object") self.assertTrue(value_f.GetError().Success(), "'expr f' is successful") value_a = frame.EvaluateExpression("a") - self.assertTrue(value_a.IsValid(), "'expr a' results in a valid SBValue object") + self.assertTrue( + value_a.IsValid(), + "'expr a' results in a valid SBValue object") self.assertTrue(value_a.GetError().Success(), "'expr a' is successful") def get_test_frame(self, exe): @@ -42,25 +52,32 @@ class TestCppIncompleteTypes(TestBase): # Get the path of the executable cwd = os.getcwd() - exe_path = os.path.join(cwd, exe) + exe_path = os.path.join(cwd, exe) # Load the executable target = self.dbg.CreateTarget(exe_path) self.assertTrue(target.IsValid(), VALID_TARGET) # Break on main function - main_breakpoint = target.BreakpointCreateBySourceRegex("break here", src_file_spec) - self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT) + main_breakpoint = target.BreakpointCreateBySourceRegex( + "break here", src_file_spec) + self.assertTrue( + main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process args = None env = None - process = target.LaunchSimple(args, env, self.get_process_working_directory()) + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) # Get frame for current thread return thread.GetSelectedFrame() diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/TestInlines.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/TestInlines.py index 284057de9dc..2dc72981c14 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/TestInlines.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/TestInlines.py @@ -2,12 +2,14 @@ from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class InlinesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -16,7 +18,9 @@ class InlinesTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('inlines.cpp', '// Set break point at this line.') + self.line = line_number( + 'inlines.cpp', + '// Set break point at this line.') @expectedFailureAll("llvm.org/pr26710", oslist=["linux"], compiler="gcc") def test(self): @@ -25,28 +29,34 @@ class InlinesTestCase(TestBase): self.runToBreakpoint() # Check that 'frame variable' finds a variable - self.expect("frame variable inner_input", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int) inner_input =') + self.expect( + "frame variable inner_input", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) inner_input =') # Check that 'expr' finds a variable self.expect("expr inner_input", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int) $0 =') + startstr='(int) $0 =') def runToBreakpoint(self): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the main. - lldbutil.run_break_set_by_file_and_line(self, "inlines.cpp", self.line, num_expected_locations=2, - loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "inlines.cpp", + self.line, + num_expected_locations=2, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/TestLambdas.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/TestLambdas.py index 97cc177aab7..284caabbc17 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/TestLambdas.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/TestLambdas.py @@ -1,4 +1,7 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [lldbinline.expectedFailureAll(oslist=["windows"])]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + lldbinline.expectedFailureAll( + oslist=["windows"])]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py index 9d4d1b54a9d..89086e7a64b 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py @@ -3,6 +3,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestWithLimitDebugInfo(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -18,32 +19,47 @@ class TestWithLimitDebugInfo(TestBase): self.assertTrue(src_file_spec.IsValid(), "breakpoint file") # Get the path of the executable - exe_path = os.path.join(cwd, 'a.out') + exe_path = os.path.join(cwd, 'a.out') # Load the executable target = self.dbg.CreateTarget(exe_path) self.assertTrue(target.IsValid(), VALID_TARGET) # Break on main function - breakpoint = target.BreakpointCreateBySourceRegex("break here", src_file_spec) - self.assertTrue(breakpoint.IsValid() and breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT) + breakpoint = target.BreakpointCreateBySourceRegex( + "break here", src_file_spec) + self.assertTrue( + breakpoint.IsValid() and breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) thread.StepInto() # Get frame for current thread frame = thread.GetSelectedFrame() v1 = frame.EvaluateExpression("1") - self.assertTrue(v1.IsValid(), "'expr 1' results in a valid SBValue object") - self.assertTrue(v1.GetError().Success(), "'expr 1' succeeds without an error.") + self.assertTrue( + v1.IsValid(), + "'expr 1' results in a valid SBValue object") + self.assertTrue( + v1.GetError().Success(), + "'expr 1' succeeds without an error.") v2 = frame.EvaluateExpression("this") - self.assertTrue(v2.IsValid(), "'expr this' results in a valid SBValue object") - self.assertTrue(v2.GetError().Success(), "'expr this' succeeds without an error.") + self.assertTrue( + v2.IsValid(), + "'expr this' results in a valid SBValue object") + self.assertTrue( + v2.GetError().Success(), + "'expr this' succeeds without an error.") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py index 12fc4c23637..977ad7ddea1 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py @@ -2,6 +2,7 @@ import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class TestMembersAndLocalsWithSameName(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -10,77 +11,101 @@ class TestMembersAndLocalsWithSameName(TestBase): self._load_exe() # Set breakpoints - bp1 = self.target.BreakpointCreateBySourceRegex("Break 1", self.src_file_spec) - self.assertTrue(bp1.IsValid() and bp1.GetNumLocations() >= 1, VALID_BREAKPOINT) - bp2 = self.target.BreakpointCreateBySourceRegex("Break 2", self.src_file_spec) - self.assertTrue(bp2.IsValid() and bp2.GetNumLocations() >= 1, VALID_BREAKPOINT) - bp3 = self.target.BreakpointCreateBySourceRegex("Break 3", self.src_file_spec) - self.assertTrue(bp3.IsValid() and bp3.GetNumLocations() >= 1, VALID_BREAKPOINT) - bp4 = self.target.BreakpointCreateBySourceRegex("Break 4", self.src_file_spec) - self.assertTrue(bp4.IsValid() and bp4.GetNumLocations() >= 1, VALID_BREAKPOINT) + bp1 = self.target.BreakpointCreateBySourceRegex( + "Break 1", self.src_file_spec) + self.assertTrue( + bp1.IsValid() and bp1.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp2 = self.target.BreakpointCreateBySourceRegex( + "Break 2", self.src_file_spec) + self.assertTrue( + bp2.IsValid() and bp2.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp3 = self.target.BreakpointCreateBySourceRegex( + "Break 3", self.src_file_spec) + self.assertTrue( + bp3.IsValid() and bp3.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp4 = self.target.BreakpointCreateBySourceRegex( + "Break 4", self.src_file_spec) + self.assertTrue( + bp4.IsValid() and bp4.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process - self.process = self.target.LaunchSimple(None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process.IsValid(), PROCESS_IS_VALID) - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) self._test_globals() self.process.Continue() - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("a"); + val = frame.EvaluateExpression("a") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 12345) - val = frame.EvaluateExpression("b"); + val = frame.EvaluateExpression("b") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 54321) - val = frame.EvaluateExpression("c"); + val = frame.EvaluateExpression("c") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 34567) self.process.Continue() - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("a"); + val = frame.EvaluateExpression("a") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 10001) - val = frame.EvaluateExpression("b"); + val = frame.EvaluateExpression("b") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 10002) - val = frame.EvaluateExpression("c"); + val = frame.EvaluateExpression("c") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 10003) self.process.Continue() - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("a"); + val = frame.EvaluateExpression("a") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 1) - val = frame.EvaluateExpression("b"); + val = frame.EvaluateExpression("b") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 2) - val = frame.EvaluateExpression("c"); + val = frame.EvaluateExpression("c") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 778899) @@ -88,77 +113,101 @@ class TestMembersAndLocalsWithSameName(TestBase): self._load_exe() # Set breakpoints - bp1 = self.target.BreakpointCreateBySourceRegex("Break 1", self.src_file_spec) - self.assertTrue(bp1.IsValid() and bp1.GetNumLocations() >= 1, VALID_BREAKPOINT) - bp5 = self.target.BreakpointCreateBySourceRegex("Break 5", self.src_file_spec) - self.assertTrue(bp5.IsValid() and bp5.GetNumLocations() >= 1, VALID_BREAKPOINT) - bp6 = self.target.BreakpointCreateBySourceRegex("Break 6", self.src_file_spec) - self.assertTrue(bp6.IsValid() and bp6.GetNumLocations() >= 1, VALID_BREAKPOINT) - bp7 = self.target.BreakpointCreateBySourceRegex("Break 7", self.src_file_spec) - self.assertTrue(bp7.IsValid() and bp7.GetNumLocations() >= 1, VALID_BREAKPOINT) + bp1 = self.target.BreakpointCreateBySourceRegex( + "Break 1", self.src_file_spec) + self.assertTrue( + bp1.IsValid() and bp1.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp5 = self.target.BreakpointCreateBySourceRegex( + "Break 5", self.src_file_spec) + self.assertTrue( + bp5.IsValid() and bp5.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp6 = self.target.BreakpointCreateBySourceRegex( + "Break 6", self.src_file_spec) + self.assertTrue( + bp6.IsValid() and bp6.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp7 = self.target.BreakpointCreateBySourceRegex( + "Break 7", self.src_file_spec) + self.assertTrue( + bp7.IsValid() and bp7.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process - self.process = self.target.LaunchSimple(None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process.IsValid(), PROCESS_IS_VALID) - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) self._test_globals() self.process.Continue() - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("a"); + val = frame.EvaluateExpression("a") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 12345) - val = frame.EvaluateExpression("b"); + val = frame.EvaluateExpression("b") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 54321) - val = frame.EvaluateExpression("c"); + val = frame.EvaluateExpression("c") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 34567) self.process.Continue() - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("a"); + val = frame.EvaluateExpression("a") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 10001) - val = frame.EvaluateExpression("b"); + val = frame.EvaluateExpression("b") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 10002) - val = frame.EvaluateExpression("c"); + val = frame.EvaluateExpression("c") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 10003) self.process.Continue() - self.assertTrue(self.process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("a"); + val = frame.EvaluateExpression("a") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 1) - val = frame.EvaluateExpression("b"); + val = frame.EvaluateExpression("b") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 2) - val = frame.EvaluateExpression("c"); + val = frame.EvaluateExpression("c") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 778899) @@ -172,26 +221,27 @@ class TestMembersAndLocalsWithSameName(TestBase): self.assertTrue(self.src_file_spec.IsValid(), "breakpoint file") # Get the path of the executable - exe_path = os.path.join(cwd, 'a.out') + exe_path = os.path.join(cwd, 'a.out') # Load the executable self.target = self.dbg.CreateTarget(exe_path) self.assertTrue(self.target.IsValid(), VALID_TARGET) def _test_globals(self): - thread = lldbutil.get_stopped_thread(self.process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) self.assertTrue(thread.IsValid()) frame = thread.GetSelectedFrame() self.assertTrue(frame.IsValid()) - val = frame.EvaluateExpression("a"); + val = frame.EvaluateExpression("a") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 112233) - val = frame.EvaluateExpression("b"); + val = frame.EvaluateExpression("b") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 445566) - val = frame.EvaluateExpression("c"); + val = frame.EvaluateExpression("c") self.assertTrue(val.IsValid()) self.assertEqual(val.GetValueAsUnsigned(), 778899) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py index 93d53c7de71..5c0d3fc9cc3 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py @@ -5,13 +5,14 @@ Test the printing of anonymous and named namespace variables. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NamespaceBreakpointTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,7 +22,12 @@ class NamespaceBreakpointTestCase(TestBase): """Test that we can set breakpoints correctly by basename to find all functions whose basename is "func".""" self.build() - names = [ "func()", "func(int)", "A::B::func()", "A::func()", "A::func(int)"] + names = [ + "func()", + "func(int)", + "A::B::func()", + "A::func()", + "A::func(int)"] # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") @@ -30,11 +36,15 @@ class NamespaceBreakpointTestCase(TestBase): module_list = lldb.SBFileSpecList() module_list.Append(lldb.SBFileSpec(exe, False)) cu_list = lldb.SBFileSpecList() - # Set a breakpoint by name "func" which should pick up all functions whose basename is "func" - bp = target.BreakpointCreateByName ("func", lldb.eFunctionNameTypeAuto, module_list, cu_list); + # Set a breakpoint by name "func" which should pick up all functions + # whose basename is "func" + bp = target.BreakpointCreateByName( + "func", lldb.eFunctionNameTypeAuto, module_list, cu_list) for bp_loc in bp: name = bp_loc.GetAddress().GetFunction().GetName() - self.assertTrue(name in names, "make sure breakpoint locations are correct for 'func' with eFunctionNameTypeAuto") + self.assertTrue( + name in names, + "make sure breakpoint locations are correct for 'func' with eFunctionNameTypeAuto") @expectedFailureAll(bugnumber="llvm.org/pr28548", compiler="gcc") def test_breakpoints_func_full(self): @@ -42,7 +52,7 @@ class NamespaceBreakpointTestCase(TestBase): (no namespaces).""" self.build() - names = [ "func()", "func(int)"] + names = ["func()", "func(int)"] # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") @@ -52,18 +62,22 @@ class NamespaceBreakpointTestCase(TestBase): module_list.Append(lldb.SBFileSpec(exe, False)) cu_list = lldb.SBFileSpecList() - # Set a breakpoint by name "func" whose fullly qualified named matches "func" which - # should pick up only functions whose basename is "func" and has no containing context - bp = target.BreakpointCreateByName ("func", lldb.eFunctionNameTypeFull, module_list, cu_list); + # Set a breakpoint by name "func" whose fullly qualified named matches "func" which + # should pick up only functions whose basename is "func" and has no + # containing context + bp = target.BreakpointCreateByName( + "func", lldb.eFunctionNameTypeFull, module_list, cu_list) for bp_loc in bp: name = bp_loc.GetAddress().GetFunction().GetName() - self.assertTrue(name in names, "make sure breakpoint locations are correct for 'func' with eFunctionNameTypeFull") + self.assertTrue( + name in names, + "make sure breakpoint locations are correct for 'func' with eFunctionNameTypeFull") def test_breakpoints_a_func_full(self): """Test that we can set breakpoints correctly by fullname to find all functions whose fully qualified name is "A::func".""" self.build() - names = [ "A::func()", "A::func(int)"] + names = ["A::func()", "A::func(int)"] # Create a target by the debugger. exe = os.path.join(os.getcwd(), "a.out") @@ -73,12 +87,16 @@ class NamespaceBreakpointTestCase(TestBase): module_list.Append(lldb.SBFileSpec(exe, False)) cu_list = lldb.SBFileSpecList() - # Set a breakpoint by name "A::func" whose fullly qualified named matches "A::func" which - # should pick up only functions whose basename is "func" and is contained in the "A" namespace - bp = target.BreakpointCreateByName ("A::func", lldb.eFunctionNameTypeFull, module_list, cu_list); + # Set a breakpoint by name "A::func" whose fullly qualified named matches "A::func" which + # should pick up only functions whose basename is "func" and is + # contained in the "A" namespace + bp = target.BreakpointCreateByName( + "A::func", lldb.eFunctionNameTypeFull, module_list, cu_list) for bp_loc in bp: name = bp_loc.GetAddress().GetFunction().GetName() - self.assertTrue(name in names, "make sure breakpoint locations are correct for 'A::func' with eFunctionNameTypeFull") + self.assertTrue( + name in names, + "make sure breakpoint locations are correct for 'A::func' with eFunctionNameTypeFull") class NamespaceTestCase(TestBase): @@ -88,14 +106,15 @@ class NamespaceTestCase(TestBase): def setUp(self): # Call super's setUp(). TestBase.setUp(self) - # Find the line numbers for declarations of namespace variables i and j. - self.line_var_i = line_number('main.cpp', - '// Find the line number for anonymous namespace variable i.') - self.line_var_j = line_number('main.cpp', - '// Find the line number for named namespace variable j.') + # Find the line numbers for declarations of namespace variables i and + # j. + self.line_var_i = line_number( + 'main.cpp', '// Find the line number for anonymous namespace variable i.') + self.line_var_j = line_number( + 'main.cpp', '// Find the line number for named namespace variable j.') # And the line number to break at. self.line_break = line_number('main.cpp', - '// Set break point at this line.') + '// Set break point at this line.') # Break inside do {} while and evaluate value self.line_break_ns1 = line_number('main.cpp', '// Evaluate ns1::value') self.line_break_ns2 = line_number('main.cpp', '// Evaluate ns2::value') @@ -104,8 +123,8 @@ class NamespaceTestCase(TestBase): self.runCmd(command, RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # rdar://problem/8668674 @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") @@ -114,22 +133,39 @@ class NamespaceTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line_break_ns1, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line_break_ns2, num_expected_locations=1, loc_exact=True) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line_break, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line_break_ns1, + num_expected_locations=1, + loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line_break_ns2, + num_expected_locations=1, + loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line_break, + num_expected_locations=1, + loc_exact=True) self.runToBkpt("run") # Evaluate ns1::value - self.expect("expression -- value", startstr = "(int) $0 = 100") + self.expect("expression -- value", startstr="(int) $0 = 100") self.runToBkpt("continue") # Evaluate ns2::value - self.expect("expression -- value", startstr = "(int) $1 = 200") - + self.expect("expression -- value", startstr="(int) $1 = 200") + self.runToBkpt("continue") - # On Mac OS X, gcc 4.2 emits the wrong debug info with respect to types. + # On Mac OS X, gcc 4.2 emits the wrong debug info with respect to + # types. slist = ['(int) a = 12', 'anon_uint', 'a_uint', 'b_uint', 'y_uint'] - if self.platformIsDarwin() and self.getCompiler() in ['clang', 'llvm-gcc']: + if self.platformIsDarwin() and self.getCompiler() in [ + 'clang', 'llvm-gcc']: slist = ['(int) a = 12', '::my_uint_t', 'anon_uint = 0', '(A::uint_t) a_uint = 1', @@ -138,16 +174,20 @@ class NamespaceTestCase(TestBase): # 'frame variable' displays the local variables with type information. self.expect('frame variable', VARIABLES_DISPLAYED_CORRECTLY, - substrs = slist) + substrs=slist) # 'frame variable' with basename 'i' should work. - self.expect("frame variable --show-declaration --show-globals i", - startstr = "main.cpp:%d: (int) (anonymous namespace)::i = 3" % self.line_var_i) + self.expect( + "frame variable --show-declaration --show-globals i", + startstr="main.cpp:%d: (int) (anonymous namespace)::i = 3" % + self.line_var_i) # main.cpp:12: (int) (anonymous namespace)::i = 3 # 'frame variable' with basename 'j' should work, too. - self.expect("frame variable --show-declaration --show-globals j", - startstr = "main.cpp:%d: (int) A::B::j = 4" % self.line_var_j) + self.expect( + "frame variable --show-declaration --show-globals j", + startstr="main.cpp:%d: (int) A::B::j = 4" % + self.line_var_j) # main.cpp:19: (int) A::B::j = 4 # 'frame variable' should support address-of operator. @@ -155,41 +195,44 @@ class NamespaceTestCase(TestBase): # 'frame variable' with fully qualified name 'A::B::j' should work. self.expect("frame variable A::B::j", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int) A::B::j = 4', - patterns = [' = 4']) + startstr='(int) A::B::j = 4', + patterns=[' = 4']) # So should the anonymous namespace case. - self.expect("frame variable '(anonymous namespace)::i'", VARIABLES_DISPLAYED_CORRECTLY, - startstr = '(int) (anonymous namespace)::i = 3', - patterns = [' = 3']) + self.expect( + "frame variable '(anonymous namespace)::i'", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) (anonymous namespace)::i = 3', + patterns=[' = 3']) # rdar://problem/8660275 # test/namespace: 'expression -- i+j' not working # This has been fixed. self.expect("expression -- i + j", - startstr = "(int) $2 = 7") + startstr="(int) $2 = 7") # (int) $2 = 7 self.runCmd("expression -- i") self.runCmd("expression -- j") # rdar://problem/8668674 - # expression command with fully qualified namespace for a variable does not work + # expression command with fully qualified namespace for a variable does + # not work self.expect("expression -- ::i", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [' = 3']) + patterns=[' = 3']) self.expect("expression -- A::B::j", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [' = 4']) + patterns=[' = 4']) # expression command with function in anonymous namespace self.expect("expression -- myanonfunc(3)", - patterns = [' = 6']) + patterns=[' = 6']) # global namespace qualification with function in anonymous namespace self.expect("expression -- ::myanonfunc(4)", - patterns = [' = 8']) + patterns=[' = 8']) self.expect("p myanonfunc", - patterns = ['\(anonymous namespace\)::myanonfunc\(int\)']) + patterns=['\(anonymous namespace\)::myanonfunc\(int\)']) - self.expect("p variadic_sum", - patterns = ['\(anonymous namespace\)::variadic_sum\(int, ...\)']) + self.expect("p variadic_sum", patterns=[ + '\(anonymous namespace\)::variadic_sum\(int, ...\)']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py index 12e8eef40cf..18e45d9798a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py @@ -5,12 +5,14 @@ Test the printing of anonymous and named namespace variables. from __future__ import print_function -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class NamespaceLookupTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,88 +21,131 @@ class NamespaceLookupTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Break inside different scopes and evaluate value - self.line_break_global_scope = line_number('ns.cpp', '// BP_global_scope') + self.line_break_global_scope = line_number( + 'ns.cpp', '// BP_global_scope') self.line_break_file_scope = line_number('ns2.cpp', '// BP_file_scope') self.line_break_ns_scope = line_number('ns2.cpp', '// BP_ns_scope') - self.line_break_nested_ns_scope = line_number('ns2.cpp', '// BP_nested_ns_scope') - self.line_break_nested_ns_scope_after_using = line_number('ns2.cpp', '// BP_nested_ns_scope_after_using') - self.line_break_before_using_directive = line_number('ns3.cpp', '// BP_before_using_directive') - self.line_break_after_using_directive = line_number('ns3.cpp', '// BP_after_using_directive') + self.line_break_nested_ns_scope = line_number( + 'ns2.cpp', '// BP_nested_ns_scope') + self.line_break_nested_ns_scope_after_using = line_number( + 'ns2.cpp', '// BP_nested_ns_scope_after_using') + self.line_break_before_using_directive = line_number( + 'ns3.cpp', '// BP_before_using_directive') + self.line_break_after_using_directive = line_number( + 'ns3.cpp', '// BP_after_using_directive') def runToBkpt(self, command): self.runCmd(command, RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - - @expectedFailureAll(oslist=["windows", "linux", "freebsd"], bugnumber="llvm.org/pr25819") + substrs=['stopped', + 'stop reason = breakpoint']) + + @expectedFailureAll( + oslist=[ + "windows", + "linux", + "freebsd"], + bugnumber="llvm.org/pr25819") def test_scope_lookup_with_run_command(self): """Test scope lookup of functions in lldb.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False) - lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False) - lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False) - lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False) - lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False) - lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns.cpp", + self.line_break_global_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_ns_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope_after_using, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_before_using_directive, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_after_using_directive, + num_expected_locations=1, + loc_exact=False) # Run to BP_global_scope at global scope self.runToBkpt("run") # Evaluate func() - should call ::func() - self.expect("expr -- func()", startstr = "(int) $0 = 1") + self.expect("expr -- func()", startstr="(int) $0 = 1") # Evaluate A::B::func() - should call A::B::func() - self.expect("expr -- A::B::func()", startstr = "(int) $1 = 4") + self.expect("expr -- A::B::func()", startstr="(int) $1 = 4") # Evaluate func(10) - should call ::func(int) - self.expect("expr -- func(10)", startstr = "(int) $2 = 11") + self.expect("expr -- func(10)", startstr="(int) $2 = 11") # Evaluate ::func() - should call A::func() - self.expect("expr -- ::func()", startstr = "(int) $3 = 1") + self.expect("expr -- ::func()", startstr="(int) $3 = 1") # Evaluate A::foo() - should call A::foo() - self.expect("expr -- A::foo()", startstr = "(int) $4 = 42") + self.expect("expr -- A::foo()", startstr="(int) $4 = 42") # Continue to BP_ns_scope at ns scope self.runToBkpt("continue") # Evaluate func(10) - should call A::func(int) - self.expect("expr -- func(10)", startstr = "(int) $5 = 13") + self.expect("expr -- func(10)", startstr="(int) $5 = 13") # Evaluate B::func() - should call B::func() - self.expect("expr -- B::func()", startstr = "(int) $6 = 4") + self.expect("expr -- B::func()", startstr="(int) $6 = 4") # Evaluate func() - should call A::func() - self.expect("expr -- func()", startstr = "(int) $7 = 3") + self.expect("expr -- func()", startstr="(int) $7 = 3") # Continue to BP_nested_ns_scope at nested ns scope self.runToBkpt("continue") # Evaluate func() - should call A::B::func() - self.expect("expr -- func()", startstr = "(int) $8 = 4") + self.expect("expr -- func()", startstr="(int) $8 = 4") # Evaluate A::func() - should call A::func() - self.expect("expr -- A::func()", startstr = "(int) $9 = 3") + self.expect("expr -- A::func()", startstr="(int) $9 = 3") # Evaluate func(10) - should call A::func(10) # NOTE: Under the rules of C++, this test would normally get an error # because A::B::func() hides A::func(), but lldb intentionally # disobeys these rules so that the intended overload can be found # by only removing duplicates if they have the same type. - self.expect("expr -- func(10)", startstr = "(int) $10 = 13") + self.expect("expr -- func(10)", startstr="(int) $10 = 13") - # Continue to BP_nested_ns_scope_after_using at nested ns scope after using declaration + # Continue to BP_nested_ns_scope_after_using at nested ns scope after + # using declaration self.runToBkpt("continue") # Evaluate A::func(10) - should call A::func(int) - self.expect("expr -- A::func(10)", startstr = "(int) $11 = 13") + self.expect("expr -- A::func(10)", startstr="(int) $11 = 13") - # Continue to BP_before_using_directive at global scope before using declaration + # Continue to BP_before_using_directive at global scope before using + # declaration self.runToBkpt("continue") # Evaluate ::func() - should call ::func() - self.expect("expr -- ::func()", startstr = "(int) $12 = 1") + self.expect("expr -- ::func()", startstr="(int) $12 = 1") # Evaluate B::func() - should call B::func() - self.expect("expr -- B::func()", startstr = "(int) $13 = 4") + self.expect("expr -- B::func()", startstr="(int) $13 = 4") - # Continue to BP_after_using_directive at global scope after using declaration + # Continue to BP_after_using_directive at global scope after using + # declaration self.runToBkpt("continue") # Evaluate ::func() - should call ::func() - self.expect("expr -- ::func()", startstr = "(int) $14 = 1") + self.expect("expr -- ::func()", startstr="(int) $14 = 1") # Evaluate B::func() - should call B::func() - self.expect("expr -- B::func()", startstr = "(int) $15 = 4") + self.expect("expr -- B::func()", startstr="(int) $15 = 4") @unittest2.expectedFailure("lldb scope lookup of functions bugs") def test_function_scope_lookup_with_run_command(self): @@ -108,26 +153,36 @@ class NamespaceLookupTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False) - lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns.cpp", + self.line_break_global_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_ns_scope, + num_expected_locations=1, + loc_exact=False) # Run to BP_global_scope at global scope self.runToBkpt("run") # Evaluate foo() - should call ::foo() # FIXME: lldb finds Y::foo because lookup for variables is done # before functions. - self.expect("expr -- foo()", startstr = "(int) $0 = 42") + self.expect("expr -- foo()", startstr="(int) $0 = 42") # Evaluate ::foo() - should call ::foo() # FIXME: lldb finds Y::foo because lookup for variables is done # before functions and :: is ignored. - self.expect("expr -- ::foo()", startstr = "(int) $1 = 42") + self.expect("expr -- ::foo()", startstr="(int) $1 = 42") # Continue to BP_ns_scope at ns scope self.runToBkpt("continue") # Evaluate foo() - should call A::foo() # FIXME: lldb finds Y::foo because lookup for variables is done # before functions. - self.expect("expr -- foo()", startstr = "(int) $2 = 42") + self.expect("expr -- foo()", startstr="(int) $2 = 42") @unittest2.expectedFailure("lldb file scope lookup bugs") def test_file_scope_lookup_with_run_command(self): @@ -135,14 +190,19 @@ class NamespaceLookupTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_file_scope, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_file_scope, + num_expected_locations=1, + loc_exact=False) # Run to BP_file_scope at file scope self.runToBkpt("run") # Evaluate func() - should call static ns2.cpp:func() # FIXME: This test fails because lldb doesn't know about file scopes so # finds the global ::func(). - self.expect("expr -- func()", startstr = "(int) $0 = 2") + self.expect("expr -- func()", startstr="(int) $0 = 2") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr25819") def test_scope_lookup_before_using_with_run_command(self): @@ -150,30 +210,51 @@ class NamespaceLookupTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_before_using_directive, + num_expected_locations=1, + loc_exact=False) - # Run to BP_before_using_directive at global scope before using declaration + # Run to BP_before_using_directive at global scope before using + # declaration self.runToBkpt("run") # Evaluate func() - should call ::func() - self.expect("expr -- func()", startstr = "(int) $0 = 1") + self.expect("expr -- func()", startstr="(int) $0 = 1") # NOTE: this test may fail on older systems that don't emit import # entries in DWARF - may need to add checks for compiler versions here. - @skipIf(compiler="gcc", oslist=["linux"], debug_info=["dwo"]) # Skip to avoid crash - @expectedFailureAll(oslist=["windows", "linux", "freebsd"], bugnumber="llvm.org/pr25819") + @skipIf( + compiler="gcc", + oslist=["linux"], + debug_info=["dwo"]) # Skip to avoid crash + @expectedFailureAll( + oslist=[ + "windows", + "linux", + "freebsd"], + bugnumber="llvm.org/pr25819") def test_scope_after_using_directive_lookup_with_run_command(self): """Test scope lookup after using directive in lldb.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_after_using_directive, + num_expected_locations=1, + loc_exact=False) - # Run to BP_after_using_directive at global scope after using declaration + # Run to BP_after_using_directive at global scope after using + # declaration self.runToBkpt("run") # Evaluate func2() - should call A::func2() - self.expect("expr -- func2()", startstr = "(int) $0 = 3") + self.expect("expr -- func2()", startstr="(int) $0 = 3") - @unittest2.expectedFailure("lldb scope lookup after using declaration bugs") + @unittest2.expectedFailure( + "lldb scope lookup after using declaration bugs") # NOTE: this test may fail on older systems that don't emit import # emtries in DWARF - may need to add checks for compiler versions here. def test_scope_after_using_declaration_lookup_with_run_command(self): @@ -181,12 +262,18 @@ class NamespaceLookupTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope_after_using, + num_expected_locations=1, + loc_exact=False) - # Run to BP_nested_ns_scope_after_using at nested ns scope after using declaration + # Run to BP_nested_ns_scope_after_using at nested ns scope after using + # declaration self.runToBkpt("run") # Evaluate func() - should call A::func() - self.expect("expr -- func()", startstr = "(int) $0 = 3") + self.expect("expr -- func()", startstr="(int) $0 = 3") @unittest2.expectedFailure("lldb scope lookup ambiguity after using bugs") def test_scope_ambiguity_after_using_lookup_with_run_command(self): @@ -194,22 +281,38 @@ class NamespaceLookupTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_after_using_directive, + num_expected_locations=1, + loc_exact=False) - # Run to BP_after_using_directive at global scope after using declaration + # Run to BP_after_using_directive at global scope after using + # declaration self.runToBkpt("run") # Evaluate func() - should get error: ambiguous # FIXME: This test fails because lldb removes duplicates if they have # the same type. - self.expect("expr -- func()", startstr = "error") - - @expectedFailureAll(oslist=["windows", "linux", "freebsd"], bugnumber="llvm.org/pr25819") + self.expect("expr -- func()", startstr="error") + + @expectedFailureAll( + oslist=[ + "windows", + "linux", + "freebsd"], + bugnumber="llvm.org/pr25819") def test_scope_lookup_shadowed_by_using_with_run_command(self): """Test scope lookup shadowed by using in lldb.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope, + num_expected_locations=1, + loc_exact=False) # Run to BP_nested_ns_scope at nested ns scope self.runToBkpt("run") @@ -218,5 +321,4 @@ class NamespaceLookupTestCase(TestBase): # because A::B::func() shadows A::func(), but lldb intentionally # disobeys these rules so that the intended overload can be found # by only removing duplicates if they have the same type. - self.expect("expr -- func(10)", startstr = "(int) $0 = 13") - + self.expect("expr -- func(10)", startstr="(int) $0 = 13") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/TestNamespaceDefinitions.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/TestNamespaceDefinitions.py index f4dd098f106..43f9003eadb 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/TestNamespaceDefinitions.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/TestNamespaceDefinitions.py @@ -3,24 +3,31 @@ from __future__ import print_function - import unittest2 import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil + class NamespaceDefinitionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(bugnumber="llvm.org/pr28948", compiler="gcc", compiler_version=["<", "4.9"]) + @expectedFailureAll( + bugnumber="llvm.org/pr28948", + compiler="gcc", + compiler_version=[ + "<", + "4.9"]) def test_expr(self): self.build() self.common_setup() - self.expect("expression -- Foo::MyClass()", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ['thing = ']) + self.expect( + "expression -- Foo::MyClass()", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['thing = ']) def setUp(self): # Call super's setUp(). @@ -29,7 +36,7 @@ class NamespaceDefinitionsTestCase(TestBase): self.source = 'main.cpp' self.line = line_number(self.source, '// Set breakpoint here') self.shlib_names = ["a", "b"] - + def common_setup(self): # Run in synchronous mode self.dbg.SetAsync(False) @@ -39,21 +46,24 @@ class NamespaceDefinitionsTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) - # Register our shared libraries for remote targets so they get automatically uploaded - environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names) + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) - + substrs=[' resolved, hit count = 1']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py index d66d2ac530e..878cc4fd4f7 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py @@ -6,6 +6,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCppNsImport(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,79 +24,116 @@ class TestCppNsImport(TestBase): # Get the path of the executable cwd = os.getcwd() exe_file = "a.out" - exe_path = os.path.join(cwd, exe_file) + exe_path = os.path.join(cwd, exe_file) # Load the executable target = self.dbg.CreateTarget(exe_path) self.assertTrue(target.IsValid(), VALID_TARGET) # Break on main function - break_0 = target.BreakpointCreateBySourceRegex("// break 0", src_file_spec) - self.assertTrue(break_0.IsValid() and break_0.GetNumLocations() >= 1, VALID_BREAKPOINT) - break_1 = target.BreakpointCreateBySourceRegex("// break 1", src_file_spec) - self.assertTrue(break_1.IsValid() and break_1.GetNumLocations() >= 1, VALID_BREAKPOINT) + break_0 = target.BreakpointCreateBySourceRegex( + "// break 0", src_file_spec) + self.assertTrue( + break_0.IsValid() and break_0.GetNumLocations() >= 1, + VALID_BREAKPOINT) + break_1 = target.BreakpointCreateBySourceRegex( + "// break 1", src_file_spec) + self.assertTrue( + break_1.IsValid() and break_1.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process args = None env = None - process = target.LaunchSimple(args, env, self.get_process_working_directory()) + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) # Get current fream of the thread at the breakpoint frame = thread.GetSelectedFrame() # Test imported namespaces test_result = frame.EvaluateExpression("n") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 1, "n = 1") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 1, + "n = 1") test_result = frame.EvaluateExpression("N::n") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 1, "N::n = 1") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 1, + "N::n = 1") test_result = frame.EvaluateExpression("nested") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 3, "nested = 3") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 3, + "nested = 3") test_result = frame.EvaluateExpression("anon") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 2, "anon = 2") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 2, + "anon = 2") test_result = frame.EvaluateExpression("global") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 4, "global = 4") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 4, + "global = 4") test_result = frame.EvaluateExpression("fun_var") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 9, "fun_var = 9") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 9, + "fun_var = 9") test_result = frame.EvaluateExpression("Fun::fun_var") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 0, "Fun::fun_var = 0") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 0, + "Fun::fun_var = 0") test_result = frame.EvaluateExpression("not_imported") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 35, "not_imported = 35") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 35, + "not_imported = 35") # Currently there is no way to distinguish between "::imported" and "imported" in ClangExpressionDeclMap so this fails #test_result = frame.EvaluateExpression("::imported") #self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 89, "::imported = 89") test_result = frame.EvaluateExpression("Imported::imported") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 99, "Imported::imported = 99") - + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 99, + "Imported::imported = 99") + test_result = frame.EvaluateExpression("imported") - self.assertTrue(test_result.IsValid() and test_result.GetError().Fail(), "imported is ambiguous") + self.assertTrue( + test_result.IsValid() and test_result.GetError().Fail(), + "imported is ambiguous") test_result = frame.EvaluateExpression("single") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 3, "single = 3") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 3, + "single = 3") # Continue to second breakpoint process.Continue() # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) # Get current fream of the thread at the breakpoint frame = thread.GetSelectedFrame() # Test function inside namespace test_result = frame.EvaluateExpression("fun_var") - self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 5, "fun_var = 5") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 5, + "fun_var = 5") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py index ff00d99d776..3d8788fa790 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py @@ -7,31 +7,35 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CPPStaticMethodsTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def setUp(self): TestBase.setUp(self) self.line = line_number('main.cpp', '// breakpoint') - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_with_run_command(self): """Test that functions with the same name are resolved correctly""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("process launch", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) self.expect("expression -- Dump(myB)", - startstr = "(int) $0 = 2") + startstr="(int) $0 = 2") self.expect("expression -- Static()", - startstr = "(int) $1 = 1") + startstr="(int) $1 = 1") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/TestPrintf.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/TestPrintf.py index 2a2c673f867..38ebe1a9a9c 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/TestPrintf.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/TestPrintf.py @@ -1,4 +1,7 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.expectedFailureAll(bugnumber="rdar://problem/24599697")] ) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + bugnumber="rdar://problem/24599697")]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py index 78a2727094a..11d221e171a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py @@ -7,13 +7,18 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class RvalueReferencesTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - - #rdar://problem/11479676 - @expectedFailureAll(compiler="icc", bugnumber="ICC (13.1, 14-beta) do not emit DW_TAG_rvalue_reference_type.") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + + # rdar://problem/11479676 + @expectedFailureAll( + compiler="icc", + bugnumber="ICC (13.1, 14-beta) do not emit DW_TAG_rvalue_reference_type.") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_with_run_command(self): """Test that rvalues are supported in the C++ expression parser""" self.build() @@ -27,24 +32,25 @@ class RvalueReferencesTestCase(TestBase): # Note that clang as of r187480 doesn't emit DW_TAG_const_type, unlike gcc 4.8.1 # With gcc 4.8.1, lldb reports the type as (int &&const) self.expect("frame variable i", - startstr = "(int &&", - substrs = ["i = 0x", "&i = 3"]) + startstr="(int &&", + substrs=["i = 0x", "&i = 3"]) self.expect("expression -- i", - startstr = "(int) ", - substrs = ["3"]) + startstr="(int) ", + substrs=["3"]) self.expect("breakpoint delete 1") self.runCmd("process continue") - + self.expect("expression -- foo(2)") self.expect("expression -- int &&j = 3; foo(j)", - error = True) + error=True) self.expect("expression -- int &&k = 6; k", - startstr = "(int) $1 = 6") + startstr="(int) $1 = 6") def set_breakpoint(self, line): - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=True) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py index d075eb65b84..ca6b27f1727 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py @@ -6,6 +6,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestCppScopes(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,25 +24,32 @@ class TestCppScopes(TestBase): # Get the path of the executable cwd = os.getcwd() exe_file = "a.out" - exe_path = os.path.join(cwd, exe_file) + exe_path = os.path.join(cwd, exe_file) # Load the executable target = self.dbg.CreateTarget(exe_path) self.assertTrue(target.IsValid(), VALID_TARGET) # Break on main function - main_breakpoint = target.BreakpointCreateBySourceRegex("// break here", src_file_spec) - self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT) + main_breakpoint = target.BreakpointCreateBySourceRegex( + "// break here", src_file_spec) + self.assertTrue( + main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) # Launch the process args = None env = None - process = target.LaunchSimple(args, env, self.get_process_working_directory()) + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) self.assertTrue(process.IsValid(), PROCESS_IS_VALID) # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) # Get current fream of the thread at the breakpoint frame = thread.GetSelectedFrame() @@ -57,12 +65,18 @@ class TestCppScopes(TestBase): 'a': 4444 } - self.assertTrue(global_variables.GetSize() == 4, "target variable returns all variables") + self.assertTrue( + global_variables.GetSize() == 4, + "target variable returns all variables") for variable in global_variables: name = variable.GetName() - self.assertTrue(name in global_variables_assert, "target variable returns wrong variable " + name) + self.assertTrue( + name in global_variables_assert, + "target variable returns wrong variable " + name) for name in global_variables_assert: value = frame.EvaluateExpression(name) assert_value = global_variables_assert[name] - self.assertTrue(value.IsValid() and value.GetValueAsSigned() == assert_value, name + " = " + str(assert_value)) + self.assertTrue( + value.IsValid() and value.GetValueAsSigned() == assert_value, + name + " = " + str(assert_value)) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py index 3158c4c5bcf..5925b10143e 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py @@ -5,13 +5,14 @@ Test that variables with signed types display correctly. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class SignedTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,7 +22,8 @@ class SignedTypesTestCase(TestBase): TestBase.setUp(self) # Find the line number to break inside main(). self.source = 'main.cpp' - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') def test(self): """Test that variables with signed types display correctly.""" @@ -34,27 +36,33 @@ class SignedTypesTestCase(TestBase): target = self.dbg.CreateTarget("a.out") self.assertTrue(target, VALID_TARGET) - lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Execute the puts(). self.runCmd("thread step-over") # Test that signed types display correctly. - self.expect("frame variable --show-types --no-args", VARIABLES_DISPLAYED_CORRECTLY, - patterns = ["\((short int|short)\) the_signed_short = 99", - "\((signed char|char)\) the_signed_char = 'c'"], - substrs = ["(int) the_signed_int = 99", - "(long) the_signed_long = 99", - "(long long) the_signed_long_long = 99"]) + self.expect( + "frame variable --show-types --no-args", + VARIABLES_DISPLAYED_CORRECTLY, + patterns=[ + "\((short int|short)\) the_signed_short = 99", + "\((signed char|char)\) the_signed_char = 'c'"], + substrs=[ + "(int) the_signed_int = 99", + "(long) the_signed_long = 99", + "(long long) the_signed_long_long = 99"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py index dd220d90527..16b56758816 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py @@ -5,18 +5,18 @@ Tests that C++ member and static variables have correct layout and scope. from __future__ import print_function - import unittest2 import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CPPStaticMembersTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - - @unittest2.expectedFailure # llvm.org/pr15401 + + @unittest2.expectedFailure # llvm.org/pr15401 @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") def test_with_run_command(self): """Test that member variables have the correct layout, scope and qualifiers when stopped inside and outside C++ methods""" @@ -28,33 +28,35 @@ class CPPStaticMembersTestCase(TestBase): self.runCmd("process launch", RUN_SUCCEEDED) self.expect("expression my_a.access()", - startstr = "(long) $0 = 10") - + startstr="(long) $0 = 10") + self.expect("expression my_a.m_a", - startstr = "(short) $1 = 1") - - # Note: SymbolFileDWARF::ParseChildMembers doesn't call AddFieldToRecordType, consistent with clang's AST layout. + startstr="(short) $1 = 1") + + # Note: SymbolFileDWARF::ParseChildMembers doesn't call + # AddFieldToRecordType, consistent with clang's AST layout. self.expect("expression my_a.s_d", - startstr = "(int) $2 = 4") - + startstr="(int) $2 = 4") + self.expect("expression my_a.s_b", - startstr = "(long) $3 = 2") - + startstr="(long) $3 = 2") + self.expect("expression A::s_b", - startstr = "(long) $4 = 2") + startstr="(long) $4 = 2") - # should not be available in global scope + # should not be available in global scope self.expect("expression s_d", - startstr = "error: use of undeclared identifier 's_d'") - + startstr="error: use of undeclared identifier 's_d'") + self.runCmd("process continue") self.expect("expression m_c", - startstr = "(char) $5 = \'\\x03\'") - + startstr="(char) $5 = \'\\x03\'") + self.expect("expression s_b", - startstr = "(long) $6 = 2") + startstr="(long) $6 = 2") self.runCmd("process continue") def set_breakpoint(self, line): - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=False) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py index 9784be189cb..9c263053879 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py @@ -7,10 +7,11 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CPPStaticMethodsTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def setUp(self): TestBase.setUp(self) self.line = line_number('main.cpp', '// Break at this line') @@ -21,17 +22,18 @@ class CPPStaticMethodsTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("process launch", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) self.expect("expression -- A::getStaticValue()", - startstr = "(int) $0 = 5") + startstr="(int) $0 = 5") self.expect("expression -- my_a.getMemberValue()", - startstr = "(int) $1 = 3") + startstr="(int) $1 = 3") diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py index e2582085702..ce5869742f4 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py @@ -5,14 +5,15 @@ Test some expressions involving STL data types. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class STLTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,7 +23,8 @@ class STLTestCase(TestBase): TestBase.setUp(self) # Find the line number to break inside main(). self.source = 'main.cpp' - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') @expectedFailureAll(bugnumber="rdar://problem/10400981") def test(self): @@ -32,42 +34,46 @@ class STLTestCase(TestBase): # The following two lines, if uncommented, will enable loggings. #self.ci.HandleCommand("log enable -f /tmp/lldb.log lldb default", res) - #self.assertTrue(res.Succeeded()) + # self.assertTrue(res.Succeeded()) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # rdar://problem/8543077 # test/stl: clang built binaries results in the breakpoint locations = 3, # is this a problem with clang generated debug info? - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # Stop at 'std::string hello_world ("Hello World!");'. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['main.cpp:%d' % self.line, - 'stop reason = breakpoint']) + substrs=['main.cpp:%d' % self.line, + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Now try some expressions.... - self.runCmd('expr for (int i = 0; i < hello_world.length(); ++i) { (void)printf("%c\\n", hello_world[i]); }') + self.runCmd( + 'expr for (int i = 0; i < hello_world.length(); ++i) { (void)printf("%c\\n", hello_world[i]); }') # rdar://problem/10373783 # rdar://problem/10400981 self.expect('expr associative_array.size()', - substrs = [' = 3']) + substrs=[' = 3']) self.expect('expr associative_array.count(hello_world)', - substrs = [' = 1']) + substrs=[' = 1']) self.expect('expr associative_array[hello_world]', - substrs = [' = 1']) + substrs=[' = 1']) self.expect('expr associative_array["hello"]', - substrs = [' = 2']) + substrs=[' = 2']) - @expectedFailureAll(compiler="icc", bugnumber="ICC (13.1, 14-beta) do not emit DW_TAG_template_type_parameter.") + @expectedFailureAll( + compiler="icc", + bugnumber="ICC (13.1, 14-beta) do not emit DW_TAG_template_type_parameter.") @add_test_categories(['pyapi']) def test_SBType_template_aspects(self): """Test APIs for getting template arguments from an SBType.""" @@ -83,13 +89,17 @@ class STLTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Get Frame #0. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) # Get the type for variable 'associative_array'. @@ -102,8 +112,9 @@ class STLTestCase(TestBase): num_template_args = map_type.GetNumberOfTemplateArguments() self.assertTrue(num_template_args > 0) - # We expect the template arguments to contain at least 'string' and 'int'. - expected_types = { 'string': False, 'int': False } + # We expect the template arguments to contain at least 'string' and + # 'int'. + expected_types = {'string': False, 'int': False} for i in range(num_template_args): t = map_type.GetTemplateArgumentType(i) self.DebugSBType(t) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py index 865516de4ed..47fdf59a27e 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py @@ -5,13 +5,14 @@ Test the lldb disassemble command on lib stdc++. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class StdCXXDisassembleTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,7 +25,9 @@ class StdCXXDisassembleTestCase(TestBase): # rdar://problem/8504895 # Crash while doing 'disassemble -n "-[NSNumber descriptionWithLocale:]" - @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") + @unittest2.skipIf( + TestBase.skipLongRunningTest(), + "Skip this long running test") def test_stdcxx_disasm(self): """Do 'disassemble' on each and every 'Code' symbol entry from the std c++ lib.""" self.build() @@ -36,7 +39,8 @@ class StdCXXDisassembleTestCase(TestBase): # is this a problem with clang generated debug info? # # Break on line 13 of main.cpp. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) @@ -46,12 +50,13 @@ class StdCXXDisassembleTestCase(TestBase): # The process should be in a 'stopped' state. self.expect(str(process), STOPPED_DUE_TO_BREAKPOINT, exe=False, - substrs = ["a.out", - "stopped"]) + substrs=["a.out", + "stopped"]) # Disassemble the functions on the call stack. self.runCmd("thread backtrace") - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) depth = thread.GetNumFrames() for i in range(depth - 1): @@ -65,7 +70,8 @@ class StdCXXDisassembleTestCase(TestBase): for i in range(target.GetNumModules()): module = target.GetModuleAtIndex(i) fs = module.GetFileSpec() - if (fs.GetFilename().startswith("libstdc++") or fs.GetFilename().startswith("libc++")): + if (fs.GetFilename().startswith("libstdc++") + or fs.GetFilename().startswith("libc++")): lib_stdcxx = str(fs) break @@ -73,7 +79,7 @@ class StdCXXDisassembleTestCase(TestBase): # module is the corresponding SBModule. self.expect(lib_stdcxx, "Libraray StdC++ is located", exe=False, - substrs = ["lib"]) + substrs=["lib"]) self.runCmd("image dump symtab '%s'" % lib_stdcxx) raw_output = self.res.GetOutput() diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/template/TestTemplateArgs.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/template/TestTemplateArgs.py index e08d3a10786..a23dc38795a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/template/TestTemplateArgs.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/template/TestTemplateArgs.py @@ -1,7 +1,7 @@ """ Test that C++ template classes that have integer parameters work correctly. -We must reconstruct the types correctly so the template types are correct +We must reconstruct the types correctly so the template types are correct and display correctly, and also make sure the expression parser works and is able the find all needed functions when evaluating expressions """ @@ -10,10 +10,11 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TemplateArgsTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + def prepareProcess(self): self.build() @@ -22,66 +23,107 @@ class TemplateArgsTestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - # Set breakpoints inside and outside methods that take pointers to the containing struct. + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. line = line_number('main.cpp', '// Breakpoint 1') - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=True) arguments = None - environment = None + environment = None # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (arguments, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - + # Get the thread of the process - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) # Get frame for current thread return thread.GetSelectedFrame() def test_integer_args(self): frame = self.prepareProcess() - - testpos = frame.FindVariable('testpos') - self.assertTrue(testpos.IsValid(), 'make sure we find a local variabble named "testpos"') + + testpos = frame.FindVariable('testpos') + self.assertTrue( + testpos.IsValid(), + 'make sure we find a local variabble named "testpos"') self.assertTrue(testpos.GetType().GetName() == 'TestObj<1>') - + expr_result = frame.EvaluateExpression("testpos.getArg()") - self.assertTrue(expr_result.IsValid(), 'got a valid expression result from expression "testpos.getArg()"'); + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "testpos.getArg()"') self.assertTrue(expr_result.GetValue() == "1", "testpos.getArg() == 1") - self.assertTrue(expr_result.GetType().GetName() == "int", 'expr_result.GetType().GetName() == "int"') - - testneg = frame.FindVariable('testneg') - self.assertTrue(testneg.IsValid(), 'make sure we find a local variabble named "testneg"') - self.assertTrue(testneg.GetType().GetName() == 'TestObj<-1>') - + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') + + testneg = frame.FindVariable('testneg') + self.assertTrue( + testneg.IsValid(), + 'make sure we find a local variabble named "testneg"') + self.assertTrue(testneg.GetType().GetName() == 'TestObj<-1>') + expr_result = frame.EvaluateExpression("testneg.getArg()") - self.assertTrue(expr_result.IsValid(), 'got a valid expression result from expression "testneg.getArg()"'); - self.assertTrue(expr_result.GetValue() == "-1", "testneg.getArg() == -1") - self.assertTrue(expr_result.GetType().GetName() == "int", 'expr_result.GetType().GetName() == "int"') + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "testneg.getArg()"') + self.assertTrue( + expr_result.GetValue() == "-1", + "testneg.getArg() == -1") + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') - # Gcc does not generate the necessary DWARF attribute for enum template parameters. + # Gcc does not generate the necessary DWARF attribute for enum template + # parameters. @expectedFailureAll(bugnumber="llvm.org/pr28354", compiler="gcc") def test_enum_args(self): frame = self.prepareProcess() - # Make sure "member" can be displayed and also used in an expression correctly - member = frame.FindVariable('member') - self.assertTrue(member.IsValid(), 'make sure we find a local variabble named "member"') - self.assertTrue(member.GetType().GetName() == 'EnumTemplate<EnumType::Member>') - + # Make sure "member" can be displayed and also used in an expression + # correctly + member = frame.FindVariable('member') + self.assertTrue( + member.IsValid(), + 'make sure we find a local variabble named "member"') + self.assertTrue(member.GetType().GetName() == + 'EnumTemplate<EnumType::Member>') + expr_result = frame.EvaluateExpression("member.getMember()") - self.assertTrue(expr_result.IsValid(), 'got a valid expression result from expression "member.getMember()"'); - self.assertTrue(expr_result.GetValue() == "123", "member.getMember() == 123") - self.assertTrue(expr_result.GetType().GetName() == "int", 'expr_result.GetType().GetName() == "int"') - - # Make sure "subclass" can be displayed and also used in an expression correctly - subclass = frame.FindVariable('subclass') - self.assertTrue(subclass.IsValid(), 'make sure we find a local variabble named "subclass"') - self.assertTrue(subclass.GetType().GetName() == 'EnumTemplate<EnumType::Subclass>') - + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "member.getMember()"') + self.assertTrue( + expr_result.GetValue() == "123", + "member.getMember() == 123") + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') + + # Make sure "subclass" can be displayed and also used in an expression + # correctly + subclass = frame.FindVariable('subclass') + self.assertTrue( + subclass.IsValid(), + 'make sure we find a local variabble named "subclass"') + self.assertTrue(subclass.GetType().GetName() == + 'EnumTemplate<EnumType::Subclass>') + expr_result = frame.EvaluateExpression("subclass.getMember()") - self.assertTrue(expr_result.IsValid(), 'got a valid expression result from expression "subclass.getMember()"'); - self.assertTrue(expr_result.GetValue() == "246", "subclass.getMember() == 246") - self.assertTrue(expr_result.GetType().GetName() == "int", 'expr_result.GetType().GetName() == "int"') + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "subclass.getMember()"') + self.assertTrue( + expr_result.GetValue() == "246", + "subclass.getMember() == 246") + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py index 5f89371aa85..ed2e257dc31 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py @@ -6,14 +6,21 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CPPThisTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - - #rdar://problem/9962849 - @expectedFailureAll(compiler="gcc", bugnumber="llvm.org/pr15439 The 'this' pointer isn't available during expression evaluation when stopped in an inlined member function") - @expectedFailureAll(compiler="icc", bugnumber="ICC doesn't emit correct DWARF inline debug info for inlined member functions.") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + + # rdar://problem/9962849 + @expectedFailureAll( + compiler="gcc", + bugnumber="llvm.org/pr15439 The 'this' pointer isn't available during expression evaluation when stopped in an inlined member function") + @expectedFailureAll( + compiler="icc", + bugnumber="ICC doesn't emit correct DWARF inline debug info for inlined member functions.") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_with_run_command(self): """Test that the appropriate member variables are available when stopped in C++ static, inline, and const methods""" self.build() @@ -27,26 +34,27 @@ class CPPThisTestCase(TestBase): self.runCmd("process launch", RUN_SUCCEEDED) self.expect("expression -- m_a = 2", - startstr = "(int) $0 = 2") - + startstr="(int) $0 = 2") + self.runCmd("process continue") - + # This would be disallowed if we enforced const. But we don't. self.expect("expression -- m_a = 2", - startstr = "(int) $1 = 2") - - self.expect("expression -- (int)getpid(); m_a", - startstr = "(int) $2 = 2") + startstr="(int) $1 = 2") + + self.expect("expression -- (int)getpid(); m_a", + startstr="(int) $2 = 2") self.runCmd("process continue") self.expect("expression -- s_a", - startstr = "(int) $3 = 5") + startstr="(int) $3 = 5") self.runCmd("process continue") self.expect("expression -- m_a", - startstr = "(int) $4 = 2") - + startstr="(int) $4 = 2") + def set_breakpoint(self, line): - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=False) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/TestUnicodeLiterals.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/TestUnicodeLiterals.py index 1ae133f0b07..842d03ae519 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/TestUnicodeLiterals.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/TestUnicodeLiterals.py @@ -6,8 +6,8 @@ Test that the expression parser returns proper Unicode strings. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * @@ -26,23 +26,30 @@ from lldbsuite.test import lldbutil # [5] = e\0\0\0 #} + class UnicodeLiteralsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_expr1(self): """Test that the expression parser returns proper Unicode strings.""" self.build() self.rdar12991846(expr=1) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_expr2(self): """Test that the expression parser returns proper Unicode strings.""" self.build() self.rdar12991846(expr=2) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") def test_expr3(self): """Test that the expression parser returns proper Unicode strings.""" self.build() @@ -53,12 +60,14 @@ class UnicodeLiteralsTestCase(TestBase): TestBase.setUp(self) # Find the line number to break for main.cpp. self.source = 'main.cpp' - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') def rdar12991846(self, expr=None): """Test that the expression parser returns proper Unicode strings.""" if self.getArchitecture() in ['i386']: - self.skipTest("Skipping because this test is known to crash on i386") + self.skipTest( + "Skipping because this test is known to crash on i386") exe = os.path.join(os.getcwd(), "a.out") @@ -67,16 +76,20 @@ class UnicodeLiteralsTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Break on the struct declration statement in main.cpp. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line) + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") - if expr == 1: self.expect('expression L"hello"', substrs = ['hello']) + if expr == 1: + self.expect('expression L"hello"', substrs=['hello']) - if expr == 2: self.expect('expression u"hello"', substrs = ['hello']) + if expr == 2: + self.expect('expression u"hello"', substrs=['hello']) - if expr == 3: self.expect('expression U"hello"', substrs = ['hello']) + if expr == 3: + self.expect('expression U"hello"', substrs=['hello']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py index 2cbb1a191e6..3afac33ab39 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py @@ -5,11 +5,11 @@ Test that template instaniations of std::vector<long> and <short> in the same mo from __future__ import print_function - import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * + class UniqueTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -18,8 +18,9 @@ class UniqueTypesTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number inside main.cpp. - self.line = line_number("main.cpp", - "// Set breakpoint here to verify that std::vector 'longs' and 'shorts' have unique types.") + self.line = line_number( + "main.cpp", + "// Set breakpoint here to verify that std::vector 'longs' and 'shorts' have unique types.") def test(self): """Test for unique types of std::vector<long> and std::vector<short>.""" @@ -27,36 +28,43 @@ class UniqueTypesTestCase(TestBase): compiler = self.getCompiler() compiler_basename = os.path.basename(compiler) - if "clang" in compiler_basename and int(self.getCompilerVersion().split('.')[0]) < 3: - self.skipTest("rdar://problem/9173060 lldb hangs while running unique-types for clang version < 3") + if "clang" in compiler_basename and int( + self.getCompilerVersion().split('.')[0]) < 3: + self.skipTest( + "rdar://problem/9173060 lldb hangs while running unique-types for clang version < 3") exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) - # Do a "frame variable --show-types longs" and verify "long" is in each line of output. + # Do a "frame variable --show-types longs" and verify "long" is in each + # line of output. self.runCmd("frame variable --show-types longs") output = self.res.GetOutput() for x in [line.strip() for line in output.split(os.linesep)]: - # Skip empty line, closing brace, and messages about more variables than can be displayed. + # Skip empty line, closing brace, and messages about more variables + # than can be displayed. if not x or x == '}' or x == '...' or "Some of your variables have more members than the debugger will show by default" in x: continue self.expect(x, "Expect type 'long'", exe=False, - substrs = ['long']) + substrs=['long']) - # Do a "frame variable --show-types shorts" and verify "short" is in each line of output. + # Do a "frame variable --show-types shorts" and verify "short" is in + # each line of output. self.runCmd("frame variable --show-types shorts") output = self.res.GetOutput() for x in [line.strip() for line in output.split(os.linesep)]: - # Skip empty line, closing brace, and messages about more variables than can be displayed. + # Skip empty line, closing brace, and messages about more variables + # than can be displayed. if not x or x == '}' or x == '...' or "Some of your variables have more members than the debugger will show by default" in x: continue self.expect(x, "Expect type 'short'", exe=False, - substrs = ['short']) + substrs=['short']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py index 30aadb38968..284e106ae75 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py @@ -5,14 +5,15 @@ Test that variables with unsigned types display correctly. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class UnsignedTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -34,23 +35,31 @@ class UnsignedTypesTestCase(TestBase): # if GCC is the target compiler, we cannot rely on an exact line match. need_exact = "gcc" not in self.getCompiler() # Break on line 19 in main() aftre the variables are assigned values. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=need_exact) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + num_expected_locations=-1, + loc_exact=need_exact) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', 'stop reason = breakpoint']) + substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # Test that unsigned types display correctly. - self.expect("frame variable --show-types --no-args", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(unsigned char) the_unsigned_char = 'c'", - patterns = ["\((short unsigned int|unsigned short)\) the_unsigned_short = 99"], - substrs = ["(unsigned int) the_unsigned_int = 99", - "(unsigned long) the_unsigned_long = 99", - "(unsigned long long) the_unsigned_long_long = 99", - "(uint32_t) the_uint32 = 99"]) + self.expect( + "frame variable --show-types --no-args", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(unsigned char) the_unsigned_char = 'c'", + patterns=["\((short unsigned int|unsigned short)\) the_unsigned_short = 99"], + substrs=[ + "(unsigned int) the_unsigned_int = 99", + "(unsigned long) the_unsigned_long = 99", + "(unsigned long long) the_unsigned_long_long = 99", + "(uint32_t) the_uint32 = 99"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py index bee148773f0..3ca0c6cb060 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py @@ -4,15 +4,19 @@ Test C++ virtual function and virtual inheritance. from __future__ import print_function -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + def Msg(expr, val): - return "'expression %s' matches the output (from compiled code): %s" % (expr, val) + return "'expression %s' matches the output (from compiled code): %s" % ( + expr, val) + class CppVirtualMadness(TestBase): @@ -29,7 +33,9 @@ class CppVirtualMadness(TestBase): self.source = 'main.cpp' self.line = line_number(self.source, '// Set first breakpoint here.') - @expectedFailureAll(compiler="icc", bugnumber="llvm.org/pr16808 lldb does not call the correct virtual function with icc.") + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr16808 lldb does not call the correct virtual function with icc.") @expectedFailureAll(oslist=['windows']) def test_virtual_madness(self): """Test that expression works correctly with virtual inheritance as well as virtual function.""" @@ -38,7 +44,7 @@ class CppVirtualMadness(TestBase): # Bring the program to the point where we can issue a series of # 'expression' command to compare against the golden output. self.dbg.SetAsync(False) - + # Create a target by the debugger. target = self.dbg.CreateTarget("a.out") self.assertTrue(target, VALID_TARGET) @@ -48,18 +54,25 @@ class CppVirtualMadness(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - + self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") # First, capture the golden output from the program itself. golden = thread.GetFrameAtIndex(0).FindVariable("golden") - self.assertTrue(golden.IsValid(), "Encountered an error reading the process's golden variable") + self.assertTrue( + golden.IsValid(), + "Encountered an error reading the process's golden variable") error = lldb.SBError() - golden_str = process.ReadCStringFromMemory(golden.AddressOf().GetValueAsUnsigned(), 4096, error); + golden_str = process.ReadCStringFromMemory( + golden.AddressOf().GetValueAsUnsigned(), 4096, error) self.assertTrue(error.Success()) self.assertTrue("c_as_C" in golden_str) @@ -84,7 +97,7 @@ class CppVirtualMadness(TestBase): self.runCmd("expression %s" % my_expr) output = self.res.GetOutput() - + # The expression output must match the oracle. self.expect(output, Msg(my_expr, val), exe=False, - substrs = [val]) + substrs=[val]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py b/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py index f9cdbca16e5..f17ba6f4a22 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py +++ b/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py @@ -1,4 +1,4 @@ -#coding=utf8 +# coding=utf8 """ Test that C++ supports wchar_t correctly. """ @@ -6,12 +6,13 @@ Test that C++ supports wchar_t correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class CxxWCharTTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,7 +22,8 @@ class CxxWCharTTestCase(TestBase): TestBase.setUp(self) # Find the line number to break for main.cpp. self.source = 'main.cpp' - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') def test(self): """Test that C++ supports wchar_t correctly.""" @@ -33,42 +35,46 @@ class CxxWCharTTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Break on the struct declration statement in main.cpp. - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line) + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.Launch() failed") # Check that we correctly report templates on wchar_t self.expect("frame variable foo_y", - substrs = ['(Foo<wchar_t>) foo_y = ']) + substrs=['(Foo<wchar_t>) foo_y = ']) # Check that we correctly report templates on int self.expect("frame variable foo_x", - substrs = ['(Foo<int>) foo_x = ']) + substrs=['(Foo<int>) foo_x = ']) # Check that we correctly report wchar_t self.expect("frame variable foo_y.object", - substrs = ['(wchar_t) foo_y.object = ']) + substrs=['(wchar_t) foo_y.object = ']) # Check that we correctly report int self.expect("frame variable foo_x.object", - substrs = ['(int) foo_x.object = ']) + substrs=['(int) foo_x.object = ']) # Check that we can run expressions that return wchar_t - self.expect("expression L'a'",substrs = ['(wchar_t) $',"L'a'"]) + self.expect("expression L'a'", substrs=['(wchar_t) $', "L'a'"]) # Mazel Tov if this works! self.expect("frame variable mazeltov", - substrs = ['(const wchar_t *) mazeltov = ','L"מזל טוב"']) + substrs=['(const wchar_t *) mazeltov = ', 'L"מזל טוב"']) + + self.expect( + "frame variable ws_NULL", + substrs=['(wchar_t *) ws_NULL = 0x0']) + self.expect("frame variable ws_empty", substrs=[' L""']) - self.expect("frame variable ws_NULL",substrs = ['(wchar_t *) ws_NULL = 0x0']) - self.expect("frame variable ws_empty",substrs = [' L""']) + self.expect("frame variable array", substrs=[ + 'L"Hey, I\'m a super wchar_t string']) + self.expect("frame variable array", substrs=['[0]'], matching=False) - self.expect("frame variable array",substrs = ['L"Hey, I\'m a super wchar_t string']) - self.expect("frame variable array",substrs = ['[0]'], matching=False) - self.expect('frame variable wchar_zero', substrs=["L'\\0'"]) self.expect('expression wchar_zero', substrs=["L'\\0'"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py b/lldb/packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py index f2e5613ffd6..306b00840df 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py +++ b/lldb/packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py @@ -1,18 +1,20 @@ """Test the go expression parser/interpreter.""" -import os, time +import os +import time import unittest2 import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGoUserExpression(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(['pyapi']) - @skipIfRemote # Not remote test suit ready + @skipIfRemote # Not remote test suit ready @skipUnlessGoInstalled def test_with_dsym_and_python_api(self): """Test GoASTUserExpress.""" @@ -25,7 +27,8 @@ class TestGoUserExpression(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "main.go" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') def check_builtin(self, name, size=0, typeclass=lldb.eTypeClassBuiltin): tl = self.target().FindTypes(name) @@ -42,23 +45,28 @@ class TestGoUserExpression(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") def go_expressions(self): frame = self.frame() @@ -66,7 +74,7 @@ class TestGoUserExpression(TestBase): self.assertEqual(1, v.GetValueAsSigned()) x = frame.EvaluateExpression("x") self.assertEqual(22, x.GetValueAsSigned()) - + a = frame.EvaluateExpression("a") self.assertEqual(3, a.GetNumChildren()) a0 = a.GetChildAtIndex(0) @@ -75,23 +83,23 @@ class TestGoUserExpression(TestBase): # Array indexing a0 = frame.EvaluateExpression("a[0]") self.assertEqual(8, a0.GetValueAsSigned()) - + # Slice indexing b1 = frame.EvaluateExpression("b[1]") self.assertEqual(9, b1.GetValueAsSigned()) - + # Test global in this package g = frame.EvaluateExpression("myGlobal") self.assertEqual(17, g.GetValueAsSigned(), str(g)) - + # Global with package name g = frame.EvaluateExpression("main.myGlobal") self.assertEqual(17, g.GetValueAsSigned(), str(g)) - + # Global with quoted package name g = frame.EvaluateExpression('"main".myGlobal') self.assertEqual(17, g.GetValueAsSigned(), str(g)) - + # Casting with package local type s = frame.EvaluateExpression("*(*myStruct)(i.data)") sb = s.GetChildMemberWithName("a") diff --git a/lldb/packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py b/lldb/packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py index 2578742467d..c48cd1f6af0 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py +++ b/lldb/packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py @@ -1,18 +1,20 @@ """Test the Go Data Formatter Plugin.""" -import os, time +import os +import time import unittest2 import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGoLanguage(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure - @skipIfRemote # Not remote test suite ready + @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure + @skipIfRemote # Not remote test suite ready @no_debug_info_test @skipUnlessGoInstalled def test_go_formatter_plugin(self): @@ -34,29 +36,37 @@ class TestGoLanguage(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + self.bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(self.bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, self.bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, self.bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") def check_formatters(self): a = self.frame().FindVariable('a') self.assertEqual('(string) a = "my string"', str(a)) b = self.frame().FindVariable('b') - self.assertEqual("([]int) b = (len 2, cap 7) {\n [0] = 0\n [1] = 0\n}", str(b)) + self.assertEqual( + "([]int) b = (len 2, cap 7) {\n [0] = 0\n [1] = 0\n}", + str(b)) if __name__ == '__main__': diff --git a/lldb/packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py b/lldb/packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py index 8aff2e514bb..e0cf9e8d775 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py +++ b/lldb/packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py @@ -3,20 +3,21 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGoASTContext(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(['pyapi']) - @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure - @skipIfRemote # Not remote test suite ready + @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure + @skipIfRemote # Not remote test suite ready @no_debug_info_test @skipUnlessGoInstalled def test_goroutine_plugin(self): @@ -40,47 +41,64 @@ class TestGoASTContext(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.bpt1 = target.BreakpointCreateByLocation(self.main_source, self.break_line1) + self.bpt1 = target.BreakpointCreateByLocation( + self.main_source, self.break_line1) self.assertTrue(self.bpt1, VALID_BREAKPOINT) - self.bpt2 = target.BreakpointCreateByLocation(self.main_source, self.break_line2) + self.bpt2 = target.BreakpointCreateByLocation( + self.main_source, self.break_line2) self.assertTrue(self.bpt2, VALID_BREAKPOINT) - self.bpt3 = target.BreakpointCreateByLocation(self.main_source, self.break_line3) + self.bpt3 = target.BreakpointCreateByLocation( + self.main_source, self.break_line3) self.assertTrue(self.bpt3, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, self.bpt1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, self.bpt1) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") def check_goroutines(self): self.assertLess(len(self.process().threads), 20) self.process().Continue() # Make sure we stopped at the 2nd breakpoint - thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process(), self.bpt2) - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + self.process(), self.bpt2) + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + # There's (at least) 21 goroutines. self.assertGreater(len(self.process().threads), 20) # self.dbg.HandleCommand("log enable lldb os") - # Now test that stepping works if the memory thread moves to a different backing thread. + # Now test that stepping works if the memory thread moves to a + # different backing thread. for i in list(range(11)): self.thread().StepOver() - self.assertEqual(lldb.eStopReasonPlanComplete, self.thread().GetStopReason(), self.thread().GetStopDescription(100)) - + self.assertEqual( + lldb.eStopReasonPlanComplete, + self.thread().GetStopReason(), + self.thread().GetStopDescription(100)) + # Disable the plugin and make sure the goroutines disappear - self.dbg.HandleCommand("settings set plugin.os.goroutines.enable false") + self.dbg.HandleCommand( + "settings set plugin.os.goroutines.enable false") self.thread().StepInstruction(False) self.assertLess(len(self.process().threads), 20) diff --git a/lldb/packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py b/lldb/packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py index bf7bc93a44b..8e158c3e82d 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py +++ b/lldb/packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py @@ -3,20 +3,21 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGoASTContext(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(['pyapi']) - @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure - @skipIfRemote # Not remote test suit ready + @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure + @skipIfRemote # Not remote test suit ready @no_debug_info_test @skipUnlessGoInstalled def test_with_dsym_and_python_api(self): @@ -31,7 +32,8 @@ class TestGoASTContext(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "main.go" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') def check_builtin(self, name, size=0, typeclass=lldb.eTypeClassBuiltin): tl = self.target().FindTypes(name) @@ -48,23 +50,28 @@ class TestGoASTContext(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") def go_builtin_types(self): address_size = self.target().GetAddressByteSize() @@ -93,19 +100,19 @@ class TestGoASTContext(TestBase): def check_main_vars(self): v = self.var('theBool') self.assertEqual('true', v.value) - + v = self.var('theInt') self.assertEqual('-7', v.value) - + v = self.var('theComplex') self.assertEqual('1 + 2i', v.value) - + v = self.var('thePointer') self.assertTrue(v.TypeIsPointerType()) self.assertEqual('-10', v.Dereference().value) self.assertEqual(1, v.GetNumChildren()) self.assertEqual('-10', v.GetChildAtIndex(0).value) - + # print() # print(os.getpid()) # time.sleep(60) @@ -115,8 +122,11 @@ class TestGoASTContext(TestBase): self.assertEqual(2, v.GetNumChildren()) self.assertEqual('7', v.GetChildAtIndex(0).value) self.assertEqual('7', v.GetChildMemberWithName('myInt').value) - self.assertEqual(v.load_addr, v.GetChildAtIndex(1).GetValueAsUnsigned()) - self.assertEqual(v.load_addr, v.GetChildMemberWithName('myPointer').GetValueAsUnsigned()) + self.assertEqual( + v.load_addr, + v.GetChildAtIndex(1).GetValueAsUnsigned()) + self.assertEqual(v.load_addr, v.GetChildMemberWithName( + 'myPointer').GetValueAsUnsigned()) # Test accessing struct fields through pointers. v = v.GetChildMemberWithName('myPointer') diff --git a/lldb/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py b/lldb/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py index d11f03b878a..e7615c8e9d8 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py +++ b/lldb/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py @@ -3,11 +3,13 @@ from __future__ import print_function - -import os, time, re +import os +import time +import re import lldb from lldbsuite.test.lldbtest import * + class MixedLanguagesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,12 +23,14 @@ class MixedLanguagesTestCase(TestBase): # Execute the cleanup function during test case tear down # to restore the frame format. def cleanup(): - self.runCmd("settings set frame-format %s" % self.format_string, check=False) + self.runCmd( + "settings set frame-format %s" % + self.format_string, check=False) self.addTearDownHook(cleanup) self.runCmd("settings show frame-format") m = re.match( - '^frame-format \(format-string\) = "(.*)\"$', - self.res.GetOutput()) + '^frame-format \(format-string\) = "(.*)\"$', + self.res.GetOutput()) self.assertTrue(m, "Bad settings string") self.format_string = m.group(1) @@ -34,23 +38,23 @@ class MixedLanguagesTestCase(TestBase): format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}`${function.name}{${function.pc-offset}}}{, lang=${language}}\n" self.runCmd("settings set frame-format %s" % format_string) self.expect("settings show frame-format", SETTING_MSG("frame-format"), - substrs = [format_string]) + substrs=[format_string]) # Run to BP at main (in main.c) and test that the language is C. self.runCmd("breakpoint set -n main") self.runCmd("run") self.expect("thread backtrace", - substrs = ["`main", "lang=c"]) + substrs=["`main", "lang=c"]) # Make sure evaluation of C++11 fails. self.expect("expr foo != nullptr", error=True, - startstr = "error") + startstr="error") # Run to BP at foo (in foo.cpp) and test that the language is C++. self.runCmd("breakpoint set -n foo") self.runCmd("continue") self.expect("thread backtrace", - substrs = ["`::foo()", "lang=c++"]) + substrs=["`::foo()", "lang=c++"]) # Make sure we can evaluate an expression requiring C++11 # (note: C++11 is enabled by default for C++). self.expect("expr foo != nullptr", - patterns = ["true"]) + patterns=["true"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/TestBitfieldIvars.py b/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/TestBitfieldIvars.py index 01bf241b038..4a3311fb5f6 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/TestBitfieldIvars.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/TestBitfieldIvars.py @@ -1,4 +1,12 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows, decorators.expectedFailureAll(bugnumber="rdar://problem/17990991")]) +lldbinline.MakeInlineTest( + __file__, + globals(), + [ + decorators.skipIfFreeBSD, + decorators.skipIfLinux, + decorators.skipIfWindows, + decorators.expectedFailureAll( + bugnumber="rdar://problem/17990991")]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py b/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py index 9fa03071c59..74e4f3bc880 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCIvarsInBlocks(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,7 +25,9 @@ class TestObjCIvarsInBlocks(TestBase): @skipUnlessDarwin @add_test_categories(['pyapi']) - @expectedFailureAll(archs=["i[3-6]86"], bugnumber="This test requires the 2.0 runtime, so it will fail on i386") + @expectedFailureAll( + archs=["i[3-6]86"], + bugnumber="This test requires the 2.0 runtime, so it will fail on i386") def test_with_python_api(self): """Test printing the ivars of the self when captured in blocks""" self.build() @@ -33,72 +36,100 @@ class TestObjCIvarsInBlocks(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateBySourceRegex ('// Break here inside the block.', self.class_source_file_spec) + breakpoint = target.BreakpointCreateBySourceRegex( + '// Break here inside the block.', self.class_source_file_spec) self.assertTrue(breakpoint, VALID_BREAKPOINT) - breakpoint_two = target.BreakpointCreateBySourceRegex ('// Break here inside the class method block.', self.class_source_file_spec) + breakpoint_two = target.BreakpointCreateBySourceRegex( + '// Break here inside the class method block.', self.class_source_file_spec) self.assertTrue(breakpoint, VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) - self.assertTrue (process, "Created a process.") - self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.") + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Created a process.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped it too.") - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] - + frame = thread.GetFrameAtIndex(0) - self.assertTrue (frame, "frame 0 is valid") - - # First use the FindVariable API to see if we can find the ivar by undecorated name: - direct_blocky = frame.GetValueForVariablePath ("blocky_ivar") + self.assertTrue(frame, "frame 0 is valid") + + # First use the FindVariable API to see if we can find the ivar by + # undecorated name: + direct_blocky = frame.GetValueForVariablePath("blocky_ivar") self.assertTrue(direct_blocky, "Found direct access to blocky_ivar.") - - # Now get it as a member of "self" and make sure the two values are equal: - self_var = frame.GetValueForVariablePath ("self") - self.assertTrue (self_var, "Found self in block.") - indirect_blocky = self_var.GetChildMemberWithName ("blocky_ivar") - self.assertTrue (indirect_blocky, "Found blocky_ivar through self") - + + # Now get it as a member of "self" and make sure the two values are + # equal: + self_var = frame.GetValueForVariablePath("self") + self.assertTrue(self_var, "Found self in block.") + indirect_blocky = self_var.GetChildMemberWithName("blocky_ivar") + self.assertTrue(indirect_blocky, "Found blocky_ivar through self") + error = lldb.SBError() direct_value = direct_blocky.GetValueAsSigned(error) - self.assertTrue (error.Success(), "Got direct value for blocky_ivar") + self.assertTrue(error.Success(), "Got direct value for blocky_ivar") + + indirect_value = indirect_blocky.GetValueAsSigned(error) + self.assertTrue(error.Success(), "Got indirect value for blocky_ivar") - indirect_value = indirect_blocky.GetValueAsSigned (error) - self.assertTrue (error.Success(), "Got indirect value for blocky_ivar") - - self.assertTrue (direct_value == indirect_value, "Direct and indirect values are equal.") + self.assertTrue( + direct_value == indirect_value, + "Direct and indirect values are equal.") # Now make sure that we can get at the captured ivar through the expression parser. - # Doing a little trivial math will force this into the real expression parser: - direct_expr = frame.EvaluateExpression ("blocky_ivar + 10") - self.assertTrue (direct_expr, "Got blocky_ivar through the expression parser") - - # Again, get the value through self directly and make sure they are the same: - indirect_expr = frame.EvaluateExpression ("self->blocky_ivar + 10") - self.assertTrue (indirect_expr, "Got blocky ivar through expression parser using self.") - - direct_value = direct_expr.GetValueAsSigned (error) - self.assertTrue (error.Success(), "Got value from direct use of expression parser") - - indirect_value = indirect_expr.GetValueAsSigned (error) - self.assertTrue (error.Success(), "Got value from indirect access using the expression parser") - - self.assertTrue (direct_value == indirect_value, "Direct ivar access and indirect through expression parser produce same value.") + # Doing a little trivial math will force this into the real expression + # parser: + direct_expr = frame.EvaluateExpression("blocky_ivar + 10") + self.assertTrue( + direct_expr, + "Got blocky_ivar through the expression parser") + + # Again, get the value through self directly and make sure they are the + # same: + indirect_expr = frame.EvaluateExpression("self->blocky_ivar + 10") + self.assertTrue( + indirect_expr, + "Got blocky ivar through expression parser using self.") + + direct_value = direct_expr.GetValueAsSigned(error) + self.assertTrue( + error.Success(), + "Got value from direct use of expression parser") + + indirect_value = indirect_expr.GetValueAsSigned(error) + self.assertTrue( + error.Success(), + "Got value from indirect access using the expression parser") + + self.assertTrue( + direct_value == indirect_value, + "Direct ivar access and indirect through expression parser produce same value.") process.Continue() - self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped at the second breakpoint.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped at the second breakpoint.") - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint_two) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint_two) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] - + frame = thread.GetFrameAtIndex(0) - self.assertTrue (frame, "frame 0 is valid") - + self.assertTrue(frame, "frame 0 is valid") + expr = frame.EvaluateExpression("(ret)") - self.assertTrue (expr, "Successfully got a local variable in a block in a class method.") + self.assertTrue( + expr, "Successfully got a local variable in a block in a class method.") - ret_value_signed = expr.GetValueAsSigned (error) + ret_value_signed = expr.GetValueAsSigned(error) # print('ret_value_signed = %i' % (ret_value_signed)) - self.assertTrue (ret_value_signed == 5, "The local variable in the block was what we expected.") + self.assertTrue( + ret_value_signed == 5, + "The local variable in the block was what we expected.") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py b/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py index c153f985660..aa2b659b84b 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ForwardDeclTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,7 +26,7 @@ class ForwardDeclTestCase(TestBase): @skipUnlessDarwin def test_expr(self): self.build() - + # Create a target by the debugger. target = self.dbg.CreateTarget("a.out") self.assertTrue(target, VALID_TARGET) @@ -33,23 +34,26 @@ class ForwardDeclTestCase(TestBase): # Create the breakpoint inside function 'main'. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) - - # Register our shared libraries for remote targets so they get automatically uploaded - environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # This should display correctly. self.expect("expression [j getMember]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 0x"]) + substrs=["= 0x"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py index 4a62d6240d9..2a81c42eb50 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py @@ -6,13 +6,14 @@ parser. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ConstStringTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,25 +31,30 @@ class ConstStringTestCase(TestBase): """Test constant string generation amd comparison by the expression parser.""" self.build(dictionary=self.d) self.setTearDownCleanup(self.d) - + exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, - substrs = [" at %s:%d" % (self.main_source, self.line), - "stop reason = breakpoint"]) + substrs=[" at %s:%d" % (self.main_source, self.line), + "stop reason = breakpoint"]) self.expect('expression (int)[str compare:@"hello"]', - startstr = "(int) $0 = 0") + startstr="(int) $0 = 0") self.expect('expression (int)[str compare:@"world"]', - startstr = "(int) $1 = -1") + startstr="(int) $1 = -1") # Test empty strings, too. self.expect('expression (int)[@"" length]', - startstr = "(int) $2 = 0") + startstr="(int) $2 = 0") self.expect('expression (int)[@"123" length]', - startstr = "(int) $3 = 3") + startstr="(int) $3 = 3") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py index 0867eec62eb..51d9d22bf44 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py @@ -5,14 +5,15 @@ Test the lldb disassemble command on foundation framework. from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class FoundationDisassembleTestCase(TestBase): @@ -20,20 +21,23 @@ class FoundationDisassembleTestCase(TestBase): # rdar://problem/8504895 # Crash while doing 'disassemble -n "-[NSNumber descriptionWithLocale:]" - @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test") + @unittest2.skipIf( + TestBase.skipLongRunningTest(), + "Skip this long running test") def test_foundation_disasm(self): """Do 'disassemble -n func' on each and every 'Code' symbol entry from the Foundation.framework.""" self.build() - + # Enable synchronous mode self.dbg.SetAsync(False) - + # Create a target by the debugger. target = self.dbg.CreateTarget("a.out") self.assertTrue(target, VALID_TARGET) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) foundation_framework = None @@ -43,7 +47,9 @@ class FoundationDisassembleTestCase(TestBase): foundation_framework = module.file.fullpath break - self.assertTrue(foundation_framework != None, "Foundation.framework path located") + self.assertTrue( + foundation_framework is not None, + "Foundation.framework path located") self.runCmd("image dump symtab '%s'" % foundation_framework) raw_output = self.res.GetOutput() # Now, grab every 'Code' symbol and feed it into the command: @@ -64,7 +70,6 @@ class FoundationDisassembleTestCase(TestBase): #print("line:", line) #print("func:", func) self.runCmd('disassemble -n "%s"' % func) - def test_simple_disasm(self): """Test the lldb 'disassemble' command""" @@ -80,25 +85,45 @@ class FoundationDisassembleTestCase(TestBase): # Stop at +[NSString stringWithFormat:]. symbol_name = "+[NSString stringWithFormat:]" - break_results = lldbutil.run_break_set_command (self, "_regexp-break %s"%(symbol_name)) - - lldbutil.check_breakpoint_result (self, break_results, symbol_name=symbol_name, num_locations=1) + break_results = lldbutil.run_break_set_command( + self, "_regexp-break %s" % (symbol_name)) + + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name=symbol_name, + num_locations=1) # Stop at -[MyString initWithNSString:]. - lldbutil.run_break_set_by_symbol (self, '-[MyString initWithNSString:]', num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + '-[MyString initWithNSString:]', + num_expected_locations=1, + sym_exact=True) # Stop at the "description" selector. - lldbutil.run_break_set_by_selector (self, 'description', num_expected_locations=1, module_name='a.out') + lldbutil.run_break_set_by_selector( + self, + 'description', + num_expected_locations=1, + module_name='a.out') # Stop at -[NSAutoreleasePool release]. - break_results = lldbutil.run_break_set_command (self, "_regexp-break -[NSAutoreleasePool release]") - lldbutil.check_breakpoint_result (self, break_results, symbol_name='-[NSAutoreleasePool release]', num_locations=1) + break_results = lldbutil.run_break_set_command( + self, "_regexp-break -[NSAutoreleasePool release]") + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name='-[NSAutoreleasePool release]', + num_locations=1) self.runCmd("run", RUN_SUCCEEDED) # First stop is +[NSString stringWithFormat:]. - self.expect("thread backtrace", "Stop at +[NSString stringWithFormat:]", - substrs = ["Foundation`+[NSString stringWithFormat:]"]) + self.expect( + "thread backtrace", + "Stop at +[NSString stringWithFormat:]", + substrs=["Foundation`+[NSString stringWithFormat:]"]) # Do the disassemble for the currently stopped function. self.runCmd("disassemble -f") @@ -108,8 +133,10 @@ class FoundationDisassembleTestCase(TestBase): self.runCmd("process continue") # Followed by a.out`-[MyString initWithNSString:]. - self.expect("thread backtrace", "Stop at a.out`-[MyString initWithNSString:]", - substrs = ["a.out`-[MyString initWithNSString:]"]) + self.expect( + "thread backtrace", + "Stop at a.out`-[MyString initWithNSString:]", + substrs=["a.out`-[MyString initWithNSString:]"]) # Do the disassemble for the currently stopped function. self.runCmd("disassemble -f") @@ -118,7 +145,7 @@ class FoundationDisassembleTestCase(TestBase): # Followed by -[MyString description]. self.expect("thread backtrace", "Stop at -[MyString description]", - substrs = ["a.out`-[MyString description]"]) + substrs=["a.out`-[MyString description]"]) # Do the disassemble for the currently stopped function. self.runCmd("disassemble -f") @@ -129,7 +156,7 @@ class FoundationDisassembleTestCase(TestBase): # Followed by -[NSAutoreleasePool release]. self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]", - substrs = ["Foundation`-[NSAutoreleasePool release]"]) + substrs=["Foundation`-[NSAutoreleasePool release]"]) # Do the disassemble for the currently stopped function. self.runCmd("disassemble -f") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py index 2a8e80f6d76..d636458ce1a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py @@ -6,8 +6,9 @@ Also lookup objective-c data types and evaluate expressions. from __future__ import print_function - -import os, os.path, time +import os +import os.path +import time import lldb import string from lldbsuite.test.decorators import * @@ -15,6 +16,8 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil file_index = 0 + + @skipUnlessDarwin class FoundationTestCase(TestBase): @@ -25,7 +28,9 @@ class FoundationTestCase(TestBase): TestBase.setUp(self) # Find the line number to break inside main(). self.main_source = "main.m" - self.line = line_number(self.main_source, '// Set break point at this line.') + self.line = line_number( + self.main_source, + '// Set break point at this line.') def test_break(self): """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'.""" @@ -34,54 +39,78 @@ class FoundationTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Stop at +[NSString stringWithFormat:]. - break_results = lldbutil.run_break_set_command(self, "_regexp-break +[NSString stringWithFormat:]") - lldbutil.check_breakpoint_result (self, break_results, symbol_name='+[NSString stringWithFormat:]', num_locations=1) + break_results = lldbutil.run_break_set_command( + self, "_regexp-break +[NSString stringWithFormat:]") + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name='+[NSString stringWithFormat:]', + num_locations=1) # Stop at -[MyString initWithNSString:]. - lldbutil.run_break_set_by_symbol (self, '-[MyString initWithNSString:]', num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + '-[MyString initWithNSString:]', + num_expected_locations=1, + sym_exact=True) # Stop at the "description" selector. - lldbutil.run_break_set_by_selector (self, 'description', num_expected_locations=1, module_name='a.out') + lldbutil.run_break_set_by_selector( + self, + 'description', + num_expected_locations=1, + module_name='a.out') # Stop at -[NSAutoreleasePool release]. - break_results = lldbutil.run_break_set_command(self, "_regexp-break -[NSAutoreleasePool release]") - lldbutil.check_breakpoint_result (self, break_results, symbol_name='-[NSAutoreleasePool release]', num_locations=1) + break_results = lldbutil.run_break_set_command( + self, "_regexp-break -[NSAutoreleasePool release]") + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name='-[NSAutoreleasePool release]', + num_locations=1) self.runCmd("run", RUN_SUCCEEDED) # First stop is +[NSString stringWithFormat:]. - self.expect("thread backtrace", "Stop at +[NSString stringWithFormat:]", - substrs = ["Foundation`+[NSString stringWithFormat:]"]) + self.expect( + "thread backtrace", + "Stop at +[NSString stringWithFormat:]", + substrs=["Foundation`+[NSString stringWithFormat:]"]) self.runCmd("process continue") # Second stop is still +[NSString stringWithFormat:]. - self.expect("thread backtrace", "Stop at +[NSString stringWithFormat:]", - substrs = ["Foundation`+[NSString stringWithFormat:]"]) + self.expect( + "thread backtrace", + "Stop at +[NSString stringWithFormat:]", + substrs=["Foundation`+[NSString stringWithFormat:]"]) self.runCmd("process continue") # Followed by a.out`-[MyString initWithNSString:]. - self.expect("thread backtrace", "Stop at a.out`-[MyString initWithNSString:]", - substrs = ["a.out`-[MyString initWithNSString:]"]) + self.expect( + "thread backtrace", + "Stop at a.out`-[MyString initWithNSString:]", + substrs=["a.out`-[MyString initWithNSString:]"]) self.runCmd("process continue") # Followed by -[MyString description]. self.expect("thread backtrace", "Stop at -[MyString description]", - substrs = ["a.out`-[MyString description]"]) + substrs=["a.out`-[MyString description]"]) self.runCmd("process continue") # Followed by the same -[MyString description]. self.expect("thread backtrace", "Stop at -[MyString description]", - substrs = ["a.out`-[MyString description]"]) + substrs=["a.out`-[MyString description]"]) self.runCmd("process continue") # Followed by -[NSAutoreleasePool release]. self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]", - substrs = ["Foundation`-[NSAutoreleasePool release]"]) + substrs=["Foundation`-[NSAutoreleasePool release]"]) # rdar://problem/8542091 # rdar://problem/8492646 @@ -92,32 +121,40 @@ class FoundationTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Stop at -[MyString description]. - lldbutil.run_break_set_by_symbol (self, '-[MyString description]', num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + '-[MyString description]', + num_expected_locations=1, + sym_exact=True) # self.expect("breakpoint set -n '-[MyString description]", BREAKPOINT_CREATED, -# startstr = "Breakpoint created: 1: name = '-[MyString description]', locations = 1") +# startstr = "Breakpoint created: 1: name = '-[MyString description]', +# locations = 1") self.runCmd("run", RUN_SUCCEEDED) # The backtrace should show we stop at -[MyString description]. self.expect("thread backtrace", "Stop at -[MyString description]", - substrs = ["a.out`-[MyString description]"]) + substrs=["a.out`-[MyString description]"]) # Lookup objc data type MyString and evaluate some expressions. self.expect("image lookup -t NSString", DATA_TYPES_DISPLAYED_CORRECTLY, - substrs = ['name = "NSString"', - 'compiler_type = "@interface NSString']) + substrs=['name = "NSString"', + 'compiler_type = "@interface NSString']) self.expect("image lookup -t MyString", DATA_TYPES_DISPLAYED_CORRECTLY, - substrs = ['name = "MyString"', - 'compiler_type = "@interface MyString', - 'NSString * str;', - 'NSDate * date;']) - - self.expect("frame variable --show-types --scope", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["ARG: (MyString *) self"], - patterns = ["ARG: \(.*\) _cmd", - "(objc_selector *)|(SEL)"]) + substrs=['name = "MyString"', + 'compiler_type = "@interface MyString', + 'NSString * str;', + 'NSDate * date;']) + + self.expect( + "frame variable --show-types --scope", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["ARG: (MyString *) self"], + patterns=[ + "ARG: \(.*\) _cmd", + "(objc_selector *)|(SEL)"]) # rdar://problem/8651752 # don't crash trying to ask clang how many children an empty record has @@ -126,28 +163,37 @@ class FoundationTestCase(TestBase): # rdar://problem/8492646 # test/foundation fails after updating to tot r115023 # self->str displays nothing as output - self.expect("frame variable --show-types self->str", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(NSString *) self->str") + self.expect( + "frame variable --show-types self->str", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(NSString *) self->str") # rdar://problem/8447030 # 'frame variable self->date' displays the wrong data member - self.expect("frame variable --show-types self->date", VARIABLES_DISPLAYED_CORRECTLY, - startstr = "(NSDate *) self->date") + self.expect( + "frame variable --show-types self->date", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(NSDate *) self->date") # This should display the str and date member fields as well. - self.expect("frame variable --show-types *self", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(MyString) *self", - "(NSString *) str", - "(NSDate *) date"]) - + self.expect( + "frame variable --show-types *self", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(MyString) *self", + "(NSString *) str", + "(NSDate *) date"]) + # isa should be accessible. self.expect("expression self->isa", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(Class)"]) + substrs=["(Class)"]) # This should fail expectedly. - self.expect("expression self->non_existent_member", - COMMAND_FAILED_AS_EXPECTED, error=True, - startstr = "error: 'MyString' does not have a member named 'non_existent_member'") + self.expect( + "expression self->non_existent_member", + COMMAND_FAILED_AS_EXPECTED, + error=True, + startstr="error: 'MyString' does not have a member named 'non_existent_member'") # Use expression parser. self.runCmd("expression self->str") @@ -163,7 +209,8 @@ class FoundationTestCase(TestBase): # self.runCmd("breakpoint delete 1") - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("process continue") @@ -171,12 +218,15 @@ class FoundationTestCase(TestBase): # test/foundation: expr -o -- my not working? # # Test new feature with r115115: - # Add "-o" option to "expression" which prints the object description if available. - self.expect("expression --object-description -- my", "Object description displayed correctly", - patterns = ["Hello from.*a.out.*with timestamp: "]) + # Add "-o" option to "expression" which prints the object description + # if available. + self.expect( + "expression --object-description -- my", + "Object description displayed correctly", + patterns=["Hello from.*a.out.*with timestamp: "]) @add_test_categories(['pyapi']) - def test_print_ivars_correctly (self): + def test_print_ivars_correctly(self): self.build() # See: <rdar://problem/8717050> lldb needs to use the ObjC runtime symbols for ivar offsets # Only fails for the ObjC 2.0 runtime. @@ -189,7 +239,8 @@ class FoundationTestCase(TestBase): self.assertTrue(break1, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) @@ -205,7 +256,7 @@ class FoundationTestCase(TestBase): cur_frame = thread.GetFrameAtIndex(0) line_number = cur_frame.GetLineEntry().GetLine() - self.assertTrue (line_number == self.line, "Hit the first breakpoint.") + self.assertTrue(line_number == self.line, "Hit the first breakpoint.") my_var = cur_frame.FindVariable("my") self.assertTrue(my_var, "Made a variable object for my") @@ -222,7 +273,9 @@ class FoundationTestCase(TestBase): my_str_value = int(my_str_var.GetValue(), 0) - self.assertTrue(str_value == my_str_value, "Got the correct value for my->str") + self.assertTrue( + str_value == my_str_value, + "Got the correct value for my->str") def test_expression_lookups_objc(self): """Test running an expression detect spurious debug info lookups (DWARF).""" @@ -231,32 +284,43 @@ class FoundationTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Stop at -[MyString initWithNSString:]. - lldbutil.run_break_set_by_symbol (self, '-[MyString initWithNSString:]', num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + '-[MyString initWithNSString:]', + num_expected_locations=1, + sym_exact=True) self.runCmd("run", RUN_SUCCEEDED) global file_index # Log any DWARF lookups ++file_index - logfile = os.path.join(os.getcwd(), "dwarf-lookups-" + self.getArchitecture() + "-" + str(file_index) + ".txt") + logfile = os.path.join( + os.getcwd(), + "dwarf-lookups-" + + self.getArchitecture() + + "-" + + str(file_index) + + ".txt") self.runCmd("log enable -f %s dwarf lookups" % (logfile)) self.runCmd("expr self") self.runCmd("log disable dwarf lookups") - + def cleanup(): - if os.path.exists (logfile): - os.unlink (logfile) - + if os.path.exists(logfile): + os.unlink(logfile) + self.addTearDownHook(cleanup) - - if os.path.exists (logfile): + + if os.path.exists(logfile): f = open(logfile) lines = f.readlines() num_errors = 0 for line in lines: if string.find(line, "$__lldb") != -1: if num_errors == 0: - print("error: found spurious name lookups when evaluating an expression:") + print( + "error: found spurious name lookups when evaluating an expression:") num_errors += 1 print(line, end='') self.assertTrue(num_errors == 0, "Spurious lookups detected") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py index 1ee01f7f35f..8f836a1da73 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py @@ -5,28 +5,44 @@ Test more expression command sequences with objective-c. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class FoundationTestCase2(TestBase): mydir = TestBase.compute_mydir(__file__) - + def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line numbers to break at. self.lines = [] - self.lines.append(line_number('main.m', '// Break here for selector: tests')) - self.lines.append(line_number('main.m', '// Break here for NSArray tests')) - self.lines.append(line_number('main.m', '// Break here for NSString tests')) - self.lines.append(line_number('main.m', '// Break here for description test')) - self.lines.append(line_number('main.m', '// Set break point at this line')) + self.lines.append( + line_number( + 'main.m', + '// Break here for selector: tests')) + self.lines.append( + line_number( + 'main.m', + '// Break here for NSArray tests')) + self.lines.append( + line_number( + 'main.m', + '// Break here for NSString tests')) + self.lines.append( + line_number( + 'main.m', + '// Break here for description test')) + self.lines.append( + line_number( + 'main.m', + '// Set break point at this line')) def test_more_expr_commands(self): """More expression commands for objective-c.""" @@ -36,15 +52,16 @@ class FoundationTestCase2(TestBase): # Create a bunch of breakpoints. for line in self.lines: - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # Test_Selector: self.runCmd("thread backtrace") self.expect("expression (char *)sel_getName(sel)", - substrs = ["(char *)", - "length"]) + substrs=["(char *)", + "length"]) self.runCmd("process continue") @@ -59,8 +76,8 @@ class FoundationTestCase2(TestBase): # Test_MyString: self.runCmd("thread backtrace") self.expect("expression (char *)sel_getName(_cmd)", - substrs = ["(char *)", - "description"]) + substrs=["(char *)", + "description"]) self.runCmd("process continue") @@ -72,25 +89,29 @@ class FoundationTestCase2(TestBase): # Break inside Test_NSArray: line = self.lines[1] - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # Test_NSArray: self.runCmd("thread backtrace") self.expect("expression (int)[nil_mutable_array count]", - patterns = ["\(int\) \$.* = 0"]) + patterns=["\(int\) \$.* = 0"]) self.expect("expression (int)[array1 count]", - patterns = ["\(int\) \$.* = 3"]) + patterns=["\(int\) \$.* = 3"]) self.expect("expression (int)[array2 count]", - patterns = ["\(int\) \$.* = 3"]) + patterns=["\(int\) \$.* = 3"]) self.expect("expression (int)array1.count", - patterns = ["\(int\) \$.* = 3"]) + patterns=["\(int\) \$.* = 3"]) self.expect("expression (int)array2.count", - patterns = ["\(int\) \$.* = 3"]) + patterns=["\(int\) \$.* = 3"]) self.runCmd("process continue") - @expectedFailureAll(oslist=["macosx"], debug_info="gmodules", bugnumber="llvm.org/pr27861") + @expectedFailureAll( + oslist=["macosx"], + debug_info="gmodules", + bugnumber="llvm.org/pr27861") def test_NSString_expr_commands(self): """Test expression commands for NSString.""" self.build() @@ -99,20 +120,21 @@ class FoundationTestCase2(TestBase): # Break inside Test_NSString: line = self.lines[2] - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # Test_NSString: self.runCmd("thread backtrace") self.expect("expression (int)[str length]", - patterns = ["\(int\) \$.* ="]) + patterns=["\(int\) \$.* ="]) self.expect("expression (int)[str_id length]", - patterns = ["\(int\) \$.* ="]) + patterns=["\(int\) \$.* ="]) self.expect("expression [str description]", - patterns = ["\(id\) \$.* = 0x"]) + patterns=["\(id\) \$.* = 0x"]) self.expect("expression (id)[str_id description]", - patterns = ["\(id\) \$.* = 0x"]) + patterns=["\(id\) \$.* = 0x"]) self.expect("expression str.length") self.expect("expression str.description") self.expect('expression str = @"new"') @@ -125,15 +147,21 @@ class FoundationTestCase2(TestBase): self.build() exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - + line = self.lines[4] - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - - self.expect("expression --show-types -- *my", - patterns = ["\(MyString\) \$.* = ", "\(MyBase\)", "\(NSObject\)", "\(Class\)"]) + + self.expect( + "expression --show-types -- *my", + patterns=[ + "\(MyString\) \$.* = ", + "\(MyBase\)", + "\(NSObject\)", + "\(Class\)"]) self.runCmd("process continue") @expectedFailureAll(archs=["i[3-6]86"]) @@ -142,30 +170,35 @@ class FoundationTestCase2(TestBase): self.build() exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - + line = self.lines[4] - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - self.expect('po [NSError errorWithDomain:@"Hello" code:35 userInfo:@{@"NSDescription" : @"be completed."}]', - substrs = ["Error Domain=Hello", "Code=35", "be completed."]) + self.expect( + 'po [NSError errorWithDomain:@"Hello" code:35 userInfo:@{@"NSDescription" : @"be completed."}]', + substrs=[ + "Error Domain=Hello", + "Code=35", + "be completed."]) self.runCmd("process continue") - + def test_NSError_p(self): """Test that p of the result of an unknown method does require a cast.""" self.build() exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - + line = self.lines[4] - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - self.expect("p [NSError thisMethodIsntImplemented:0]", - error = True, - patterns = ["no known method", "cast the message send to the method's return type"]) + self.expect("p [NSError thisMethodIsntImplemented:0]", error=True, patterns=[ + "no known method", "cast the message send to the method's return type"]) self.runCmd("process continue") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py index 13ef44f195b..8ef9f39434e 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py @@ -5,14 +5,15 @@ Test SBValue.GetObjectDescription() with the value from SBTarget.FindGlobalVaria from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjectDescriptionAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,7 +23,8 @@ class ObjectDescriptionAPITestCase(TestBase): TestBase.setUp(self) # Find the line number to break at. self.source = 'main.m' - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # rdar://problem/10857337 @skipUnlessDarwin @@ -42,11 +44,13 @@ class ObjectDescriptionAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Make sure we hit our breakpoint: - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] frame0 = thread.GetFrameAtIndex(0) @@ -59,7 +63,8 @@ class ObjectDescriptionAPITestCase(TestBase): print("val:", v) print("object description:", v.GetObjectDescription()) if v.GetName() == 'my_global_str': - self.assertTrue(v.GetObjectDescription() == 'This is a global string') + self.assertTrue(v.GetObjectDescription() == + 'This is a global string') # But not here! value_list2 = target.FindGlobalVariables('my_global_str', 3) @@ -69,4 +74,5 @@ class ObjectDescriptionAPITestCase(TestBase): print("val:", v) print("object description:", v.GetObjectDescription()) if v.GetName() == 'my_global_str': - self.assertTrue(v.GetObjectDescription() == 'This is a global string') + self.assertTrue(v.GetObjectDescription() == + 'This is a global string') diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py index 8b37f9309ac..334ebba8e64 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py @@ -5,19 +5,23 @@ Test that Objective-C methods from the runtime work correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class RuntimeTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["macosx"], debug_info="gmodules", bugnumber="llvm.org/pr27862") + @expectedFailureAll( + oslist=["macosx"], + debug_info="gmodules", + bugnumber="llvm.org/pr27862") def test_break(self): """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'.""" if self.getArchitecture() != 'x86_64': @@ -28,23 +32,31 @@ class RuntimeTypesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Stop at -[MyString description]. - lldbutil.run_break_set_by_symbol (self, '-[MyString description]', num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + '-[MyString description]', + num_expected_locations=1, + sym_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The backtrace should show we stop at -[MyString description]. self.expect("thread backtrace", "Stop at -[MyString description]", - substrs = ["a.out`-[MyString description]"]) + substrs=["a.out`-[MyString description]"]) # Use runtime information about NSString. # The length property should be usable. self.expect("expression str.length", VARIABLES_DISPLAYED_CORRECTLY, - patterns = [r"(\(unsigned long long\))|\(NSUInteger\)"]) + patterns=[r"(\(unsigned long long\))|\(NSUInteger\)"]) # Static methods on NSString should work. - self.expect("expr [NSString stringWithCString:\"foo\" encoding:1]", VALID_TYPE, - substrs = ["(id)", "$1"]) + self.expect( + "expr [NSString stringWithCString:\"foo\" encoding:1]", + VALID_TYPE, + substrs=[ + "(id)", + "$1"]) self.expect("po $1", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo"]) + substrs=["foo"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py index b75a874c814..6e5bc4d9fb0 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py @@ -5,7 +5,6 @@ Test symbol table access for main.m. from __future__ import print_function - import os import time @@ -14,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class FoundationSymtabTestCase(TestBase): @@ -23,7 +23,8 @@ class FoundationSymtabTestCase(TestBase): '-[MyString dealloc]', '-[MyString description]', '-[MyString descriptionPauses]', # synthesized property - '-[MyString setDescriptionPauses:]', # synthesized property + # synthesized property + '-[MyString setDescriptionPauses:]', 'Test_Selector', 'Test_NSString', 'Test_MyString', @@ -42,7 +43,8 @@ class FoundationSymtabTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # # Exercise Python APIs to access the symbol table entries. diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/TestGlobalObjects.py b/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/TestGlobalObjects.py index 24ae1a8852b..bcd4a41e0df 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/TestGlobalObjects.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/TestGlobalObjects.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCGlobalVar(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,26 +30,31 @@ class TestObjCGlobalVar(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bkpt = target.BreakpointCreateBySourceRegex ('NSLog', self.main_source) + bkpt = target.BreakpointCreateBySourceRegex('NSLog', self.main_source) self.assertTrue(bkpt, VALID_BREAKPOINT) # Before we launch, make an SBValue for our global object pointer: g_obj_ptr = target.FindFirstGlobalVariable("g_obj_ptr") self.assertTrue(g_obj_ptr.GetError().Success(), "Made the g_obj_ptr") - self.assertTrue(g_obj_ptr.GetValueAsUnsigned(10) == 0, "g_obj_ptr is initially null") + self.assertTrue( + g_obj_ptr.GetValueAsUnsigned(10) == 0, + "g_obj_ptr is initially null") # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, bkpt) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, bkpt) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint 1.") + self.fail("Failed to stop at breakpoint 1.") thread = threads[0] dyn_value = g_obj_ptr.GetDynamicValue(lldb.eDynamicCanRunTarget) - self.assertTrue(dyn_value.GetError().Success(), "Dynamic value is valid") + self.assertTrue( + dyn_value.GetError().Success(), + "Dynamic value is valid") self.assertTrue(dyn_value.GetObjectDescription() == "Some NSString") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py b/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py index ee5589cb96c..ee21189ab7c 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py @@ -3,7 +3,6 @@ from __future__ import print_function - import unittest2 import os import subprocess @@ -14,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class HiddenIvarsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,11 +25,14 @@ class HiddenIvarsTestCase(TestBase): self.source = 'main.m' self.line = line_number(self.source, '// breakpoint1') # The makefile names of the shared libraries as they appear in DYLIB_NAME. - # The names should have no loading "lib" or extension as they will be localized + # The names should have no loading "lib" or extension as they will be + # localized self.shlib_names = ["InternalDefiner"] @skipUnlessDarwin - @skipIf(debug_info=no_match("dsym"), bugnumber="This test requires a stripped binary and a dSYM") + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") def test_expr_stripped(self): if self.getArchitecture() == 'i386': self.skipTest("requires modern objc runtime") @@ -46,7 +49,9 @@ class HiddenIvarsTestCase(TestBase): self.expr(False) @skipUnlessDarwin - @skipIf(debug_info=no_match("dsym"), bugnumber="This test requires a stripped binary and a dSYM") + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") def test_frame_variable_stripped(self): if self.getArchitecture() == 'i386': self.skipTest("requires modern objc runtime") @@ -70,14 +75,22 @@ class HiddenIvarsTestCase(TestBase): else: self.build() self.common_setup(False) - self.expect("frame variable k->bar", VARIABLES_DISPLAYED_CORRECTLY, substrs = ["= 3"]) - + self.expect( + "frame variable k->bar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 3"]) + def common_setup(self, strip): - + if strip: - self.assertTrue(subprocess.call(['/usr/bin/strip', '-Sx', 'libInternalDefiner.dylib']) == 0, 'stripping dylib succeeded') - self.assertTrue(subprocess.call(['/bin/rm', '-rf', 'libInternalDefiner.dylib.dSYM']) == 0, 'remove dylib dSYM file succeeded') - self.assertTrue(subprocess.call(['/usr/bin/strip', '-Sx', 'a.out']) == 0, 'stripping a.out succeeded') + self.assertTrue(subprocess.call( + ['/usr/bin/strip', '-Sx', 'libInternalDefiner.dylib']) == 0, 'stripping dylib succeeded') + self.assertTrue(subprocess.call(['/bin/rm', + '-rf', + 'libInternalDefiner.dylib.dSYM']) == 0, + 'remove dylib dSYM file succeeded') + self.assertTrue(subprocess.call( + ['/usr/bin/strip', '-Sx', 'a.out']) == 0, 'stripping a.out succeeded') # Create a target by the debugger. target = self.dbg.CreateTarget("a.out") self.assertTrue(target, VALID_TARGET) @@ -85,91 +98,140 @@ class HiddenIvarsTestCase(TestBase): # Create the breakpoint inside function 'main'. breakpoint = target.BreakpointCreateByLocation(self.source, self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) - - # Register our shared libraries for remote targets so they get automatically uploaded - environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - + exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) def expr(self, strip): self.common_setup(strip) # This should display correctly. - self.expect("expression (j->_definer->foo)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 4"]) + self.expect( + "expression (j->_definer->foo)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 4"]) - self.expect("expression (j->_definer->bar)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 5"]) + self.expect( + "expression (j->_definer->bar)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 5"]) if strip: - self.expect("expression *(j->_definer)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 4"]) + self.expect( + "expression *(j->_definer)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo = 4"]) else: - self.expect("expression *(j->_definer)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 4", "bar = 5"]) + self.expect( + "expression *(j->_definer)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 4", + "bar = 5"]) self.expect("expression (k->foo)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 2"]) + substrs=["= 2"]) self.expect("expression (k->bar)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 3"]) + substrs=["= 3"]) - self.expect("expression k.filteredDataSource", VARIABLES_DISPLAYED_CORRECTLY, - substrs = [' = 0x', '"2 elements"']) + self.expect( + "expression k.filteredDataSource", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + ' = 0x', + '"2 elements"']) if strip: self.expect("expression *(k)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 2", ' = 0x', '"2 elements"']) - else: - self.expect("expression *(k)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 2", "bar = 3", '_filteredDataSource = 0x', '"2 elements"']) + substrs=["foo = 2", ' = 0x', '"2 elements"']) + else: + self.expect( + "expression *(k)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 2", + "bar = 3", + '_filteredDataSource = 0x', + '"2 elements"']) def frame_var(self, strip): self.common_setup(strip) # This should display correctly. - self.expect("frame variable j->_definer->foo", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 4"]) + self.expect( + "frame variable j->_definer->foo", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 4"]) if not strip: - self.expect("frame variable j->_definer->bar", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 5"]) - + self.expect( + "frame variable j->_definer->bar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 5"]) + if strip: - self.expect("frame variable *j->_definer", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 4"]) + self.expect( + "frame variable *j->_definer", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo = 4"]) else: - self.expect("frame variable *j->_definer", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 4", "bar = 5"]) + self.expect( + "frame variable *j->_definer", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 4", + "bar = 5"]) self.expect("frame variable k->foo", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["= 2"]) + substrs=["= 2"]) - self.expect("frame variable k->_filteredDataSource", VARIABLES_DISPLAYED_CORRECTLY, - substrs = [' = 0x', '"2 elements"']) + self.expect( + "frame variable k->_filteredDataSource", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + ' = 0x', + '"2 elements"']) if strip: - self.expect("frame variable *k", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 2", '_filteredDataSource = 0x', '"2 elements"']) + self.expect( + "frame variable *k", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 2", + '_filteredDataSource = 0x', + '"2 elements"']) else: - self.expect("frame variable *k", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo = 2", "bar = 3", '_filteredDataSource = 0x', '"2 elements"']) + self.expect( + "frame variable *k", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 2", + "bar = 3", + '_filteredDataSource = 0x', + '"2 elements"']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py b/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py index b91725d57c6..94f01e4045b 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py @@ -5,8 +5,8 @@ Test that dynamically discovered ivars of type IMP do not crash LLDB from __future__ import print_function - -import os, time +import os +import time import re import lldb @@ -15,7 +15,8 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -def execute_command (command): + +def execute_command(command): # print('%% %s' % (command)) (exit_status, output) = seven.get_command_status_output(command) # if output: @@ -23,6 +24,7 @@ def execute_command (command): # print('status = %u' % (exit_status)) return exit_status + class ObjCiVarIMPTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -34,8 +36,9 @@ class ObjCiVarIMPTestCase(TestBase): if self.getArchitecture() == 'i386': # rdar://problem/9946499 self.skipTest("Dynamic types for ObjC V1 runtime not implemented") - + execute_command("make repro") + def cleanup(): execute_command("make cleanup") self.addTearDownHook(cleanup) @@ -43,23 +46,25 @@ class ObjCiVarIMPTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoint - bkpt = lldbutil.run_break_set_by_source_regexp (self, "break here") + bkpt = lldbutil.run_break_set_by_source_regexp(self, "break here") # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - self.expect('frame variable --ptr-depth=1 --show-types -d run -- object', substrs=[ - '(MyClass *) object = 0x', - '(void *) myImp = 0x' - ]) - self.expect('disassemble --start-address `((MyClass*)object)->myImp`', substrs=[ - '-[MyClass init]' - ]) + self.expect( + 'frame variable --ptr-depth=1 --show-types -d run -- object', + substrs=[ + '(MyClass *) object = 0x', + '(void *) myImp = 0x']) + self.expect( + 'disassemble --start-address `((MyClass*)object)->myImp`', + substrs=['-[MyClass init]']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py b/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py index fece47625a8..8af906e0842 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py @@ -3,10 +3,10 @@ from __future__ import print_function - from distutils.version import StrictVersion import unittest2 -import os, time +import os +import time import lldb import platform @@ -14,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCModulesAutoImportTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,28 +27,30 @@ class ObjCModulesAutoImportTestCase(TestBase): @skipUnlessDarwin @unittest2.expectedFailure("rdar://problem/19991953") - @expectedFailureDarwin # clang: error: unknown argument: '-gmodules' - @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") + @expectedFailureDarwin # clang: error: unknown argument: '-gmodules' + @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion( + '12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") def test_expr(self): self.build() exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) self.runCmd("settings set target.auto-import-clang-modules true") self.expect("p getpid()", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["pid_t"]) + substrs=["pid_t"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py b/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py index 56fcaa05078..aa8414267db 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py @@ -3,7 +3,6 @@ from __future__ import print_function - import unittest2 import platform from distutils.version import StrictVersion @@ -12,6 +11,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class IncompleteModulesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,7 +24,8 @@ class IncompleteModulesTestCase(TestBase): @skipUnlessDarwin @unittest2.expectedFailure("rdar://20416388") - @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") + @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion( + '12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") @skipIfDarwin # llvm.org/pr26267 def test_expr(self): self.build() @@ -32,29 +33,37 @@ class IncompleteModulesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) - self.runCmd("settings set target.clang-module-search-paths \"" + os.getcwd() + "\"") + self.runCmd( + "settings set target.clang-module-search-paths \"" + + os.getcwd() + + "\"") self.expect("expr @import myModule; 3", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["int", "3"]) + substrs=["int", "3"]) - self.expect("expr [myObject privateMethod]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["int", "5"]) + self.expect( + "expr [myObject privateMethod]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "int", + "5"]) self.expect("expr MIN(2,3)", "#defined macro was found", - substrs = ["int", "2"]) + substrs=["int", "2"]) self.expect("expr MAX(2,3)", "#undefd macro was correcltly not found", - error=True) + error=True) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py b/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py index 6a9d9b518e1..87c75cefe64 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py @@ -3,11 +3,11 @@ from __future__ import print_function - from distutils.version import StrictVersion import unittest2 -import os, time +import os +import time import platform import lldb @@ -15,6 +15,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ModulesInlineFunctionsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,7 +27,8 @@ class ModulesInlineFunctionsTestCase(TestBase): self.line = line_number('main.m', '// Set breakpoint here.') @skipUnlessDarwin - @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") + @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion( + '12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") @expectedFailureDarwin("llvm.org/pr25743") def test_expr(self): self.build() @@ -34,23 +36,27 @@ class ModulesInlineFunctionsTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) - self.runCmd("settings set target.clang-module-search-paths \"" + os.getcwd() + "\"") + self.runCmd( + "settings set target.clang-module-search-paths \"" + + os.getcwd() + + "\"") self.expect("expr @import myModule; 3", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["int", "3"]) + substrs=["int", "3"]) self.expect("expr isInline(2)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["4"]) + substrs=["4"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py b/lldb/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py index 0efdb305584..d91e2a70c8c 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py @@ -3,9 +3,9 @@ from __future__ import print_function - import unittest2 -import os, time +import os +import time import platform from distutils.version import StrictVersion @@ -14,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCModulesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,7 +27,8 @@ class ObjCModulesTestCase(TestBase): @skipUnlessDarwin @unittest2.expectedFailure("rdar://20416388") - @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") + @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion( + '12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") def test_expr(self): if not self.applies(): return @@ -36,36 +38,48 @@ class ObjCModulesTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) self.expect("expr @import Darwin; 3", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["int", "3"]) + substrs=["int", "3"]) self.expect("expr getpid()", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["pid_t"]) + substrs=["pid_t"]) - self.expect("expr @import Foundation; 4", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["int", "4"]) + self.expect( + "expr @import Foundation; 4", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "int", + "4"]) self.expect("expr string.length", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["NSUInteger", "5"]) + substrs=["NSUInteger", "5"]) self.expect("expr array.count", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["NSUInteger", "3"]) - - self.expect("p *[NSURL URLWithString:@\"http://lldb.llvm.org\"]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["NSURL", "isa", "_urlString"]) - - self.expect("p [NSURL URLWithString:@\"http://lldb.llvm.org\"].scheme", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["http"]) + substrs=["NSUInteger", "3"]) + + self.expect( + "p *[NSURL URLWithString:@\"http://lldb.llvm.org\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "NSURL", + "isa", + "_urlString"]) + + self.expect( + "p [NSURL URLWithString:@\"http://lldb.llvm.org\"].scheme", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["http"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py index c702eafa1f2..5b91f9848a9 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py @@ -5,13 +5,14 @@ Make sure that ivars of Objective-C++ classes are visible in LLDB. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCXXTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,9 +27,10 @@ class ObjCXXTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp (self, 'breakpoint 1', num_expected_locations=1) + lldbutil.run_break_set_by_source_regexp( + self, 'breakpoint 1', num_expected_locations=1) self.runCmd("run", RUN_SUCCEEDED) self.expect("expr f->f", "Found ivar in class", - substrs = ["= 3"]) + substrs=["= 3"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py index fa390cb0ad7..0f82cc68df8 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py @@ -5,20 +5,21 @@ Use lldb Python API to test base class resolution for ObjC classes from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCDynamicValueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): - # Call super's setUp(). + # Call super's setUp(). TestBase.setUp(self) self.line = line_number('main.m', '// Set breakpoint here.') @@ -36,13 +37,14 @@ class ObjCDynamicValueTestCase(TestBase): # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoints: target.BreakpointCreateByLocation('main.m', self.line) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) @@ -50,10 +52,17 @@ class ObjCDynamicValueTestCase(TestBase): var = self.frame().FindVariable("foo") var_ptr_type = var.GetType() var_pte_type = var_ptr_type.GetPointeeType() - self.assertTrue(var_ptr_type.GetNumberOfDirectBaseClasses() == 1, "Foo * has one base class") - self.assertTrue(var_pte_type.GetNumberOfDirectBaseClasses() == 1, "Foo has one base class") - - self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex(0).IsValid(), "Foo * has a valid base class") - self.assertTrue(var_pte_type.GetDirectBaseClassAtIndex(0).IsValid(), "Foo * has a valid base class") - - self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex(0).GetName() == var_pte_type.GetDirectBaseClassAtIndex(0).GetName(), "Foo and its pointer type don't agree on their base class") + self.assertTrue( + var_ptr_type.GetNumberOfDirectBaseClasses() == 1, + "Foo * has one base class") + self.assertTrue( + var_pte_type.GetNumberOfDirectBaseClasses() == 1, + "Foo has one base class") + + self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex( + 0).IsValid(), "Foo * has a valid base class") + self.assertTrue(var_pte_type.GetDirectBaseClassAtIndex( + 0).IsValid(), "Foo * has a valid base class") + + self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex(0).GetName() == var_pte_type.GetDirectBaseClassAtIndex( + 0).GetName(), "Foo and its pointer type don't agree on their base class") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py index 3ff76d4194d..d92daab8035 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCBuiltinTypes(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +20,8 @@ class TestObjCBuiltinTypes(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "main.cpp" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @add_test_categories(['pyapi']) @@ -32,25 +34,31 @@ class TestObjCBuiltinTypes(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - - # Now make sure we can call a function in the class method we've stopped in. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the class method we've + # stopped in. frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") - self.expect("expr (foo)", patterns = ["\(ns::id\) \$.* = 0"]) + self.expect("expr (foo)", patterns=["\(ns::id\) \$.* = 0"]) - self.expect("expr id my_id = 0; my_id", patterns = ["\(id\) \$.* = nil"]) + self.expect("expr id my_id = 0; my_id", patterns=["\(id\) \$.* = nil"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py index 901d84fb96d..1bd8f1af230 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py @@ -5,23 +5,24 @@ Use lldb Python API to make sure the dynamic checkers are doing their jobs. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCCheckerTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): - # Call super's setUp(). + # Call super's setUp(). TestBase.setUp(self) - # Find the line number to break for main.c. + # Find the line number to break for main.c. self.source_name = 'main.m' @skipUnlessDarwin @@ -36,41 +37,43 @@ class ObjCCheckerTestCase(TestBase): # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoints: - - main_bkpt = target.BreakpointCreateBySourceRegex ("Set a breakpoint here.", lldb.SBFileSpec (self.source_name)) + main_bkpt = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here.", lldb.SBFileSpec(self.source_name)) self.assertTrue(main_bkpt and main_bkpt.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, main_bkpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, main_bkpt) + self.assertTrue(len(threads) == 1) thread = threads[0] # - # The class Simple doesn't have a count method. Make sure that we don't + # The class Simple doesn't have a count method. Make sure that we don't # actually try to send count but catch it as an unrecognized selector. frame = thread.GetFrameAtIndex(0) expr_value = frame.EvaluateExpression("(int) [my_simple count]", False) expr_error = expr_value.GetError() - self.assertTrue (expr_error.Fail()) - + self.assertTrue(expr_error.Fail()) + # Make sure the call produced no NSLog stdout. stdout = process.GetSTDOUT(100) - self.assertTrue (stdout is None or (len(stdout) == 0)) - + self.assertTrue(stdout is None or (len(stdout) == 0)) + # Make sure the error is helpful: err_string = expr_error.GetCString() - self.assertTrue ("selector" in err_string) + self.assertTrue("selector" in err_string) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py index a5767562c07..5140f26c4fd 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCClassMethod(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,12 +20,13 @@ class TestObjCClassMethod(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "class.m" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @expectedFailureAll(archs=["i[3-6]86"]) @add_test_categories(['pyapi']) - #rdar://problem/9745789 "expression" can't call functions in class methods + # rdar://problem/9745789 "expression" can't call functions in class methods def test_with_python_api(self): """Test calling functions in class methods.""" self.build() @@ -33,25 +35,32 @@ class TestObjCClassMethod(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - - # Now make sure we can call a function in the class method we've stopped in. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the class method we've + # stopped in. frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") - cmd_value = frame.EvaluateExpression ("(int)[Foo doSomethingWithString:@\"Hello\"]") - self.assertTrue (cmd_value.IsValid()) - self.assertTrue (cmd_value.GetValueAsUnsigned() == 5) + cmd_value = frame.EvaluateExpression( + "(int)[Foo doSomethingWithString:@\"Hello\"]") + self.assertTrue(cmd_value.IsValid()) + self.assertTrue(cmd_value.GetValueAsUnsigned() == 5) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py index fc8a8129fa3..8b3f444b27a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py @@ -5,13 +5,14 @@ Test that we are able to properly report a usable dynamic type from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class ObjCDynamicSBTypeTestCase(TestBase): @@ -36,28 +37,57 @@ class ObjCDynamicSBTypeTestCase(TestBase): exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - v_object = self.frame().FindVariable("object").GetDynamicValue(lldb.eDynamicCanRunTarget) - v_base = self.frame().FindVariable("base").GetDynamicValue(lldb.eDynamicCanRunTarget) - self.assertTrue(v_object.GetTypeName() == "MyDerivedClass *", "The NSObject is properly type-named") - self.assertTrue(v_base.GetTypeName() == "MyDerivedClass *", "The Base is properly type-named") + v_object = self.frame().FindVariable( + "object").GetDynamicValue(lldb.eDynamicCanRunTarget) + v_base = self.frame().FindVariable( + "base").GetDynamicValue(lldb.eDynamicCanRunTarget) + self.assertTrue( + v_object.GetTypeName() == "MyDerivedClass *", + "The NSObject is properly type-named") + self.assertTrue( + v_base.GetTypeName() == "MyDerivedClass *", + "The Base is properly type-named") object_type = v_object.GetType() base_type = v_base.GetType() - self.assertTrue(object_type.GetName() == "MyDerivedClass *", "The dynamic SBType for NSObject is for the correct type") - self.assertTrue(base_type.GetName() == "MyDerivedClass *", "The dynamic SBType for Base is for the correct type") + self.assertTrue( + object_type.GetName() == "MyDerivedClass *", + "The dynamic SBType for NSObject is for the correct type") + self.assertTrue( + base_type.GetName() == "MyDerivedClass *", + "The dynamic SBType for Base is for the correct type") object_pointee_type = object_type.GetPointeeType() base_pointee_type = base_type.GetPointeeType() - self.assertTrue(object_pointee_type.GetName() == "MyDerivedClass", "The dynamic type for NSObject figures out its pointee type just fine") - self.assertTrue(base_pointee_type.GetName() == "MyDerivedClass", "The dynamic type for Base figures out its pointee type just fine") + self.assertTrue( + object_pointee_type.GetName() == "MyDerivedClass", + "The dynamic type for NSObject figures out its pointee type just fine") + self.assertTrue( + base_pointee_type.GetName() == "MyDerivedClass", + "The dynamic type for Base figures out its pointee type just fine") - self.assertTrue(object_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", "The dynamic type for NSObject can go back to its base class") - self.assertTrue(base_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", "The dynamic type for Base can go back to its base class") + self.assertTrue( + object_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", + "The dynamic type for NSObject can go back to its base class") + self.assertTrue( + base_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", + "The dynamic type for Base can go back to its base class") - self.assertTrue(object_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex(0).GetName() == "NSObject", "The dynamic type for NSObject can go up the hierarchy") - self.assertTrue(base_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex(0).GetName() == "NSObject", "The dynamic type for Base can go up the hierarchy") + self.assertTrue(object_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex( + 0).GetName() == "NSObject", "The dynamic type for NSObject can go up the hierarchy") + self.assertTrue(base_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex( + 0).GetName() == "NSObject", "The dynamic type for Base can go up the hierarchy") - self.assertTrue(object_pointee_type.GetNumberOfFields() == 2, "The dynamic type for NSObject has 2 fields") - self.assertTrue(base_pointee_type.GetNumberOfFields() == 2, "The dynamic type for Base has 2 fields") + self.assertTrue( + object_pointee_type.GetNumberOfFields() == 2, + "The dynamic type for NSObject has 2 fields") + self.assertTrue( + base_pointee_type.GetNumberOfFields() == 2, + "The dynamic type for Base has 2 fields") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py index 8720ede04cb..a115d4f1573 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py @@ -5,30 +5,33 @@ Use lldb Python API to test dynamic values in ObjC from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCDynamicValueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): - # Call super's setUp(). + # Call super's setUp(). TestBase.setUp(self) - # Find the line number to break for main.c. + # Find the line number to break for main.c. self.source_name = 'dynamic-value.m' - self.set_property_line = line_number(self.source_name, '// This is the line in setProperty, make sure we step to here.') - self.handle_SourceBase = line_number(self.source_name, - '// Break here to check dynamic values.') - self.main_before_setProperty_line = line_number(self.source_name, - '// Break here to see if we can step into real method.') + self.set_property_line = line_number( + self.source_name, + '// This is the line in setProperty, make sure we step to here.') + self.handle_SourceBase = line_number( + self.source_name, '// Break here to check dynamic values.') + self.main_before_setProperty_line = line_number( + self.source_name, '// Break here to see if we can step into real method.') @skipUnlessDarwin @add_test_categories(['pyapi']) @@ -44,29 +47,33 @@ class ObjCDynamicValueTestCase(TestBase): # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoints: - handle_SourceBase_bkpt = target.BreakpointCreateByLocation(self.source_name, self.handle_SourceBase) + handle_SourceBase_bkpt = target.BreakpointCreateByLocation( + self.source_name, self.handle_SourceBase) self.assertTrue(handle_SourceBase_bkpt and handle_SourceBase_bkpt.GetNumLocations() == 1, VALID_BREAKPOINT) - main_before_setProperty_bkpt = target.BreakpointCreateByLocation(self.source_name, self.main_before_setProperty_line) + main_before_setProperty_bkpt = target.BreakpointCreateByLocation( + self.source_name, self.main_before_setProperty_line) self.assertTrue(main_before_setProperty_bkpt and main_before_setProperty_bkpt.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, main_before_setProperty_bkpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, main_before_setProperty_bkpt) + self.assertTrue(len(threads) == 1) thread = threads[0] # @@ -74,53 +81,73 @@ class ObjCDynamicValueTestCase(TestBase): # make sure we can get that properly: frame = thread.GetFrameAtIndex(0) - myObserver = frame.FindVariable('myObserver', lldb.eDynamicCanRunTarget) - self.assertTrue (myObserver) - myObserver_source = myObserver.GetChildMemberWithName ('_source', lldb.eDynamicCanRunTarget) - self.examine_SourceDerived_ptr (myObserver_source) + myObserver = frame.FindVariable( + 'myObserver', lldb.eDynamicCanRunTarget) + self.assertTrue(myObserver) + myObserver_source = myObserver.GetChildMemberWithName( + '_source', lldb.eDynamicCanRunTarget) + self.examine_SourceDerived_ptr(myObserver_source) # - # Make sure a static value can be correctly turned into a dynamic value. + # Make sure a static value can be correctly turned into a dynamic + # value. frame = thread.GetFrameAtIndex(0) - myObserver_static = frame.FindVariable('myObserver', lldb.eNoDynamicValues) - self.assertTrue (myObserver_static) - myObserver = myObserver_static.GetDynamicValue (lldb.eDynamicCanRunTarget) - myObserver_source = myObserver.GetChildMemberWithName ('_source', lldb.eDynamicCanRunTarget) - self.examine_SourceDerived_ptr (myObserver_source) + myObserver_static = frame.FindVariable( + 'myObserver', lldb.eNoDynamicValues) + self.assertTrue(myObserver_static) + myObserver = myObserver_static.GetDynamicValue( + lldb.eDynamicCanRunTarget) + myObserver_source = myObserver.GetChildMemberWithName( + '_source', lldb.eDynamicCanRunTarget) + self.examine_SourceDerived_ptr(myObserver_source) # The "frame var" code uses another path to get into children, so let's # make sure that works as well: result = lldb.SBCommandReturnObject() - self.expect('frame var -d run-target myObserver->_source', 'frame var finds its way into a child member', - patterns = ['\(SourceDerived \*\)']) - - # check that our ObjC GetISA() does a good job at hiding KVO swizzled classes - - self.expect('frame var -d run-target myObserver->_source -T', 'the KVO-ed class is hidden', - substrs = ['SourceDerived']) + self.expect( + 'frame var -d run-target myObserver->_source', + 'frame var finds its way into a child member', + patterns=['\(SourceDerived \*\)']) + + # check that our ObjC GetISA() does a good job at hiding KVO swizzled + # classes - self.expect('frame var -d run-target myObserver->_source -T', 'the KVO-ed class is hidden', matching = False, - substrs = ['NSKVONotify']) + self.expect( + 'frame var -d run-target myObserver->_source -T', + 'the KVO-ed class is hidden', + substrs=['SourceDerived']) + + self.expect( + 'frame var -d run-target myObserver->_source -T', + 'the KVO-ed class is hidden', + matching=False, + substrs=['NSKVONotify']) # This test is not entirely related to the main thrust of this test case, but since we're here, - # try stepping into setProperty, and make sure we get into the version in Source: + # try stepping into setProperty, and make sure we get into the version + # in Source: thread.StepInto() - threads = lldbutil.get_stopped_threads (process, lldb.eStopReasonPlanComplete) - self.assertTrue (len(threads) == 1) + threads = lldbutil.get_stopped_threads( + process, lldb.eStopReasonPlanComplete) + self.assertTrue(len(threads) == 1) line_entry = threads[0].GetFrameAtIndex(0).GetLineEntry() - self.assertEqual (line_entry.GetLine(), self.set_property_line) - self.assertEqual (line_entry.GetFileSpec().GetFilename(), self.source_name) + self.assertEqual(line_entry.GetLine(), self.set_property_line) + self.assertEqual( + line_entry.GetFileSpec().GetFilename(), + self.source_name) - # Okay, back to the main business. Continue to the handle_SourceBase and make sure we get the correct dynamic value. + # Okay, back to the main business. Continue to the handle_SourceBase + # and make sure we get the correct dynamic value. - threads = lldbutil.continue_to_breakpoint (process, handle_SourceBase_bkpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.continue_to_breakpoint( + process, handle_SourceBase_bkpt) + self.assertTrue(len(threads) == 1) thread = threads[0] frame = thread.GetFrameAtIndex(0) @@ -130,49 +157,55 @@ class ObjCDynamicValueTestCase(TestBase): noDynamic = lldb.eNoDynamicValues useDynamic = lldb.eDynamicCanRunTarget - object_static = frame.FindVariable ('object', noDynamic) - object_dynamic = frame.FindVariable ('object', useDynamic) + object_static = frame.FindVariable('object', noDynamic) + object_dynamic = frame.FindVariable('object', useDynamic) - # Delete this object to make sure that this doesn't cause havoc with the dynamic object that depends on it. + # Delete this object to make sure that this doesn't cause havoc with + # the dynamic object that depends on it. del (object_static) - self.examine_SourceDerived_ptr (object_dynamic) - + self.examine_SourceDerived_ptr(object_dynamic) + # Get "this" using FindValue, make sure that works too: - object_static = frame.FindValue ('object', lldb.eValueTypeVariableArgument, noDynamic) - object_dynamic = frame.FindValue ('object', lldb.eValueTypeVariableArgument, useDynamic) + object_static = frame.FindValue( + 'object', lldb.eValueTypeVariableArgument, noDynamic) + object_dynamic = frame.FindValue( + 'object', lldb.eValueTypeVariableArgument, useDynamic) del (object_static) - self.examine_SourceDerived_ptr (object_dynamic) + self.examine_SourceDerived_ptr(object_dynamic) # Get "this" using the EvaluateExpression: - object_static = frame.EvaluateExpression ('object', noDynamic) - object_dynamic = frame.EvaluateExpression ('object', useDynamic) + object_static = frame.EvaluateExpression('object', noDynamic) + object_dynamic = frame.EvaluateExpression('object', useDynamic) del (object_static) - self.examine_SourceDerived_ptr (object_dynamic) - + self.examine_SourceDerived_ptr(object_dynamic) + # Continue again to the handle_SourceBase and make sure we get the correct dynamic value. # This one looks exactly the same, but in fact this is an "un-KVO'ed" version of SourceBase, so - # its isa pointer points to SourceBase not NSKVOSourceBase or whatever... + # its isa pointer points to SourceBase not NSKVOSourceBase or + # whatever... - threads = lldbutil.continue_to_breakpoint (process, handle_SourceBase_bkpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.continue_to_breakpoint( + process, handle_SourceBase_bkpt) + self.assertTrue(len(threads) == 1) thread = threads[0] frame = thread.GetFrameAtIndex(0) # Get "object" using FindVariable: - object_static = frame.FindVariable ('object', noDynamic) - object_dynamic = frame.FindVariable ('object', useDynamic) + object_static = frame.FindVariable('object', noDynamic) + object_dynamic = frame.FindVariable('object', useDynamic) - # Delete this object to make sure that this doesn't cause havoc with the dynamic object that depends on it. + # Delete this object to make sure that this doesn't cause havoc with + # the dynamic object that depends on it. del (object_static) - self.examine_SourceDerived_ptr (object_dynamic) + self.examine_SourceDerived_ptr(object_dynamic) - def examine_SourceDerived_ptr (self, object): - self.assertTrue (object) - self.assertTrue (object.GetTypeName().find ('SourceDerived') != -1) - derivedValue = object.GetChildMemberWithName ('_derivedValue') - self.assertTrue (derivedValue) - self.assertTrue (int (derivedValue.GetValue(), 0) == 30) + def examine_SourceDerived_ptr(self, object): + self.assertTrue(object) + self.assertTrue(object.GetTypeName().find('SourceDerived') != -1) + derivedValue = object.GetChildMemberWithName('_derivedValue') + self.assertTrue(derivedValue) + self.assertTrue(int(derivedValue.GetValue(), 0) == 30) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py index 049b41e08d0..03121e6f956 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCIvarOffsets(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +20,8 @@ class TestObjCIvarOffsets(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "main.m" - self.stop_line = line_number(self.main_source, '// Set breakpoint here.') + self.stop_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @add_test_categories(['pyapi']) @@ -31,45 +33,54 @@ class TestObjCIvarOffsets(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateByLocation(self.main_source, self.stop_line) + breakpoint = target.BreakpointCreateByLocation( + self.main_source, self.stop_line) self.assertTrue(breakpoint, VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) - self.assertTrue (process, "Created a process.") - self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.") + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Created a process.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped it too.") - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] - + frame = thread.GetFrameAtIndex(0) - self.assertTrue (frame, "frame 0 is valid") - + self.assertTrue(frame, "frame 0 is valid") + mine = thread.GetFrameAtIndex(0).FindVariable("mine") self.assertTrue(mine, "Found local variable mine.") - + # Test the value object value for BaseClass->_backed_int error = lldb.SBError() - mine_backed_int = mine.GetChildMemberWithName ("_backed_int") - self.assertTrue(mine_backed_int, "Found mine->backed_int local variable.") - backed_value = mine_backed_int.GetValueAsSigned (error) - self.assertTrue (error.Success()) - self.assertTrue (backed_value == 1111) - + mine_backed_int = mine.GetChildMemberWithName("_backed_int") + self.assertTrue( + mine_backed_int, + "Found mine->backed_int local variable.") + backed_value = mine_backed_int.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(backed_value == 1111) + # Test the value object value for DerivedClass->_derived_backed_int - mine_derived_backed_int = mine.GetChildMemberWithName ("_derived_backed_int") - self.assertTrue(mine_derived_backed_int, "Found mine->derived_backed_int local variable.") - derived_backed_value = mine_derived_backed_int.GetValueAsSigned (error) - self.assertTrue (error.Success()) - self.assertTrue (derived_backed_value == 3333) + mine_derived_backed_int = mine.GetChildMemberWithName( + "_derived_backed_int") + self.assertTrue(mine_derived_backed_int, + "Found mine->derived_backed_int local variable.") + derived_backed_value = mine_derived_backed_int.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(derived_backed_value == 3333) # Make sure we also get bit-field offsets correct: - mine_flag2 = mine.GetChildMemberWithName ("flag2") + mine_flag2 = mine.GetChildMemberWithName("flag2") self.assertTrue(mine_flag2, "Found mine->flag2 local variable.") - flag2_value = mine_flag2.GetValueAsUnsigned (error) - self.assertTrue (error.Success()) - self.assertTrue (flag2_value == 7) + flag2_value = mine_flag2.GetValueAsUnsigned(error) + self.assertTrue(error.Success()) + self.assertTrue(flag2_value == 7) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py index 791ce27dad0..804905106df 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py @@ -1,4 +1,6 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, decorators.skipIfWindows]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py index d9007c57bfb..dde9ebadba4 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCIvarStripped(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,10 +20,13 @@ class TestObjCIvarStripped(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "main.m" - self.stop_line = line_number(self.main_source, '// Set breakpoint here.') + self.stop_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin - @skipIf(debug_info=no_match("dsym"), bugnumber="This test requires a stripped binary and a dSYM") + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") @add_test_categories(['pyapi']) def test_with_python_api(self): """Test that we can find stripped Objective-C ivars in the runtime""" @@ -34,26 +38,33 @@ class TestObjCIvarStripped(TestBase): self.dbg.HandleCommand("add-dsym a.out.dSYM") - breakpoint = target.BreakpointCreateByLocation(self.main_source, self.stop_line) - self.assertTrue(breakpoint.IsValid() and breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT) + breakpoint = target.BreakpointCreateByLocation( + self.main_source, self.stop_line) + self.assertTrue( + breakpoint.IsValid() and breakpoint.GetNumLocations() > 0, + VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) - self.assertTrue (process, "Created a process.") - self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.") + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Created a process.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped it too.") - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) thread = thread_list[0] - + frame = thread.GetFrameAtIndex(0) - self.assertTrue (frame, "frame 0 is valid") - + self.assertTrue(frame, "frame 0 is valid") + # Test the expression for mc->_foo error = lldb.SBError() - ivar = frame.EvaluateExpression ("(mc->_foo)") + ivar = frame.EvaluateExpression("(mc->_foo)") self.assertTrue(ivar, "Got result for mc->_foo") - ivar_value = ivar.GetValueAsSigned (error) - self.assertTrue (error.Success()) - self.assertTrue (ivar_value == 3) + ivar_value = ivar.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(ivar_value == 3) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py index 65139b16229..ba4cfdff6fc 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py @@ -3,9 +3,9 @@ from __future__ import print_function - import unittest2 -import os, time +import os +import time import platform from distutils.version import StrictVersion @@ -15,6 +15,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCNewSyntaxTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,80 +27,131 @@ class ObjCNewSyntaxTestCase(TestBase): self.line = line_number('main.m', '// Set breakpoint 0 here.') @skipUnlessDarwin - @expectedFailureAll(oslist=['macosx'], compiler='clang', compiler_version=['<', '7.0.0']) - @expectedFailureAll(oslist=['macosx'], debug_info=['gmodules'], bugnumber='rdar://27792848') - @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") + @expectedFailureAll( + oslist=['macosx'], + compiler='clang', + compiler_version=[ + '<', + '7.0.0']) + @expectedFailureAll( + oslist=['macosx'], + debug_info=['gmodules'], + bugnumber='rdar://27792848') + @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion( + '12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+") def test_expr(self): self.build() exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) - - self.expect("expr --object-description -- immutable_array[0]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo"]) - - self.expect("expr --object-description -- mutable_array[0]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["foo"]) - - self.expect("expr --object-description -- mutable_array[0] = @\"bar\"", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["bar"]) - - self.expect("expr --object-description -- mutable_array[0]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["bar"]) - - self.expect("expr --object-description -- immutable_dictionary[@\"key\"]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["value"]) - - self.expect("expr --object-description -- mutable_dictionary[@\"key\"]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["value"]) - - self.expect("expr --object-description -- mutable_dictionary[@\"key\"] = @\"object\"", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["object"]) - - self.expect("expr --object-description -- mutable_dictionary[@\"key\"]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["object"]) - - self.expect("expr --object-description -- @[ @\"foo\", @\"bar\" ]", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["NSArray", "foo", "bar"]) - - self.expect("expr --object-description -- @{ @\"key\" : @\"object\" }", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["key", "object"]) - - self.expect("expr --object-description -- @'a'", VARIABLES_DISPLAYED_CORRECTLY, - substrs = [str(ord('a'))]) - - self.expect("expr --object-description -- @1", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["1"]) - - self.expect("expr --object-description -- @1l", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["1"]) - - self.expect("expr --object-description -- @1ul", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["1"]) - - self.expect("expr --object-description -- @1ll", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["1"]) - - self.expect("expr --object-description -- @1ull", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["1"]) + substrs=[' resolved, hit count = 1']) + + self.expect( + "expr --object-description -- immutable_array[0]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo"]) + + self.expect( + "expr --object-description -- mutable_array[0]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo"]) + + self.expect( + "expr --object-description -- mutable_array[0] = @\"bar\"", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["bar"]) + + self.expect( + "expr --object-description -- mutable_array[0]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["bar"]) + + self.expect( + "expr --object-description -- immutable_dictionary[@\"key\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["value"]) + + self.expect( + "expr --object-description -- mutable_dictionary[@\"key\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["value"]) + + self.expect( + "expr --object-description -- mutable_dictionary[@\"key\"] = @\"object\"", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["object"]) + + self.expect( + "expr --object-description -- mutable_dictionary[@\"key\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["object"]) + + self.expect( + "expr --object-description -- @[ @\"foo\", @\"bar\" ]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "NSArray", + "foo", + "bar"]) + + self.expect( + "expr --object-description -- @{ @\"key\" : @\"object\" }", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "key", + "object"]) + + self.expect("expr --object-description -- @'a'", + VARIABLES_DISPLAYED_CORRECTLY, substrs=[str(ord('a'))]) + + self.expect( + "expr --object-description -- @1", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1l", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1ul", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1ll", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1ull", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) self.expect("expr -- @123.45", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["NSNumber", "123.45"]) - - self.expect("expr --object-description -- @( 1 + 3 )", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["4"]) - self.expect("expr -- @((char*)\"Hello world\" + 6)", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["NSString", "world"]) + substrs=["NSNumber", "123.45"]) + + self.expect( + "expr --object-description -- @( 1 + 3 )", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["4"]) + self.expect( + "expr -- @((char*)\"Hello world\" + 6)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "NSString", + "world"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py index 2c3ac27d418..08e9594be69 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py @@ -10,8 +10,8 @@ optimized it into a register. from __future__ import print_function - -import os, time +import os +import time import lldb import re @@ -21,6 +21,8 @@ from lldbsuite.test import lldbutil # rdar://problem/9087739 # test failure: objc_optimized does not work for "-C clang -A i386" + + @skipUnlessDarwin class ObjcOptimizedTestCase(TestBase): @@ -35,15 +37,24 @@ class ObjcOptimizedTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_symbol (self, self.method_spec, num_expected_locations=1, sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, + self.method_spec, + num_expected_locations=1, + sym_exact=True) self.runCmd("run", RUN_SUCCEEDED) - self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, - substrs = ["stop reason = breakpoint"], - patterns = ["frame.*0:.*%s %s" % (self.myclass, self.mymethod)]) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint"], + patterns=[ + "frame.*0:.*%s %s" % + (self.myclass, + self.mymethod)]) self.expect('expression member', - startstr = "(int) $0 = 5") + startstr="(int) $0 = 5") # <rdar://problem/12693963> interp = self.dbg.GetCommandInterpreter() @@ -59,7 +70,7 @@ class ObjcOptimizedTestCase(TestBase): desired_pointer = mo.group(0) self.expect('expression (self)', - substrs = [("(%s *) $1 = " % self.myclass), desired_pointer]) + substrs=[("(%s *) $1 = " % self.myclass), desired_pointer]) self.expect('expression self->non_member', error=True, - substrs = ["does not have a member named 'non_member'"]) + substrs=["does not have a member named 'non_member'"]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py index 22fe3136a51..790bc9c0861 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py @@ -5,23 +5,24 @@ Use lldb Python API to verify that expression evaluation for property references from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCPropertyTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): - # Call super's setUp(). + # Call super's setUp(). TestBase.setUp(self) - # Find the line number to break for main.c. + # Find the line number to break for main.c. self.source_name = 'main.m' @skipUnlessDarwin @@ -36,61 +37,68 @@ class ObjCPropertyTestCase(TestBase): # Create a target from the debugger. - target = self.dbg.CreateTarget (exe) + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set up our breakpoints: - - main_bkpt = target.BreakpointCreateBySourceRegex ("Set a breakpoint here.", lldb.SBFileSpec (self.source_name)) + + main_bkpt = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here.", lldb.SBFileSpec(self.source_name)) self.assertTrue(main_bkpt and main_bkpt.GetNumLocations() == 1, VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, main_bkpt) - self.assertTrue (len(threads) == 1) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, main_bkpt) + self.assertTrue(len(threads) == 1) thread = threads[0] frame = thread.GetFrameAtIndex(0) - mine = frame.FindVariable ("mine") - self.assertTrue (mine.IsValid()) - access_count = mine.GetChildMemberWithName ("_access_count") - self.assertTrue (access_count.IsValid()) - start_access_count = access_count.GetValueAsUnsigned (123456) - self.assertTrue (start_access_count != 123456) + mine = frame.FindVariable("mine") + self.assertTrue(mine.IsValid()) + access_count = mine.GetChildMemberWithName("_access_count") + self.assertTrue(access_count.IsValid()) + start_access_count = access_count.GetValueAsUnsigned(123456) + self.assertTrue(start_access_count != 123456) # # The first set of tests test calling the getter & setter of # a property that actually only has a getter & setter and no # @property. # - nonexistant_value = frame.EvaluateExpression("mine.nonexistantInt", False) + nonexistant_value = frame.EvaluateExpression( + "mine.nonexistantInt", False) nonexistant_error = nonexistant_value.GetError() - self.assertTrue (nonexistant_error.Success()) - nonexistant_int = nonexistant_value.GetValueAsUnsigned (123456) - self.assertTrue (nonexistant_int == 6) - - # Calling the getter function would up the access count, so make sure that happened. - - new_access_count = access_count.GetValueAsUnsigned (123456) - self.assertTrue (new_access_count - start_access_count == 1) + self.assertTrue(nonexistant_error.Success()) + nonexistant_int = nonexistant_value.GetValueAsUnsigned(123456) + self.assertTrue(nonexistant_int == 6) + + # Calling the getter function would up the access count, so make sure + # that happened. + + new_access_count = access_count.GetValueAsUnsigned(123456) + self.assertTrue(new_access_count - start_access_count == 1) start_access_count = new_access_count # # Now call the setter, then make sure that - nonexistant_change = frame.EvaluateExpression("mine.nonexistantInt = 10", False) + nonexistant_change = frame.EvaluateExpression( + "mine.nonexistantInt = 10", False) nonexistant_error = nonexistant_change.GetError() - self.assertTrue (nonexistant_error.Success()) + self.assertTrue(nonexistant_error.Success()) + + # Calling the setter function would up the access count, so make sure + # that happened. - # Calling the setter function would up the access count, so make sure that happened. - - new_access_count = access_count.GetValueAsUnsigned (123456) - self.assertTrue (new_access_count - start_access_count == 1) + new_access_count = access_count.GetValueAsUnsigned(123456) + self.assertTrue(new_access_count - start_access_count == 1) start_access_count = new_access_count # @@ -100,30 +108,32 @@ class ObjCPropertyTestCase(TestBase): backed_value = frame.EvaluateExpression("mine.backedInt", False) backed_error = backed_value.GetError() - self.assertTrue (backed_error.Success()) - backing_value = mine.GetChildMemberWithName ("_backedInt") - self.assertTrue (backing_value.IsValid()) - self.assertTrue (backed_value.GetValueAsUnsigned (12345) == backing_value.GetValueAsUnsigned(23456)) + self.assertTrue(backed_error.Success()) + backing_value = mine.GetChildMemberWithName("_backedInt") + self.assertTrue(backing_value.IsValid()) + self.assertTrue(backed_value.GetValueAsUnsigned(12345) + == backing_value.GetValueAsUnsigned(23456)) unbacked_value = frame.EvaluateExpression("mine.unbackedInt", False) unbacked_error = unbacked_value.GetError() - self.assertTrue (unbacked_error.Success()) + self.assertTrue(unbacked_error.Success()) - idWithProtocol_value = frame.EvaluateExpression("mine.idWithProtocol", False) + idWithProtocol_value = frame.EvaluateExpression( + "mine.idWithProtocol", False) idWithProtocol_error = idWithProtocol_value.GetError() - self.assertTrue (idWithProtocol_error.Success()) - self.assertTrue (idWithProtocol_value.GetTypeName() == "id") + self.assertTrue(idWithProtocol_error.Success()) + self.assertTrue(idWithProtocol_value.GetTypeName() == "id") # Make sure that class property getter works as expected value = frame.EvaluateExpression("BaseClass.classInt", False) - self.assertTrue (value.GetError().Success()) - self.assertTrue (value.GetValueAsUnsigned (11111) == 123) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned(11111) == 123) # Make sure that class property setter works as expected value = frame.EvaluateExpression("BaseClass.classInt = 234", False) - self.assertTrue (value.GetError().Success()) + self.assertTrue(value.GetError().Success()) # Verify that setter above actually worked value = frame.EvaluateExpression("BaseClass.classInt", False) - self.assertTrue (value.GetError().Success()) - self.assertTrue (value.GetValueAsUnsigned (11111) == 234) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned(11111) == 234) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py index 791ce27dad0..804905106df 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py @@ -1,4 +1,6 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, decorators.skipIfWindows]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py index 7d88292a051..65dc5ace544 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCStaticMethodStripped(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,11 +20,14 @@ class TestObjCStaticMethodStripped(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "static.m" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @add_test_categories(['pyapi']) - @skipIf(debug_info=no_match("dsym"), bugnumber="This test requires a stripped binary and a dSYM") + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") #<rdar://problem/12042992> def test_with_python_api(self): """Test calling functions in static methods with a stripped binary.""" @@ -35,31 +39,42 @@ class TestObjCStaticMethodStripped(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - - # Now make sure we can call a function in the static method we've stopped in. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the static method we've + # stopped in. frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") - cmd_value = frame.EvaluateExpression ("(char *) sel_getName (_cmd)") - self.assertTrue (cmd_value.IsValid()) + cmd_value = frame.EvaluateExpression("(char *) sel_getName (_cmd)") + self.assertTrue(cmd_value.IsValid()) sel_name = cmd_value.GetSummary() - self.assertTrue (sel_name == "\"doSomethingWithString:\"", "Got the right value for the selector as string.") + self.assertTrue( + sel_name == "\"doSomethingWithString:\"", + "Got the right value for the selector as string.") - cmd_value = frame.EvaluateExpression ("[Foo doSomethingElseWithString:string]") - self.assertTrue (cmd_value.IsValid()) + cmd_value = frame.EvaluateExpression( + "[Foo doSomethingElseWithString:string]") + self.assertTrue(cmd_value.IsValid()) string_length = cmd_value.GetValueAsUnsigned() - self.assertTrue (string_length == 27, "Got the right value from another class method on the same class.") + self.assertTrue( + string_length == 27, + "Got the right value from another class method on the same class.") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py index ccba42db4eb..9f74d86d633 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCStaticMethod(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +20,8 @@ class TestObjCStaticMethod(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "static.m" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @add_test_categories(['pyapi']) @@ -32,31 +34,42 @@ class TestObjCStaticMethod(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - - # Now make sure we can call a function in the static method we've stopped in. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the static method we've + # stopped in. frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") - cmd_value = frame.EvaluateExpression ("(char *) sel_getName (_cmd)") - self.assertTrue (cmd_value.IsValid()) + cmd_value = frame.EvaluateExpression("(char *) sel_getName (_cmd)") + self.assertTrue(cmd_value.IsValid()) sel_name = cmd_value.GetSummary() - self.assertTrue (sel_name == "\"doSomethingWithString:\"", "Got the right value for the selector as string.") + self.assertTrue( + sel_name == "\"doSomethingWithString:\"", + "Got the right value for the selector as string.") - cmd_value = frame.EvaluateExpression ("[self doSomethingElseWithString:string]") - self.assertTrue (cmd_value.IsValid()) + cmd_value = frame.EvaluateExpression( + "[self doSomethingElseWithString:string]") + self.assertTrue(cmd_value.IsValid()) string_length = cmd_value.GetValueAsUnsigned() - self.assertTrue (string_length == 27, "Got the right value from another class method on the same class.") + self.assertTrue( + string_length == 27, + "Got the right value from another class method on the same class.") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py index d035287cfa0..8516ef3281f 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py @@ -3,16 +3,17 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCStepping(TestBase): - def getCategories (self): + def getCategories(self): return ['basic_process'] mydir = TestBase.compute_mydir(__file__) @@ -22,11 +23,16 @@ class TestObjCStepping(TestBase): TestBase.setUp(self) # Find the line numbers that we will step to in main: self.main_source = "stepping-tests.m" - self.source_randomMethod_line = line_number (self.main_source, '// Source randomMethod start line.') - self.sourceBase_randomMethod_line = line_number (self.main_source, '// SourceBase randomMethod start line.') - self.source_returnsStruct_start_line = line_number (self.main_source, '// Source returnsStruct start line.') - self.sourceBase_returnsStruct_start_line = line_number (self.main_source, '// SourceBase returnsStruct start line.') - self.stepped_past_nil_line = line_number (self.main_source, '// Step over nil should stop here.') + self.source_randomMethod_line = line_number( + self.main_source, '// Source randomMethod start line.') + self.sourceBase_randomMethod_line = line_number( + self.main_source, '// SourceBase randomMethod start line.') + self.source_returnsStruct_start_line = line_number( + self.main_source, '// Source returnsStruct start line.') + self.sourceBase_returnsStruct_start_line = line_number( + self.main_source, '// SourceBase returnsStruct start line.') + self.stepped_past_nil_line = line_number( + self.main_source, '// Step over nil should stop here.') @skipUnlessDarwin @add_test_categories(['pyapi']) @@ -38,57 +44,65 @@ class TestObjCStepping(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) breakpoints_to_disable = [] - break1 = target.BreakpointCreateBySourceRegex ("// Set first breakpoint here.", self.main_source_spec) + break1 = target.BreakpointCreateBySourceRegex( + "// Set first breakpoint here.", self.main_source_spec) self.assertTrue(break1, VALID_BREAKPOINT) - breakpoints_to_disable.append (break1) + breakpoints_to_disable.append(break1) - break2 = target.BreakpointCreateBySourceRegex ("// Set second breakpoint here.", self.main_source_spec) + break2 = target.BreakpointCreateBySourceRegex( + "// Set second breakpoint here.", self.main_source_spec) self.assertTrue(break2, VALID_BREAKPOINT) - breakpoints_to_disable.append (break2) + breakpoints_to_disable.append(break2) - break3 = target.BreakpointCreateBySourceRegex ('// Set third breakpoint here.', self.main_source_spec) + break3 = target.BreakpointCreateBySourceRegex( + '// Set third breakpoint here.', self.main_source_spec) self.assertTrue(break3, VALID_BREAKPOINT) - breakpoints_to_disable.append (break3) + breakpoints_to_disable.append(break3) - break4 = target.BreakpointCreateBySourceRegex ('// Set fourth breakpoint here.', self.main_source_spec) + break4 = target.BreakpointCreateBySourceRegex( + '// Set fourth breakpoint here.', self.main_source_spec) self.assertTrue(break4, VALID_BREAKPOINT) - breakpoints_to_disable.append (break4) + breakpoints_to_disable.append(break4) - break5 = target.BreakpointCreateBySourceRegex ('// Set fifth breakpoint here.', self.main_source_spec) + break5 = target.BreakpointCreateBySourceRegex( + '// Set fifth breakpoint here.', self.main_source_spec) self.assertTrue(break5, VALID_BREAKPOINT) - breakpoints_to_disable.append (break5) + breakpoints_to_disable.append(break5) - break_returnStruct_call_super = target.BreakpointCreateBySourceRegex ('// Source returnsStruct call line.', self.main_source_spec) + break_returnStruct_call_super = target.BreakpointCreateBySourceRegex( + '// Source returnsStruct call line.', self.main_source_spec) self.assertTrue(break_returnStruct_call_super, VALID_BREAKPOINT) - breakpoints_to_disable.append (break_returnStruct_call_super) + breakpoints_to_disable.append(break_returnStruct_call_super) - break_step_nil = target.BreakpointCreateBySourceRegex ('// Set nil step breakpoint here.', self.main_source_spec) + break_step_nil = target.BreakpointCreateBySourceRegex( + '// Set nil step breakpoint here.', self.main_source_spec) self.assertTrue(break_step_nil, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint 1.") + self.fail("Failed to stop at breakpoint 1.") thread = threads[0] mySource = thread.GetFrameAtIndex(0).FindVariable("mySource") self.assertTrue(mySource, "Found mySource local variable.") - mySource_isa = mySource.GetChildMemberWithName ("isa") + mySource_isa = mySource.GetChildMemberWithName("isa") self.assertTrue(mySource_isa, "Found mySource->isa local variable.") - className = mySource_isa.GetSummary () + className = mySource_isa.GetSummary() if self.TraceOn(): - print(mySource_isa) + print(mySource_isa) # Lets delete mySource so we can check that after stepping a child variable # with no parent persists and is useful. @@ -97,77 +111,114 @@ class TestObjCStepping(TestBase): # Now step in, that should leave us in the Source randomMethod: thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.source_randomMethod_line, "Stepped into Source randomMethod.") + self.assertTrue( + line_number == self.source_randomMethod_line, + "Stepped into Source randomMethod.") - # Now step in again, through the super call, and that should leave us in the SourceBase randomMethod: + # Now step in again, through the super call, and that should leave us + # in the SourceBase randomMethod: thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.sourceBase_randomMethod_line, "Stepped through super into SourceBase randomMethod.") + self.assertTrue( + line_number == self.sourceBase_randomMethod_line, + "Stepped through super into SourceBase randomMethod.") - threads = lldbutil.continue_to_breakpoint (process, break2) - self.assertTrue (len(threads) == 1, "Continued to second breakpoint in main.") + threads = lldbutil.continue_to_breakpoint(process, break2) + self.assertTrue( + len(threads) == 1, + "Continued to second breakpoint in main.") - # Again, step in twice gets us to a stret method and a stret super call: + # Again, step in twice gets us to a stret method and a stret super + # call: thread = threads[0] thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.source_returnsStruct_start_line, "Stepped into Source returnsStruct.") - - threads = lldbutil.continue_to_breakpoint (process, break_returnStruct_call_super) - self.assertTrue (len(threads) == 1, "Stepped to the call super line in Source returnsStruct.") + self.assertTrue( + line_number == self.source_returnsStruct_start_line, + "Stepped into Source returnsStruct.") + + threads = lldbutil.continue_to_breakpoint( + process, break_returnStruct_call_super) + self.assertTrue( + len(threads) == 1, + "Stepped to the call super line in Source returnsStruct.") thread = threads[0] thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.sourceBase_returnsStruct_start_line, "Stepped through super into SourceBase returnsStruct.") + self.assertTrue( + line_number == self.sourceBase_returnsStruct_start_line, + "Stepped through super into SourceBase returnsStruct.") - # Cool now continue to get past the call that initializes the Observer, and then do our steps in again to see that - # we can find our way when we're stepping through a KVO swizzled object. + # Cool now continue to get past the call that initializes the Observer, and then do our steps in again to see that + # we can find our way when we're stepping through a KVO swizzled + # object. - threads = lldbutil.continue_to_breakpoint (process, break3) - self.assertTrue (len(threads) == 1, "Continued to third breakpoint in main, our object should now be swizzled.") + threads = lldbutil.continue_to_breakpoint(process, break3) + self.assertTrue( + len(threads) == 1, + "Continued to third breakpoint in main, our object should now be swizzled.") - newClassName = mySource_isa.GetSummary () + newClassName = mySource_isa.GetSummary() if self.TraceOn(): - print(mySource_isa) + print(mySource_isa) - self.assertTrue (newClassName != className, "The isa did indeed change, swizzled!") + self.assertTrue( + newClassName != className, + "The isa did indeed change, swizzled!") # Now step in, that should leave us in the Source randomMethod: thread = threads[0] thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.source_randomMethod_line, "Stepped into Source randomMethod in swizzled object.") + self.assertTrue( + line_number == self.source_randomMethod_line, + "Stepped into Source randomMethod in swizzled object.") - # Now step in again, through the super call, and that should leave us in the SourceBase randomMethod: + # Now step in again, through the super call, and that should leave us + # in the SourceBase randomMethod: thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.sourceBase_randomMethod_line, "Stepped through super into SourceBase randomMethod in swizzled object.") - - threads = lldbutil.continue_to_breakpoint (process, break4) - self.assertTrue (len(threads) == 1, "Continued to fourth breakpoint in main.") + self.assertTrue( + line_number == self.sourceBase_randomMethod_line, + "Stepped through super into SourceBase randomMethod in swizzled object.") + + threads = lldbutil.continue_to_breakpoint(process, break4) + self.assertTrue( + len(threads) == 1, + "Continued to fourth breakpoint in main.") thread = threads[0] - # Again, step in twice gets us to a stret method and a stret super call: + # Again, step in twice gets us to a stret method and a stret super + # call: thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.source_returnsStruct_start_line, "Stepped into Source returnsStruct in swizzled object.") - - threads = lldbutil.continue_to_breakpoint(process, break_returnStruct_call_super) - self.assertTrue (len(threads) == 1, "Stepped to the call super line in Source returnsStruct - second time.") + self.assertTrue( + line_number == self.source_returnsStruct_start_line, + "Stepped into Source returnsStruct in swizzled object.") + + threads = lldbutil.continue_to_breakpoint( + process, break_returnStruct_call_super) + self.assertTrue( + len(threads) == 1, + "Stepped to the call super line in Source returnsStruct - second time.") thread = threads[0] thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.sourceBase_returnsStruct_start_line, "Stepped through super into SourceBase returnsStruct in swizzled object.") + self.assertTrue( + line_number == self.sourceBase_returnsStruct_start_line, + "Stepped through super into SourceBase returnsStruct in swizzled object.") for bkpt in breakpoints_to_disable: bkpt.SetEnabled(False) - threads = lldbutil.continue_to_breakpoint (process, break_step_nil) - self.assertTrue (len(threads) == 1, "Continued to step nil breakpoint.") + threads = lldbutil.continue_to_breakpoint(process, break_step_nil) + self.assertTrue(len(threads) == 1, "Continued to step nil breakpoint.") thread.StepInto() line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() - self.assertTrue (line_number == self.stepped_past_nil_line, "Step in over dispatch to nil stepped over.") + self.assertTrue( + line_number == self.stepped_past_nil_line, + "Step in over dispatch to nil stepped over.") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py index b2f2af76632..75f726340ef 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCStructArgument(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +20,8 @@ class TestObjCStructArgument(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "test.m" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @add_test_categories(['pyapi']) @@ -31,28 +33,36 @@ class TestObjCStructArgument(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") - self.expect("p [summer sumThings:tts]", substrs = ['9']) + self.expect("p [summer sumThings:tts]", substrs=['9']) - self.expect("po [NSValue valueWithRect:rect]", substrs = ['NSRect: {{0, 0}, {10, 20}}']) + self.expect( + "po [NSValue valueWithRect:rect]", + substrs=['NSRect: {{0, 0}, {10, 20}}']) - # Now make sure we can call a method that returns a struct without crashing. - cmd_value = frame.EvaluateExpression ("[provider getRange]") - self.assertTrue (cmd_value.IsValid()) + # Now make sure we can call a method that returns a struct without + # crashing. + cmd_value = frame.EvaluateExpression("[provider getRange]") + self.assertTrue(cmd_value.IsValid()) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py index 5a8722e71a4..6e56c06e8ae 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCClassMethod(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +20,8 @@ class TestObjCClassMethod(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "test.m" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @add_test_categories(['pyapi']) @@ -31,24 +33,30 @@ class TestObjCClassMethod(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") - # Now make sure we can call a method that returns a struct without crashing. - cmd_value = frame.EvaluateExpression ("[provider getRange]") - self.assertTrue (cmd_value.IsValid()) + # Now make sure we can call a method that returns a struct without + # crashing. + cmd_value = frame.EvaluateExpression("[provider getRange]") + self.assertTrue(cmd_value.IsValid()) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py index 39a0fb716ab..bf6befb4211 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestObjCSuperMethod(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,7 +20,8 @@ class TestObjCSuperMethod(TestBase): TestBase.setUp(self) # Find the line numbers to break inside main(). self.main_source = "class.m" - self.break_line = line_number(self.main_source, '// Set breakpoint here.') + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') @skipUnlessDarwin @expectedFailureAll(archs=["i[3-6]86"]) @@ -32,29 +34,35 @@ class TestObjCSuperMethod(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line) + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) self.assertTrue(bpt, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt) + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) # Make sure we stopped at the first breakpoint. - self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.") - self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.") - - # Now make sure we can call a function in the class method we've stopped in. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the class method we've + # stopped in. frame = thread_list[0].GetFrameAtIndex(0) - self.assertTrue (frame, "Got a valid frame 0 frame.") + self.assertTrue(frame, "Got a valid frame 0 frame.") - cmd_value = frame.EvaluateExpression ("[self get]") - self.assertTrue (cmd_value.IsValid()) - self.assertTrue (cmd_value.GetValueAsUnsigned() == 2) + cmd_value = frame.EvaluateExpression("[self get]") + self.assertTrue(cmd_value.IsValid()) + self.assertTrue(cmd_value.GetValueAsUnsigned() == 2) - cmd_value = frame.EvaluateExpression ("[super get]") - self.assertTrue (cmd_value.IsValid()) - self.assertTrue (cmd_value.GetValueAsUnsigned() == 1) + cmd_value = frame.EvaluateExpression("[super get]") + self.assertTrue(cmd_value.IsValid()) + self.assertTrue(cmd_value.GetValueAsUnsigned() == 1) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py b/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py index 33f7a0519fa..288f912dc79 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py @@ -5,13 +5,14 @@ Test "print object" where another thread blocks the print object from making pro from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class PrintObjTestCase(TestBase): @@ -47,14 +48,16 @@ class PrintObjTestCase(TestBase): self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.runCmd("thread backtrace all") # Let's get the current stopped thread. We'd like to switch to the # other thread to issue our 'po lock_me' command. import lldbsuite.test.lldbutil as lldbutil - this_thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + this_thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertTrue(this_thread) # Find the other thread. The iteration protocol of SBProcess and the @@ -65,7 +68,8 @@ class PrintObjTestCase(TestBase): other_thread = t break - # Set the other thread as the selected thread to issue our 'po' command.other + # Set the other thread as the selected thread to issue our 'po' + # command.other self.assertTrue(other_thread) process.SetSelectedThread(other_thread) if self.TraceOn(): @@ -86,4 +90,4 @@ class PrintObjTestCase(TestBase): break self.expect("po lock_me", OBJECT_PRINTED_CORRECTLY, - substrs = ['I am pretty special.']) + substrs=['I am pretty special.']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py b/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py index 32f2e7c8d6d..fe7d5d48ca7 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py @@ -5,13 +5,14 @@ Test that objective-c method returning BOOL works correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class MethodReturningBOOLTestCase(TestBase): @@ -35,12 +36,13 @@ class MethodReturningBOOLTestCase(TestBase): exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, - substrs = [" at %s:%d" % (self.main_source, self.line), - "stop reason = breakpoint"]) + substrs=[" at %s:%d" % (self.main_source, self.line), + "stop reason = breakpoint"]) # rdar://problem/9691614 self.runCmd('p (int)[my isValid]') diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py b/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py index a4654d4bd1b..1375a78f87a 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py @@ -5,13 +5,14 @@ Test that CoreFoundation classes CFGregorianDate and CFRange are not improperly from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class Rdar10967107TestCase(TestBase): @@ -35,11 +36,38 @@ class Rdar10967107TestCase(TestBase): exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # check that each type is correctly bound to its list of children - self.expect("frame variable cf_greg_date --raw", substrs = ['year','month','day','hour','minute','second']) - self.expect("frame variable cf_range --raw", substrs = ['location','length']) + self.expect( + "frame variable cf_greg_date --raw", + substrs=[ + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second']) + self.expect( + "frame variable cf_range --raw", + substrs=[ + 'location', + 'length']) # check that printing both does not somehow confuse LLDB - self.expect("frame variable --raw", substrs = ['year','month','day','hour','minute','second','location','length']) + self.expect( + "frame variable --raw", + substrs=[ + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'location', + 'length']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py b/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py index f1d38f8b7d3..26afe71d1de 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py @@ -5,13 +5,14 @@ Test that we do not attempt to make a dynamic type for a 'const char*' from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class Rdar10967107TestCase(TestBase): @@ -35,32 +36,47 @@ class Rdar10967107TestCase(TestBase): exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - # check that we correctly see the const char*, even with dynamic types on - self.expect("frame variable my_string", substrs = ['const char *']) - self.expect("frame variable my_string --dynamic-type run-target", substrs = ['const char *']) + # check that we correctly see the const char*, even with dynamic types + # on + self.expect("frame variable my_string", substrs=['const char *']) + self.expect( + "frame variable my_string --dynamic-type run-target", + substrs=['const char *']) # check that expr also gets it right - self.expect("expr my_string", substrs = ['const char *']) - self.expect("expr -d run -- my_string", substrs = ['const char *']) + self.expect("expr my_string", substrs=['const char *']) + self.expect("expr -d run -- my_string", substrs=['const char *']) # but check that we get the real Foolie as such - self.expect("frame variable my_foolie", substrs = ['FoolMeOnce *']) - self.expect("frame variable my_foolie --dynamic-type run-target", substrs = ['FoolMeOnce *']) + self.expect("frame variable my_foolie", substrs=['FoolMeOnce *']) + self.expect( + "frame variable my_foolie --dynamic-type run-target", + substrs=['FoolMeOnce *']) # check that expr also gets it right - self.expect("expr my_foolie", substrs = ['FoolMeOnce *']) - self.expect("expr -d run -- my_foolie", substrs = ['FoolMeOnce *']) + self.expect("expr my_foolie", substrs=['FoolMeOnce *']) + self.expect("expr -d run -- my_foolie", substrs=['FoolMeOnce *']) # now check that assigning a true string does not break anything self.runCmd("next") - # check that we correctly see the const char*, even with dynamic types on - self.expect("frame variable my_string", substrs = ['const char *']) - self.expect("frame variable my_string --dynamic-type run-target", substrs = ['const char *']) + # check that we correctly see the const char*, even with dynamic types + # on + self.expect("frame variable my_string", substrs=['const char *']) + self.expect( + "frame variable my_string --dynamic-type run-target", + substrs=['const char *']) # check that expr also gets it right - self.expect("expr my_string", substrs = ['const char *']) - self.expect("expr -d run -- my_string", substrs = ['const char *']) + self.expect("expr my_string", substrs=['const char *']) + self.expect("expr -d run -- my_string", substrs=['const char *']) # but check that we get the real Foolie as such - self.expect("frame variable my_foolie", substrs = ['FoolMeOnce *']) - self.expect("frame variable my_foolie --dynamic-type run-target", substrs = ['FoolMeOnce *']) + self.expect("frame variable my_foolie", substrs=['FoolMeOnce *']) + self.expect( + "frame variable my_foolie --dynamic-type run-target", + substrs=['FoolMeOnce *']) # check that expr also gets it right - self.expect("expr my_foolie", substrs = ['FoolMeOnce *']) - self.expect("expr -d run -- my_foolie", substrs = ['FoolMeOnce *']) + self.expect("expr my_foolie", substrs=['FoolMeOnce *']) + self.expect("expr -d run -- my_foolie", substrs=['FoolMeOnce *']) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py b/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py index 7bc92595ef3..d431e98ba79 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py @@ -5,13 +5,14 @@ Test that we are able to find out how many children NSWindow has from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class Rdar12408181TestCase(TestBase): @@ -35,15 +36,29 @@ class Rdar12408181TestCase(TestBase): exe = os.path.join(os.getcwd(), self.exe_name) self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) - if self.frame().EvaluateExpression('(void*)_CGSDefaultConnection()').GetValueAsUnsigned() != 0: + if self.frame().EvaluateExpression( + '(void*)_CGSDefaultConnection()').GetValueAsUnsigned() != 0: window = self.frame().FindVariable("window") window_dynamic = window.GetDynamicValue(lldb.eDynamicCanRunTarget) - self.assertTrue(window.GetNumChildren() > 1, "NSWindow (static) only has 1 child!") - self.assertTrue(window_dynamic.GetNumChildren() > 1, "NSWindow (dynamic) only has 1 child!") - self.assertTrue(window.GetChildAtIndex(0).IsValid(), "NSWindow (static) has an invalid child") - self.assertTrue(window_dynamic.GetChildAtIndex(0).IsValid(), "NSWindow (dynamic) has an invalid child") + self.assertTrue( + window.GetNumChildren() > 1, + "NSWindow (static) only has 1 child!") + self.assertTrue( + window_dynamic.GetNumChildren() > 1, + "NSWindow (dynamic) only has 1 child!") + self.assertTrue( + window.GetChildAtIndex(0).IsValid(), + "NSWindow (static) has an invalid child") + self.assertTrue( + window_dynamic.GetChildAtIndex(0).IsValid(), + "NSWindow (dynamic) has an invalid child") else: self.skipTest('no WindowServer connection') diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py b/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py index c8f9a9c82c6..820ddcd9ec6 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestRealDefinition(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,29 +23,35 @@ class TestRealDefinition(TestBase): self.build() self.common_setup() - line = line_number('Foo.m', '// Set breakpoint where Bar is an interface') - lldbutil.run_break_set_by_file_and_line (self, 'Foo.m', line, num_expected_locations=1, loc_exact=True); + line = line_number( + 'Foo.m', '// Set breakpoint where Bar is an interface') + lldbutil.run_break_set_by_file_and_line( + self, 'Foo.m', line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Run and stop at Foo self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) self.runCmd("continue", RUN_SUCCEEDED) # Run at stop at main self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) - + substrs=[' resolved, hit count = 1']) + # This should display correctly. - self.expect("frame variable foo->_bar->_hidden_ivar", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(NSString *)", "foo->_bar->_hidden_ivar = 0x"]) + self.expect( + "frame variable foo->_bar->_hidden_ivar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(NSString *)", + "foo->_bar->_hidden_ivar = 0x"]) @skipUnlessDarwin def test_frame_var_after_stop_at_implementation(self): @@ -54,29 +61,35 @@ class TestRealDefinition(TestBase): self.build() self.common_setup() - line = line_number('Bar.m', '// Set breakpoint where Bar is an implementation') - lldbutil.run_break_set_by_file_and_line (self, 'Bar.m', line, num_expected_locations=1, loc_exact=True) + line = line_number( + 'Bar.m', '// Set breakpoint where Bar is an implementation') + lldbutil.run_break_set_by_file_and_line( + self, 'Bar.m', line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # Run and stop at Foo self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) self.runCmd("continue", RUN_SUCCEEDED) # Run at stop at main self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) # This should display correctly. - self.expect("frame variable foo->_bar->_hidden_ivar", VARIABLES_DISPLAYED_CORRECTLY, - substrs = ["(NSString *)", "foo->_bar->_hidden_ivar = 0x"]) + self.expect( + "frame variable foo->_bar->_hidden_ivar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(NSString *)", + "foo->_bar->_hidden_ivar = 0x"]) def common_setup(self): exe = os.path.join(os.getcwd(), "a.out") @@ -84,4 +97,5 @@ class TestRealDefinition(TestBase): # Break inside the foo function which takes a bar_ptr argument. line = line_number('main.m', '// Set breakpoint in main') - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py b/lldb/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py index 004563c55be..48c4313375c 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py @@ -6,10 +6,11 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCSelfTestCase(TestBase): - + mydir = TestBase.compute_mydir(__file__) - + @skipUnlessDarwin def test_with_run_command(self): """Test that the appropriate member variables are available when stopped in Objective-C class and instance methods""" @@ -22,16 +23,17 @@ class ObjCSelfTestCase(TestBase): self.runCmd("process launch", RUN_SUCCEEDED) self.expect("expression -- m_a = 2", - startstr = "(int) $0 = 2") - + startstr="(int) $0 = 2") + self.runCmd("process continue") - + # This would be disallowed if we enforced const. But we don't. self.expect("expression -- m_a = 2", error=True) - - self.expect("expression -- s_a", - startstr = "(int) $1 = 5") + + self.expect("expression -- s_a", + startstr="(int) $1 = 5") def set_breakpoint(self, line): - lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/TestObjCSingleEntryDictionary.py b/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/TestObjCSingleEntryDictionary.py index 7c294ef8cc6..97b137818a0 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/TestObjCSingleEntryDictionary.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/TestObjCSingleEntryDictionary.py @@ -3,9 +3,9 @@ from __future__ import print_function - import unittest2 -import os, time +import os +import time import platform from distutils.version import StrictVersion @@ -15,6 +15,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCSingleEntryDictionaryTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -32,37 +33,46 @@ class ObjCSingleEntryDictionaryTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # Break inside the foo function which takes a bar_ptr argument. - lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, - substrs = [' resolved, hit count = 1']) + substrs=[' resolved, hit count = 1']) d1 = self.frame().FindVariable("d1") d1.SetPreferSyntheticValue(True) d1.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) - - self.assertTrue(d1.GetNumChildren() == 1, "dictionary has != 1 child elements") + + self.assertTrue( + d1.GetNumChildren() == 1, + "dictionary has != 1 child elements") pair = d1.GetChildAtIndex(0) pair.SetPreferSyntheticValue(True) pair.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) - - self.assertTrue(pair.GetNumChildren() == 2, "pair has != 2 child elements") - + + self.assertTrue( + pair.GetNumChildren() == 2, + "pair has != 2 child elements") + key = pair.GetChildMemberWithName("key") value = pair.GetChildMemberWithName("value") - + key.SetPreferSyntheticValue(True) key.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) value.SetPreferSyntheticValue(True) value.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) - - self.assertTrue(key.GetSummary() == '@"key"', "key doesn't contain key") - self.assertTrue(value.GetSummary() == '@"value"', "value doesn't contain value") + + self.assertTrue( + key.GetSummary() == '@"key"', + "key doesn't contain key") + self.assertTrue( + value.GetSummary() == '@"value"', + "value doesn't contain value") diff --git a/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/TestVariadicMethods.py b/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/TestVariadicMethods.py index 791ce27dad0..804905106df 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/TestVariadicMethods.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/TestVariadicMethods.py @@ -1,4 +1,6 @@ from lldbsuite.test import lldbinline from lldbsuite.test import decorators -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, decorators.skipIfWindows]) diff --git a/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py b/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py index 49bc148dd57..9b0c1f5eaef 100644 --- a/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py +++ b/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py @@ -1,4 +1,6 @@ from lldbsuite.test import decorators from lldbsuite.test import lldbinline -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, decorators.skipIfWindows]) diff --git a/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py b/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py index 483697789c3..d0f41393075 100644 --- a/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py +++ b/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py @@ -6,13 +6,13 @@ Test lldb ability to unwind a stack with a function containing a call to the from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BuiltinTrapTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,8 +23,14 @@ class BuiltinTrapTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Set break point at this line.') - @expectedFailureAll("llvm.org/pr15936", compiler="gcc", compiler_version=["<=","4.6"]) - @expectedFailureAll(archs="arm", compiler="gcc", triple=".*-android") # gcc generates incorrect linetable + @expectedFailureAll( + "llvm.org/pr15936", + compiler="gcc", + compiler_version=[ + "<=", + "4.6"]) + # gcc generates incorrect linetable + @expectedFailureAll(archs="arm", compiler="gcc", triple=".*-android") @expectedFailureAll(oslist=['linux'], archs=['arm']) @skipIfWindows def test_with_run_command(self): @@ -32,22 +38,22 @@ class BuiltinTrapTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, - num_expected_locations=1, - loc_exact=True) + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # print backtrace, expect both 'bar' and 'main' functions to be listed - self.expect('bt', substrs = ['bar', 'main']) + self.expect('bt', substrs=['bar', 'main']) # go up one frame self.runCmd("up", RUN_SUCCEEDED) # evaluate a local - self.expect('p foo', substrs = ['= 5']) + self.expect('p foo', substrs=['= 5']) diff --git a/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py b/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py index 8421a8d473e..82ed362ff60 100644 --- a/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py +++ b/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py @@ -6,13 +6,13 @@ over a thread creation instruction. from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CreateDuringInstructionStepTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,7 +23,10 @@ class CreateDuringInstructionStepTestCase(TestBase): @skipUnlessPlatform(['linux']) @expectedFailureAndroid('llvm.org/pr24737', archs=['arm']) - @expectedFailureAll(oslist=["linux"], archs=["arm"], bugnumber="llvm.org/pr24737") + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr24737") def test_step_inst(self): self.build(dictionary=self.getBuildFlags()) exe = os.path.join(os.getcwd(), "a.out") @@ -32,36 +35,53 @@ class CreateDuringInstructionStepTestCase(TestBase): # This should create a breakpoint in the stepping thread. breakpoint = target.BreakpointCreateByName("main") - self.assertTrue(breakpoint and breakpoint.IsValid(), "Breakpoint is valid") + self.assertTrue( + breakpoint and breakpoint.IsValid(), + "Breakpoint is valid") # Run the program. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) - threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint) + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) self.assertEqual(len(threads), 1, STOPPED_DUE_TO_BREAKPOINT) thread = threads[0] self.assertTrue(thread and thread.IsValid(), "Thread is valid") # Make sure we see only one threads - self.assertEqual(process.GetNumThreads(), 1, 'Number of expected threads and actual threads do not match.') + self.assertEqual( + process.GetNumThreads(), + 1, + 'Number of expected threads and actual threads do not match.') # Keep stepping until we see the thread creation while process.GetNumThreads() < 2: thread.StepInstruction(False) - self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED) - self.assertEqual(thread.GetStopReason(), lldb.eStopReasonPlanComplete, "Step operation succeeded") + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + self.assertEqual( + thread.GetStopReason(), + lldb.eStopReasonPlanComplete, + "Step operation succeeded") if self.TraceOn(): self.runCmd("disassemble --pc") if self.TraceOn(): self.runCmd("thread list") - # We have successfully caught thread creation. Now just run to completion + # We have successfully caught thread creation. Now just run to + # completion process.Continue() # At this point, the inferior process should have exited. diff --git a/lldb/packages/Python/lldbsuite/test/lldbbench.py b/lldb/packages/Python/lldbsuite/test/lldbbench.py index 6b568f87466..26ee6c21bd9 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbbench.py +++ b/lldb/packages/Python/lldbsuite/test/lldbbench.py @@ -8,6 +8,7 @@ import time # LLDB modules from .lldbtest import * + class Stopwatch(object): """Stopwatch provides a simple utility to start/stop your stopwatch multiple times. Each start/stop is equal to a lap, with its elapsed time accumulated @@ -64,7 +65,8 @@ class Stopwatch(object): if self.__start__ is None: self.__start__ = time.time() else: - raise Exception("start() already called, did you forget to stop() first?") + raise Exception( + "start() already called, did you forget to stop() first?") # Return self to facilitate the context manager __enter__ protocol. return self @@ -75,7 +77,7 @@ class Stopwatch(object): self.__total_elapsed__ += elapsed self.__laps__ += 1 self.__nums__.append(elapsed) - self.__start__ = None # Reset __start__ to be None again. + self.__start__ = None # Reset __start__ to be None again. else: raise Exception("stop() called without first start()?") @@ -87,32 +89,30 @@ class Stopwatch(object): """Equal to total elapsed time divided by the number of laps.""" return self.__total_elapsed__ / self.__laps__ - #def sigma(self): + # def sigma(self): # """Return the standard deviation of the available samples.""" # if self.__laps__ <= 0: # return None # return numpy.std(self.__nums__) def __str__(self): - return "Avg: %f (Laps: %d, Total Elapsed Time: %f, min=%f, max=%f)" % (self.avg(), - self.__laps__, - self.__total_elapsed__, - min(self.__nums__), - max(self.__nums__)) + return "Avg: %f (Laps: %d, Total Elapsed Time: %f, min=%f, max=%f)" % (self.avg( + ), self.__laps__, self.__total_elapsed__, min(self.__nums__), max(self.__nums__)) + class BenchBase(TestBase): """ Abstract base class for benchmark tests. """ + def setUp(self): """Fixture for unittest test case setup.""" super(BenchBase, self).setUp() - #TestBase.setUp(self) + # TestBase.setUp(self) self.stopwatch = Stopwatch() def tearDown(self): """Fixture for unittest test case teardown.""" super(BenchBase, self).tearDown() - #TestBase.tearDown(self) + # TestBase.tearDown(self) del self.stopwatch - diff --git a/lldb/packages/Python/lldbsuite/test/lldbcurses.py b/lldb/packages/Python/lldbsuite/test/lldbcurses.py index bc1fbf00d37..ae0082ce9b7 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbcurses.py +++ b/lldb/packages/Python/lldbsuite/test/lldbcurses.py @@ -4,14 +4,16 @@ from __future__ import absolute_import import curses import curses.panel import sys -import time +import time # Third-party modules import six # LLDB modules + class Point(object): + def __init__(self, x, y): self.x = x self.y = y @@ -27,11 +29,13 @@ class Point(object): def __ne__(self, rhs): return self.x != rhs.x or self.y != rhs.y - + def is_valid_coordinate(self): return self.x >= 0 and self.y >= 0 - + + class Size(object): + def __init__(self, w, h): self.w = w self.h = h @@ -48,11 +52,13 @@ class Size(object): def __ne__(self, rhs): return self.w != rhs.w or self.h != rhs.h + class Rect(object): + def __init__(self, x=0, y=0, w=0, h=0): self.origin = Point(x, y) self.size = Size(w, h) - + def __repr__(self): return str(self) @@ -70,7 +76,7 @@ class Rect(object): def get_max_y(self): return self.origin.y + self.size.h - + def contains_point(self, pt): if pt.x < self.get_max_x(): if pt.y < self.get_max_y(): @@ -84,12 +90,16 @@ class Rect(object): def __ne__(self, rhs): return self.origin != rhs.origin or self.size != rhs.size + class QuitException(Exception): + def __init__(self): super(QuitException, self).__init__('QuitException') + class Window(object): - def __init__(self, window, delegate = None, can_become_first_responder = True): + + def __init__(self, window, delegate=None, can_become_first_responder=True): self.window = window self.parent = None self.delegate = delegate @@ -97,11 +107,11 @@ class Window(object): self.first_responders = list() self.can_become_first_responder = can_become_first_responder self.key_actions = dict() - + def add_child(self, window): self.children.append(window) window.parent = self - + def resize(self, size): self.window.resize(size.h, size.w) @@ -109,7 +119,13 @@ class Window(object): if child in self.children: frame = self.get_frame() orig_frame = child.get_frame() - new_frame = Rect(x=orig_frame.origin.x, y=orig_frame.origin.y, w=orig_frame.size.w + delta_size.w, h=orig_frame.size.h + delta_size.h) + new_frame = Rect( + x=orig_frame.origin.x, + y=orig_frame.origin.y, + w=orig_frame.size.w + + delta_size.w, + h=orig_frame.size.h + + delta_size.h) old_child_max_x = orig_frame.get_max_x() new_child_max_x = new_frame.get_max_x() window_max_x = frame.get_max_x() @@ -122,7 +138,7 @@ class Window(object): new_frame.origin.x -= new_child_max_x - window_max_x child.set_position(new_frame.origin) child.resize(new_frame.size) - + if adjust_neighbors: #print('orig_frame = %s\r\n' % (str(orig_frame)), end='') for curr_child in self.children: @@ -131,32 +147,33 @@ class Window(object): curr_child_frame = curr_child.get_frame() if delta_size.w != 0: #print('curr_child_frame = %s\r\n' % (str(curr_child_frame)), end='') - if curr_child_frame.get_min_x() == orig_frame.get_max_x(): + if curr_child_frame.get_min_x() == orig_frame.get_max_x(): curr_child_frame.origin.x += delta_size.w curr_child_frame.size.w -= delta_size.w #print('adjusted curr_child_frame = %s\r\n' % (str(curr_child_frame)), end='') - curr_child.resize (curr_child_frame.size) - curr_child.slide_position (Size(w=delta_size.w, h=0)) + curr_child.resize(curr_child_frame.size) + curr_child.slide_position( + Size(w=delta_size.w, h=0)) elif curr_child_frame.get_max_x() == orig_frame.get_min_x(): curr_child_frame.size.w -= delta_size.w #print('adjusted curr_child_frame = %s\r\n' % (str(curr_child_frame)), end='') - curr_child.resize (curr_child_frame.size) - + curr_child.resize(curr_child_frame.size) + def add_key_action(self, arg, callback, decription): if isinstance(arg, list): for key in arg: self.add_key_action(key, callback, description) else: if isinstance(arg, six.integer_types): - key_action_dict = { 'key' : arg, - 'callback' : callback, - 'description' : decription } + key_action_dict = {'key': arg, + 'callback': callback, + 'description': decription} self.key_actions[arg] = key_action_dict - elif isinstance(arg, basestring): + elif isinstance(arg, basestring): key_integer = ord(arg) - key_action_dict = { 'key' : key_integer, - 'callback' : callback, - 'description' : decription } + key_action_dict = {'key': key_integer, + 'callback': callback, + 'description': decription} self.key_actions[key_integer] = key_action_dict else: raise ValueError @@ -164,16 +181,16 @@ class Window(object): def draw_title_box(self, title): is_in_first_responder_chain = self.is_in_first_responder_chain() if is_in_first_responder_chain: - self.attron (curses.A_REVERSE) + self.attron(curses.A_REVERSE) self.box() if is_in_first_responder_chain: - self.attroff (curses.A_REVERSE) + self.attroff(curses.A_REVERSE) if title: self.addstr(Point(x=2, y=0), ' ' + title + ' ') - + def remove_child(self, window): self.children.remove(window) - + def get_first_responder(self): if len(self.first_responders): return self.first_responders[-1] @@ -182,12 +199,16 @@ class Window(object): def set_first_responder(self, window): if window.can_become_first_responder: - if six.callable(getattr(window, "hidden", None)) and window.hidden(): + if six.callable( + getattr( + window, + "hidden", + None)) and window.hidden(): return False - if not window in self.children: + if window not in self.children: self.add_child(window) # See if we have a current first responder, and if we do, let it know that - # it will be resigning as first responder + # it will be resigning as first responder first_responder = self.get_first_responder() if first_responder: first_responder.relinquish_first_responder() @@ -199,29 +220,31 @@ class Window(object): return True else: return False - + def push_first_responder(self, window): - # Only push the window as the new first responder if the window isn't already the first responder + # Only push the window as the new first responder if the window isn't + # already the first responder if window != self.get_first_responder(): self.first_responders.append(window) - - def pop_first_responder(self, window): - # Only pop the window from the first responder list if it is the first responder + + def pop_first_responder(self, window): + # Only pop the window from the first responder list if it is the first + # responder if window == self.get_first_responder(): old_first_responder = self.first_responders.pop() old_first_responder.relinquish_first_responder() return True else: return False - + def relinquish_first_responder(self): '''Override if there is something that you need to do when you lose first responder status.''' - pass - - # def resign_first_responder(self, remove_from_parent, new_first_responder): + pass + + # def resign_first_responder(self, remove_from_parent, new_first_responder): # success = False # if self.parent: - # if self.is_first_responder(): + # if self.is_first_responder(): # self.relinquish_first_responder() # if len(self.parent.first_responder): # self.parent.first_responder = None @@ -253,21 +276,21 @@ class Window(object): num_children = len(self.children) if num_children == 1: return self.set_first_responder(self.children[0]) - for (i,window) in enumerate(self.children): + for (i, window) in enumerate(self.children): if window.is_first_responder(): break if i < num_children: - for i in range(i+1,num_children): + for i in range(i + 1, num_children): if self.set_first_responder(self.children[i]): return True for i in range(0, i): if self.set_first_responder(self.children[i]): return True - + def point_in_window(self, pt): size = self.get_size() return pt.x >= 0 and pt.x < size.w and pt.y >= 0 and pt.y < size.h - + def addch(self, c): try: self.window.addch(c) @@ -291,6 +314,7 @@ class Window(object): self.window.addnstr(pt.y, pt.x, str, n) except: pass + def addnstr(self, str, n): try: self.window.addnstr(str, n) @@ -298,19 +322,26 @@ class Window(object): pass def attron(self, attr): - return self.window.attron (attr) + return self.window.attron(attr) def attroff(self, attr): - return self.window.attroff (attr) + return self.window.attroff(attr) def box(self, vertch=0, horch=0): if vertch == 0: vertch = curses.ACS_VLINE - if horch == 0: + if horch == 0: horch = curses.ACS_HLINE self.window.box(vertch, horch) - def get_contained_rect(self, top_inset=0, bottom_inset=0, left_inset=0, right_inset=0, height=-1, width=-1): + def get_contained_rect( + self, + top_inset=0, + bottom_inset=0, + left_inset=0, + right_inset=0, + height=-1, + width=-1): '''Get a rectangle based on the top "height" lines of this window''' rect = self.get_frame() x = rect.origin.x + left_inset @@ -323,11 +354,11 @@ class Window(object): w = rect.size.w - (left_inset + right_inset) else: w = width - return Rect (x = x, y = y, w = w, h = h) + return Rect(x=x, y=y, w=w, h=h) def erase(self): self.window.erase() - + def get_cursor(self): (y, x) = self.window.getyx() return Point(x=x, y=y) @@ -341,11 +372,11 @@ class Window(object): position = self.get_position_in_parent() size = self.get_size() return Rect(x=position.x, y=position.y, w=size.w, h=size.h) - + def get_position_in_parent(self): (y, x) = self.window.getparyx() return Point(x, y) - + def get_position(self): (y, x) = self.window.getbegyx() return Point(x, y) @@ -362,22 +393,22 @@ class Window(object): curses.panel.update_panels() self.move(Point(x=0, y=0)) return self.window.refresh() - + def resize(self, size): return self.window.resize(size.h, size.w) - + def timeout(self, timeout_msec): return self.window.timeout(timeout_msec) def handle_key(self, key, check_parent=True): '''Handle a key press in this window.''' - + # First try the first responder if this window has one, but don't allow # it to check with its parent (False second parameter) so we don't recurse # and get a stack overflow for first_responder in reversed(self.first_responders): if first_responder.handle_key(key, False): - return True + return True # Check our key map to see if we have any actions. Actions don't take # any arguments, they must be callable @@ -391,23 +422,23 @@ class Window(object): key_action['callback']() return True # Check if the window delegate wants to handle this key press - if self.delegate: + if self.delegate: if six.callable(getattr(self.delegate, "handle_key", None)): if self.delegate.handle_key(self, key): return True if self.delegate(self, key): return True - # Check if we have a parent window and if so, let the parent + # Check if we have a parent window and if so, let the parent # window handle the key press if check_parent and self.parent: return self.parent.handle_key(key, True) else: - return False # Key not handled + return False # Key not handled def update(self): for child in self.children: child.update() - + def quit_action(self): raise QuitException @@ -425,17 +456,17 @@ class Window(object): else: c = c << 8 | escape_key self.timeout(timeout_msec) - return c - + return c + def key_event_loop(self, timeout_msec=-1, n=sys.maxsize): '''Run an event loop to receive key presses and pass them along to the responder chain. - + timeout_msec is the timeout it milliseconds. If the value is -1, an infinite wait will be used. It the value is zero, a non-blocking mode will be used, and if greater than zero it will wait for a key press for timeout_msec milliseconds. - + n is the number of times to go through the event loop before exiting''' done = False while not done and n > 0: @@ -447,10 +478,21 @@ class Window(object): done = True n -= 1 + class Panel(Window): - def __init__(self, frame, delegate = None, can_become_first_responder = True): - window = curses.newwin(frame.size.h,frame.size.w, frame.origin.y, frame.origin.x) - super(Panel, self).__init__(window, delegate, can_become_first_responder) + + def __init__(self, frame, delegate=None, can_become_first_responder=True): + window = curses.newwin( + frame.size.h, + frame.size.w, + frame.origin.y, + frame.origin.x) + super( + Panel, + self).__init__( + window, + delegate, + can_become_first_responder) self.panel = curses.panel.new_panel(window) def hide(self): @@ -464,31 +506,63 @@ class Panel(Window): def top(self): return self.panel.top() - + def set_position(self, pt): self.panel.move(pt.y, pt.x) - + def slide_position(self, size): new_position = self.get_position() new_position.x = new_position.x + size.w new_position.y = new_position.y + size.h self.set_position(new_position) + class BoxedPanel(Panel): - def __init__(self, frame, title, delegate = None, can_become_first_responder = True): - super(BoxedPanel, self).__init__(frame, delegate, can_become_first_responder) + + def __init__(self, frame, title, delegate=None, + can_become_first_responder=True): + super( + BoxedPanel, + self).__init__( + frame, + delegate, + can_become_first_responder) self.title = title self.lines = list() self.first_visible_idx = 0 self.selected_idx = -1 - self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item") - self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item") - self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the list") - self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the list") - self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the list") - self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the list") - self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page") - self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward") + self.add_key_action( + curses.KEY_UP, + self.select_prev, + "Select the previous item") + self.add_key_action( + curses.KEY_DOWN, + self.select_next, + "Select the next item") + self.add_key_action( + curses.KEY_HOME, + self.scroll_begin, + "Go to the beginning of the list") + self.add_key_action( + curses.KEY_END, + self.scroll_end, + "Go to the end of the list") + self.add_key_action( + 0x1b4f48, + self.scroll_begin, + "Go to the beginning of the list") + self.add_key_action( + 0x1b4f46, + self.scroll_end, + "Go to the end of the list") + self.add_key_action( + curses.KEY_PPAGE, + self.scroll_page_backward, + "Scroll to previous page") + self.add_key_action( + curses.KEY_NPAGE, + self.scroll_page_forward, + "Scroll to next forward") self.update() def clear(self, update=True): @@ -497,21 +571,21 @@ class BoxedPanel(Panel): self.selected_idx = -1 if update: self.update() - + def get_usable_width(self): - '''Valid usable width is 0 to (width - 3) since the left and right lines display the box around + '''Valid usable width is 0 to (width - 3) since the left and right lines display the box around this frame and we skip a leading space''' w = self.get_size().w if w > 3: - return w-3 + return w - 3 else: return 0 - + def get_usable_height(self): '''Valid line indexes are 0 to (height - 2) since the top and bottom lines display the box around this frame.''' h = self.get_size().h if h > 2: - return h-2 + return h - 2 else: return 0 @@ -520,24 +594,25 @@ class BoxedPanel(Panel): line_idx = global_line_idx - self.first_visible_idx num_lines = self.get_usable_height() if line_idx < num_lines: - return Point(x=2, y=1+line_idx) + return Point(x=2, y=1 + line_idx) else: - return Point(x=-1, y=-1) # return an invalid coordinate if the line index isn't valid - - def set_title (self, title, update=True): + # return an invalid coordinate if the line index isn't valid + return Point(x=-1, y=-1) + + def set_title(self, title, update=True): self.title = title if update: self.update() - def scroll_to_line (self, idx): + def scroll_to_line(self, idx): if idx < len(self.lines): self.selected_idx = idx - max_visible_lines = self.get_usable_height() + max_visible_lines = self.get_usable_height() if idx < self.first_visible_idx or idx >= self.first_visible_idx + max_visible_lines: self.first_visible_idx = idx self.refresh() - def scroll_begin (self): + def scroll_begin(self): self.first_visible_idx = 0 if len(self.lines) > 0: self.selected_idx = 0 @@ -545,39 +620,39 @@ class BoxedPanel(Panel): self.selected_idx = -1 self.update() - def scroll_end (self): + def scroll_end(self): max_visible_lines = self.get_usable_height() num_lines = len(self.lines) if num_lines > max_visible_lines: self.first_visible_idx = num_lines - max_visible_lines else: self.first_visible_idx = 0 - self.selected_idx = num_lines-1 + self.selected_idx = num_lines - 1 self.update() - + def scroll_page_backward(self): - num_lines = len(self.lines) - max_visible_lines = self.get_usable_height() + num_lines = len(self.lines) + max_visible_lines = self.get_usable_height() new_index = self.first_visible_idx - max_visible_lines if new_index < 0: self.first_visible_idx = 0 else: self.first_visible_idx = new_index self.refresh() - + def scroll_page_forward(self): - max_visible_lines = self.get_usable_height() + max_visible_lines = self.get_usable_height() self.first_visible_idx += max_visible_lines self._adjust_first_visible_line() self.refresh() - def select_next (self): + def select_next(self): self.selected_idx += 1 if self.selected_idx >= len(self.lines): self.selected_idx = len(self.lines) - 1 self.refresh() - - def select_prev (self): + + def select_prev(self): self.selected_idx -= 1 if self.selected_idx < 0: if len(self.lines) > 0: @@ -588,13 +663,14 @@ class BoxedPanel(Panel): def get_selected_idx(self): return self.selected_idx - + def _adjust_first_visible_line(self): num_lines = len(self.lines) max_visible_lines = self.get_usable_height() - if (self.first_visible_idx >= num_lines) or (num_lines - self.first_visible_idx) > max_visible_lines: + if (self.first_visible_idx >= num_lines) or ( + num_lines - self.first_visible_idx) > max_visible_lines: self.first_visible_idx = num_lines - max_visible_lines - + def append_line(self, s, update=True): self.lines.append(s) self._adjust_first_visible_line() @@ -611,9 +687,9 @@ class BoxedPanel(Panel): self._adjust_first_visible_line() if update: self.update() - + def update(self): - self.erase() + self.erase() self.draw_title_box(self.title) max_width = self.get_usable_width() for line_idx in range(self.first_visible_idx, len(self.lines)): @@ -621,11 +697,11 @@ class BoxedPanel(Panel): if pt.is_valid_coordinate(): is_selected = line_idx == self.selected_idx if is_selected: - self.attron (curses.A_REVERSE) + self.attron(curses.A_REVERSE) self.move(pt) self.addnstr(self.lines[line_idx], max_width) if is_selected: - self.attroff (curses.A_REVERSE) + self.attroff(curses.A_REVERSE) else: return @@ -636,16 +712,19 @@ class BoxedPanel(Panel): for (idx, line) in enumerate(self.lines): # Remove any tabs from lines since they hose up the display if "\t" in line: - self.lines[idx] = (8*' ').join(line.split('\t')) + self.lines[idx] = (8 * ' ').join(line.split('\t')) self.selected_idx = 0 self.first_visible_idx = 0 self.refresh() + class Item(object): + def __init__(self, title, action): self.title = title self.action = action + class TreeItemDelegate(object): def might_have_children(self): @@ -663,21 +742,29 @@ class TreeItemDelegate(object): def draw_item(self, tree_window, item): self.draw_item_string(tree_window, item, item.title) - + def do_action(self): pass + class TreeItem(object): - def __init__(self, delegate, parent = None, title = None, action = None, is_expanded = False): + + def __init__( + self, + delegate, + parent=None, + title=None, + action=None, + is_expanded=False): self.parent = parent self.title = title - self.action = action + self.action = action self.delegate = delegate - self.is_expanded = not parent or is_expanded == True + self.is_expanded = not parent or is_expanded self._might_have_children = None self.children = None self._children_might_have_children = False - + def get_children(self): if self.is_expanded and self.might_have_children(): if self.children is None: @@ -691,7 +778,7 @@ class TreeItem(object): self._children_might_have_children = False self.children = None return self.children - + def append_visible_items(self, items): items.append(self) children = self.get_children() @@ -705,7 +792,8 @@ class TreeItem(object): # Root item always might have children self._might_have_children = True else: - # Check with the delegate to see if the item might have children + # Check with the delegate to see if the item might have + # children self._might_have_children = self.delegate.might_have_children() return self._might_have_children @@ -717,10 +805,10 @@ class TreeItem(object): self.children = self.delegate.update_children(self) for child in self.children: child.update_children() - else: + else: self.children = None return self.children - + def get_num_visible_rows(self): rows = 1 if self.is_expanded: @@ -729,6 +817,7 @@ class TreeItem(object): for child in children: rows += child.get_num_visible_rows() return rows + def draw(self, tree_window, row): display_row = tree_window.get_display_row(row) if display_row >= 0: @@ -736,79 +825,112 @@ class TreeItem(object): if self.parent: self.parent.draw_tree_for_child(tree_window, self, 0) if self.might_have_children(): - tree_window.addch (curses.ACS_DIAMOND) - tree_window.addch (curses.ACS_HLINE) + tree_window.addch(curses.ACS_DIAMOND) + tree_window.addch(curses.ACS_HLINE) elif self.parent and self.parent.children_might_have_children(): if self.parent.parent: - tree_window.addch (curses.ACS_HLINE) - tree_window.addch (curses.ACS_HLINE) + tree_window.addch(curses.ACS_HLINE) + tree_window.addch(curses.ACS_HLINE) else: - tree_window.addch (' ') - tree_window.addch (' ') + tree_window.addch(' ') + tree_window.addch(' ') is_selected = tree_window.is_selected(row) if is_selected: - tree_window.attron (curses.A_REVERSE) + tree_window.attron(curses.A_REVERSE) self.delegate.draw_item(tree_window, self) if is_selected: - tree_window.attroff (curses.A_REVERSE) - - def draw_tree_for_child (self, tree_window, child, reverse_depth): + tree_window.attroff(curses.A_REVERSE) + + def draw_tree_for_child(self, tree_window, child, reverse_depth): if self.parent: - self.parent.draw_tree_for_child (tree_window, self, reverse_depth + 1) + self.parent.draw_tree_for_child( + tree_window, self, reverse_depth + 1) if self.children[-1] == child: # Last child if reverse_depth == 0: - tree_window.addch (curses.ACS_LLCORNER) - tree_window.addch (curses.ACS_HLINE) + tree_window.addch(curses.ACS_LLCORNER) + tree_window.addch(curses.ACS_HLINE) else: - tree_window.addch (' ') - tree_window.addch (' ') + tree_window.addch(' ') + tree_window.addch(' ') else: # Middle child if reverse_depth == 0: - tree_window.addch (curses.ACS_LTEE) - tree_window.addch (curses.ACS_HLINE) + tree_window.addch(curses.ACS_LTEE) + tree_window.addch(curses.ACS_HLINE) else: - tree_window.addch (curses.ACS_VLINE) - tree_window.addch (' ') - - def was_selected(self): + tree_window.addch(curses.ACS_VLINE) + tree_window.addch(' ') + + def was_selected(self): self.delegate.do_action() - + + class TreePanel(Panel): + def __init__(self, frame, title, root_item): self.root_item = root_item self.title = title self.first_visible_idx = 0 self.selected_idx = 0 self.items = None - super(TreePanel, self).__init__(frame) - self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item") - self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item") - self.add_key_action(curses.KEY_RIGHT,self.right_arrow, "Expand an item") - self.add_key_action(curses.KEY_LEFT, self.left_arrow, "Unexpand an item or navigate to parent") - self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the tree") - self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the tree") - self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the tree") - self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the tree") - self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page") - self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward") + super(TreePanel, self).__init__(frame) + self.add_key_action( + curses.KEY_UP, + self.select_prev, + "Select the previous item") + self.add_key_action( + curses.KEY_DOWN, + self.select_next, + "Select the next item") + self.add_key_action( + curses.KEY_RIGHT, + self.right_arrow, + "Expand an item") + self.add_key_action( + curses.KEY_LEFT, + self.left_arrow, + "Unexpand an item or navigate to parent") + self.add_key_action( + curses.KEY_HOME, + self.scroll_begin, + "Go to the beginning of the tree") + self.add_key_action( + curses.KEY_END, + self.scroll_end, + "Go to the end of the tree") + self.add_key_action( + 0x1b4f48, + self.scroll_begin, + "Go to the beginning of the tree") + self.add_key_action( + 0x1b4f46, + self.scroll_end, + "Go to the end of the tree") + self.add_key_action( + curses.KEY_PPAGE, + self.scroll_page_backward, + "Scroll to previous page") + self.add_key_action( + curses.KEY_NPAGE, + self.scroll_page_forward, + "Scroll to next forward") def get_selected_item(self): if self.selected_idx < len(self.items): return self.items[self.selected_idx] else: return None - + def select_item(self, item): if self.items and item in self.items: self.selected_idx = self.items.index(item) return True else: return False - + def get_visible_items(self): - # Clear self.items when you want to update all chidren + # Clear self.items when you want to update all chidren if self.items is None: self.items = list() children = self.root_item.get_children() @@ -816,15 +938,15 @@ class TreePanel(Panel): for child in children: child.append_visible_items(self.items) return self.items - + def update(self): - self.erase() - self.draw_title_box(self.title) + self.erase() + self.draw_title_box(self.title) visible_items = self.get_visible_items() for (row, child) in enumerate(visible_items): - child.draw(self, row) + child.draw(self, row) - def get_item_draw_point(self, row): + def get_item_draw_point(self, row): display_row = self.get_display_row(row) if display_row >= 0: return Point(2, display_row + 1) @@ -834,28 +956,29 @@ class TreePanel(Panel): def get_display_row(self, row): if row >= self.first_visible_idx: display_row = row - self.first_visible_idx - if display_row < self.get_size().h-2: - return display_row + if display_row < self.get_size().h - 2: + return display_row return -1 def is_selected(self, row): return row == self.selected_idx - def get_num_lines(self): + def get_num_lines(self): self.get_visible_items() return len(self.items) - + def get_num_visible_lines(self): - return self.get_size().h-2 - def select_next (self): - self.selected_idx += 1 + return self.get_size().h - 2 + + def select_next(self): + self.selected_idx += 1 num_lines = self.get_num_lines() if self.selected_idx >= num_lines: - self.selected_idx = num_lines - 1 + self.selected_idx = num_lines - 1 self._selection_changed() self.refresh() - def select_prev (self): + def select_prev(self): self.selected_idx -= 1 if self.selected_idx < 0: num_lines = self.get_num_lines() @@ -866,7 +989,7 @@ class TreePanel(Panel): self._selection_changed() self.refresh() - def scroll_begin (self): + def scroll_begin(self): self.first_visible_idx = 0 num_lines = self.get_num_lines() if num_lines > 0: @@ -874,36 +997,35 @@ class TreePanel(Panel): else: self.selected_idx = -1 self.refresh() - + def redisplay_tree(self): self.items = None self.refresh() - def right_arrow(self): + def right_arrow(self): selected_item = self.get_selected_item() if selected_item and selected_item.is_expanded == False: selected_item.is_expanded = True self.redisplay_tree() - + def left_arrow(self): selected_item = self.get_selected_item() if selected_item: - if selected_item.is_expanded == True: + if selected_item.is_expanded: selected_item.is_expanded = False self.redisplay_tree() elif selected_item.parent: if self.select_item(selected_item.parent): self.refresh() - - def scroll_end (self): + def scroll_end(self): num_visible_lines = self.get_num_visible_lines() num_lines = self.get_num_lines() if num_lines > num_visible_lines: self.first_visible_idx = num_lines - num_visible_lines else: self.first_visible_idx = 0 - self.selected_idx = num_lines-1 + self.selected_idx = num_lines - 1 self.refresh() def scroll_page_backward(self): @@ -912,7 +1034,7 @@ class TreePanel(Panel): if new_index < 0: self.selected_idx = 0 else: - self.selected_idx = new_index + self.selected_idx = new_index self._selection_changed() self.refresh() @@ -926,59 +1048,87 @@ class TreePanel(Panel): self._selection_changed() self.refresh() - def _selection_changed(self): - num_lines = self.get_num_lines() + def _selection_changed(self): + num_lines = self.get_num_lines() num_visible_lines = self.get_num_visible_lines() last_visible_index = self.first_visible_idx + num_visible_lines if self.selected_idx >= last_visible_index: - self.first_visible_idx += (self.selected_idx - last_visible_index + 1) + self.first_visible_idx += (self.selected_idx - + last_visible_index + 1) if self.selected_idx < self.first_visible_idx: - self.first_visible_idx = self.selected_idx + self.first_visible_idx = self.selected_idx if self.selected_idx >= 0 and self.selected_idx < len(self.items): item = self.items[self.selected_idx] item.was_selected() class Menu(BoxedPanel): + def __init__(self, title, items): max_title_width = 0 for item in items: if max_title_width < len(item.title): max_title_width = len(item.title) - frame = Rect(x=0, y=0, w=max_title_width+4, h=len(items)+2) - super(Menu, self).__init__(frame, title=None, delegate=None, can_become_first_responder=True) + frame = Rect(x=0, y=0, w=max_title_width + 4, h=len(items) + 2) + super( + Menu, + self).__init__( + frame, + title=None, + delegate=None, + can_become_first_responder=True) self.selected_idx = 0 self.title = title self.items = items for (item_idx, item) in enumerate(items): self.set_line(item_idx, item.title) self.hide() - + def update(self): super(Menu, self).update() def relinquish_first_responder(self): if not self.hidden(): - self.hide() - - def perform_action(self): + self.hide() + + def perform_action(self): selected_idx = self.get_selected_idx() if selected_idx < len(self.items): action = self.items[selected_idx].action if action: action() - + + class MenuBar(Panel): + def __init__(self, frame): super(MenuBar, self).__init__(frame, can_become_first_responder=True) self.menus = list() self.selected_menu_idx = -1 - self.add_key_action(curses.KEY_LEFT, self.select_prev, "Select the previous menu") - self.add_key_action(curses.KEY_RIGHT, self.select_next, "Select the next menu") - self.add_key_action(curses.KEY_DOWN, lambda: self.select(0), "Select the first menu") - self.add_key_action(27, self.relinquish_first_responder, "Hide current menu") - self.add_key_action(curses.KEY_ENTER, self.perform_action, "Select the next menu item") - self.add_key_action(10, self.perform_action, "Select the next menu item") + self.add_key_action( + curses.KEY_LEFT, + self.select_prev, + "Select the previous menu") + self.add_key_action( + curses.KEY_RIGHT, + self.select_next, + "Select the next menu") + self.add_key_action( + curses.KEY_DOWN, + lambda: self.select(0), + "Select the first menu") + self.add_key_action( + 27, + self.relinquish_first_responder, + "Hide current menu") + self.add_key_action( + curses.KEY_ENTER, + self.perform_action, + "Select the next menu item") + self.add_key_action( + 10, + self.perform_action, + "Select the next menu item") def insert_menu(self, menu, index=sys.maxsize): if index >= len(self.menus): @@ -989,8 +1139,8 @@ class MenuBar(Panel): for menu in self.menus: menu.set_position(pt) pt.x += len(menu.title) + 5 - - def perform_action(self): + + def perform_action(self): '''If no menu is visible, show the first menu. If a menu is visible, perform the action associated with the selected menu item in the menu''' menu_visible = False @@ -1004,22 +1154,22 @@ class MenuBar(Panel): self._selected_menu_changed() else: self.select(0) - + def relinquish_first_responder(self): if self.selected_menu_idx >= 0: self.selected_menu_idx = -1 self._selected_menu_changed() - + def _selected_menu_changed(self): for (menu_idx, menu) in enumerate(self.menus): is_hidden = menu.hidden() - if menu_idx != self.selected_menu_idx: + if menu_idx != self.selected_menu_idx: if not is_hidden: if self.parent.pop_first_responder(menu) == False: menu.hide() for (menu_idx, menu) in enumerate(self.menus): is_hidden = menu.hidden() - if menu_idx == self.selected_menu_idx: + if menu_idx == self.selected_menu_idx: if is_hidden: menu.show() self.parent.push_first_responder(menu) @@ -1030,8 +1180,8 @@ class MenuBar(Panel): if index < len(self.menus): self.selected_menu_idx = index self._selected_menu_changed() - - def select_next (self): + + def select_next(self): num_menus = len(self.menus) if self.selected_menu_idx == -1: if num_menus > 0: @@ -1044,7 +1194,7 @@ class MenuBar(Panel): self.selected_menu_idx = -1 self._selected_menu_changed() - def select_prev (self): + def select_prev(self): num_menus = len(self.menus) if self.selected_menu_idx == -1: if num_menus > 0: @@ -1061,41 +1211,47 @@ class MenuBar(Panel): self.erase() is_in_first_responder_chain = self.is_in_first_responder_chain() if is_in_first_responder_chain: - self.attron (curses.A_REVERSE) + self.attron(curses.A_REVERSE) pt = Point(x=0, y=0) - for menu in self.menus: + for menu in self.menus: self.addstr(pt, '| ' + menu.title + ' ') pt.x += len(menu.title) + 5 - self.addstr(pt, '|') + self.addstr(pt, '|') width = self.get_size().w while pt.x < width: self.addch_at_point(pt, ' ') - pt.x += 1 + pt.x += 1 if is_in_first_responder_chain: - self.attroff (curses.A_REVERSE) + self.attroff(curses.A_REVERSE) for menu in self.menus: menu.update() - - + + class StatusPanel(Panel): + def __init__(self, frame): - super(StatusPanel, self).__init__(frame, delegate=None, can_become_first_responder=False) + super( + StatusPanel, + self).__init__( + frame, + delegate=None, + can_become_first_responder=False) self.status_items = list() self.status_dicts = dict() self.next_status_x = 1 - + def add_status_item(self, name, title, format, width, value, update=True): - status_item_dict = { 'name': name, - 'title' : title, - 'width' : width, - 'format' : format, - 'value' : value, - 'x' : self.next_status_x } + status_item_dict = {'name': name, + 'title': title, + 'width': width, + 'format': format, + 'value': value, + 'x': self.next_status_x} index = len(self.status_items) self.status_items.append(status_item_dict) self.status_dicts[name] = index - self.next_status_x += width + 2; + self.next_status_x += width + 2 if update: self.update() @@ -1106,7 +1262,7 @@ class StatusPanel(Panel): status_item_dict['value'] = status_item_dict['value'] + 1 if update: self.update() - + def update_status(self, name, value, update=True): if name in self.status_dicts: status_item_idx = self.status_dicts[name] @@ -1114,13 +1270,22 @@ class StatusPanel(Panel): status_item_dict['value'] = status_item_dict['format'] % (value) if update: self.update() + def update(self): - self.erase(); + self.erase() for status_item_dict in self.status_items: - self.addnstr_at_point(Point(x=status_item_dict['x'], y=0), '%s: %s' % (status_item_dict['title'], status_item_dict['value']), status_item_dict['width']) + self.addnstr_at_point( + Point( + x=status_item_dict['x'], + y=0), + '%s: %s' % + (status_item_dict['title'], + status_item_dict['value']), + status_item_dict['width']) stdscr = None + def intialize_curses(): global stdscr stdscr = curses.initscr() @@ -1133,6 +1298,7 @@ def intialize_curses(): pass return Window(stdscr) + def terminate_curses(): global stdscr if stdscr: @@ -1140,4 +1306,3 @@ def terminate_curses(): curses.echo() curses.nocbreak() curses.endwin() - diff --git a/lldb/packages/Python/lldbsuite/test/lldbinline.py b/lldb/packages/Python/lldbsuite/test/lldbinline.py index 6a61b2eaf55..240a75a1a82 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbinline.py +++ b/lldb/packages/Python/lldbsuite/test/lldbinline.py @@ -13,19 +13,21 @@ from . import configuration from . import lldbutil from .decorators import * + def source_type(filename): _, extension = os.path.splitext(filename) return { - '.c' : 'C_SOURCES', - '.cpp' : 'CXX_SOURCES', - '.cxx' : 'CXX_SOURCES', - '.cc' : 'CXX_SOURCES', - '.m' : 'OBJC_SOURCES', - '.mm' : 'OBJCXX_SOURCES' + '.c': 'C_SOURCES', + '.cpp': 'CXX_SOURCES', + '.cxx': 'CXX_SOURCES', + '.cc': 'CXX_SOURCES', + '.m': 'OBJC_SOURCES', + '.mm': 'OBJCXX_SOURCES' }.get(extension, None) class CommandParser: + def __init__(self): self.breakpoints = [] @@ -46,27 +48,31 @@ class CommandParser: file_handle = open(source_file) lines = file_handle.readlines() line_number = 0 - current_breakpoint = None # non-NULL means we're looking through whitespace to find additional commands + # non-NULL means we're looking through whitespace to find + # additional commands + current_breakpoint = None for line in lines: - line_number = line_number + 1 # 1-based, so we do this first + line_number = line_number + 1 # 1-based, so we do this first (command, new_breakpoint) = self.parse_one_command(line) if new_breakpoint: current_breakpoint = None - if command != None: - if current_breakpoint == None: + if command is not None: + if current_breakpoint is None: current_breakpoint = {} current_breakpoint['file_name'] = source_file current_breakpoint['line_number'] = line_number current_breakpoint['command'] = command self.breakpoints.append(current_breakpoint) else: - current_breakpoint['command'] = current_breakpoint['command'] + "\n" + command + current_breakpoint['command'] = current_breakpoint[ + 'command'] + "\n" + command def set_breakpoints(self, target): for breakpoint in self.breakpoints: - breakpoint['breakpoint'] = target.BreakpointCreateByLocation(breakpoint['file_name'], breakpoint['line_number']) + breakpoint['breakpoint'] = target.BreakpointCreateByLocation( + breakpoint['file_name'], breakpoint['line_number']) def handle_breakpoint(self, test, breakpoint_id): for breakpoint in self.breakpoints: @@ -74,12 +80,14 @@ class CommandParser: test.execute_user_command(breakpoint['command']) return + class InlineTest(TestBase): # Internal implementation def getRerunArgs(self): # The -N option says to NOT run a if it matches the option argument, so - # if we are using dSYM we say to NOT run dwarf (-N dwarf) and vice versa. + # if we are using dSYM we say to NOT run dwarf (-N dwarf) and vice + # versa. if self.using_dsym is None: # The test was skipped altogether. return "" @@ -104,7 +112,8 @@ class InlineTest(TestBase): makefile = open("Makefile", 'w+') - level = os.sep.join([".."] * len(self.mydir.split(os.sep))) + os.sep + "make" + level = os.sep.join( + [".."] * len(self.mydir.split(os.sep))) + os.sep + "make" makefile.write("LEVEL = " + level + "\n") @@ -112,8 +121,10 @@ class InlineTest(TestBase): line = t + " := " + " ".join(categories[t]) makefile.write(line + "\n") - if ('OBJCXX_SOURCES' in list(categories.keys())) or ('OBJC_SOURCES' in list(categories.keys())): - makefile.write("LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n") + if ('OBJCXX_SOURCES' in list(categories.keys())) or ( + 'OBJC_SOURCES' in list(categories.keys())): + makefile.write( + "LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n") if ('CXX_SOURCES' in list(categories.keys())): makefile.write("CXXFLAGS += -std=c++11\n") @@ -154,7 +165,7 @@ class InlineTest(TestBase): def do_test(self): exe_name = "a.out" exe = os.path.join(os.getcwd(), exe_name) - source_files = [ f for f in os.listdir(os.getcwd()) if source_type(f) ] + source_files = [f for f in os.listdir(os.getcwd()) if source_type(f)] target = self.dbg.CreateTarget(exe) parser = CommandParser() @@ -164,17 +175,17 @@ class InlineTest(TestBase): process = target.LaunchSimple(None, None, os.getcwd()) while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint): - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - breakpoint_id = thread.GetStopReasonDataAtIndex (0) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + breakpoint_id = thread.GetStopReasonDataAtIndex(0) parser.handle_breakpoint(self, breakpoint_id) process.Continue() - # Utilities for testcases - def check_expression (self, expression, expected_result, use_summary = True): - value = self.frame().EvaluateExpression (expression) - self.assertTrue(value.IsValid(), expression+"returned a valid value") + def check_expression(self, expression, expected_result, use_summary=True): + value = self.frame().EvaluateExpression(expression) + self.assertTrue(value.IsValid(), expression + "returned a valid value") if self.TraceOn(): print(value.GetSummary()) print(value.GetValue()) @@ -182,12 +193,14 @@ class InlineTest(TestBase): answer = value.GetSummary() else: answer = value.GetValue() - report_str = "%s expected: %s got: %s"%(expression, expected_result, answer) + report_str = "%s expected: %s got: %s" % ( + expression, expected_result, answer) self.assertTrue(answer == expected_result, report_str) + def ApplyDecoratorsToFunction(func, decorators): tmp = func - if type(decorators) == list: + if isinstance(decorators, list): for decorator in decorators: tmp = decorator(tmp) elif hasattr(decorators, '__call__'): @@ -212,20 +225,27 @@ def MakeInlineTest(__file, __globals, decorators=None): test.name = test_name target_platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2] - if test_categories.is_supported_on_platform("dsym", target_platform, configuration.compilers): - test.test_with_dsym = ApplyDecoratorsToFunction(test._InlineTest__test_with_dsym, decorators) - if test_categories.is_supported_on_platform("dwarf", target_platform, configuration.compilers): - test.test_with_dwarf = ApplyDecoratorsToFunction(test._InlineTest__test_with_dwarf, decorators) - if test_categories.is_supported_on_platform("dwo", target_platform, configuration.compilers): - test.test_with_dwo = ApplyDecoratorsToFunction(test._InlineTest__test_with_dwo, decorators) - if test_categories.is_supported_on_platform("gmodules", target_platform, configuration.compilers): - test.test_with_gmodules = ApplyDecoratorsToFunction(test._InlineTest__test_with_gmodules, decorators) + if test_categories.is_supported_on_platform( + "dsym", target_platform, configuration.compilers): + test.test_with_dsym = ApplyDecoratorsToFunction( + test._InlineTest__test_with_dsym, decorators) + if test_categories.is_supported_on_platform( + "dwarf", target_platform, configuration.compilers): + test.test_with_dwarf = ApplyDecoratorsToFunction( + test._InlineTest__test_with_dwarf, decorators) + if test_categories.is_supported_on_platform( + "dwo", target_platform, configuration.compilers): + test.test_with_dwo = ApplyDecoratorsToFunction( + test._InlineTest__test_with_dwo, decorators) + if test_categories.is_supported_on_platform( + "gmodules", target_platform, configuration.compilers): + test.test_with_gmodules = ApplyDecoratorsToFunction( + test._InlineTest__test_with_gmodules, decorators) # Add the test case to the globals, and hide InlineTest - __globals.update({test_name : test}) + __globals.update({test_name: test}) # Keep track of the original test filename so we report it # correctly in test results. test.test_filename = __file return test - diff --git a/lldb/packages/Python/lldbsuite/test/lldbpexpect.py b/lldb/packages/Python/lldbsuite/test/lldbpexpect.py index d37d6fa4f8c..a19e6efa9f0 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbpexpect.py +++ b/lldb/packages/Python/lldbsuite/test/lldbpexpect.py @@ -20,7 +20,7 @@ else: import pexpect class PExpectTest(TestBase): - + mydir = TestBase.compute_mydir(__file__) def setUp(self): @@ -30,40 +30,66 @@ else: pass def launch(self, timeout=None): - if timeout is None: timeout = 30 + if timeout is None: + timeout = 30 logfile = sys.stdout if self.TraceOn() else None - self.child = pexpect.spawn('%s --no-use-colors %s' % (lldbtest_config.lldbExec, self.launchArgs()), logfile=logfile) + self.child = pexpect.spawn( + '%s --no-use-colors %s' % + (lldbtest_config.lldbExec, self.launchArgs()), logfile=logfile) self.child.timeout = timeout self.timeout = timeout def expect(self, patterns=None, timeout=None, exact=None): - if patterns is None: return None - if timeout is None: timeout = self.timeout - if exact is None: exact = False + if patterns is None: + return None + if timeout is None: + timeout = self.timeout + if exact is None: + exact = False if exact: return self.child.expect_exact(patterns, timeout=timeout) else: return self.child.expect(patterns, timeout=timeout) def expectall(self, patterns=None, timeout=None, exact=None): - if patterns is None: return None - if timeout is None: timeout = self.timeout - if exact is None: exact = False + if patterns is None: + return None + if timeout is None: + timeout = self.timeout + if exact is None: + exact = False for pattern in patterns: self.expect(pattern, timeout=timeout, exact=exact) - def sendimpl(self, sender, command, patterns=None, timeout=None, exact=None): + def sendimpl( + self, + sender, + command, + patterns=None, + timeout=None, + exact=None): sender(command) return self.expect(patterns=patterns, timeout=timeout, exact=exact) def send(self, command, patterns=None, timeout=None, exact=None): - return self.sendimpl(self.child.send, command, patterns, timeout, exact) + return self.sendimpl( + self.child.send, + command, + patterns, + timeout, + exact) def sendline(self, command, patterns=None, timeout=None, exact=None): - return self.sendimpl(self.child.sendline, command, patterns, timeout, exact) + return self.sendimpl( + self.child.sendline, + command, + patterns, + timeout, + exact) def quit(self, gracefully=None): - if gracefully is None: gracefully = True + if gracefully is None: + gracefully = True self.child.sendeof() self.child.close(force=not gracefully) self.child = None diff --git a/lldb/packages/Python/lldbsuite/test/lldbplatform.py b/lldb/packages/Python/lldbsuite/test/lldbplatform.py index 33927df6c0f..84c027d88ff 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbplatform.py +++ b/lldb/packages/Python/lldbsuite/test/lldbplatform.py @@ -12,19 +12,20 @@ import six import use_lldb_suite import lldb -windows, linux, macosx, darwin, ios, darwin_all, freebsd, netbsd, bsd_all, android = range(10) +windows, linux, macosx, darwin, ios, darwin_all, freebsd, netbsd, bsd_all, android = range( + 10) __name_lookup = { - windows : ["windows"], - linux : ["linux"], - macosx : ["macosx"], - darwin : ["darwin"], - ios : ["ios"], - darwin_all : ["macosx", "darwin", "ios"], - freebsd : ["freebsd"], - netbsd : ["netbsd"], - bsd_all : ["freebsd", "netbsd"], - android : ["android"] + windows: ["windows"], + linux: ["linux"], + macosx: ["macosx"], + darwin: ["darwin"], + ios: ["ios"], + darwin_all: ["macosx", "darwin", "ios"], + freebsd: ["freebsd"], + netbsd: ["netbsd"], + bsd_all: ["freebsd", "netbsd"], + android: ["android"] } diff --git a/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py b/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py index e04a5404407..0d5254bc0e7 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py +++ b/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py @@ -18,32 +18,40 @@ from . import configuration import use_lldb_suite import lldb + def check_first_register_readable(test_case): arch = test_case.getArchitecture() if arch in ['x86_64', 'i386']: - test_case.expect("register read eax", substrs = ['eax = 0x']) + test_case.expect("register read eax", substrs=['eax = 0x']) elif arch in ['arm']: - test_case.expect("register read r0", substrs = ['r0 = 0x']) + test_case.expect("register read r0", substrs=['r0 = 0x']) elif arch in ['aarch64']: - test_case.expect("register read x0", substrs = ['x0 = 0x']) - elif re.match("mips",arch): - test_case.expect("register read zero", substrs = ['zero = 0x']) + test_case.expect("register read x0", substrs=['x0 = 0x']) + elif re.match("mips", arch): + test_case.expect("register read zero", substrs=['zero = 0x']) elif arch in ['s390x']: - test_case.expect("register read r0", substrs = ['r0 = 0x']) + test_case.expect("register read r0", substrs=['r0 = 0x']) else: # TODO: Add check for other architectures - test_case.fail("Unsupported architecture for test case (arch: %s)" % test_case.getArchitecture()) + test_case.fail( + "Unsupported architecture for test case (arch: %s)" % + test_case.getArchitecture()) + def _run_adb_command(cmd, device_id): device_id_args = [] if device_id: device_id_args = ["-s", device_id] full_cmd = ["adb"] + device_id_args + cmd - p = subprocess.Popen(full_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + p = subprocess.Popen( + full_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) stdout, stderr = p.communicate() return p.returncode, stdout, stderr + def _target_is_android(): if not hasattr(_target_is_android, 'result'): triple = lldb.DBG.GetSelectedPlatform().GetTriple() @@ -51,6 +59,7 @@ def _target_is_android(): _target_is_android.result = match is not None return _target_is_android.result + def android_device_api(): if not hasattr(android_device_api, 'result'): assert configuration.lldb_platform_url is not None @@ -69,9 +78,11 @@ def android_device_api(): raise LookupError( ">>> Unable to determine the API level of the Android device.\n" ">>> stdout:\n%s\n" - ">>> stderr:\n%s\n" % (stdout, stderr)) + ">>> stderr:\n%s\n" % + (stdout, stderr)) return android_device_api.result + def match_android_device(device_arch, valid_archs=None, valid_api_levels=None): if not _target_is_android(): return False @@ -82,6 +93,7 @@ def match_android_device(device_arch, valid_archs=None, valid_api_levels=None): return True + def finalize_build_dictionary(dictionary): if _target_is_android(): if dictionary is None: @@ -91,6 +103,7 @@ def finalize_build_dictionary(dictionary): dictionary["PIE"] = 1 return dictionary + def getHostPlatform(): """Returns the host platform running the test suite.""" # Attempts to return a platform name matching a target Triple platform. @@ -111,6 +124,7 @@ def getHostPlatform(): def getDarwinOSTriples(): return ['darwin', 'macosx', 'ios'] + def getPlatform(): """Returns the target platform which the tests are running on.""" platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2] @@ -120,10 +134,12 @@ def getPlatform(): platform = 'netbsd' return platform + def platformIsDarwin(): """Returns true if the OS triple for the selected platform is any valid apple OS""" return getPlatform() in getDarwinOSTriples() + class _PlatformContext(object): """Value object class which contains platform-specific options.""" @@ -132,6 +148,7 @@ class _PlatformContext(object): self.shlib_prefix = shlib_prefix self.shlib_extension = shlib_extension + def createPlatformContext(): if platformIsDarwin(): return _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib') @@ -140,9 +157,10 @@ def createPlatformContext(): else: return None + def hasChattyStderr(test_case): """Some targets produce garbage on the standard error output. This utility function determines whether the tests can be strict about the expected stderr contents.""" if match_android_device(test_case.getArchitecture(), ['aarch64'], [22]): - return True # The dynamic linker on the device will complain about unknown DT entries + return True # The dynamic linker on the device will complain about unknown DT entries return False diff --git a/lldb/packages/Python/lldbsuite/test/lldbtest.py b/lldb/packages/Python/lldbsuite/test/lldbtest.py index ee876bd1116..ae355a80c52 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbtest.py +++ b/lldb/packages/Python/lldbsuite/test/lldbtest.py @@ -28,7 +28,7 @@ Collected 72 tests Ran 72 tests in 135.468s OK -$ +$ """ from __future__ import absolute_import @@ -74,20 +74,23 @@ from lldbsuite.support import funcutils # directory at the same time # Enable it to cause test failures and stderr messages if dotest instances try to run in # the same directory simultaneously -# it is disabled by default because it litters the test directories with ".dirlock" files +# it is disabled by default because it litters the test directories with +# ".dirlock" files debug_confirm_directory_exclusivity = False # See also dotest.parseOptionsAndInitTestdirs(), where the environment variables -# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options. +# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' +# options. # By default, traceAlways is False. -if "LLDB_COMMAND_TRACE" in os.environ and os.environ["LLDB_COMMAND_TRACE"]=="YES": +if "LLDB_COMMAND_TRACE" in os.environ and os.environ[ + "LLDB_COMMAND_TRACE"] == "YES": traceAlways = True else: traceAlways = False # By default, doCleanup is True. -if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"]=="NO": +if "LLDB_DO_CLEANUP" in os.environ and os.environ["LLDB_DO_CLEANUP"] == "NO": doCleanup = False else: doCleanup = True @@ -182,27 +185,37 @@ VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly" WATCHPOINT_CREATED = "Watchpoint created successfully" + def CMD_MSG(str): '''A generic "Command '%s' returns successfully" message generator.''' return "Command '%s' returns successfully" % str + def COMPLETION_MSG(str_before, str_after): '''A generic message generator for the completion mechanism.''' return "'%s' successfully completes to '%s'" % (str_before, str_after) + def EXP_MSG(str, actual, exe): '''A generic "'%s' returns expected result" message generator if exe. Otherwise, it generates "'%s' matches expected result" message.''' - - return "'%s' %s expected result, got '%s'" % (str, 'returns' if exe else 'matches', actual.strip()) + + return "'%s' %s expected result, got '%s'" % ( + str, 'returns' if exe else 'matches', actual.strip()) + def SETTING_MSG(setting): '''A generic "Value of setting '%s' is correct" message generator.''' return "Value of setting '%s' is correct" % setting + def EnvArray(): """Returns an env variable array from the os.environ map object.""" - return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values()))) + return list(map(lambda k, + v: k + "=" + v, + list(os.environ.keys()), + list(os.environ.values()))) + def line_number(filename, string_to_match): """Helper function to return the line number of the first matched string.""" @@ -210,8 +223,11 @@ def line_number(filename, string_to_match): for i, line in enumerate(f): if line.find(string_to_match) != -1: # Found our match. - return i+1 - raise Exception("Unable to find '%s' within file %s" % (string_to_match, filename)) + return i + 1 + raise Exception( + "Unable to find '%s' within file %s" % + (string_to_match, filename)) + def pointer_size(): """Return the pointer size of the host system.""" @@ -219,10 +235,12 @@ def pointer_size(): a_pointer = ctypes.c_void_p(0xffff) return 8 * ctypes.sizeof(a_pointer) + def is_exe(fpath): """Returns true if fpath is an executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + def which(program): """Returns the full path to a program; None otherwise.""" fpath, fname = os.path.split(program) @@ -236,12 +254,14 @@ def which(program): return exe_file return None + class recording(SixStringIO): """ A nice little context manager for recording the debugger interactions into our session object. If trace flag is ON, it also emits the interactions into the stderr. """ + def __init__(self, test, trace): """Create a SixStringIO instance; record the session obj and trace flag.""" SixStringIO.__init__(self) @@ -269,6 +289,7 @@ class recording(SixStringIO): print(self.getvalue(), file=self.session) self.close() + @add_metaclass(abc.ABCMeta) class _BaseProcess(object): @@ -284,6 +305,7 @@ class _BaseProcess(object): def terminate(self): """Terminates previously launched process..""" + class _LocalProcess(_BaseProcess): def __init__(self, trace_on): @@ -296,25 +318,31 @@ class _LocalProcess(_BaseProcess): return self._proc.pid def launch(self, executable, args): - self._proc = Popen([executable] + args, - stdout = open(os.devnull) if not self._trace_on else None, - stdin = PIPE) + self._proc = Popen( + [executable] + args, + stdout=open( + os.devnull) if not self._trace_on else None, + stdin=PIPE) def terminate(self): - if self._proc.poll() == None: + if self._proc.poll() is None: # Terminate _proc like it does the pexpect - signals_to_try = [sig for sig in ['SIGHUP', 'SIGCONT', 'SIGINT'] if sig in dir(signal)] + signals_to_try = [ + sig for sig in [ + 'SIGHUP', + 'SIGCONT', + 'SIGINT'] if sig in dir(signal)] for sig in signals_to_try: try: self._proc.send_signal(getattr(signal, sig)) time.sleep(self._delayafterterminate) - if self._proc.poll() != None: + if self._proc.poll() is not None: return except ValueError: pass # Windows says SIGINT is not a valid signal to send self._proc.terminate() time.sleep(self._delayafterterminate) - if self._proc.poll() != None: + if self._proc.poll() is not None: return self._proc.kill() time.sleep(self._delayafterterminate) @@ -322,6 +350,7 @@ class _LocalProcess(_BaseProcess): def poll(self): return self._proc.poll() + class _RemoteProcess(_BaseProcess): def __init__(self, install_remote): @@ -335,19 +364,24 @@ class _RemoteProcess(_BaseProcess): def launch(self, executable, args): if self._install_remote: src_path = executable - dst_path = lldbutil.append_to_process_working_directory(os.path.basename(executable)) + dst_path = lldbutil.append_to_process_working_directory( + os.path.basename(executable)) dst_file_spec = lldb.SBFileSpec(dst_path, False) - err = lldb.remote_platform.Install(lldb.SBFileSpec(src_path, True), dst_file_spec) + err = lldb.remote_platform.Install( + lldb.SBFileSpec(src_path, True), dst_file_spec) if err.Fail(): - raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (src_path, dst_path, err)) + raise Exception( + "remote_platform.Install('%s', '%s') failed: %s" % + (src_path, dst_path, err)) else: dst_path = executable dst_file_spec = lldb.SBFileSpec(executable, False) launch_info = lldb.SBLaunchInfo(args) launch_info.SetExecutableFile(dst_file_spec, True) - launch_info.SetWorkingDirectory(lldb.remote_platform.GetWorkingDirectory()) + launch_info.SetWorkingDirectory( + lldb.remote_platform.GetWorkingDirectory()) # Redirect stdout and stderr to /dev/null launch_info.AddSuppressFileAction(1, False, True) @@ -355,7 +389,9 @@ class _RemoteProcess(_BaseProcess): err = lldb.remote_platform.Launch(launch_info) if err.Fail(): - raise Exception("remote_platform.Launch('%s', '%s') failed: %s" % (dst_path, args, err)) + raise Exception( + "remote_platform.Launch('%s', '%s') failed: %s" % + (dst_path, args, err)) self._pid = launch_info.GetProcessID() def terminate(self): @@ -363,6 +399,8 @@ class _RemoteProcess(_BaseProcess): # From 2.7's subprocess.check_output() convenience function. # Return a tuple (stdoutdata, stderrdata). + + def system(commands, **kwargs): r"""Run an os command with arguments and return its output as a byte string. @@ -393,15 +431,23 @@ def system(commands, **kwargs): error = "" for shellCommand in commandList: if 'stdout' in kwargs: - raise ValueError('stdout argument not allowed, it will be overridden.') - if 'shell' in kwargs and kwargs['shell']==False: + raise ValueError( + 'stdout argument not allowed, it will be overridden.') + if 'shell' in kwargs and kwargs['shell'] == False: raise ValueError('shell=False not allowed') - process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, **kwargs) + process = Popen( + shellCommand, + stdout=PIPE, + stderr=PIPE, + shell=True, + universal_newlines=True, + **kwargs) pid = process.pid this_output, this_error = process.communicate() retcode = process.poll() - # Enable trace on failure return while tracking down FreeBSD buildbot issues + # Enable trace on failure return while tracking down FreeBSD buildbot + # issues trace = traceAlways if not trace and retcode and sys.platform.startswith("freebsd"): trace = True @@ -431,6 +477,7 @@ def system(commands, **kwargs): error = error + this_error return (output, error) + def getsource_if_available(obj): """ Return the text of the source code for an object if available. Otherwise, @@ -442,6 +489,7 @@ def getsource_if_available(obj): except: return repr(obj) + def builder_module(): if sys.platform.startswith("freebsd"): return __import__("builder_freebsd") @@ -459,7 +507,7 @@ class Base(unittest2.TestCase): Abstract base for performing lldb (see TestBase) or other generic tests (see BenchBase for one example). lldbtest.Base works with the test driver to accomplish things. - + """ # The concrete subclass should override this attribute. @@ -470,16 +518,16 @@ class Base(unittest2.TestCase): @staticmethod def compute_mydir(test_file): - '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows: - + '''Subclasses should call this function to correctly calculate the required "mydir" attribute as follows: + mydir = TestBase.compute_mydir(__file__)''' test_dir = os.path.dirname(test_file) - return test_dir[len(os.environ["LLDB_TEST"])+1:] - + return test_dir[len(os.environ["LLDB_TEST"]) + 1:] + def TraceOn(self): """Returns True if we are in trace mode (tracing detailed test execution).""" return traceAlways - + @classmethod def setUpClass(cls): """ @@ -514,7 +562,12 @@ class Base(unittest2.TestCase): cls.dir_lock.acquire() # read the previous owner from the lock file lock_id = cls.dir_lock.handle.read() - print("LOCK ERROR: {} wants to lock '{}' but it is already locked by '{}'".format(cls.__name__, full_dir, lock_id), file=sys.stderr) + print( + "LOCK ERROR: {} wants to lock '{}' but it is already locked by '{}'".format( + cls.__name__, + full_dir, + lock_id), + file=sys.stderr) raise ioerror # Set platform context. @@ -535,7 +588,10 @@ class Base(unittest2.TestCase): # Subclass might have specific cleanup function defined. if getattr(cls, "classCleanup", None): if traceAlways: - print("Call class-specific cleanup function for class:", cls, file=sys.stderr) + print( + "Call class-specific cleanup function for class:", + cls, + file=sys.stderr) try: cls.classCleanup() except: @@ -557,7 +613,8 @@ class Base(unittest2.TestCase): By default, we skip long running test case. This can be overridden by passing '-l' to the test driver (dotest.py). """ - if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]: + if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ[ + "LLDB_SKIP_LONG_RUNNING_TEST"]: return False else: return True @@ -587,9 +644,11 @@ class Base(unittest2.TestCase): # communicate gdb-remote categories to debugserver os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories - self.ci.HandleCommand(log_enable + channel_with_categories, self.res) + self.ci.HandleCommand( + log_enable + channel_with_categories, self.res) if not self.res.Succeeded(): - raise Exception('log enable failed (check LLDB_LOG_OPTION env variable)') + raise Exception( + 'log enable failed (check LLDB_LOG_OPTION env variable)') # Communicate log path name to debugserver & lldb-server # For remote debugging, these variables need to be set when starting the platform @@ -600,7 +659,8 @@ class Base(unittest2.TestCase): os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path # Communicate channels to lldb-server - os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels) + os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join( + lldbtest_config.channels) self.addTearDownHook(self.disableLogChannelsForCurrentTest) @@ -611,7 +671,8 @@ class Base(unittest2.TestCase): channel = channel_and_categories.split(' ', 1)[0] self.ci.HandleCommand("log disable " + channel, self.res) if not self.res.Succeeded(): - raise Exception('log disable failed (check LLDB_LOG_OPTION env variable)') + raise Exception( + 'log disable failed (check LLDB_LOG_OPTION env variable)') # Retrieve the server log (if any) from the remote system. It is assumed the server log # is writing to the "server.log" file in the current test directory. This can be @@ -619,19 +680,21 @@ class Base(unittest2.TestCase): # platform. If the remote logging is not enabled, then just let the Get() command silently # fail. if lldb.remote_platform: - lldb.remote_platform.Get(lldb.SBFileSpec("server.log"), - lldb.SBFileSpec(self.getLogBasenameForCurrentTest()+"-server.log")) + lldb.remote_platform.Get( + lldb.SBFileSpec("server.log"), lldb.SBFileSpec( + self.getLogBasenameForCurrentTest() + "-server.log")) def setPlatformWorkingDir(self): if not lldb.remote_platform or not configuration.lldb_platform_working_dir: return remote_test_dir = lldbutil.join_remote_paths( - configuration.lldb_platform_working_dir, - self.getArchitecture(), - str(self.test_number), - self.mydir) - error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700 + configuration.lldb_platform_working_dir, + self.getArchitecture(), + str(self.test_number), + self.mydir) + error = lldb.remote_platform.MakeDirectory( + remote_test_dir, 448) # 448 = 0o700 if error.Success(): lldb.remote_platform.SetWorkingDirectory(remote_test_dir) @@ -643,11 +706,13 @@ class Base(unittest2.TestCase): # TODO: Make it working on Windows when we need it for remote debugging support # TODO: Replace the heuristic to remove the files with a logic what collects the # list of files we have to remove during test runs. - shell_cmd = lldb.SBPlatformShellCommand("rm %s/*" % remote_test_dir) + shell_cmd = lldb.SBPlatformShellCommand( + "rm %s/*" % remote_test_dir) lldb.remote_platform.Run(shell_cmd) self.addTearDownHook(clean_working_directory) else: - print("error: making remote directory '%s': %s" % (remote_test_dir, error)) + print("error: making remote directory '%s': %s" % ( + remote_test_dir, error)) def setUp(self): """Fixture for unittest test case setup. @@ -655,7 +720,7 @@ class Base(unittest2.TestCase): It works with the test driver to conditionally skip tests and does other initializations.""" #import traceback - #traceback.print_stack() + # traceback.print_stack() if "LIBCXX_PATH" in os.environ: self.libcxxPath = os.environ["LIBCXX_PATH"] @@ -718,9 +783,9 @@ class Base(unittest2.TestCase): # (self.session) is then dumped into a session specific file for # diagnosis. self.__cleanup_errored__ = False - self.__errored__ = False - self.__failed__ = False - self.__expected__ = False + self.__errored__ = False + self.__failed__ = False + self.__expected__ = False # We are also interested in unexpected success. self.__unexpected__ = False # And skipped tests. @@ -757,7 +822,7 @@ class Base(unittest2.TestCase): self.setPlatformWorkingDir() self.enableLogChannelsForCurrentTest() - #Initialize debug_info + # Initialize debug_info self.debug_info = None def setAsync(self, value): @@ -786,7 +851,8 @@ class Base(unittest2.TestCase): otherwise the test suite will leak processes. """ - proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn()) + proc = _RemoteProcess( + install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn()) proc.launch(executable, args) self.subprocesses.append(proc) return proc @@ -806,7 +872,7 @@ class Base(unittest2.TestCase): os.dup2(fd, 1) os.dup2(fd, 2) # This call causes the child to have its of group ID - os.setpgid(0,0) + os.setpgid(0, 0) os.execvp(executable, [executable] + args) # Give the child time to get through the execvp() call time.sleep(0.1) @@ -836,6 +902,7 @@ class Base(unittest2.TestCase): self.sys_stdout_hidden = True old_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') + def restore_stdout(): sys.stdout = old_stdout self.addTearDownHook(restore_stdout) @@ -862,9 +929,12 @@ class Base(unittest2.TestCase): """ if six.callable(hook): with recording(self, traceAlways) as sbuf: - print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf) + print( + "Adding tearDown hook:", + getsource_if_available(hook), + file=sbuf) self.hooks.append(hook) - + return self def deletePexpectChild(self): @@ -878,7 +948,8 @@ class Base(unittest2.TestCase): if self.child_in_script_interpreter: self.child.sendline('quit()') self.child.expect_exact(self.child_prompt) - self.child.sendline('settings set interpreter.prompt-on-quit false') + self.child.sendline( + 'settings set interpreter.prompt-on-quit false') self.child.sendline('quit') self.child.expect(pexpect.EOF) except (ValueError, pexpect.ExceptionPexpect): @@ -898,18 +969,21 @@ class Base(unittest2.TestCase): def tearDown(self): """Fixture for unittest test case teardown.""" #import traceback - #traceback.print_stack() + # traceback.print_stack() self.deletePexpectChild() # Check and run any hook functions. for hook in reversed(self.hooks): with recording(self, traceAlways) as sbuf: - print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf) + print( + "Executing tearDown hook:", + getsource_if_available(hook), + file=sbuf) if funcutils.requires_self(hook): hook(self) else: - hook() # try the plain call and hope it works + hook() # try the plain call and hope it works del self.hooks @@ -951,17 +1025,19 @@ class Base(unittest2.TestCase): # Once by the Python unittest framework, and a second time by us. print("FAIL", file=sbuf) - def markExpectedFailure(self,err,bugnumber): + def markExpectedFailure(self, err, bugnumber): """Callback invoked when an expected failure/error occurred.""" self.__expected__ = True with recording(self, False) as sbuf: # False because there's no need to write "expected failure" to the # stderr twice. # Once by the Python unittest framework, and a second time by us. - if bugnumber == None: + if bugnumber is None: print("expected failure", file=sbuf) else: - print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf) + print( + "expected failure (problem id:" + str(bugnumber) + ")", + file=sbuf) def markSkippedTest(self): """Callback invoked when a test is skipped.""" @@ -979,10 +1055,12 @@ class Base(unittest2.TestCase): # False because there's no need to write "unexpected success" to the # stderr twice. # Once by the Python unittest framework, and a second time by us. - if bugnumber == None: + if bugnumber is None: print("unexpected success", file=sbuf) else: - print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf) + print( + "unexpected success (problem id:" + str(bugnumber) + ")", + file=sbuf) def getRerunArgs(self): return " -f %s.%s" % (self.__class__.__name__, self._testMethodName) @@ -995,7 +1073,7 @@ class Base(unittest2.TestCase): <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method> """ dname = os.path.join(os.environ["LLDB_TEST"], - os.environ["LLDB_SESSION_DIRNAME"]) + os.environ["LLDB_SESSION_DIRNAME"]) if not os.path.isdir(dname): os.mkdir(dname) @@ -1014,7 +1092,8 @@ class Base(unittest2.TestCase): compiler = compiler[2:] if os.path.altsep is not None: compiler = compiler.replace(os.path.altsep, os.path.sep) - components.extend([x for x in compiler.split(os.path.sep) if x != ""]) + components.extend( + [x for x in compiler.split(os.path.sep) if x != ""]) elif c == 'a': components.append(self.getArchitecture()) elif c == 'm': @@ -1078,11 +1157,19 @@ class Base(unittest2.TestCase): benchmarks = False import datetime - print("Session info generated @", datetime.datetime.now().ctime(), file=self.session) - print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session) - print("./dotest.py %s -v %s %s" % (self.getRunOptions(), - ('+b' if benchmarks else '-t'), - self.getRerunArgs()), file=self.session) + print( + "Session info generated @", + datetime.datetime.now().ctime(), + file=self.session) + print( + "To rerun this test, issue the following command from the 'test' directory:\n", + file=self.session) + print( + "./dotest.py %s -v %s %s" % + (self.getRunOptions(), + ('+b' if benchmarks else '-t'), + self.getRerunArgs()), + file=self.session) self.session.close() del self.session @@ -1135,10 +1222,11 @@ class Base(unittest2.TestCase): ] output = check_output(command) - str = output.decode("utf-8"); + str = output.decode("utf-8") for line in str.splitlines(): - m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line) + m = re.search( + "Current executable set to '.*' \\((.*)\\)\\.", line) if m: self.lldbArchitecture = m.group(1) break @@ -1198,16 +1286,16 @@ class Base(unittest2.TestCase): Any operator other than the following defaults to an equality test: '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not' """ - if (compiler_version == None): + if (compiler_version is None): return True operator = str(compiler_version[0]) version = compiler_version[1] - if (version == None): + if (version is None): return True if (operator == '>'): return self.getCompilerVersion() > version - if (operator == '>=' or operator == '=>'): + if (operator == '>=' or operator == '=>'): return self.getCompilerVersion() >= version if (operator == '<'): return self.getCompilerVersion() < version @@ -1219,7 +1307,7 @@ class Base(unittest2.TestCase): def expectedCompiler(self, compilers): """Returns True iff any element of compilers is a sub-string of the current compiler.""" - if (compilers == None): + if (compilers is None): return True for compiler in compilers: @@ -1230,7 +1318,7 @@ class Base(unittest2.TestCase): def expectedArch(self, archs): """Returns True iff any element of archs is a sub-string of the current architecture.""" - if (archs == None): + if (archs is None): return True for arch in archs: @@ -1260,16 +1348,16 @@ class Base(unittest2.TestCase): """ Returns the proper -stdlib flag, or empty if not required.""" if self.platformIsDarwin() or self.getPlatform() == "freebsd": stdlibflag = "-stdlib=libc++" - else: # this includes NetBSD + else: # this includes NetBSD stdlibflag = "" return stdlibflag def getstdFlag(self): """ Returns the proper stdflag. """ if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion(): - stdflag = "-std=c++0x" + stdflag = "-std=c++0x" else: - stdflag = "-std=c++11" + stdflag = "-std=c++11" return stdflag def buildDriver(self, sources, exe_name): @@ -1279,28 +1367,40 @@ class Base(unittest2.TestCase): stdflag = self.getstdFlag() stdlibflag = self.getstdlibFlag() - + lib_dir = os.environ["LLDB_LIB_DIR"] if sys.platform.startswith("darwin"): dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB') - d = {'CXX_SOURCES' : sources, - 'EXE' : exe_name, - 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag), - 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir, - 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir), - } + d = {'CXX_SOURCES': sources, + 'EXE': exe_name, + 'CFLAGS_EXTRAS': "%s %s" % (stdflag, stdlibflag), + 'FRAMEWORK_INCLUDES': "-F%s" % lib_dir, + 'LD_EXTRAS': "%s -Wl,-rpath,%s" % (dsym, lib_dir), + } elif sys.platform.rstrip('0123456789') in ('freebsd', 'linux', 'netbsd') or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile': - d = {'CXX_SOURCES' : sources, - 'EXE' : exe_name, - 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")), - 'LD_EXTRAS' : "-L%s -llldb" % lib_dir} + d = { + 'CXX_SOURCES': sources, + 'EXE': exe_name, + 'CFLAGS_EXTRAS': "%s %s -I%s" % (stdflag, + stdlibflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-L%s -llldb" % lib_dir} elif sys.platform.startswith('win'): - d = {'CXX_SOURCES' : sources, - 'EXE' : exe_name, - 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")), - 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]} + d = { + 'CXX_SOURCES': sources, + 'EXE': exe_name, + 'CFLAGS_EXTRAS': "%s %s -I%s" % (stdflag, + stdlibflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]} if self.TraceOn(): - print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources)) + print( + "Building LLDB Driver (%s) from sources %s" % + (exe_name, sources)) self.buildDefault(dictionary=d) @@ -1312,64 +1412,124 @@ class Base(unittest2.TestCase): lib_dir = os.environ["LLDB_LIB_DIR"] if self.platformIsDarwin(): dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB') - d = {'DYLIB_CXX_SOURCES' : sources, - 'DYLIB_NAME' : lib_name, - 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag, - 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir, - 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir), - } + d = {'DYLIB_CXX_SOURCES': sources, + 'DYLIB_NAME': lib_name, + 'CFLAGS_EXTRAS': "%s -stdlib=libc++" % stdflag, + 'FRAMEWORK_INCLUDES': "-F%s" % lib_dir, + 'LD_EXTRAS': "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir), + } elif self.getPlatform() in ('freebsd', 'linux', 'netbsd') or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile': - d = {'DYLIB_CXX_SOURCES' : sources, - 'DYLIB_NAME' : lib_name, - 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")), - 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir} + d = { + 'DYLIB_CXX_SOURCES': sources, + 'DYLIB_NAME': lib_name, + 'CFLAGS_EXTRAS': "%s -I%s -fPIC" % (stdflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-shared -L%s -llldb" % lib_dir} elif self.getPlatform() == 'windows': - d = {'DYLIB_CXX_SOURCES' : sources, - 'DYLIB_NAME' : lib_name, - 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")), - 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]} + d = { + 'DYLIB_CXX_SOURCES': sources, + 'DYLIB_NAME': lib_name, + 'CFLAGS_EXTRAS': "%s -I%s -fPIC" % (stdflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]} if self.TraceOn(): - print("Building LLDB Library (%s) from sources %s" % (lib_name, sources)) + print( + "Building LLDB Library (%s) from sources %s" % + (lib_name, sources)) self.buildDefault(dictionary=d) - + def buildProgram(self, sources, exe_name): """ Platform specific way to build an executable from C/C++ sources. """ - d = {'CXX_SOURCES' : sources, - 'EXE' : exe_name} + d = {'CXX_SOURCES': sources, + 'EXE': exe_name} self.buildDefault(dictionary=d) - def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True): + def buildDefault( + self, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Platform specific way to build the default binaries.""" module = builder_module() dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) - if not module.buildDefault(self, architecture, compiler, dictionary, clean): + if not module.buildDefault( + self, + architecture, + compiler, + dictionary, + clean): raise Exception("Don't know how to build default binary") - def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True): + def buildDsym( + self, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Platform specific way to build binaries with dsym info.""" module = builder_module() - if not module.buildDsym(self, architecture, compiler, dictionary, clean): + if not module.buildDsym( + self, + architecture, + compiler, + dictionary, + clean): raise Exception("Don't know how to build binary with dsym") - def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True): + def buildDwarf( + self, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Platform specific way to build binaries with dwarf maps.""" module = builder_module() dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) - if not module.buildDwarf(self, architecture, compiler, dictionary, clean): + if not module.buildDwarf( + self, + architecture, + compiler, + dictionary, + clean): raise Exception("Don't know how to build binary with dwarf") - def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True): + def buildDwo( + self, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Platform specific way to build binaries with dwarf maps.""" module = builder_module() dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) - if not module.buildDwo(self, architecture, compiler, dictionary, clean): + if not module.buildDwo( + self, + architecture, + compiler, + dictionary, + clean): raise Exception("Don't know how to build binary with dwo") - def buildGModules(self, architecture=None, compiler=None, dictionary=None, clean=True): + def buildGModules( + self, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Platform specific way to build binaries with gmodules info.""" module = builder_module() - if not module.buildGModules(self, architecture, compiler, dictionary, clean): + if not module.buildGModules( + self, + architecture, + compiler, + dictionary, + clean): raise Exception("Don't know how to build binary with gmodules") def buildGo(self): @@ -1379,18 +1539,20 @@ class Base(unittest2.TestCase): def signBinary(self, binary_path): if sys.platform.startswith("darwin"): - codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path) + codesign_cmd = "codesign --force --sign lldb_codesign %s" % ( + binary_path) call(codesign_cmd, shell=True) def findBuiltClang(self): """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler).""" paths_to_try = [ - "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang", - "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang", - "llvm-build/Release/x86_64/Release/bin/clang", - "llvm-build/Debug/x86_64/Debug/bin/clang", + "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang", + "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang", + "llvm-build/Release/x86_64/Release/bin/clang", + "llvm-build/Debug/x86_64/Debug/bin/clang", ] - lldb_root_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..") + lldb_root_path = os.path.join( + os.path.dirname(__file__), "..", "..", "..", "..") for p in paths_to_try: path = os.path.join(lldb_root_path, p) if os.path.exists(path): @@ -1400,17 +1562,22 @@ class Base(unittest2.TestCase): path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang") if os.path.exists(path): return path - + return os.environ["CC"] - def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False): + def getBuildFlags( + self, + use_cpp11=True, + use_libcxx=False, + use_libstdcxx=False): """ Returns a dictionary (which can be provided to build* functions above) which contains OS-specific build flags. """ cflags = "" ldflags = "" - # On Mac OS X, unless specifically requested to use libstdc++, use libc++ + # On Mac OS X, unless specifically requested to use libstdc++, use + # libc++ if not use_libstdcxx and self.platformIsDarwin(): use_libcxx = True @@ -1420,7 +1587,8 @@ class Base(unittest2.TestCase): libcxxInclude = os.path.join(self.libcxxPath, "include") libcxxLib = os.path.join(self.libcxxPath, "lib") if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib): - cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib) + cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % ( + libcxxInclude, libcxxLib, libcxxLib) if use_cpp11: cflags += "-std=" @@ -1435,15 +1603,17 @@ class Base(unittest2.TestCase): elif "clang" in self.getCompiler(): cflags += " -stdlib=libstdc++" - return {'CFLAGS_EXTRAS' : cflags, - 'LD_EXTRAS' : ldflags, - } + return {'CFLAGS_EXTRAS': cflags, + 'LD_EXTRAS': ldflags, + } def cleanup(self, dictionary=None): """Platform specific way to do cleanup after build.""" module = builder_module() if not module.cleanup(self, dictionary): - raise Exception("Don't know how to do cleanup with dictionary: "+dictionary) + raise Exception( + "Don't know how to do cleanup with dictionary: " + + dictionary) def getLLDBLibraryEnvVal(self): """ Returns the path that the OS-specific library search environment variable @@ -1451,7 +1621,8 @@ class Base(unittest2.TestCase): library. If an environment variable named self.dylibPath is already set, the new path is appended to it and returned. """ - existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None + existing_library_path = os.environ[ + self.dylibPath] if self.dylibPath in os.environ else None lib_dir = os.environ["LLDB_LIB_DIR"] if existing_library_path: return "%s:%s" % (existing_library_path, lib_dir) @@ -1464,7 +1635,7 @@ class Base(unittest2.TestCase): if self.getPlatform() in ('freebsd', 'linux', 'netbsd'): return ['libc++.so.1'] else: - return ['libc++.1.dylib','libc++abi.dylib'] + return ['libc++.1.dylib', 'libc++abi.dylib'] # Metaclass for TestBase to change the list of test metods when a new TestCase is loaded. # We change the test methods to create a new test method for each test for each debug info we are @@ -1472,27 +1643,40 @@ class Base(unittest2.TestCase): # the new test method we remove the old method at the same time. This functionality can be # supressed by at test case level setting the class attribute NO_DEBUG_INFO_TESTCASE or at test # level by using the decorator @no_debug_info_test. + + class LLDBTestCaseFactory(type): + def __new__(cls, name, bases, attrs): - original_testcase = super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, attrs) + original_testcase = super( + LLDBTestCaseFactory, cls).__new__( + cls, name, bases, attrs) if original_testcase.NO_DEBUG_INFO_TESTCASE: return original_testcase newattrs = {} for attrname, attrvalue in attrs.items(): - if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False): - target_platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2] + if attrname.startswith("test") and not getattr( + attrvalue, "__no_debug_info_test__", False): + target_platform = lldb.DBG.GetSelectedPlatform( + ).GetTriple().split('-')[2] # If any debug info categories were explicitly tagged, assume that list to be - # authoritative. If none were specified, try with all debug info formats. - all_dbginfo_categories = set(test_categories.debug_info_categories) - categories = set(getattr(attrvalue, "categories", [])) & all_dbginfo_categories + # authoritative. If none were specified, try with all debug + # info formats. + all_dbginfo_categories = set( + test_categories.debug_info_categories) + categories = set( + getattr( + attrvalue, + "categories", + [])) & all_dbginfo_categories if not categories: categories = all_dbginfo_categories - supported_categories = [x for x in categories - if test_categories.is_supported_on_platform( - x, target_platform, configuration.compilers)] + supported_categories = [ + x for x in categories if test_categories.is_supported_on_platform( + x, target_platform, configuration.compilers)] if "dsym" in supported_categories: @decorators.add_test_categories(["dsym"]) @wraps(attrvalue) @@ -1535,9 +1719,18 @@ class LLDBTestCaseFactory(type): else: newattrs[attrname] = attrvalue - return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs) + return super( + LLDBTestCaseFactory, + cls).__new__( + cls, + name, + bases, + newattrs) + +# Setup the metaclass for this class to change the list of the test +# methods when a new class is loaded + -# Setup the metaclass for this class to change the list of the test methods when a new class is loaded @add_metaclass(LLDBTestCaseFactory) class TestBase(Base): """ @@ -1597,11 +1790,11 @@ class TestBase(Base): # Maximum allowed attempts when launching the inferior process. # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable. - maxLaunchCount = 3; + maxLaunchCount = 3 # Time to wait before the next launching attempt in second(s). # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable. - timeWaitNextLaunch = 1.0; + timeWaitNextLaunch = 1.0 # Returns the list of categories to which this test case belongs # by default, look for a ".categories" file, and read its contents @@ -1615,30 +1808,32 @@ class TestBase(Base): folder = inspect.getfile(self.__class__) folder = os.path.dirname(folder) while folder != '/': - categories_file_name = os.path.join(folder,".categories") - if os.path.exists(categories_file_name): - categories_file = open(categories_file_name,'r') - categories = categories_file.readline() - categories_file.close() - categories = str.replace(categories,'\n','') - categories = str.replace(categories,'\r','') - return categories.split(',') - else: - folder = os.path.dirname(folder) - continue + categories_file_name = os.path.join(folder, ".categories") + if os.path.exists(categories_file_name): + categories_file = open(categories_file_name, 'r') + categories = categories_file.readline() + categories_file.close() + categories = str.replace(categories, '\n', '') + categories = str.replace(categories, '\r', '') + return categories.split(',') + else: + folder = os.path.dirname(folder) + continue def setUp(self): #import traceback - #traceback.print_stack() + # traceback.print_stack() - # Works with the test driver to conditionally skip tests via decorators. + # Works with the test driver to conditionally skip tests via + # decorators. Base.setUp(self) if "LLDB_MAX_LAUNCH_COUNT" in os.environ: self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"]) if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ: - self.timeWaitNextLaunch = float(os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"]) + self.timeWaitNextLaunch = float( + os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"]) # We want our debugger to be synchronous. self.dbg.SetAsync(False) @@ -1653,7 +1848,7 @@ class TestBase(Base): def registerSharedLibrariesWithTarget(self, target, shlibs): '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing - + Any modules in the target that have their remote install file specification set will get uploaded to the remote host. This function registers the local copies of the shared libraries with the target and sets their remote install locations so they will @@ -1676,12 +1871,14 @@ class TestBase(Base): # basename like "libFoo.so". So figure out which one it is and resolve the local copy # of the shared library accordingly if os.path.exists(name): - local_shlib_path = name # name is the full path to the local shared library + local_shlib_path = name # name is the full path to the local shared library else: # Check relative names - local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension) + local_shlib_path = os.path.join( + os.getcwd(), shlib_prefix + name + shlib_extension) if not os.path.exists(local_shlib_path): - local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension) + local_shlib_path = os.path.join( + os.getcwd(), name + shlib_extension) if not os.path.exists(local_shlib_path): local_shlib_path = os.path.join(os.getcwd(), name) @@ -1693,8 +1890,10 @@ class TestBase(Base): if lldb.remote_platform: # We must set the remote install location if we want the shared library # to get uploaded to the remote target - remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path)) - shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False)) + remote_shlib_path = lldbutil.append_to_process_working_directory( + os.path.basename(local_shlib_path)) + shlib_module.SetRemoteInstallFileSpec( + lldb.SBFileSpec(remote_shlib_path, False)) return environment @@ -1717,20 +1916,22 @@ class TestBase(Base): def frame(self): if not self.dbg: raise Exception('Invalid debugger instance') - return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + return self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() def get_process_working_directory(self): '''Get the working directory that should be used when launching processes for local or remote processes.''' if lldb.remote_platform: - # Remote tests set the platform working directory up in TestBase.setUp() + # Remote tests set the platform working directory up in + # TestBase.setUp() return lldb.remote_platform.GetWorkingDirectory() else: # local tests change directory into each test subdirectory - return os.getcwd() - + return os.getcwd() + def tearDown(self): #import traceback - #traceback.print_stack() + # traceback.print_stack() # Ensure all the references to SB objects have gone away so that we can # be sure that all test-specific resources have been freed before we @@ -1767,8 +1968,9 @@ class TestBase(Base): from .lldbutil import stop_reason_to_str self.runCmd('thread list') output = self.res.GetOutput() - thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" % - stop_reason_to_str(stop_reason)) + thread_line_pattern = re.compile( + "^[ *] thread #([0-9]+):.*stop reason = %s" % + stop_reason_to_str(stop_reason)) for line in output.splitlines(): matched = thread_line_pattern.match(line) if matched: @@ -1815,7 +2017,15 @@ class TestBase(Base): self.assertTrue(self.res.Succeeded(), msg if msg else CMD_MSG(cmd)) - def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True): + def match( + self, + str, + patterns, + msg=None, + trace=False, + error=False, + matching=True, + exe=True): """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern Otherwise, all the arguments have the same meanings as for the expect function""" @@ -1824,8 +2034,14 @@ class TestBase(Base): if exe: # First run the command. If we are expecting error, set check=False. - # Pass the assert message along since it provides more semantic info. - self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error) + # Pass the assert message along since it provides more semantic + # info. + self.runCmd( + str, + msg=msg, + trace=( + True if trace else False), + check=not error) # Then compare the output against expected strings. output = self.res.GetError() if error else self.res.GetOutput() @@ -1856,9 +2072,21 @@ class TestBase(Base): self.assertTrue(matched if matching else not matched, msg if msg else EXP_MSG(str, output, exe)) - return match_object - - def expect(self, str, msg=None, patterns=None, startstr=None, endstr=None, substrs=None, trace=False, error=False, matching=True, exe=True, inHistory=False): + return match_object + + def expect( + self, + str, + msg=None, + patterns=None, + startstr=None, + endstr=None, + substrs=None, + trace=False, + error=False, + matching=True, + exe=True, + inHistory=False): """ Similar to runCmd; with additional expect style output matching ability. @@ -1886,8 +2114,15 @@ class TestBase(Base): if exe: # First run the command. If we are expecting error, set check=False. - # Pass the assert message along since it provides more semantic info. - self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory) + # Pass the assert message along since it provides more semantic + # info. + self.runCmd( + str, + msg=msg, + trace=( + True if trace else False), + check=not error, + inHistory=inHistory) # Then compare the output against expected strings. output = self.res.GetError() if error else self.res.GetOutput() @@ -1898,7 +2133,7 @@ class TestBase(Base): "Command '" + str + "' is expected to fail!") else: # No execution required, just compare str against the golden input. - if isinstance(str,lldb.SBCommandReturnObject): + if isinstance(str, lldb.SBCommandReturnObject): output = str.GetOutput() else: output = str @@ -1910,7 +2145,8 @@ class TestBase(Base): # Start from the startstr, if specified. # If there's no startstr, set the initial state appropriately. - matched = output.startswith(startstr) if startstr else (True if matching else False) + matched = output.startswith(startstr) if startstr else ( + True if matching else False) if startstr: with recording(self, trace) as sbuf: @@ -1956,17 +2192,22 @@ class TestBase(Base): def invoke(self, obj, name, trace=False): """Use reflection to call a method dynamically with no argument.""" trace = (True if traceAlways else trace) - + method = getattr(obj, name) import inspect self.assertTrue(inspect.ismethod(method), name + "is a method name of object: " + str(obj)) result = method() with recording(self, trace) as sbuf: - print(str(method) + ":", result, file=sbuf) + print(str(method) + ":", result, file=sbuf) return result - def build(self, architecture=None, compiler=None, dictionary=None, clean=True): + def build( + self, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Platform specific way to build the default binaries.""" module = builder_module() dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) @@ -1979,7 +2220,8 @@ class TestBase(Base): elif self.debug_info == "dwo": return self.buildDwo(architecture, compiler, dictionary, clean) elif self.debug_info == "gmodules": - return self.buildGModules(architecture, compiler, dictionary, clean) + return self.buildGModules( + architecture, compiler, dictionary, clean) else: self.fail("Can't build for debug info: %s" % self.debug_info) @@ -2002,15 +2244,24 @@ class TestBase(Base): err = sys.stderr err.write(val.GetName() + ":\n") - err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n') - err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n') - err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n') - err.write('\t' + "Value -> " + str(val.GetValue()) + '\n') - err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n') - err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n') - err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n') - err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n') - err.write('\t' + "Location -> " + val.GetLocation() + '\n') + err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n') + err.write('\t' + "ByteSize -> " + + str(val.GetByteSize()) + '\n') + err.write('\t' + "NumChildren -> " + + str(val.GetNumChildren()) + '\n') + err.write('\t' + "Value -> " + str(val.GetValue()) + '\n') + err.write('\t' + "ValueAsUnsigned -> " + + str(val.GetValueAsUnsigned()) + '\n') + err.write( + '\t' + + "ValueType -> " + + value_type_to_str( + val.GetValueType()) + + '\n') + err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n') + err.write('\t' + "IsPointerType -> " + + str(val.TypeIsPointerType()) + '\n') + err.write('\t' + "Location -> " + val.GetLocation() + '\n') def DebugSBType(self, type): """Debug print a SBType object, if traceAlways is True.""" @@ -2019,9 +2270,12 @@ class TestBase(Base): err = sys.stderr err.write(type.GetName() + ":\n") - err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n') - err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n') - err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n') + err.write('\t' + "ByteSize -> " + + str(type.GetByteSize()) + '\n') + err.write('\t' + "IsPointerType -> " + + str(type.IsPointerType()) + '\n') + err.write('\t' + "IsReferenceType -> " + + str(type.IsReferenceType()) + '\n') def DebugPExpect(self, child): """Debug the spwaned pexpect object.""" @@ -2038,8 +2292,10 @@ class TestBase(Base): # On Windows, the first attempt to delete a recently-touched file can fail # because of a race with antimalware scanners. This function will detect a # failure and retry. -def remove_file(file, num_retries = 1, sleep_duration = 0.5): - for i in range(num_retries+1): + + +def remove_file(file, num_retries=1, sleep_duration=0.5): + for i in range(num_retries + 1): try: os.remove(file) return True diff --git a/lldb/packages/Python/lldbsuite/test/lldbtest_config.py b/lldb/packages/Python/lldbsuite/test/lldbtest_config.py index c2d4549437b..2e8e302fc7a 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbtest_config.py +++ b/lldb/packages/Python/lldbsuite/test/lldbtest_config.py @@ -18,4 +18,3 @@ log_success = False # path to the lldb command line executable tool lldbExec = None - diff --git a/lldb/packages/Python/lldbsuite/test/lldbutil.py b/lldb/packages/Python/lldbsuite/test/lldbutil.py index 45e9bb407d1..7732dbe6dff 100644 --- a/lldb/packages/Python/lldbsuite/test/lldbutil.py +++ b/lldb/packages/Python/lldbsuite/test/lldbutil.py @@ -30,6 +30,7 @@ def is_exe(fpath): """Returns True if fpath is an executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + def which(program): """Returns the full path to a program; None otherwise.""" fpath, fname = os.path.split(program) @@ -47,6 +48,7 @@ def which(program): # Disassembly for an SBFunction or an SBSymbol object # =================================================== + def disassemble(target, function_or_symbol): """Disassemble the function or symbol given a target. @@ -62,6 +64,7 @@ def disassemble(target, function_or_symbol): # Integer (byte size 1, 2, 4, and 8) to bytearray conversion # ========================================================== + def int_to_bytearray(val, bytesize): """Utility function to convert an integer into a bytearray. @@ -87,6 +90,7 @@ def int_to_bytearray(val, bytesize): packed = struct.pack(fmt, val) return bytearray(packed) + def bytearray_to_int(bytes, bytesize): """Utility function to convert a bytearray into an integer. @@ -142,7 +146,7 @@ def get_description(obj, option=None): if not success: return None return stream.GetData() - + # ================================================= # Convert some enum value to its string counterpart @@ -177,6 +181,7 @@ def state_type_to_str(enum): else: raise Exception("Unknown StateType enum") + def stop_reason_to_str(enum): """Returns the stopReason string given an enum.""" if enum == lldb.eStopReasonInvalid: @@ -202,6 +207,7 @@ def stop_reason_to_str(enum): else: raise Exception("Unknown StopReason enum") + def symbol_type_to_str(enum): """Returns the symbolType string given an enum.""" if enum == lldb.eSymbolTypeInvalid: @@ -253,6 +259,7 @@ def symbol_type_to_str(enum): elif enum == lldb.eSymbolTypeUndefined: return "undefined" + def value_type_to_str(enum): """Returns the valueType string given an enum.""" if enum == lldb.eValueTypeInvalid: @@ -280,12 +287,12 @@ def value_type_to_str(enum): # ================================================== def sort_stopped_threads(process, - breakpoint_threads = None, - crashed_threads = None, - watchpoint_threads = None, - signal_threads = None, - exiting_threads = None, - other_threads = None): + breakpoint_threads=None, + crashed_threads=None, + watchpoint_threads=None, + signal_threads=None, + exiting_threads=None, + other_threads=None): """ Fills array *_threads with threads stopped for the corresponding stop reason. """ @@ -314,8 +321,16 @@ def sort_stopped_threads(process, # Utility functions for setting breakpoints # ================================================== -def run_break_set_by_file_and_line (test, file_name, line_number, extra_options = None, num_expected_locations = 1, loc_exact=False, module_name=None): - """Set a breakpoint by file and line, returning the breakpoint number. + +def run_break_set_by_file_and_line( + test, + file_name, + line_number, + extra_options=None, + num_expected_locations=1, + loc_exact=False, + module_name=None): + """Set a breakpoint by file and line, returning the breakpoint number. If extra_options is not None, then we append it to the breakpoint set command. @@ -323,10 +338,10 @@ def run_break_set_by_file_and_line (test, file_name, line_number, extra_options If loc_exact is true, we check that there is one location, and that location must be at the input file and line number.""" - if file_name == None: - command = 'breakpoint set -l %d'%(line_number) + if file_name is None: + command = 'breakpoint set -l %d' % (line_number) else: - command = 'breakpoint set -f "%s" -l %d'%(file_name, line_number) + command = 'breakpoint set -f "%s" -l %d' % (file_name, line_number) if module_name: command += " --shlib '%s'" % (module_name) @@ -334,20 +349,36 @@ def run_break_set_by_file_and_line (test, file_name, line_number, extra_options if extra_options: command += " " + extra_options - break_results = run_break_set_command (test, command) + break_results = run_break_set_command(test, command) if num_expected_locations == 1 and loc_exact: - check_breakpoint_result (test, break_results, num_locations=num_expected_locations, file_name = file_name, line_number = line_number, module_name=module_name) + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations, + file_name=file_name, + line_number=line_number, + module_name=module_name) else: - check_breakpoint_result (test, break_results, num_locations = num_expected_locations) + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) - return get_bpno_from_match (break_results) -def run_break_set_by_symbol (test, symbol, extra_options = None, num_expected_locations = -1, sym_exact = False, module_name=None): +def run_break_set_by_symbol( + test, + symbol, + extra_options=None, + num_expected_locations=-1, + sym_exact=False, + module_name=None): """Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line. If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match.""" - command = 'breakpoint set -n "%s"'%(symbol) + command = 'breakpoint set -n "%s"' % (symbol) if module_name: command += " --shlib '%s'" % (module_name) @@ -355,16 +386,30 @@ def run_break_set_by_symbol (test, symbol, extra_options = None, num_expected_lo if extra_options: command += " " + extra_options - break_results = run_break_set_command (test, command) + break_results = run_break_set_command(test, command) if num_expected_locations == 1 and sym_exact: - check_breakpoint_result (test, break_results, num_locations = num_expected_locations, symbol_name = symbol, module_name=module_name) + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations, + symbol_name=symbol, + module_name=module_name) else: - check_breakpoint_result (test, break_results, num_locations = num_expected_locations) + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) - return get_bpno_from_match (break_results) + return get_bpno_from_match(break_results) -def run_break_set_by_selector (test, selector, extra_options = None, num_expected_locations = -1, module_name=None): + +def run_break_set_by_selector( + test, + selector, + extra_options=None, + num_expected_locations=-1, + module_name=None): """Set a breakpoint by selector. Common options are the same as run_break_set_by_file_and_line.""" command = 'breakpoint set -S "%s"' % (selector) @@ -375,42 +420,68 @@ def run_break_set_by_selector (test, selector, extra_options = None, num_expecte if extra_options: command += " " + extra_options - break_results = run_break_set_command (test, command) + break_results = run_break_set_command(test, command) if num_expected_locations == 1: - check_breakpoint_result (test, break_results, num_locations = num_expected_locations, symbol_name = selector, symbol_match_exact=False, module_name=module_name) + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations, + symbol_name=selector, + symbol_match_exact=False, + module_name=module_name) else: - check_breakpoint_result (test, break_results, num_locations = num_expected_locations) + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) - return get_bpno_from_match (break_results) -def run_break_set_by_regexp (test, regexp, extra_options=None, num_expected_locations=-1): +def run_break_set_by_regexp( + test, + regexp, + extra_options=None, + num_expected_locations=-1): """Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line.""" - command = 'breakpoint set -r "%s"'%(regexp) + command = 'breakpoint set -r "%s"' % (regexp) if extra_options: command += " " + extra_options - - break_results = run_break_set_command (test, command) - - check_breakpoint_result (test, break_results, num_locations=num_expected_locations) - return get_bpno_from_match (break_results) + break_results = run_break_set_command(test, command) -def run_break_set_by_source_regexp (test, regexp, extra_options=None, num_expected_locations=-1): + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) + + +def run_break_set_by_source_regexp( + test, + regexp, + extra_options=None, + num_expected_locations=-1): """Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line.""" - command = 'breakpoint set -p "%s"'%(regexp) + command = 'breakpoint set -p "%s"' % (regexp) if extra_options: command += " " + extra_options - - break_results = run_break_set_command (test, command) - - check_breakpoint_result (test, break_results, num_locations=num_expected_locations) - return get_bpno_from_match (break_results) + break_results = run_break_set_command(test, command) + + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) -def run_break_set_command (test, command): - """Run the command passed in - it must be some break set variant - and analyze the result. + return get_bpno_from_match(break_results) + + +def run_break_set_command(test, command): + """Run the command passed in - it must be some break set variant - and analyze the result. Returns a dictionary of information gleaned from the command-line results. Will assert if the breakpoint setting fails altogether. @@ -427,11 +498,12 @@ def run_break_set_command (test, command): module - module address - address at which the breakpoint was set.""" - patterns = [r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>[0-9]+) locations\.$", - r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>no) locations \(pending\)\.", - r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>[+\-]{0,1}[^+]+)( \+ (?P<offset>[0-9]+)){0,1}( \[inlined\] (?P<inline_symbol>.*)){0,1} at (?P<file>[^:]+):(?P<line_no>[0-9]+), address = (?P<address>0x[0-9a-fA-F]+)$", - r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>.*)( \+ (?P<offset>[0-9]+)){0,1}, address = (?P<address>0x[0-9a-fA-F]+)$"] - match_object = test.match (command, patterns) + patterns = [ + r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>[0-9]+) locations\.$", + r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>no) locations \(pending\)\.", + r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>[+\-]{0,1}[^+]+)( \+ (?P<offset>[0-9]+)){0,1}( \[inlined\] (?P<inline_symbol>.*)){0,1} at (?P<file>[^:]+):(?P<line_no>[0-9]+), address = (?P<address>0x[0-9a-fA-F]+)$", + r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>.*)( \+ (?P<offset>[0-9]+)){0,1}, address = (?P<address>0x[0-9a-fA-F]+)$"] + match_object = test.match(command, patterns) break_results = match_object.groupdict() # We always insert the breakpoint number, setting it to -1 if we couldn't find it @@ -440,7 +512,7 @@ def run_break_set_command (test, command): break_results['bpno'] = -1 else: break_results['bpno'] = int(break_results['bpno']) - + # We always insert the number of locations # If ONE location is set for the breakpoint, then the output doesn't mention locations, but it has to be 1... # We also make sure it is an integer. @@ -455,61 +527,101 @@ def run_break_set_command (test, command): num_locations = int(break_results['num_locations']) break_results['num_locations'] = num_locations - + if 'line_no' in break_results: break_results['line_no'] = int(break_results['line_no']) return break_results -def get_bpno_from_match (break_results): - return int (break_results['bpno']) -def check_breakpoint_result (test, break_results, file_name=None, line_number=-1, symbol_name=None, symbol_match_exact=True, module_name=None, offset=-1, num_locations=-1): +def get_bpno_from_match(break_results): + return int(break_results['bpno']) + + +def check_breakpoint_result( + test, + break_results, + file_name=None, + line_number=-1, + symbol_name=None, + symbol_match_exact=True, + module_name=None, + offset=-1, + num_locations=-1): out_num_locations = break_results['num_locations'] if num_locations == -1: - test.assertTrue (out_num_locations > 0, "Expecting one or more locations, got none.") + test.assertTrue(out_num_locations > 0, + "Expecting one or more locations, got none.") else: - test.assertTrue (num_locations == out_num_locations, "Expecting %d locations, got %d."%(num_locations, out_num_locations)) + test.assertTrue( + num_locations == out_num_locations, + "Expecting %d locations, got %d." % + (num_locations, + out_num_locations)) if file_name: out_file_name = "" if 'file' in break_results: out_file_name = break_results['file'] - test.assertTrue (file_name == out_file_name, "Breakpoint file name '%s' doesn't match resultant name '%s'."%(file_name, out_file_name)) + test.assertTrue( + file_name == out_file_name, + "Breakpoint file name '%s' doesn't match resultant name '%s'." % + (file_name, + out_file_name)) if line_number != -1: out_line_number = -1 if 'line_no' in break_results: out_line_number = break_results['line_no'] - test.assertTrue (line_number == out_line_number, "Breakpoint line number %s doesn't match resultant line %s."%(line_number, out_line_number)) + test.assertTrue( + line_number == out_line_number, + "Breakpoint line number %s doesn't match resultant line %s." % + (line_number, + out_line_number)) if symbol_name: out_symbol_name = "" - # Look first for the inlined symbol name, otherwise use the symbol name: + # Look first for the inlined symbol name, otherwise use the symbol + # name: if 'inline_symbol' in break_results and break_results['inline_symbol']: out_symbol_name = break_results['inline_symbol'] elif 'symbol' in break_results: out_symbol_name = break_results['symbol'] if symbol_match_exact: - test.assertTrue(symbol_name == out_symbol_name, "Symbol name '%s' doesn't match resultant symbol '%s'."%(symbol_name, out_symbol_name)) + test.assertTrue( + symbol_name == out_symbol_name, + "Symbol name '%s' doesn't match resultant symbol '%s'." % + (symbol_name, + out_symbol_name)) else: - test.assertTrue(out_symbol_name.find(symbol_name) != -1, "Symbol name '%s' isn't in resultant symbol '%s'."%(symbol_name, out_symbol_name)) + test.assertTrue( + out_symbol_name.find(symbol_name) != - + 1, + "Symbol name '%s' isn't in resultant symbol '%s'." % + (symbol_name, + out_symbol_name)) if module_name: out_module_name = None if 'module' in break_results: out_module_name = break_results['module'] - - test.assertTrue (module_name.find(out_module_name) != -1, "Symbol module name '%s' isn't in expected module name '%s'."%(out_module_name, module_name)) + + test.assertTrue( + module_name.find(out_module_name) != - + 1, + "Symbol module name '%s' isn't in expected module name '%s'." % + (out_module_name, + module_name)) # ================================================== # Utility functions related to Threads and Processes # ================================================== + def get_stopped_threads(process, reason): """Returns the thread(s) with the specified stop reason in a list. @@ -521,6 +633,7 @@ def get_stopped_threads(process, reason): threads.append(t) return threads + def get_stopped_thread(process, reason): """A convenience function which returns the first thread with the given stop reason or None. @@ -549,28 +662,32 @@ def get_stopped_thread(process, reason): return None return threads[0] + def get_threads_stopped_at_breakpoint_id(process, bpid): """ For a stopped process returns the thread stopped at the breakpoint passed in bkpt""" stopped_threads = [] threads = [] - stopped_threads = get_stopped_threads (process, lldb.eStopReasonBreakpoint) + stopped_threads = get_stopped_threads(process, lldb.eStopReasonBreakpoint) if len(stopped_threads) == 0: return threads - + for thread in stopped_threads: # Make sure we've hit our breakpoint... - break_id = thread.GetStopReasonDataAtIndex (0) + break_id = thread.GetStopReasonDataAtIndex(0) if break_id == bpid: threads.append(thread) return threads -def get_threads_stopped_at_breakpoint (process, bkpt): + +def get_threads_stopped_at_breakpoint(process, bkpt): return get_threads_stopped_at_breakpoint_id(process, bkpt.GetID()) -def get_one_thread_stopped_at_breakpoint_id(process, bpid, require_exactly_one = True): + +def get_one_thread_stopped_at_breakpoint_id( + process, bpid, require_exactly_one=True): threads = get_threads_stopped_at_breakpoint_id(process, bpid) if len(threads) == 0: return None @@ -579,20 +696,27 @@ def get_one_thread_stopped_at_breakpoint_id(process, bpid, require_exactly_one = return threads[0] -def get_one_thread_stopped_at_breakpoint(process, bkpt, require_exactly_one = True): - return get_one_thread_stopped_at_breakpoint_id(process, bkpt.GetID(), require_exactly_one) -def is_thread_crashed (test, thread): +def get_one_thread_stopped_at_breakpoint( + process, bkpt, require_exactly_one=True): + return get_one_thread_stopped_at_breakpoint_id( + process, bkpt.GetID(), require_exactly_one) + + +def is_thread_crashed(test, thread): """In the test suite we dereference a null pointer to simulate a crash. The way this is reported depends on the platform.""" if test.platformIsDarwin(): - return thread.GetStopReason() == lldb.eStopReasonException and "EXC_BAD_ACCESS" in thread.GetStopDescription(100) + return thread.GetStopReason( + ) == lldb.eStopReasonException and "EXC_BAD_ACCESS" in thread.GetStopDescription(100) elif test.getPlatform() == "linux": - return thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex(0) == thread.GetProcess().GetUnixSignals().GetSignalNumberFromName("SIGSEGV") + return thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex( + 0) == thread.GetProcess().GetUnixSignals().GetSignalNumberFromName("SIGSEGV") else: return "invalid address" in thread.GetStopDescription(100) -def get_crashed_threads (test, process): + +def get_crashed_threads(test, process): threads = [] if process.GetState() != lldb.eStateStopped: return threads @@ -601,13 +725,15 @@ def get_crashed_threads (test, process): threads.append(thread) return threads -def continue_to_breakpoint (process, bkpt): + +def continue_to_breakpoint(process, bkpt): """ Continues the process, if it stops, returns the threads stopped at bkpt; otherwise, returns None""" process.Continue() if process.GetState() != lldb.eStateStopped: return None else: - return get_threads_stopped_at_breakpoint (process, bkpt) + return get_threads_stopped_at_breakpoint(process, bkpt) + def get_caller_symbol(thread): """ @@ -658,7 +784,8 @@ def get_filenames(thread): Returns a sequence of file names from the stack frames of this thread. """ def GetFilename(i): - return thread.GetFrameAtIndex(i).GetLineEntry().GetFileSpec().GetFilename() + return thread.GetFrameAtIndex( + i).GetLineEntry().GetFileSpec().GetFilename() return list(map(GetFilename, list(range(thread.GetNumFrames())))) @@ -678,7 +805,8 @@ def get_module_names(thread): Returns a sequence of module names from the stack frames of this thread. """ def GetModuleName(i): - return thread.GetFrameAtIndex(i).GetModule().GetFileSpec().GetFilename() + return thread.GetFrameAtIndex( + i).GetModule().GetFileSpec().GetFilename() return list(map(GetModuleName, list(range(thread.GetNumFrames())))) @@ -693,7 +821,7 @@ def get_stack_frames(thread): return list(map(GetStackFrame, list(range(thread.GetNumFrames())))) -def print_stacktrace(thread, string_buffer = False): +def print_stacktrace(thread, string_buffer=False): """Prints a simple stack trace of this thread.""" output = SixStringIO() if string_buffer else sys.stdout @@ -709,11 +837,15 @@ def print_stacktrace(thread, string_buffer = False): addrs = get_pc_addresses(thread) if thread.GetStopReason() != lldb.eStopReasonInvalid: - desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason()) + desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason()) else: desc = "" - print("Stack trace for thread id={0:#x} name={1} queue={2} ".format( - thread.GetThreadID(), thread.GetName(), thread.GetQueueName()) + desc, file=output) + print( + "Stack trace for thread id={0:#x} name={1} queue={2} ".format( + thread.GetThreadID(), + thread.GetName(), + thread.GetQueueName()) + desc, + file=output) for i in range(depth): frame = thread.GetFrameAtIndex(i) @@ -724,20 +856,34 @@ def print_stacktrace(thread, string_buffer = False): file_addr = addrs[i].GetFileAddress() start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress() symbol_offset = file_addr - start_addr - print(" frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format( - num=i, addr=load_addr, mod=mods[i], symbol=symbols[i], offset=symbol_offset), file=output) + print( + " frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format( + num=i, + addr=load_addr, + mod=mods[i], + symbol=symbols[i], + offset=symbol_offset), + file=output) else: - print(" frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format( - num=i, addr=load_addr, mod=mods[i], - func='%s [inlined]' % funcs[i] if frame.IsInlined() else funcs[i], - file=files[i], line=lines[i], - args=get_args_as_string(frame, showFuncName=False) if not frame.IsInlined() else '()'), file=output) + print( + " frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format( + num=i, + addr=load_addr, + mod=mods[i], + func='%s [inlined]' % + funcs[i] if frame.IsInlined() else funcs[i], + file=files[i], + line=lines[i], + args=get_args_as_string( + frame, + showFuncName=False) if not frame.IsInlined() else '()'), + file=output) if string_buffer: return output.getvalue() -def print_stacktraces(process, string_buffer = False): +def print_stacktraces(process, string_buffer=False): """Prints the stack traces of all the threads.""" output = SixStringIO() if string_buffer else sys.stdout @@ -750,16 +896,21 @@ def print_stacktraces(process, string_buffer = False): if string_buffer: return output.getvalue() -def expect_state_changes(test, listener, process, states, timeout = 5): + +def expect_state_changes(test, listener, process, states, timeout=5): """Listens for state changed events on the listener and makes sure they match what we expect. Stop-and-restart events (where GetRestartedFromEvent() returns true) are ignored.""" for expected_state in states: def get_next_event(): event = lldb.SBEvent() - if not listener.WaitForEventForBroadcasterWithType(timeout, process.GetBroadcaster(), - lldb.SBProcess.eBroadcastBitStateChanged, event): - test.fail("Timed out while waiting for a transition to state %s" % + if not listener.WaitForEventForBroadcasterWithType( + timeout, + process.GetBroadcaster(), + lldb.SBProcess.eBroadcastBitStateChanged, + event): + test.fail( + "Timed out while waiting for a transition to state %s" % lldb.SBDebugger.StateAsCString(expected_state)) return event @@ -768,16 +919,21 @@ def expect_state_changes(test, listener, process, states, timeout = 5): lldb.SBProcess.GetRestartedFromEvent(event)): # Ignore restarted event and the subsequent running event. event = get_next_event() - test.assertEqual(lldb.SBProcess.GetStateFromEvent(event), lldb.eStateRunning, - "Restarted event followed by a running event") + test.assertEqual( + lldb.SBProcess.GetStateFromEvent(event), + lldb.eStateRunning, + "Restarted event followed by a running event") event = get_next_event() - test.assertEqual(lldb.SBProcess.GetStateFromEvent(event), expected_state) + test.assertEqual( + lldb.SBProcess.GetStateFromEvent(event), + expected_state) # =================================== # Utility functions related to Frames # =================================== + def get_parent_frame(frame): """ Returns the parent frame of the input frame object; None if not available. @@ -793,6 +949,7 @@ def get_parent_frame(frame): # If we reach here, no parent has been found, return None. return None + def get_args_as_string(frame, showFuncName=True): """ Returns the args of the input frame object as a string. @@ -801,8 +958,8 @@ def get_args_as_string(frame, showFuncName=True): # locals => False # statics => False # in_scope_only => True - vars = frame.GetVariables(True, False, False, True) # type of SBValueList - args = [] # list of strings + vars = frame.GetVariables(True, False, False, True) # type of SBValueList + args = [] # list of strings for var in vars: args.append("(%s)%s=%s" % (var.GetTypeName(), var.GetName(), @@ -817,37 +974,46 @@ def get_args_as_string(frame, showFuncName=True): return "%s(%s)" % (name, ", ".join(args)) else: return "(%s)" % (", ".join(args)) - -def print_registers(frame, string_buffer = False): + + +def print_registers(frame, string_buffer=False): """Prints all the register sets of the frame.""" output = SixStringIO() if string_buffer else sys.stdout print("Register sets for " + str(frame), file=output) - registerSet = frame.GetRegisters() # Return type of SBValueList. - print("Frame registers (size of register set = %d):" % registerSet.GetSize(), file=output) + registerSet = frame.GetRegisters() # Return type of SBValueList. + print("Frame registers (size of register set = %d):" % + registerSet.GetSize(), file=output) for value in registerSet: #print(value, file=output) - print("%s (number of children = %d):" % (value.GetName(), value.GetNumChildren()), file=output) + print("%s (number of children = %d):" % + (value.GetName(), value.GetNumChildren()), file=output) for child in value: - print("Name: %s, Value: %s" % (child.GetName(), child.GetValue()), file=output) + print( + "Name: %s, Value: %s" % + (child.GetName(), + child.GetValue()), + file=output) if string_buffer: return output.getvalue() + def get_registers(frame, kind): """Returns the registers given the frame and the kind of registers desired. Returns None if there's no such kind. """ - registerSet = frame.GetRegisters() # Return type of SBValueList. + registerSet = frame.GetRegisters() # Return type of SBValueList. for value in registerSet: if kind.lower() in value.GetName().lower(): return value return None + def get_GPRs(frame): """Returns the general purpose registers of the frame as an SBValue. @@ -861,6 +1027,7 @@ def get_GPRs(frame): """ return get_registers(frame, "general purpose") + def get_FPRs(frame): """Returns the floating point registers of the frame as an SBValue. @@ -874,6 +1041,7 @@ def get_FPRs(frame): """ return get_registers(frame, "floating point") + def get_ESRs(frame): """Returns the exception state registers of the frame as an SBValue. @@ -891,8 +1059,10 @@ def get_ESRs(frame): # Utility classes/functions for SBValues # ====================================== + class BasicFormatter(object): """The basic formatter inspects the value object and prints the value.""" + def format(self, value, buffer=None, indent=0): if not buffer: output = SixStringIO() @@ -901,25 +1071,28 @@ class BasicFormatter(object): # If there is a summary, it suffices. val = value.GetSummary() # Otherwise, get the value. - if val == None: + if val is None: val = value.GetValue() - if val == None and value.GetNumChildren() > 0: + if val is None and value.GetNumChildren() > 0: val = "%s (location)" % value.GetLocation() print("{indentation}({type}) {name} = {value}".format( - indentation = ' ' * indent, - type = value.GetTypeName(), - name = value.GetName(), - value = val), file=output) + indentation=' ' * indent, + type=value.GetTypeName(), + name=value.GetName(), + value=val), file=output) return output.getvalue() + class ChildVisitingFormatter(BasicFormatter): """The child visiting formatter prints the value and its immediate children. The constructor takes a keyword arg: indent_child, which defaults to 2. """ + def __init__(self, indent_child=2): """Default indentation of 2 SPC's for the children.""" self.cindent = indent_child + def format(self, value, buffer=None): if not buffer: output = SixStringIO() @@ -928,21 +1101,25 @@ class ChildVisitingFormatter(BasicFormatter): BasicFormatter.format(self, value, buffer=output) for child in value: - BasicFormatter.format(self, child, buffer=output, indent=self.cindent) + BasicFormatter.format( + self, child, buffer=output, indent=self.cindent) return output.getvalue() + class RecursiveDecentFormatter(BasicFormatter): """The recursive decent formatter prints the value and the decendents. The constructor takes two keyword args: indent_level, which defaults to 0, and indent_child, which defaults to 2. The current indentation level is determined by indent_level, while the immediate children has an additional - indentation by inden_child. + indentation by inden_child. """ + def __init__(self, indent_level=0, indent_child=2): self.lindent = indent_level self.cindent = indent_child + def format(self, value, buffer=None): if not buffer: output = SixStringIO() @@ -952,14 +1129,16 @@ class RecursiveDecentFormatter(BasicFormatter): BasicFormatter.format(self, value, buffer=output, indent=self.lindent) new_indent = self.lindent + self.cindent for child in value: - if child.GetSummary() != None: - BasicFormatter.format(self, child, buffer=output, indent=new_indent) + if child.GetSummary() is not None: + BasicFormatter.format( + self, child, buffer=output, indent=new_indent) else: if child.GetNumChildren() > 0: rdf = RecursiveDecentFormatter(indent_level=new_indent) rdf.format(child, buffer=output) else: - BasicFormatter.format(self, child, buffer=output, indent=new_indent) + BasicFormatter.format( + self, child, buffer=output, indent=new_indent) return output.getvalue() @@ -967,12 +1146,14 @@ class RecursiveDecentFormatter(BasicFormatter): # Utility functions for path manipulation on remote platforms # =========================================================== + def join_remote_paths(*paths): # TODO: update with actual platform name for remote windows once it exists if lldb.remote_platform.GetName() == 'remote-windows': return os.path.join(*paths).replace(os.path.sep, '\\') return os.path.join(*paths).replace(os.path.sep, '/') + def append_to_process_working_directory(*paths): remote = lldb.remote_platform if remote: @@ -985,6 +1166,7 @@ def append_to_process_working_directory(*paths): import signal + def get_signal_number(signal_name): platform = lldb.remote_platform if platform and platform.IsValid(): @@ -996,20 +1178,23 @@ def get_signal_number(signal_name): # No remote platform; fall back to using local python signals. return getattr(signal, signal_name) + class PrintableRegex(object): + def __init__(self, text): self.regex = re.compile(text) self.text = text - + def match(self, str): return self.regex.match(str) - + def __str__(self): return "%s" % (self.text) - + def __repr__(self): return "re.compile(%s) -> %s" % (self.text, self.regex) + def skip_if_callable(test, mycallable, reason): if six.callable(mycallable): if mycallable(test): @@ -1017,6 +1202,7 @@ def skip_if_callable(test, mycallable, reason): return True return False + def skip_if_library_missing(test, target, library): def find_library(target, library): for module in target.modules: @@ -1028,11 +1214,18 @@ def skip_if_library_missing(test, target, library): if library.match(filename): return False return True + def find_library_callable(test): return find_library(target, library) - return skip_if_callable(test, find_library_callable, "could not find library matching '%s' in target %s" % (library, target)) + return skip_if_callable( + test, + find_library_callable, + "could not find library matching '%s' in target %s" % + (library, + target)) + -def wait_for_file_on_target(testcase, file_path, max_attempts = 6): +def wait_for_file_on_target(testcase, file_path, max_attempts=6): for i in range(max_attempts): err, retcode, msg = testcase.run_platform_command("ls %s" % file_path) if err.Success() and retcode == 0: @@ -1042,10 +1235,13 @@ def wait_for_file_on_target(testcase, file_path, max_attempts = 6): import time time.sleep(pow(2, i) * 0.25) else: - testcase.fail("File %s not found even after %d attempts." % (file_path, max_attempts)) + testcase.fail( + "File %s not found even after %d attempts." % + (file_path, max_attempts)) err, retcode, data = testcase.run_platform_command("cat %s" % (file_path)) - testcase.assertTrue(err.Success() and retcode == 0, - "Failed to read file %s: %s, retcode: %d" % (file_path, err.GetCString(), retcode)) + testcase.assertTrue( + err.Success() and retcode == 0, "Failed to read file %s: %s, retcode: %d" % + (file_path, err.GetCString(), retcode)) return data diff --git a/lldb/packages/Python/lldbsuite/test/lock.py b/lldb/packages/Python/lldbsuite/test/lock.py index 89823b88abc..0e3af4a6b16 100644 --- a/lldb/packages/Python/lldbsuite/test/lock.py +++ b/lldb/packages/Python/lldbsuite/test/lock.py @@ -5,6 +5,7 @@ Interprocess mutex based on file locks import fcntl import os + class Lock: def __init__(self, filename): diff --git a/lldb/packages/Python/lldbsuite/test/logging/TestLogging.py b/lldb/packages/Python/lldbsuite/test/logging/TestLogging.py index cba587e5d8a..690c4f6ea69 100644 --- a/lldb/packages/Python/lldbsuite/test/logging/TestLogging.py +++ b/lldb/packages/Python/lldbsuite/test/logging/TestLogging.py @@ -5,13 +5,15 @@ Test lldb logging. This test just makes sure logging doesn't crash, and produce from __future__ import print_function - -import os, time, string +import os +import time +import string import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LogTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,86 +26,97 @@ class LogTestCase(TestBase): cls.RemoveTempFile(cls.truncate_log_file) cls.RemoveTempFile(cls.append_log_file) - def test (self): + def test(self): self.build() if self.debug_info == "dsym": - self.command_log_tests ("dsym") + self.command_log_tests("dsym") else: - self.command_log_tests ("dwarf") + self.command_log_tests("dwarf") - def command_log_tests (self, type): - exe = os.path.join (os.getcwd(), "a.out") + def command_log_tests(self, type): + exe = os.path.join(os.getcwd(), "a.out") self.expect("file " + exe, - patterns = [ "Current executable set to .*a.out" ]) + patterns=["Current executable set to .*a.out"]) - log_file = os.path.join (os.getcwd(), "lldb-commands-log-%s-%s-%s.txt" % (type, - os.path.basename(self.getCompiler()), - self.getArchitecture())) + log_file = os.path.join( + os.getcwd(), + "lldb-commands-log-%s-%s-%s.txt" % + (type, + os.path.basename( + self.getCompiler()), + self.getArchitecture())) - if (os.path.exists (log_file)): - os.remove (log_file) + if (os.path.exists(log_file)): + os.remove(log_file) # By default, Debugger::EnableLog() will set log options to # PREPEND_THREAD_NAME + OPTION_THREADSAFE. We don't want the # threadnames here, so we enable just threadsafe (-t). - self.runCmd ("log enable -t -f '%s' lldb commands" % (log_file)) - - self.runCmd ("command alias bp breakpoint") - - self.runCmd ("bp set -n main") + self.runCmd("log enable -t -f '%s' lldb commands" % (log_file)) + + self.runCmd("command alias bp breakpoint") - self.runCmd ("bp l") + self.runCmd("bp set -n main") + + self.runCmd("bp l") self.runCmd("log disable lldb") - self.assertTrue (os.path.isfile (log_file)) + self.assertTrue(os.path.isfile(log_file)) - f = open (log_file) + f = open(log_file) log_lines = f.readlines() - f.close () - os.remove (log_file) + f.close() + os.remove(log_file) - self.assertGreater(len(log_lines), 0, "Something was written to the log file.") + self.assertGreater( + len(log_lines), + 0, + "Something was written to the log file.") # Check that lldb truncates its log files @no_debug_info_test - def test_log_truncate (self): - if (os.path.exists (self.truncate_log_file)): - os.remove (self.truncate_log_file) + def test_log_truncate(self): + if (os.path.exists(self.truncate_log_file)): + os.remove(self.truncate_log_file) # put something in our log file with open(self.truncate_log_file, "w") as f: for i in range(1, 1000): f.write("bacon\n") - self.runCmd ("log enable -t -f '%s' lldb commands" % (self.truncate_log_file)) - self.runCmd ("help log") - self.runCmd ("log disable lldb") + self.runCmd( + "log enable -t -f '%s' lldb commands" % + (self.truncate_log_file)) + self.runCmd("help log") + self.runCmd("log disable lldb") - self.assertTrue (os.path.isfile (self.truncate_log_file)) + self.assertTrue(os.path.isfile(self.truncate_log_file)) with open(self.truncate_log_file, "r") as f: - contents = f.read () + contents = f.read() # check that it got removed self.assertEquals(contents.find("bacon"), -1) # Check that lldb can append to a log file @no_debug_info_test - def test_log_append (self): - if (os.path.exists (self.append_log_file)): - os.remove (self.append_log_file) + def test_log_append(self): + if (os.path.exists(self.append_log_file)): + os.remove(self.append_log_file) # put something in our log file with open(self.append_log_file, "w") as f: f.write("bacon\n") - self.runCmd ("log enable -t -a -f '%s' lldb commands" % (self.append_log_file)) - self.runCmd ("help log") - self.runCmd ("log disable lldb") + self.runCmd( + "log enable -t -a -f '%s' lldb commands" % + (self.append_log_file)) + self.runCmd("help log") + self.runCmd("log disable lldb") - self.assertTrue (os.path.isfile (self.append_log_file)) + self.assertTrue(os.path.isfile(self.append_log_file)) with open(self.append_log_file, "r") as f: - contents = f.read () + contents = f.read() # check that it is still there self.assertEquals(contents.find("bacon"), 0) diff --git a/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py b/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py index f4f6e313a1f..ec20ee2a24c 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py @@ -3,14 +3,15 @@ from __future__ import print_function - -import os, time +import os +import time import lldb import sys from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class AddDsymMidExecutionCommandCase(TestBase): @@ -21,7 +22,7 @@ class AddDsymMidExecutionCommandCase(TestBase): TestBase.setUp(self) self.source = 'main.c' - @no_debug_info_test # Prevent the genaration of the dwarf version of this test + @no_debug_info_test # Prevent the genaration of the dwarf version of this test def test_add_dsym_mid_execution(self): """Test that add-dsym mid-execution loads the symbols at the right place for a slid binary.""" self.buildDsym(clean=True) @@ -30,11 +31,12 @@ class AddDsymMidExecutionCommandCase(TestBase): self.target = self.dbg.CreateTarget(exe) self.assertTrue(self.target, VALID_TARGET) - main_bp = self.target.BreakpointCreateByName ("main", "a.out") + main_bp = self.target.BreakpointCreateByName("main", "a.out") self.assertTrue(main_bp, VALID_BREAKPOINT) self.runCmd("settings set target.disable-aslr false") - self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory()) + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(self.process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. @@ -44,4 +46,4 @@ class AddDsymMidExecutionCommandCase(TestBase): self.runCmd("add-dsym hide.app/Contents/a.out.dSYM") self.expect("frame select", - substrs = ['a.out`main at main.c']) + substrs=['a.out`main at main.c']) diff --git a/lldb/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py b/lldb/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py index afd933dc211..ff1ca2a9381 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py @@ -5,19 +5,20 @@ Test that clang produces the __apple accelerator tables, for example, __apple_ty from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from lldbsuite.test.lldbutil import symbol_type_to_str + class AppleTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - #rdar://problem/11166975 + # rdar://problem/11166975 @skipUnlessDarwin def test_debug_info_for_apple_types(self): """Test that __apple_types section does get produced by clang.""" @@ -27,7 +28,8 @@ class AppleTypesTestCase(TestBase): self.build() if self.debug_info == "dsym": - exe = os.path.join(os.getcwd(), "a.out.dSYM/Contents/Resources/DWARF/a.out") + exe = os.path.join(os.getcwd(), + "a.out.dSYM/Contents/Resources/DWARF/a.out") else: exe = os.path.join(os.getcwd(), "main.o") diff --git a/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py b/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py index f8b884003ad..e717e2ecdd9 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestIndirectFunctions(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,60 +31,83 @@ class TestIndirectFunctions(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) - break1 = target.BreakpointCreateBySourceRegex ("Set breakpoint here to step in indirect.", self.main_source_spec) + break1 = target.BreakpointCreateBySourceRegex( + "Set breakpoint here to step in indirect.", self.main_source_spec) self.assertTrue(break1, VALID_BREAKPOINT) - break2 = target.BreakpointCreateBySourceRegex ("Set breakpoint here to step in reexported.", self.main_source_spec) + break2 = target.BreakpointCreateBySourceRegex( + "Set breakpoint here to step in reexported.", self.main_source_spec) self.assertTrue(break2, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint 1.") + self.fail("Failed to stop at breakpoint 1.") thread = threads[0] - # Now do a step-into, and we should end up in the hidden target of this indirect function. + # Now do a step-into, and we should end up in the hidden target of this + # indirect function. thread.StepInto() curr_function = thread.GetFrameAtIndex(0).GetFunctionName() - self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.") - - # Now set a breakpoint using the indirect symbol name, and make sure we get to that: - break_indirect = target.BreakpointCreateByName ("call_through_indirect"); - self.assertTrue (break_indirect, VALID_BREAKPOINT) - - # Now continue should take us to the second call through the indirect symbol: - - threads = lldbutil.continue_to_breakpoint (process, break_indirect) - self.assertTrue (len(threads) == 1, "Stopped at breakpoint in indirect function.") + self.assertTrue( + curr_function == "call_through_indirect_hidden", + "Stepped into indirect symbols.") + + # Now set a breakpoint using the indirect symbol name, and make sure we + # get to that: + break_indirect = target.BreakpointCreateByName("call_through_indirect") + self.assertTrue(break_indirect, VALID_BREAKPOINT) + + # Now continue should take us to the second call through the indirect + # symbol: + + threads = lldbutil.continue_to_breakpoint(process, break_indirect) + self.assertTrue( + len(threads) == 1, + "Stopped at breakpoint in indirect function.") curr_function = thread.GetFrameAtIndex(0).GetFunctionName() - self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.") + self.assertTrue( + curr_function == "call_through_indirect_hidden", + "Stepped into indirect symbols.") # Delete this breakpoint so it won't get in the way: - target.BreakpointDelete (break_indirect.GetID()) + target.BreakpointDelete(break_indirect.GetID()) - # Now continue to the site of the first re-exported function call in main: - threads = lldbutil.continue_to_breakpoint (process, break2) + # Now continue to the site of the first re-exported function call in + # main: + threads = lldbutil.continue_to_breakpoint(process, break2) - # This is stepping Into through a re-exported symbol to an indirect symbol: + # This is stepping Into through a re-exported symbol to an indirect + # symbol: thread.StepInto() curr_function = thread.GetFrameAtIndex(0).GetFunctionName() - self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.") - - # And the last bit is to set a breakpoint on the re-exported symbol and make sure we are again in out target function. - break_reexported = target.BreakpointCreateByName ("reexport_to_indirect"); - self.assertTrue (break_reexported, VALID_BREAKPOINT) - - # Now continue should take us to the second call through the indirect symbol: - - threads = lldbutil.continue_to_breakpoint (process, break_reexported) - self.assertTrue (len(threads) == 1, "Stopped at breakpoint in reexported function target.") + self.assertTrue( + curr_function == "call_through_indirect_hidden", + "Stepped into indirect symbols.") + + # And the last bit is to set a breakpoint on the re-exported symbol and + # make sure we are again in out target function. + break_reexported = target.BreakpointCreateByName( + "reexport_to_indirect") + self.assertTrue(break_reexported, VALID_BREAKPOINT) + + # Now continue should take us to the second call through the indirect + # symbol: + + threads = lldbutil.continue_to_breakpoint(process, break_reexported) + self.assertTrue( + len(threads) == 1, + "Stopped at breakpoint in reexported function target.") curr_function = thread.GetFrameAtIndex(0).GetFunctionName() - self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.") + self.assertTrue( + curr_function == "call_through_indirect_hidden", + "Stepped into indirect symbols.") diff --git a/lldb/packages/Python/lldbsuite/test/macosx/nslog/TestDarwinNSLogOutput.py b/lldb/packages/Python/lldbsuite/test/macosx/nslog/TestDarwinNSLogOutput.py index 15d25bb713a..1e9596785f9 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/nslog/TestDarwinNSLogOutput.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/nslog/TestDarwinNSLogOutput.py @@ -18,6 +18,7 @@ from lldbsuite.test import decorators from lldbsuite.test import lldbtest from lldbsuite.test import lldbtest_config + @decorators.skipUnlessDarwin class DarwinNSLogOutputTestCase(lldbtest.TestBase): NO_DEBUG_INFO_TESTCASE = True @@ -125,7 +126,9 @@ class DarwinNSLogOutputTestCase(lldbtest.TestBase): ]) self.assertIsNotNone(self.child.match) self.assertGreater(len(self.child.match.groups()), 0) - self.assertEqual("This is a message from NSLog", self.child.match.group(1)) + self.assertEqual( + "This is a message from NSLog", + self.child.match.group(1)) def test_nslog_output_is_suppressed_with_env_var(self): """Test that NSLog() output does not show up with the ignore env var.""" diff --git a/lldb/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py b/lldb/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py index db2e071914c..a70878f73e2 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py @@ -5,14 +5,15 @@ Test that debug symbols have the correct order as specified by the order file. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class OrderFileTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,7 +31,7 @@ class OrderFileTestCase(TestBase): output = self.res.GetOutput() mo_f3 = re.search("Code +.+f3", output) mo_f1 = re.search("Code +.+f1", output) - + # Match objects for f3 and f1 must exist and f3 must come before f1. self.assertTrue(mo_f3 and mo_f1 and mo_f3.start() < mo_f1.start(), "Symbols have correct order by the order file") diff --git a/lldb/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py b/lldb/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py index 81384cb7e76..2d86f860d52 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py @@ -3,20 +3,21 @@ from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestQueues(TestBase): mydir = TestBase.compute_mydir(__file__) @skipUnlessDarwin - @add_test_categories(['pyapi']) + @add_test_categories(['pyapi']) def test_with_python_api(self): """Test queues inspection SB APIs.""" self.build() @@ -30,16 +31,34 @@ class TestQueues(TestBase): self.main_source = "main.c" def check_queue_for_valid_queue_id(self, queue): - self.assertTrue(queue.GetQueueID() != 0, "Check queue %s for valid QueueID (got 0x%x)" % (queue.GetName(), queue.GetQueueID())) - - def check_running_and_pending_items_on_queue(self, queue, expected_running, expected_pending): - self.assertTrue(queue.GetNumPendingItems() == expected_pending, "queue %s should have %d pending items, instead has %d pending items" % (queue.GetName(), expected_pending, (queue.GetNumPendingItems()))) - self.assertTrue(queue.GetNumRunningItems() == expected_running, "queue %s should have %d running items, instead has %d running items" % (queue.GetName(), expected_running, (queue.GetNumRunningItems()))) + self.assertTrue( + queue.GetQueueID() != 0, "Check queue %s for valid QueueID (got 0x%x)" % + (queue.GetName(), queue.GetQueueID())) + + def check_running_and_pending_items_on_queue( + self, queue, expected_running, expected_pending): + self.assertTrue( + queue.GetNumPendingItems() == expected_pending, + "queue %s should have %d pending items, instead has %d pending items" % + (queue.GetName(), + expected_pending, + (queue.GetNumPendingItems()))) + self.assertTrue( + queue.GetNumRunningItems() == expected_running, + "queue %s should have %d running items, instead has %d running items" % + (queue.GetName(), + expected_running, + (queue.GetNumRunningItems()))) def check_number_of_threads_owned_by_queue(self, queue, number_threads): - self.assertTrue(queue.GetNumThreads() == number_threads, "queue %s should have %d thread executing, but has %d" % (queue.GetName(), number_threads, queue.GetNumThreads())) - - def check_queue_kind (self, queue, kind): + self.assertTrue( + queue.GetNumThreads() == number_threads, + "queue %s should have %d thread executing, but has %d" % + (queue.GetName(), + number_threads, + queue.GetNumThreads())) + + def check_queue_kind(self, queue, kind): expected_kind_string = "Unknown" if kind == lldb.eQueueKindSerial: expected_kind_string = "Serial queue" @@ -50,15 +69,39 @@ class TestQueues(TestBase): actual_kind_string = "Serial queue" if queue.GetKind() == lldb.eQueueKindConcurrent: actual_kind_string = "Concurrent queue" - self.assertTrue(queue.GetKind() == kind, "queue %s is expected to be a %s but it is actually a %s" % (queue.GetName(), expected_kind_string, actual_kind_string)) + self.assertTrue( + queue.GetKind() == kind, + "queue %s is expected to be a %s but it is actually a %s" % + (queue.GetName(), + expected_kind_string, + actual_kind_string)) def check_queues_threads_match_queue(self, queue): for idx in range(0, queue.GetNumThreads()): t = queue.GetThreadAtIndex(idx) - self.assertTrue(t.IsValid(), "Queue %s's thread #%d must be valid" % (queue.GetName(), idx)) - self.assertTrue(t.GetQueueID() == queue.GetQueueID(), "Queue %s has a QueueID of %d but its thread #%d has a QueueID of %d" % (queue.GetName(), queue.GetQueueID(), idx, t.GetQueueID())) - self.assertTrue(t.GetQueueName() == queue.GetName(), "Queue %s has a QueueName of %s but its thread #%d has a QueueName of %s" % (queue.GetName(), queue.GetName(), idx, t.GetQueueName())) - self.assertTrue(t.GetQueue().GetQueueID() == queue.GetQueueID(), "Thread #%d's Queue's QueueID of %d is not the same as the QueueID of its owning queue %d" % (idx, t.GetQueue().GetQueueID(), queue.GetQueueID())) + self.assertTrue( + t.IsValid(), "Queue %s's thread #%d must be valid" % + (queue.GetName(), idx)) + self.assertTrue( + t.GetQueueID() == queue.GetQueueID(), + "Queue %s has a QueueID of %d but its thread #%d has a QueueID of %d" % + (queue.GetName(), + queue.GetQueueID(), + idx, + t.GetQueueID())) + self.assertTrue( + t.GetQueueName() == queue.GetName(), + "Queue %s has a QueueName of %s but its thread #%d has a QueueName of %s" % + (queue.GetName(), + queue.GetName(), + idx, + t.GetQueueName())) + self.assertTrue( + t.GetQueue().GetQueueID() == queue.GetQueueID(), + "Thread #%d's Queue's QueueID of %d is not the same as the QueueID of its owning queue %d" % + (idx, + t.GetQueue().GetQueueID(), + queue.GetQueueID())) def queues(self): """Test queues inspection SB APIs without libBacktraceRecording.""" @@ -66,53 +109,58 @@ class TestQueues(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) - break1 = target.BreakpointCreateByName ("stopper", 'a.out') + self.main_source_spec = lldb.SBFileSpec(self.main_source) + break1 = target.BreakpointCreateByName("stopper", 'a.out') self.assertTrue(break1, VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint 1.") + self.fail("Failed to stop at breakpoint 1.") queue_submittor_1 = lldb.SBQueue() queue_performer_1 = lldb.SBQueue() queue_performer_2 = lldb.SBQueue() queue_performer_3 = lldb.SBQueue() - for idx in range (0, process.GetNumQueues()): - q = process.GetQueueAtIndex(idx) - if q.GetName() == "com.apple.work_submittor_1": - queue_submittor_1 = q - if q.GetName() == "com.apple.work_performer_1": - queue_performer_1 = q - if q.GetName() == "com.apple.work_performer_2": - queue_performer_2 = q - if q.GetName() == "com.apple.work_performer_3": - queue_performer_3 = q - - self.assertTrue(queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), "Got all four expected queues: %s %s %s %s" % (queue_submittor_1.IsValid(), queue_performer_1.IsValid(), queue_performer_2.IsValid(), queue_performer_3.IsValid())) - - self.check_queue_for_valid_queue_id (queue_submittor_1) - self.check_queue_for_valid_queue_id (queue_performer_1) - self.check_queue_for_valid_queue_id (queue_performer_2) - self.check_queue_for_valid_queue_id (queue_performer_3) - - self.check_number_of_threads_owned_by_queue (queue_submittor_1, 1) - self.check_number_of_threads_owned_by_queue (queue_performer_1, 1) - self.check_number_of_threads_owned_by_queue (queue_performer_2, 1) - self.check_number_of_threads_owned_by_queue (queue_performer_3, 4) - - self.check_queue_kind (queue_submittor_1, lldb.eQueueKindSerial) - self.check_queue_kind (queue_performer_1, lldb.eQueueKindSerial) - self.check_queue_kind (queue_performer_2, lldb.eQueueKindSerial) - self.check_queue_kind (queue_performer_3, lldb.eQueueKindConcurrent) - - self.check_queues_threads_match_queue (queue_submittor_1) - self.check_queues_threads_match_queue (queue_performer_1) - self.check_queues_threads_match_queue (queue_performer_2) - self.check_queues_threads_match_queue (queue_performer_3) - - + for idx in range(0, process.GetNumQueues()): + q = process.GetQueueAtIndex(idx) + if q.GetName() == "com.apple.work_submittor_1": + queue_submittor_1 = q + if q.GetName() == "com.apple.work_performer_1": + queue_performer_1 = q + if q.GetName() == "com.apple.work_performer_2": + queue_performer_2 = q + if q.GetName() == "com.apple.work_performer_3": + queue_performer_3 = q + + self.assertTrue( + queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), + "Got all four expected queues: %s %s %s %s" % + (queue_submittor_1.IsValid(), + queue_performer_1.IsValid(), + queue_performer_2.IsValid(), + queue_performer_3.IsValid())) + + self.check_queue_for_valid_queue_id(queue_submittor_1) + self.check_queue_for_valid_queue_id(queue_performer_1) + self.check_queue_for_valid_queue_id(queue_performer_2) + self.check_queue_for_valid_queue_id(queue_performer_3) + + self.check_number_of_threads_owned_by_queue(queue_submittor_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_2, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_3, 4) + + self.check_queue_kind(queue_submittor_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_2, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_3, lldb.eQueueKindConcurrent) + + self.check_queues_threads_match_queue(queue_submittor_1) + self.check_queues_threads_match_queue(queue_performer_1) + self.check_queues_threads_match_queue(queue_performer_2) + self.check_queues_threads_match_queue(queue_performer_3) # We have threads running with all the different dispatch QoS service # levels - find those threads and check that we can get the correct @@ -135,109 +183,172 @@ class TestQueues(TestBase): if th.GetName() == "background QoS": background_thread = th - self.assertTrue(user_initiated_thread.IsValid(), "Found user initiated QoS thread") - self.assertTrue(user_interactive_thread.IsValid(), "Found user interactive QoS thread") + self.assertTrue( + user_initiated_thread.IsValid(), + "Found user initiated QoS thread") + self.assertTrue( + user_interactive_thread.IsValid(), + "Found user interactive QoS thread") self.assertTrue(utility_thread.IsValid(), "Found utility QoS thread") - self.assertTrue(unspecified_thread.IsValid(), "Found unspecified QoS thread") - self.assertTrue(background_thread.IsValid(), "Found background QoS thread") + self.assertTrue( + unspecified_thread.IsValid(), + "Found unspecified QoS thread") + self.assertTrue( + background_thread.IsValid(), + "Found background QoS thread") stream = lldb.SBStream() - self.assertTrue(user_initiated_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for user initiated QoS thread") - self.assertTrue(stream.GetData() == "User Initiated", "user initiated QoS thread name is valid") + self.assertTrue( + user_initiated_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for user initiated QoS thread") + self.assertTrue( + stream.GetData() == "User Initiated", + "user initiated QoS thread name is valid") stream.Clear() - self.assertTrue(user_interactive_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for user interactive QoS thread") - self.assertTrue(stream.GetData() == "User Interactive", "user interactive QoS thread name is valid") + self.assertTrue( + user_interactive_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for user interactive QoS thread") + self.assertTrue( + stream.GetData() == "User Interactive", + "user interactive QoS thread name is valid") stream.Clear() - self.assertTrue(utility_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for utility QoS thread") - self.assertTrue(stream.GetData() == "Utility", "utility QoS thread name is valid") + self.assertTrue( + utility_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for utility QoS thread") + self.assertTrue( + stream.GetData() == "Utility", + "utility QoS thread name is valid") stream.Clear() - self.assertTrue(unspecified_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for unspecified QoS thread") - self.assertTrue(stream.GetData() == "User Initiated", "unspecified QoS thread name is valid") + self.assertTrue( + unspecified_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for unspecified QoS thread") + self.assertTrue( + stream.GetData() == "User Initiated", + "unspecified QoS thread name is valid") stream.Clear() - self.assertTrue(background_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for background QoS thread") - self.assertTrue(stream.GetData() == "Background", "background QoS thread name is valid") + self.assertTrue( + background_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for background QoS thread") + self.assertTrue( + stream.GetData() == "Background", + "background QoS thread name is valid") def queues_with_libBacktraceRecording(self): """Test queues inspection SB APIs with libBacktraceRecording present.""" exe = os.path.join(os.getcwd(), "a.out") - if not os.path.isfile('/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib'): - self.skipTest ("Skipped because libBacktraceRecording.dylib was present on the system.") - - if not os.path.isfile('/usr/lib/system/introspection/libdispatch.dylib'): - self.skipTest ("Skipped because introspection libdispatch dylib is not present.") - + if not os.path.isfile( + '/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib'): + self.skipTest( + "Skipped because libBacktraceRecording.dylib was present on the system.") + + if not os.path.isfile( + '/usr/lib/system/introspection/libdispatch.dylib'): + self.skipTest( + "Skipped because introspection libdispatch dylib is not present.") + target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source) - break1 = target.BreakpointCreateByName ("stopper", 'a.out') + break1 = target.BreakpointCreateByName("stopper", 'a.out') self.assertTrue(break1, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, ['DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib', 'DYLD_LIBRARY_PATH=/usr/lib/system/introspection'], self.get_process_working_directory()) + process = target.LaunchSimple( + None, + [ + 'DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib', + 'DYLD_LIBRARY_PATH=/usr/lib/system/introspection'], + self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint 1.") + self.fail("Failed to stop at breakpoint 1.") libbtr_module_filespec = lldb.SBFileSpec("libBacktraceRecording.dylib") - libbtr_module = target.FindModule (libbtr_module_filespec) + libbtr_module = target.FindModule(libbtr_module_filespec) if not libbtr_module.IsValid(): - self.skipTest ("Skipped because libBacktraceRecording.dylib was not loaded into the process.") + self.skipTest( + "Skipped because libBacktraceRecording.dylib was not loaded into the process.") - self.assertTrue(process.GetNumQueues() >= 4, "Found the correct number of queues.") + self.assertTrue( + process.GetNumQueues() >= 4, + "Found the correct number of queues.") queue_submittor_1 = lldb.SBQueue() queue_performer_1 = lldb.SBQueue() queue_performer_2 = lldb.SBQueue() queue_performer_3 = lldb.SBQueue() - for idx in range (0, process.GetNumQueues()): - q = process.GetQueueAtIndex(idx) - if q.GetName() == "com.apple.work_submittor_1": - queue_submittor_1 = q - if q.GetName() == "com.apple.work_performer_1": - queue_performer_1 = q - if q.GetName() == "com.apple.work_performer_2": - queue_performer_2 = q - if q.GetName() == "com.apple.work_performer_3": - queue_performer_3 = q - - self.assertTrue(queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), "Got all four expected queues: %s %s %s %s" % (queue_submittor_1.IsValid(), queue_performer_1.IsValid(), queue_performer_2.IsValid(), queue_performer_3.IsValid())) - - self.check_queue_for_valid_queue_id (queue_submittor_1) - self.check_queue_for_valid_queue_id (queue_performer_1) - self.check_queue_for_valid_queue_id (queue_performer_2) - self.check_queue_for_valid_queue_id (queue_performer_3) - - self.check_running_and_pending_items_on_queue (queue_submittor_1, 1, 0) - self.check_running_and_pending_items_on_queue (queue_performer_1, 1, 3) - self.check_running_and_pending_items_on_queue (queue_performer_2, 1, 9999) - self.check_running_and_pending_items_on_queue (queue_performer_3, 4, 0) - - self.check_number_of_threads_owned_by_queue (queue_submittor_1, 1) - self.check_number_of_threads_owned_by_queue (queue_performer_1, 1) - self.check_number_of_threads_owned_by_queue (queue_performer_2, 1) - self.check_number_of_threads_owned_by_queue (queue_performer_3, 4) - - self.check_queue_kind (queue_submittor_1, lldb.eQueueKindSerial) - self.check_queue_kind (queue_performer_1, lldb.eQueueKindSerial) - self.check_queue_kind (queue_performer_2, lldb.eQueueKindSerial) - self.check_queue_kind (queue_performer_3, lldb.eQueueKindConcurrent) - - - self.check_queues_threads_match_queue (queue_submittor_1) - self.check_queues_threads_match_queue (queue_performer_1) - self.check_queues_threads_match_queue (queue_performer_2) - self.check_queues_threads_match_queue (queue_performer_3) - - self.assertTrue(queue_performer_2.GetPendingItemAtIndex(0).IsValid(), "queue 2's pending item #0 is valid") - self.assertTrue(queue_performer_2.GetPendingItemAtIndex(0).GetAddress().GetSymbol().GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2") - self.assertTrue(queue_performer_2.GetNumPendingItems() == 9999, "verify that queue 2 still has 9999 pending items") - self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9998).IsValid(), "queue 2's pending item #9998 is valid") - self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9998).GetAddress().GetSymbol().GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2") - self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9999).IsValid() == False, "queue 2's pending item #9999 is invalid") + for idx in range(0, process.GetNumQueues()): + q = process.GetQueueAtIndex(idx) + if q.GetName() == "com.apple.work_submittor_1": + queue_submittor_1 = q + if q.GetName() == "com.apple.work_performer_1": + queue_performer_1 = q + if q.GetName() == "com.apple.work_performer_2": + queue_performer_2 = q + if q.GetName() == "com.apple.work_performer_3": + queue_performer_3 = q + + self.assertTrue( + queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), + "Got all four expected queues: %s %s %s %s" % + (queue_submittor_1.IsValid(), + queue_performer_1.IsValid(), + queue_performer_2.IsValid(), + queue_performer_3.IsValid())) + + self.check_queue_for_valid_queue_id(queue_submittor_1) + self.check_queue_for_valid_queue_id(queue_performer_1) + self.check_queue_for_valid_queue_id(queue_performer_2) + self.check_queue_for_valid_queue_id(queue_performer_3) + + self.check_running_and_pending_items_on_queue(queue_submittor_1, 1, 0) + self.check_running_and_pending_items_on_queue(queue_performer_1, 1, 3) + self.check_running_and_pending_items_on_queue( + queue_performer_2, 1, 9999) + self.check_running_and_pending_items_on_queue(queue_performer_3, 4, 0) + + self.check_number_of_threads_owned_by_queue(queue_submittor_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_2, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_3, 4) + + self.check_queue_kind(queue_submittor_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_2, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_3, lldb.eQueueKindConcurrent) + + self.check_queues_threads_match_queue(queue_submittor_1) + self.check_queues_threads_match_queue(queue_performer_1) + self.check_queues_threads_match_queue(queue_performer_2) + self.check_queues_threads_match_queue(queue_performer_3) + + self.assertTrue(queue_performer_2.GetPendingItemAtIndex( + 0).IsValid(), "queue 2's pending item #0 is valid") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex(0).GetAddress().GetSymbol( + ).GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2") + self.assertTrue( + queue_performer_2.GetNumPendingItems() == 9999, + "verify that queue 2 still has 9999 pending items") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex( + 9998).IsValid(), "queue 2's pending item #9998 is valid") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9998).GetAddress().GetSymbol( + ).GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex( + 9999).IsValid() == False, "queue 2's pending item #9999 is invalid") diff --git a/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py b/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py index 4e2dfb0eeb6..096064896ea 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestSafeFuncCalls(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,36 +30,44 @@ class TestSafeFuncCalls(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - self.main_source_spec = lldb.SBFileSpec (self.main_source) - break1 = target.BreakpointCreateByName ("stopper", 'a.out') + self.main_source_spec = lldb.SBFileSpec(self.main_source) + break1 = target.BreakpointCreateByName("stopper", 'a.out') self.assertTrue(break1, VALID_BREAKPOINT) - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) if len(threads) != 1: - self.fail ("Failed to stop at breakpoint 1.") + self.fail("Failed to stop at breakpoint 1.") self.check_number_of_threads(process) main_thread = lldb.SBThread() select_thread = lldb.SBThread() - for idx in range (0, process.GetNumThreads()): - t = process.GetThreadAtIndex (idx) + for idx in range(0, process.GetNumThreads()): + t = process.GetThreadAtIndex(idx) if t.GetName() == "main thread": main_thread = t if t.GetName() == "select thread": select_thread = t - self.assertTrue(main_thread.IsValid() and select_thread.IsValid(), "Got both expected threads") + self.assertTrue( + main_thread.IsValid() and select_thread.IsValid(), + "Got both expected threads") - self.safe_to_call_func_on_main_thread (main_thread) - self.safe_to_call_func_on_select_thread (select_thread) + self.safe_to_call_func_on_main_thread(main_thread) + self.safe_to_call_func_on_select_thread(select_thread) def check_number_of_threads(self, process): - self.assertTrue(process.GetNumThreads() == 2, "Check that the process has two threads when sitting at the stopper() breakpoint") - - def safe_to_call_func_on_main_thread (self, main_thread): - self.assertTrue(main_thread.SafeToCallFunctions() == True, "It is safe to call functions on the main thread") - - def safe_to_call_func_on_select_thread (self, select_thread): - self.assertTrue(select_thread.SafeToCallFunctions() == False, "It is not safe to call functions on the select thread") + self.assertTrue( + process.GetNumThreads() == 2, + "Check that the process has two threads when sitting at the stopper() breakpoint") + + def safe_to_call_func_on_main_thread(self, main_thread): + self.assertTrue(main_thread.SafeToCallFunctions(), + "It is safe to call functions on the main thread") + + def safe_to_call_func_on_select_thread(self, select_thread): + self.assertTrue( + select_thread.SafeToCallFunctions() == False, + "It is not safe to call functions on the select thread") diff --git a/lldb/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py b/lldb/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py index 70a83ea9079..988611935c1 100644 --- a/lldb/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py +++ b/lldb/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py @@ -3,14 +3,15 @@ from __future__ import print_function - import unittest2 -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class UniversalTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,12 +20,12 @@ class UniversalTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number('main.c', '// Set break point at this line.') + self.line = line_number('main.c', '// Set break point at this line.') @add_test_categories(['pyapi']) @skipUnlessDarwin - @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in ['i386', 'x86_64'], - "requires i386 or x86_64") + @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in [ + 'i386', 'x86_64'], "requires i386 or x86_64") def test_sbdebugger_create_target_with_file_and_target_triple(self): """Test the SBDebugger.CreateTargetWithFileAndTargetTriple() API.""" # Invoke the default build rule. @@ -34,16 +35,18 @@ class UniversalTestCase(TestBase): exe = os.path.join(os.getcwd(), "testit") # Create a target by the debugger. - target = self.dbg.CreateTargetWithFileAndTargetTriple(exe, "i386-apple-macosx") + target = self.dbg.CreateTargetWithFileAndTargetTriple( + exe, "i386-apple-macosx") self.assertTrue(target, VALID_TARGET) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) @skipUnlessDarwin - @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in ['i386', 'x86_64'], - "requires i386 or x86_64") + @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in [ + 'i386', 'x86_64'], "requires i386 or x86_64") def test_process_launch_for_universal(self): """Test process launch of a universal binary.""" from lldbsuite.test.lldbutil import print_registers @@ -56,11 +59,12 @@ class UniversalTestCase(TestBase): # By default, x86_64 is assumed if no architecture is specified. self.expect("file " + exe, CURRENT_EXECUTABLE_SET, - startstr = "Current executable set to ", - substrs = ["testit' (x86_64)."]) + startstr="Current executable set to ", + substrs=["testit' (x86_64)."]) # Break inside the main. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) # We should be able to launch the x86_64 executable. self.runCmd("run", RUN_SUCCEEDED) @@ -75,17 +79,18 @@ class UniversalTestCase(TestBase): frame = process.GetThreadAtIndex(0).GetFrameAtIndex(0) registers = print_registers(frame, string_buffer=True) self.expect(registers, exe=False, - substrs = ['Name: rax']) + substrs=['Name: rax']) self.runCmd("continue") # Now specify i386 as the architecture for "testit". self.expect("file -a i386 " + exe, CURRENT_EXECUTABLE_SET, - startstr = "Current executable set to ", - substrs = ["testit' (i386)."]) + startstr="Current executable set to ", + substrs=["testit' (i386)."]) # Break inside the main. - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) # We should be able to launch the i386 executable as well. self.runCmd("run", RUN_SUCCEEDED) @@ -97,24 +102,26 @@ class UniversalTestCase(TestBase): "32-bit process launched") pointerSize = self.invoke(process, 'GetAddressByteSize') - self.assertTrue(pointerSize == 4, - "AddressByteSize of 32-bit process should be 4, got %d instead." % pointerSize) + self.assertTrue( + pointerSize == 4, + "AddressByteSize of 32-bit process should be 4, got %d instead." % + pointerSize) frame = process.GetThreadAtIndex(0).GetFrameAtIndex(0) registers = print_registers(frame, string_buffer=True) self.expect(registers, exe=False, - substrs = ['Name: eax']) + substrs=['Name: eax']) self.runCmd("continue") - @skipUnlessDarwin - @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in ['i386', 'x86_64'], - "requires i386 or x86_64") + @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in [ + 'i386', 'x86_64'], "requires i386 or x86_64") def test_process_attach_with_wrong_arch(self): """Test that when we attach to a binary from the wrong fork of a universal binary, we fix up the ABI correctly.""" # Now keep the architecture at 32 bit, but switch the binary we launch to - # 64 bit, and make sure on attach we switch to the correct architecture. + # 64 bit, and make sure on attach we switch to the correct + # architecture. # Invoke the default build rule. self.build() @@ -122,23 +129,27 @@ class UniversalTestCase(TestBase): # Note that "testit" is a universal binary. exe = os.path.join(os.getcwd(), "testit") - # Create a target by the debugger. - target = self.dbg.CreateTargetWithFileAndTargetTriple(exe, "i386-apple-macosx") + target = self.dbg.CreateTargetWithFileAndTargetTriple( + exe, "i386-apple-macosx") self.assertTrue(target, VALID_TARGET) pointer_size = target.GetAddressByteSize() self.assertTrue(pointer_size == 4, "Initially we were 32 bit.") - bkpt = target.BreakpointCreateBySourceRegex("sleep", lldb.SBFileSpec("main.c")) - self.assertTrue (bkpt.IsValid(), "Valid breakpoint") - self.assertTrue(bkpt.GetNumLocations() >= 1, "Our main breakpoint has locations.") + bkpt = target.BreakpointCreateBySourceRegex( + "sleep", lldb.SBFileSpec("main.c")) + self.assertTrue(bkpt.IsValid(), "Valid breakpoint") + self.assertTrue( + bkpt.GetNumLocations() >= 1, + "Our main breakpoint has locations.") popen = self.spawnSubprocess(exe, ["keep_waiting"]) self.addTearDownHook(self.cleanupSubprocesses) error = lldb.SBError() empty_listener = lldb.SBListener() - process = target.AttachToProcessWithID(empty_listener, popen.pid, error) + process = target.AttachToProcessWithID( + empty_listener, popen.pid, error) self.assertTrue(error.Success(), "Attached to process.") pointer_size = target.GetAddressByteSize() @@ -153,4 +164,6 @@ class UniversalTestCase(TestBase): threads = lldbutil.continue_to_breakpoint(process, bkpt) self.assertTrue(len(threads) == 1) thread = threads[0] - self.assertTrue(thread.GetNumFrames() > 1, "We were able to backtrace.") + self.assertTrue( + thread.GetNumFrames() > 1, + "We were able to backtrace.") diff --git a/lldb/packages/Python/lldbsuite/test/plugins/builder_base.py b/lldb/packages/Python/lldbsuite/test/plugins/builder_base.py index a467a458d5d..bd6656bd5e8 100644 --- a/lldb/packages/Python/lldbsuite/test/plugins/builder_base.py +++ b/lldb/packages/Python/lldbsuite/test/plugins/builder_base.py @@ -23,36 +23,41 @@ import lldbsuite.test.lldbtest as lldbtest import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test_event import build_exception + def getArchitecture(): """Returns the architecture in effect the test suite is running with.""" return os.environ["ARCH"] if "ARCH" in os.environ else "" + def getCompiler(): """Returns the compiler in effect the test suite is running with.""" compiler = os.environ.get("CC", "clang") compiler = lldbutil.which(compiler) return os.path.realpath(compiler) + def getArchFlag(): """Returns the flag required to specify the arch""" compiler = getCompiler() if compiler is None: - return "" + return "" elif "gcc" in compiler: - archflag = "-m" + archflag = "-m" elif "clang" in compiler: - archflag = "-arch" + archflag = "-arch" else: - archflag = None + archflag = None return ("ARCHFLAG=" + archflag) if archflag else "" + def getMake(): """Returns the name for GNU make""" if platform.system() == "FreeBSD" or platform.system() == "NetBSD": - return "gmake" + return "gmake" else: - return "make" + return "make" + def getArchSpec(architecture): """ @@ -65,6 +70,7 @@ def getArchSpec(architecture): return ("ARCH=" + arch) if arch else "" + def getCCSpec(compiler): """ Helper function to return the key-value string to specify the compiler @@ -78,6 +84,7 @@ def getCCSpec(compiler): else: return "" + def getCmdLine(d): """ Helper function to return a properly formatted command line argument(s) @@ -109,55 +116,87 @@ def runBuildCommands(commands, sender): raise build_exception.BuildError(called_process_error) -def buildDefault(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): +def buildDefault( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Build the binaries the default way.""" commands = [] if clean: commands.append([getMake(), "clean", getCmdLine(dictionary)]) - commands.append([getMake(), getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)]) + commands.append([getMake(), getArchSpec(architecture), + getCCSpec(compiler), getCmdLine(dictionary)]) runBuildCommands(commands, sender=sender) # True signifies that we can handle building default. return True -def buildDwarf(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildDwarf( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Build the binaries with dwarf debug info.""" commands = [] if clean: commands.append([getMake(), "clean", getCmdLine(dictionary)]) - commands.append([getMake(), "MAKE_DSYM=NO", getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)]) + commands.append([getMake(), "MAKE_DSYM=NO", getArchSpec( + architecture), getCCSpec(compiler), getCmdLine(dictionary)]) runBuildCommands(commands, sender=sender) # True signifies that we can handle building dwarf. return True -def buildDwo(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildDwo( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Build the binaries with dwarf debug info.""" commands = [] if clean: commands.append([getMake(), "clean", getCmdLine(dictionary)]) - commands.append([getMake(), "MAKE_DSYM=NO", "MAKE_DWO=YES", getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)]) + commands.append([getMake(), "MAKE_DSYM=NO", "MAKE_DWO=YES", getArchSpec( + architecture), getCCSpec(compiler), getCmdLine(dictionary)]) runBuildCommands(commands, sender=sender) # True signifies that we can handle building dwo. return True -def buildGModules(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildGModules( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Build the binaries with dwarf debug info.""" commands = [] if clean: commands.append([getMake(), "clean", getCmdLine(dictionary)]) - commands.append([getMake(), "MAKE_DSYM=NO", "MAKE_GMODULES=YES", getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)]) + commands.append([getMake(), + "MAKE_DSYM=NO", + "MAKE_GMODULES=YES", + getArchSpec(architecture), + getCCSpec(compiler), + getCmdLine(dictionary)]) lldbtest.system(commands, sender=sender) # True signifies that we can handle building with gmodules. return True + def cleanup(sender=None, dictionary=None): """Perform a platform-specific cleanup after the test.""" #import traceback - #traceback.print_stack() + # traceback.print_stack() commands = [] if os.path.isfile("Makefile"): commands.append([getMake(), "clean", getCmdLine(dictionary)]) diff --git a/lldb/packages/Python/lldbsuite/test/plugins/builder_darwin.py b/lldb/packages/Python/lldbsuite/test/plugins/builder_darwin.py index 8a907ccec2d..06a2a86d47a 100644 --- a/lldb/packages/Python/lldbsuite/test/plugins/builder_darwin.py +++ b/lldb/packages/Python/lldbsuite/test/plugins/builder_darwin.py @@ -5,13 +5,20 @@ import lldbsuite.test.lldbtest as lldbtest from builder_base import * -def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): """Build the binaries with dsym debug info.""" commands = [] if clean: commands.append(["make", "clean", getCmdLine(dictionary)]) - commands.append(["make", "MAKE_DSYM=YES", getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)]) + commands.append(["make", "MAKE_DSYM=YES", getArchSpec( + architecture), getCCSpec(compiler), getCmdLine(dictionary)]) runBuildCommands(commands, sender=sender) diff --git a/lldb/packages/Python/lldbsuite/test/plugins/builder_freebsd.py b/lldb/packages/Python/lldbsuite/test/plugins/builder_freebsd.py index e56be429823..d9e654dc32f 100644 --- a/lldb/packages/Python/lldbsuite/test/plugins/builder_freebsd.py +++ b/lldb/packages/Python/lldbsuite/test/plugins/builder_freebsd.py @@ -1,4 +1,10 @@ from builder_base import * -def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): return False diff --git a/lldb/packages/Python/lldbsuite/test/plugins/builder_linux.py b/lldb/packages/Python/lldbsuite/test/plugins/builder_linux.py index e56be429823..d9e654dc32f 100644 --- a/lldb/packages/Python/lldbsuite/test/plugins/builder_linux.py +++ b/lldb/packages/Python/lldbsuite/test/plugins/builder_linux.py @@ -1,4 +1,10 @@ from builder_base import * -def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): return False diff --git a/lldb/packages/Python/lldbsuite/test/plugins/builder_netbsd.py b/lldb/packages/Python/lldbsuite/test/plugins/builder_netbsd.py index e56be429823..d9e654dc32f 100644 --- a/lldb/packages/Python/lldbsuite/test/plugins/builder_netbsd.py +++ b/lldb/packages/Python/lldbsuite/test/plugins/builder_netbsd.py @@ -1,4 +1,10 @@ from builder_base import * -def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): return False diff --git a/lldb/packages/Python/lldbsuite/test/plugins/builder_win32.py b/lldb/packages/Python/lldbsuite/test/plugins/builder_win32.py index e56be429823..d9e654dc32f 100644 --- a/lldb/packages/Python/lldbsuite/test/plugins/builder_win32.py +++ b/lldb/packages/Python/lldbsuite/test/plugins/builder_win32.py @@ -1,4 +1,10 @@ from builder_base import * -def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True): + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + clean=True): return False diff --git a/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py index a3dd91fe880..39975632dcb 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py @@ -5,14 +5,15 @@ Test SBBreakpoint APIs. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class BreakpointAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -36,11 +37,15 @@ class BreakpointAPITestCase(TestBase): # Now delete it: did_delete = target.BreakpointDelete(breakpoint.GetID()) - self.assertTrue (did_delete, "Did delete the breakpoint we just created.") + self.assertTrue( + did_delete, + "Did delete the breakpoint we just created.") # Make sure we can't find it: - del_bkpt = target.FindBreakpointByID (breakpoint.GetID()) - self.assertTrue (not del_bkpt, "We did delete the breakpoint.") + del_bkpt = target.FindBreakpointByID(breakpoint.GetID()) + self.assertTrue(not del_bkpt, "We did delete the breakpoint.") # Finally make sure the original breakpoint is no longer valid. - self.assertTrue (not breakpoint, "Breakpoint we deleted is no longer valid.") + self.assertTrue( + not breakpoint, + "Breakpoint we deleted is no longer valid.") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py b/lldb/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py index 3d9309e26ce..cc09096ed2f 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py @@ -5,14 +5,15 @@ Test SBType APIs to fetch member function types. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SBTypeMemberFunctionsTest(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -44,35 +45,56 @@ class SBTypeMemberFunctionsTest(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Get Frame #0. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) - + variable = frame0.FindVariable("d") Derived = variable.GetType() Base = Derived.GetDirectBaseClassAtIndex(0).GetType() - self.assertTrue(Derived.GetNumberOfMemberFunctions() == 2, "Derived declares two methods") - self.assertTrue(Derived.GetMemberFunctionAtIndex(0).GetType().GetFunctionReturnType().GetName() == "int", "Derived::dImpl returns int") - - self.assertTrue(Base.GetNumberOfMemberFunctions() == 4, "Base declares three methods") - self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetType().GetFunctionArgumentTypes().GetSize() == 3, "Base::sfunc takes three arguments") - self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetName() == "sfunc", "Base::sfunc not found") - self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetKind() == lldb.eMemberFunctionKindStaticMethod, "Base::sfunc is a static") - self.assertTrue(Base.GetMemberFunctionAtIndex(2).GetType().GetFunctionArgumentTypes().GetSize() == 0, "Base::dat takes no arguments") - self.assertTrue(Base.GetMemberFunctionAtIndex(1).GetType().GetFunctionArgumentTypes().GetTypeAtIndex(1).GetName() == "char", "Base::bar takes a second 'char' argument") - self.assertTrue(Base.GetMemberFunctionAtIndex(1).GetName() == "bar", "Base::bar not found") - + self.assertTrue( + Derived.GetNumberOfMemberFunctions() == 2, + "Derived declares two methods") + self.assertTrue(Derived.GetMemberFunctionAtIndex(0).GetType( + ).GetFunctionReturnType().GetName() == "int", "Derived::dImpl returns int") + + self.assertTrue( + Base.GetNumberOfMemberFunctions() == 4, + "Base declares three methods") + self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetType( + ).GetFunctionArgumentTypes().GetSize() == 3, "Base::sfunc takes three arguments") + self.assertTrue(Base.GetMemberFunctionAtIndex( + 3).GetName() == "sfunc", "Base::sfunc not found") + self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetKind( + ) == lldb.eMemberFunctionKindStaticMethod, "Base::sfunc is a static") + self.assertTrue(Base.GetMemberFunctionAtIndex(2).GetType( + ).GetFunctionArgumentTypes().GetSize() == 0, "Base::dat takes no arguments") + self.assertTrue(Base.GetMemberFunctionAtIndex(1).GetType().GetFunctionArgumentTypes( + ).GetTypeAtIndex(1).GetName() == "char", "Base::bar takes a second 'char' argument") + self.assertTrue(Base.GetMemberFunctionAtIndex( + 1).GetName() == "bar", "Base::bar not found") + variable = frame0.FindVariable("thingy") Thingy = variable.GetType() - - self.assertTrue(Thingy.GetNumberOfMemberFunctions() == 2, "Thingy declares two methods") - - self.assertTrue(Thingy.GetMemberFunctionAtIndex(0).GetReturnType().GetName() == "id", "Thingy::init returns an id") - self.assertTrue(Thingy.GetMemberFunctionAtIndex(1).GetNumberOfArguments() == 2, "Thingy::foo takes two arguments") - self.assertTrue(Thingy.GetMemberFunctionAtIndex(1).GetArgumentTypeAtIndex(0).GetName() == "int", "Thingy::foo takes an int") + + self.assertTrue( + Thingy.GetNumberOfMemberFunctions() == 2, + "Thingy declares two methods") + + self.assertTrue(Thingy.GetMemberFunctionAtIndex( + 0).GetReturnType().GetName() == "id", "Thingy::init returns an id") + self.assertTrue( + Thingy.GetMemberFunctionAtIndex(1).GetNumberOfArguments() == 2, + "Thingy::foo takes two arguments") + self.assertTrue(Thingy.GetMemberFunctionAtIndex(1).GetArgumentTypeAtIndex( + 0).GetName() == "int", "Thingy::foo takes an int") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py index d8ac342f475..1cd15646f97 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py @@ -30,7 +30,7 @@ class DebuggerAPITestCase(TestBase): self.dbg.GetInternalVariableValue(None, None) # FIXME (filcab): We must first allow for the swig bindings to know if # a Python callback is set. (Check python-typemaps.swig) - #self.dbg.SetLoggingCallback(None) + # self.dbg.SetLoggingCallback(None) self.dbg.SetPrompt(None) self.dbg.SetCurrentPlatform(None) self.dbg.SetCurrentPlatformSDKRoot(None) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py index 3e2ff2ffa9d..4739df00085 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py @@ -14,14 +14,15 @@ after default construction. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class APIDefaultConstructorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -125,7 +126,8 @@ class APIDefaultConstructorTestCase(TestBase): @add_test_categories(['pyapi']) @no_debug_info_test - # darwin: This test passes with swig 3.0.2, fails w/3.0.5 other tests fail with 2.0.12 http://llvm.org/pr23488 + # darwin: This test passes with swig 3.0.2, fails w/3.0.5 other tests fail + # with 2.0.12 http://llvm.org/pr23488 def test_SBError(self): obj = lldb.SBError() if self.TraceOn(): @@ -228,8 +230,9 @@ class APIDefaultConstructorTestCase(TestBase): @add_test_categories(['pyapi']) @no_debug_info_test - # Py3 asserts due to a bug in SWIG. Trying to upstream a patch to fix this in 3.0.8 - @skipIf(py_version=['>=', (3,0)], swig_version=['<', (3,0,8)]) + # Py3 asserts due to a bug in SWIG. Trying to upstream a patch to fix + # this in 3.0.8 + @skipIf(py_version=['>=', (3, 0)], swig_version=['<', (3, 0, 8)]) def test_SBModule(self): obj = lldb.SBModule() if self.TraceOn(): @@ -347,7 +350,7 @@ class APIDefaultConstructorTestCase(TestBase): except: # Exception is expected. return - + # Unreachable code because lldb.SBType() should fail. # Do fuzz testing on the invalid obj, it should not crash lldb. import sb_type diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py index f0e979543a4..8f9665d3a73 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetFileAddress() obj.GetLoadAddress(lldb.SBTarget()) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py index 3eeb24b4273..00654ca1246 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.IsInlined() obj.GetInlinedName() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py index 2c05990edae..3bdf5879d30 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetID() obj.ClearAllBreakpointSites() @@ -28,7 +29,7 @@ def fuzz_obj(obj): obj.SetQueueName("my queue") obj.GetQueueName() obj.SetScriptCallbackFunction(None) - obj.SetScriptCallbackBody (None) + obj.SetScriptCallbackBody(None) obj.GetNumResolvedLocations() obj.GetNumLocations() obj.GetDescription(lldb.SBStream()) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py index 2251892643b..26bf6f69c5d 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetAddress() obj.GetLoadAddress() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py index 27539e855cd..b2f5ab5b2c5 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.BroadcastEventByType(lldb.eBreakpointEventTypeInvalidType, True) obj.BroadcastEvent(lldb.SBEvent(), False) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py index d4b90840657..9793e9be20e 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py index 92755ffa395..0c27c94b752 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetFileSpec() obj.GetNumLineEntries() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py index e7c188f09ba..77e45c861e8 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.SetAsync(True) obj.SetAsync(False) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py index 7e069323bf3..9c0f8d8e6d8 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetCString() obj.Fail() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py index c64f9ba927c..4c24c606fa2 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetDataFlavor() obj.GetType() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py index 3aa9235b8a1..33b4d69cd6a 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.Exists() obj.ResolveExecutableLocation() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py index 41edaff02ed..4637fc428d8 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() @@ -32,6 +33,9 @@ def fuzz_obj(obj): obj.FindVariable("my_var") obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) obj.FindValue("your_var", lldb.eValueTypeVariableGlobal) - obj.FindValue("your_var", lldb.eValueTypeVariableStatic, lldb.eDynamicCanRunTarget) + obj.FindValue( + "your_var", + lldb.eValueTypeVariableStatic, + lldb.eDynamicCanRunTarget) obj.GetDescription(lldb.SBStream()) obj.Clear() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py index fb88d37ac19..bd9c887e50f 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetName() obj.GetMangledName() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py index b961bc389e3..e0be4132fc0 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetAddress() obj.GetByteSize() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py index 09d62f97048..8870bf5de47 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetSize() obj.GetInstructionAtIndex(0xffffffff) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py index d97f2517f4b..9c89792791f 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetStartAddress() obj.GetEndAddress() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py index 0747547b9cf..5f0ebdae73b 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.AddEvent(lldb.SBEvent()) obj.StartListeningForEvents(lldb.SBBroadcaster(), 0xffffffff) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py index 0b9aa99167a..175550a5a0f 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetFileSpec() obj.GetPlatformFileSpec() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py index 40132b19958..5a3e1e6903c 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetTarget() obj.GetByteOrder() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py index 899130abe27..5e25e94d017 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.IsValid() obj.GetName() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py index 9d8242c9b27..44111addba5 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.AppendString("another string") obj.AppendString(None) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py index 4a4c67a0880..d2d107a13c2 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetName() obj.GetMangledName() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py index 01b5b7b793e..ac4392539db 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetModule() obj.GetCompileUnit() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py index 3b01be3e344..af7f17b69e7 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetProcess() listener = lldb.SBListener() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py index b69b22ea6a9..088972532f7 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetStopReason() obj.GetStopReasonDataCount() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py index 5c801c1fbf2..6016a9004ec 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py @@ -5,10 +5,11 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetName() obj.GetByteSize() - #obj.GetEncoding(5) + # obj.GetEncoding(5) obj.GetNumberChildren(True) member = lldb.SBTypeMember() obj.GetChildAtIndex(True, 0, member) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py index 2bb8c58e254..f283177425a 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetError() obj.GetID() @@ -40,26 +41,26 @@ def fuzz_obj(obj): for child_val in obj: s = str(child_val) error = lldb.SBError() - obj.GetValueAsSigned (error, 0) - obj.GetValueAsUnsigned (error, 0) + obj.GetValueAsSigned(error, 0) + obj.GetValueAsUnsigned(error, 0) obj.GetValueAsSigned(0) obj.GetValueAsUnsigned(0) - obj.GetDynamicValue (lldb.eNoDynamicValues) - obj.GetStaticValue () + obj.GetDynamicValue(lldb.eNoDynamicValues) + obj.GetStaticValue() obj.IsDynamic() invalid_type = lldb.SBType() - obj.CreateChildAtOffset ("a", 12, invalid_type) - obj.Cast (invalid_type) - obj.CreateValueFromExpression ("pt->x", "pt->x") - obj.CreateValueFromAddress ("x", 0x123, invalid_type) + obj.CreateChildAtOffset("a", 12, invalid_type) + obj.Cast(invalid_type) + obj.CreateValueFromExpression("pt->x", "pt->x") + obj.CreateValueFromAddress("x", 0x123, invalid_type) invalid_data = lldb.SBData() - obj.CreateValueFromData ("x", invalid_data, invalid_type) + obj.CreateValueFromData("x", invalid_data, invalid_type) obj.GetValueForExpressionPath("[0]") obj.AddressOf() obj.GetLoadAddress() obj.GetAddress() - obj.GetPointeeData (0, 1) - obj.GetData () + obj.GetPointeeData(0, 1) + obj.GetData() obj.GetTarget() obj.GetProcess() obj.GetThread() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py index 32f12f93dd8..cbd9810c44e 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.Append(lldb.SBValue()) obj.GetSize() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py index f462e62ff16..b30d3bb8014 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py @@ -5,6 +5,7 @@ Fuzz tests an object after the default construction to make sure it does not cra import sys import lldb + def fuzz_obj(obj): obj.GetID() obj.IsValid() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py b/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py index 311791cca01..97261c70ec9 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py @@ -5,14 +5,15 @@ Use lldb Python API to disassemble raw machine code bytes from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DisassembleRawDataTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,16 +25,16 @@ class DisassembleRawDataTestCase(TestBase): """Test disassembling raw bytes with the API.""" # Create a target from the debugger. arch = self.getArchitecture() - if re.match("mips*el",arch): - target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "mipsel") - raw_bytes = bytearray([0x21,0xf0, 0xa0, 0x03]) - elif re.match("mips",arch): - target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "mips") - raw_bytes = bytearray([0x03,0xa0, 0xf0, 0x21]) + if re.match("mips*el", arch): + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "mipsel") + raw_bytes = bytearray([0x21, 0xf0, 0xa0, 0x03]) + elif re.match("mips", arch): + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "mips") + raw_bytes = bytearray([0x03, 0xa0, 0xf0, 0x21]) else: - target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "x86_64") + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "x86_64") raw_bytes = bytearray([0x48, 0x89, 0xe5]) - + self.assertTrue(target, VALID_TARGET) insts = target.GetInstructions(lldb.SBAddress(0, target), raw_bytes) @@ -43,9 +44,11 @@ class DisassembleRawDataTestCase(TestBase): print() print("Raw bytes: ", [hex(x) for x in raw_bytes]) print("Disassembled%s" % str(inst)) - if re.match("mips",arch): - self.assertTrue (inst.GetMnemonic(target) == "move") - self.assertTrue (inst.GetOperands(target) == '$' + "fp, " + '$' + "sp") + if re.match("mips", arch): + self.assertTrue(inst.GetMnemonic(target) == "move") + self.assertTrue(inst.GetOperands(target) == + '$' + "fp, " + '$' + "sp") else: - self.assertTrue (inst.GetMnemonic(target) == "movq") - self.assertTrue (inst.GetOperands(target) == '%' + "rsp, " + '%' + "rbp") + self.assertTrue(inst.GetMnemonic(target) == "movq") + self.assertTrue(inst.GetOperands(target) == + '%' + "rsp, " + '%' + "rbp") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py b/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py index f991ab329a8..6e548f243ef 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py @@ -5,25 +5,28 @@ Use lldb Python API to disassemble raw machine code bytes from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class Disassemble_VST1_64(TestBase): mydir = TestBase.compute_mydir(__file__) - @skipTestIfFn(lambda : True, "llvm.org/pr24575: all tests get ERRORs in dotest.py after this") + @skipTestIfFn( + lambda: True, + "llvm.org/pr24575: all tests get ERRORs in dotest.py after this") @add_test_categories(['pyapi']) @no_debug_info_test def test_disassemble_invalid_vst_1_64_raw_data(self): """Test disassembling invalid vst1.64 raw bytes with the API.""" # Create a target from the debugger. - target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "thumbv7") + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "thumbv7") self.assertTrue(target, VALID_TARGET) raw_bytes = bytearray([0xf0, 0xb5, 0x03, 0xaf, @@ -55,5 +58,5 @@ class Disassemble_VST1_64(TestBase): print() print("Raw bytes: ", [hex(x) for x in raw_bytes]) print("Disassembled%s" % str(inst)) - - self.assertTrue (inst.GetMnemonic(target) == "vst1.64") + + self.assertTrue(inst.GetMnemonic(target) == "vst1.64") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/event/TestEvents.py b/lldb/packages/Python/lldbsuite/test/python_api/event/TestEvents.py index 1c23f50e9d4..e9ea0bd0087 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/event/TestEvents.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/event/TestEvents.py @@ -5,14 +5,15 @@ Test lldb Python event APIs. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipIfLinux # llvm.org/pr25924, sometimes generating SIGSEGV class EventAPITestCase(TestBase): @@ -22,10 +23,13 @@ class EventAPITestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line = line_number('main.c', '// Find the line number of function "c" here.') + self.line = line_number( + 'main.c', '// Find the line number of function "c" here.') @add_test_categories(['pyapi']) - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr23730 Flaky, fails ~1/10 cases") + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23730 Flaky, fails ~1/10 cases") def test_listen_for_and_print_event(self): """Exercise SBEvent API.""" self.build() @@ -44,18 +48,20 @@ class EventAPITestCase(TestBase): # Now launch the process, and do not stop at the entry point. error = lldb.SBError() - process = target.Launch (listener, - None, # argv - None, # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working directory - 0, # launch flags - False, # Stop at entry - error) # error - - self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error + + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) # Create an empty event object. event = lldb.SBEvent() @@ -66,7 +72,9 @@ class EventAPITestCase(TestBase): # Create MyListeningThread class to wait for any kind of event. import threading + class MyListeningThread(threading.Thread): + def run(self): count = 0 # Let's only try at most 4 times to retrieve any kind of event. @@ -79,7 +87,10 @@ class EventAPITestCase(TestBase): desc = lldbutil.get_description(event) print("Event description:", desc) print("Event data flavor:", event.GetDataFlavor()) - print("Process state:", lldbutil.state_type_to_str(process.GetState())) + print( + "Process state:", + lldbutil.state_type_to_str( + process.GetState())) print() else: if traceOn: @@ -106,7 +117,7 @@ class EventAPITestCase(TestBase): # Shouldn't we be testing against some kind of expectation here? @add_test_categories(['pyapi']) - @expectedFlakeyLinux("llvm.org/pr23730") # Flaky, fails ~1/100 cases + @expectedFlakeyLinux("llvm.org/pr23730") # Flaky, fails ~1/100 cases @expectedFlakeyOS(oslist=["windows"]) def test_wait_for_event(self): """Exercise SBListener.WaitForEvent() API.""" @@ -131,16 +142,16 @@ class EventAPITestCase(TestBase): # Now launch the process, and do not stop at entry point. error = lldb.SBError() - process = target.Launch (listener, - None, # argv - None, # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working directory - 0, # launch flags - False, # Stop at entry - error) # error + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Create an empty event object. @@ -149,7 +160,9 @@ class EventAPITestCase(TestBase): # Create MyListeningThread to wait for any kind of event. import threading + class MyListeningThread(threading.Thread): + def run(self): count = 0 # Let's only try at most 3 times to retrieve any kind of event. @@ -179,9 +192,11 @@ class EventAPITestCase(TestBase): self.assertTrue(event, "My listening thread successfully received an event") - @skipIfFreeBSD # llvm.org/pr21325 + @skipIfFreeBSD # llvm.org/pr21325 @add_test_categories(['pyapi']) - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr23617 Flaky, fails ~1/10 cases") + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23617 Flaky, fails ~1/10 cases") @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") def test_add_listener_to_broadcaster(self): """Exercise some SBBroadcaster APIs.""" @@ -205,22 +220,21 @@ class EventAPITestCase(TestBase): # Now launch the process, and do not stop at the entry point. error = lldb.SBError() - process = target.Launch (listener, - None, # argv - None, # envp - None, # stdin_path - None, # stdout_path - None, # stderr_path - None, # working directory - 0, # launch flags - False, # Stop at entry - error) # error + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error # Create an empty event object. event = lldb.SBEvent() self.assertFalse(event, "Event should not be valid initially") - # The finite state machine for our custom listening thread, with an # initial state of None, which means no event has been received. # It changes to 'connected' after 'connected' event is received (for remote platforms) @@ -231,9 +245,12 @@ class EventAPITestCase(TestBase): self.state = None # Create MyListeningThread to wait for state changed events. - # By design, a "running" event is expected following by a "stopped" event. + # By design, a "running" event is expected following by a "stopped" + # event. import threading + class MyListeningThread(threading.Thread): + def run(self): #print("Running MyListeningThread:", self) @@ -248,19 +265,21 @@ class EventAPITestCase(TestBase): #print("Event description:", desc) match = pattern.search(desc) if not match: - break; + break if match.group(1) == 'connected': # When debugging remote targets with lldb-server, we # first get the 'connected' event. - self.context.assertTrue(self.context.state == None) + self.context.assertTrue(self.context.state is None) self.context.state = 'connected' continue elif match.group(1) == 'running': - self.context.assertTrue(self.context.state == None or self.context.state == 'connected') + self.context.assertTrue( + self.context.state is None or self.context.state == 'connected') self.context.state = 'running' continue elif match.group(1) == 'stopped': - self.context.assertTrue(self.context.state == 'running') + self.context.assertTrue( + self.context.state == 'running') # Whoopee, both events have been received! self.context.state = 'stopped' break diff --git a/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py b/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py index 49bc148dd57..9b0c1f5eaef 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py @@ -1,4 +1,6 @@ from lldbsuite.test import decorators from lldbsuite.test import lldbinline -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, decorators.skipIfWindows]) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py b/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py index 9c1fd1e7bef..0a0ac2d0577 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py @@ -3,13 +3,15 @@ from __future__ import print_function - -import os, sys, time +import os +import sys +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SBFrameFindValueTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,26 +28,57 @@ class SBFrameFindValueTestCase(TestBase): # Create the target target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - + # Set the breakpoints - breakpoint = target.BreakpointCreateBySourceRegex('Set breakpoint here', lldb.SBFileSpec("main.cpp")) + breakpoint = target.BreakpointCreateBySourceRegex( + 'Set breakpoint here', lldb.SBFileSpec("main.cpp")) self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple(None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be at our breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1) self.thread = threads[0] self.frame = self.thread.frames[0] self.assertTrue(self.frame, "Frame 0 is valid.") - self.assertTrue(self.frame.GetVariables(True,True,False,True).GetSize() == 2, "variable count is off") - self.assertFalse(self.frame.FindValue("NoSuchThing",lldb.eValueTypeVariableArgument,lldb.eDynamicCanRunTarget).IsValid(), "found something that should not be here") - self.assertTrue(self.frame.GetVariables(True,True,False,True).GetSize() == 2, "variable count is off after failed FindValue()") - self.assertTrue(self.frame.FindValue("a",lldb.eValueTypeVariableArgument,lldb.eDynamicCanRunTarget).IsValid(), "FindValue() didn't find an argument") - self.assertTrue(self.frame.GetVariables(True,True,False,True).GetSize() == 2, "variable count is off after successful FindValue()") + self.assertTrue( + self.frame.GetVariables( + True, + True, + False, + True).GetSize() == 2, + "variable count is off") + self.assertFalse( + self.frame.FindValue( + "NoSuchThing", + lldb.eValueTypeVariableArgument, + lldb.eDynamicCanRunTarget).IsValid(), + "found something that should not be here") + self.assertTrue( + self.frame.GetVariables( + True, + True, + False, + True).GetSize() == 2, + "variable count is off after failed FindValue()") + self.assertTrue( + self.frame.FindValue( + "a", + lldb.eValueTypeVariableArgument, + lldb.eDynamicCanRunTarget).IsValid(), + "FindValue() didn't find an argument") + self.assertTrue( + self.frame.GetVariables( + True, + True, + False, + True).GetSize() == 2, + "variable count is off after successful FindValue()") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py index babae237b8c..667bd58adce 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py @@ -3,13 +3,15 @@ from __future__ import print_function - -import os, sys, time +import os +import sys +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SBFormattersAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,19 +26,20 @@ class SBFormattersAPITestCase(TestBase): """Test Python APIs for working with formatters""" self.build() self.setTearDownCleanup() - + """Test Python APIs for working with formatters""" self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): @@ -51,265 +54,402 @@ class SBFormattersAPITestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - format = lldb.SBTypeFormat(lldb.eFormatHex) category = self.dbg.GetDefaultCategory() - category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"),format) + category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"), format) self.expect("frame variable foo.A", - substrs = ['0x00000001']) + substrs=['0x00000001']) self.expect("frame variable foo.E", matching=False, - substrs = ['b8cca70a']) + substrs=['b8cca70a']) - category.AddTypeFormat(lldb.SBTypeNameSpecifier("long"),format) + category.AddTypeFormat(lldb.SBTypeNameSpecifier("long"), format) self.expect("frame variable foo.A", - substrs = ['0x00000001']) + substrs=['0x00000001']) self.expect("frame variable foo.E", - substrs = ['b8cca70a']) - + substrs=['b8cca70a']) + format.format = lldb.eFormatOctal - category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"),format) + category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"), format) self.expect("frame variable foo.A", - substrs = ['01']) + substrs=['01']) self.expect("frame variable foo.E", - substrs = ['b8cca70a']) - + substrs=['b8cca70a']) + category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("int")) category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("long")) self.expect("frame variable foo.A", matching=False, - substrs = ['01']) + substrs=['01']) self.expect("frame variable foo.E", matching=False, - substrs = ['b8cca70a']) + substrs=['b8cca70a']) - summary = lldb.SBTypeSummary.CreateWithSummaryString("the hello world you'll never see") + summary = lldb.SBTypeSummary.CreateWithSummaryString( + "the hello world you'll never see") summary.SetSummaryString('hello world') new_category = self.dbg.GetCategory("foobar") - self.assertFalse(new_category.IsValid(), "getting a non-existing category worked") + self.assertFalse( + new_category.IsValid(), + "getting a non-existing category worked") new_category = self.dbg.CreateCategory("foobar") new_category.enabled = True - new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("^.*t$",True),summary) + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier( + "^.*t$", True), summary) self.expect("frame variable foo.A", - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.E", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.B", - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.F", - substrs = ['hello world']) + substrs=['hello world']) new_category.enabled = False self.expect("frame variable foo.A", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.E", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.B", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.F", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.dbg.DeleteCategory(new_category.GetName()) self.expect("frame variable foo.A", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.E", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.B", matching=False, - substrs = ['hello world']) + substrs=['hello world']) self.expect("frame variable foo.F", matching=False, - substrs = ['hello world']) + substrs=['hello world']) filter = lldb.SBTypeFilter(0) filter.AppendExpressionPath("A") filter.AppendExpressionPath("D") - self.assertTrue(filter.GetNumberOfExpressionPaths() == 2, "filter with two items does not have two items") + self.assertTrue( + filter.GetNumberOfExpressionPaths() == 2, + "filter with two items does not have two items") - category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) self.expect("frame variable foo", - substrs = ['A = 1', 'D = 6.28']) + substrs=['A = 1', 'D = 6.28']) self.expect("frame variable foo", matching=False, - substrs = ['B = ', 'C = ', 'E = ', 'F = ']) + substrs=['B = ', 'C = ', 'E = ', 'F = ']) - category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct",True)) + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier( + "JustAStruct", True)) self.expect("frame variable foo", - substrs = ['A = 1', 'D = 6.28']) + substrs=['A = 1', 'D = 6.28']) self.expect("frame variable foo", matching=False, - substrs = ['B = ', 'C = ', 'E = ', 'F = ']) + substrs=['B = ', 'C = ', 'E = ', 'F = ']) - category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct",False)) + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier( + "JustAStruct", False)) self.expect("frame variable foo", - substrs = ['A = 1', 'D = 6.28']) + substrs=['A = 1', 'D = 6.28']) self.expect("frame variable foo", matching=True, - substrs = ['B = ', 'C = ', 'E = ', 'F = ']) + substrs=['B = ', 'C = ', 'E = ', 'F = ']) self.runCmd("command script import --allow-reload ./synth.py") self.expect("frame variable foo", matching=False, - substrs = ['X = 1']) + substrs=['X = 1']) self.dbg.GetCategory("JASSynth").SetEnabled(True) self.expect("frame variable foo", matching=True, - substrs = ['X = 1']) + substrs=['X = 1']) self.dbg.GetCategory("CCCSynth").SetEnabled(True) - self.expect("frame variable ccc", matching=True, - substrs = ['CCC object with leading value (int) a = 111', 'a = 111', 'b = 222', 'c = 333']) - - foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo') + self.expect( + "frame variable ccc", + matching=True, + substrs=[ + 'CCC object with leading value (int) a = 111', + 'a = 111', + 'b = 222', + 'c = 333']) + + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') self.assertTrue(foo_var.IsValid(), 'could not find foo') - self.assertTrue(foo_var.GetDeclaration().IsValid(), 'foo declaration is invalid') - - self.assertTrue(foo_var.GetNumChildren() == 2, 'synthetic value has wrong number of child items (synth)') - self.assertTrue(foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 1, 'foo_synth.X has wrong value (synth)') - self.assertFalse(foo_var.GetChildMemberWithName('B').IsValid(), 'foo_synth.B is valid but should not (synth)') + self.assertTrue( + foo_var.GetDeclaration().IsValid(), + 'foo declaration is invalid') + + self.assertTrue( + foo_var.GetNumChildren() == 2, + 'synthetic value has wrong number of child items (synth)') + self.assertTrue( + foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 1, + 'foo_synth.X has wrong value (synth)') + self.assertFalse( + foo_var.GetChildMemberWithName('B').IsValid(), + 'foo_synth.B is valid but should not (synth)') self.dbg.GetCategory("JASSynth").SetEnabled(False) - foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo') + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') self.assertTrue(foo_var.IsValid(), 'could not find foo') - self.assertFalse(foo_var.GetNumChildren() == 2, 'still seeing synthetic value') + self.assertFalse( + foo_var.GetNumChildren() == 2, + 'still seeing synthetic value') filter = lldb.SBTypeFilter(0) filter.AppendExpressionPath("A") filter.AppendExpressionPath("D") - category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) self.expect("frame variable foo", - substrs = ['A = 1', 'D = 6.28']) + substrs=['A = 1', 'D = 6.28']) - foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo') + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') self.assertTrue(foo_var.IsValid(), 'could not find foo') - self.assertTrue(foo_var.GetNumChildren() == 2, 'synthetic value has wrong number of child items (filter)') - self.assertTrue(foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 0, 'foo_synth.X has wrong value (filter)') - self.assertTrue(foo_var.GetChildMemberWithName('A').GetValueAsUnsigned() == 1, 'foo_synth.A has wrong value (filter)') - - self.assertTrue(filter.ReplaceExpressionPathAtIndex(0,"C"), "failed to replace an expression path in filter") + self.assertTrue( + foo_var.GetNumChildren() == 2, + 'synthetic value has wrong number of child items (filter)') + self.assertTrue( + foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 0, + 'foo_synth.X has wrong value (filter)') + self.assertTrue( + foo_var.GetChildMemberWithName('A').GetValueAsUnsigned() == 1, + 'foo_synth.A has wrong value (filter)') + + self.assertTrue(filter.ReplaceExpressionPathAtIndex( + 0, "C"), "failed to replace an expression path in filter") self.expect("frame variable foo", - substrs = ['A = 1', 'D = 6.28']) - category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter) + substrs=['A = 1', 'D = 6.28']) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) self.expect("frame variable foo", - substrs = ["C = 'e'", 'D = 6.28']) - category.AddTypeFilter(lldb.SBTypeNameSpecifier("FooType"),filter) - filter.ReplaceExpressionPathAtIndex(1,"F") + substrs=["C = 'e'", 'D = 6.28']) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("FooType"), filter) + filter.ReplaceExpressionPathAtIndex(1, "F") self.expect("frame variable foo", - substrs = ["C = 'e'", 'D = 6.28']) - category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter) + substrs=["C = 'e'", 'D = 6.28']) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) self.expect("frame variable foo", - substrs = ["C = 'e'", 'F = 0']) + substrs=["C = 'e'", 'F = 0']) self.expect("frame variable bar", - substrs = ["C = 'e'", 'D = 6.28']) + substrs=["C = 'e'", 'D = 6.28']) - foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo') + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') self.assertTrue(foo_var.IsValid(), 'could not find foo') - self.assertTrue(foo_var.GetChildMemberWithName('C').GetValueAsUnsigned() == ord('e'), 'foo_synth.C has wrong value (filter)') - - chosen = self.dbg.GetFilterForType(lldb.SBTypeNameSpecifier("JustAStruct")) - self.assertTrue(chosen.count == 2, "wrong filter found for JustAStruct") - self.assertTrue(chosen.GetExpressionPathAtIndex(0) == 'C', "wrong item at index 0 for JustAStruct") - self.assertTrue(chosen.GetExpressionPathAtIndex(1) == 'F', "wrong item at index 1 for JustAStruct") - - self.assertFalse(category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing filter worked") - self.assertFalse(category.DeleteTypeSummary(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing summary worked") - self.assertFalse(category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing format worked") - self.assertFalse(category.DeleteTypeSynthetic(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing synthetic worked") - - self.assertFalse(category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("")),"deleting a filter for '' worked") - self.assertFalse(category.DeleteTypeSummary(lldb.SBTypeNameSpecifier("")),"deleting a summary for '' worked") - self.assertFalse(category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("")),"deleting a format for '' worked") - self.assertFalse(category.DeleteTypeSynthetic(lldb.SBTypeNameSpecifier("")),"deleting a synthetic for '' worked") + self.assertTrue( + foo_var.GetChildMemberWithName('C').GetValueAsUnsigned() == ord('e'), + 'foo_synth.C has wrong value (filter)') + + chosen = self.dbg.GetFilterForType( + lldb.SBTypeNameSpecifier("JustAStruct")) + self.assertTrue( + chosen.count == 2, + "wrong filter found for JustAStruct") + self.assertTrue( + chosen.GetExpressionPathAtIndex(0) == 'C', + "wrong item at index 0 for JustAStruct") + self.assertTrue( + chosen.GetExpressionPathAtIndex(1) == 'F', + "wrong item at index 1 for JustAStruct") + + self.assertFalse( + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing filter worked") + self.assertFalse( + category.DeleteTypeSummary( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing summary worked") + self.assertFalse( + category.DeleteTypeFormat( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing format worked") + self.assertFalse( + category.DeleteTypeSynthetic( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing synthetic worked") + + self.assertFalse( + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier("")), + "deleting a filter for '' worked") + self.assertFalse( + category.DeleteTypeSummary( + lldb.SBTypeNameSpecifier("")), + "deleting a summary for '' worked") + self.assertFalse( + category.DeleteTypeFormat( + lldb.SBTypeNameSpecifier("")), + "deleting a format for '' worked") + self.assertFalse( + category.DeleteTypeSynthetic( + lldb.SBTypeNameSpecifier("")), + "deleting a synthetic for '' worked") try: - self.assertFalse(category.AddTypeSummary(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a summary valued None worked") + self.assertFalse( + category.AddTypeSummary( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a summary valued None worked") except: - pass + pass else: - self.assertFalse(True, "adding a summary valued None worked") + self.assertFalse(True, "adding a summary valued None worked") try: - self.assertFalse(category.AddTypeFilter(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a filter valued None worked") + self.assertFalse( + category.AddTypeFilter( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a filter valued None worked") except: - pass + pass else: - self.assertFalse(True, "adding a filter valued None worked") + self.assertFalse(True, "adding a filter valued None worked") try: - self.assertFalse(category.AddTypeSynthetic(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a synthetic valued None worked") + self.assertFalse( + category.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a synthetic valued None worked") except: - pass + pass else: - self.assertFalse(True, "adding a synthetic valued None worked") + self.assertFalse(True, "adding a synthetic valued None worked") try: - self.assertFalse(category.AddTypeFormat(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a format valued None worked") + self.assertFalse( + category.AddTypeFormat( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a format valued None worked") except: - pass + pass else: - self.assertFalse(True, "adding a format valued None worked") - - - self.assertFalse(category.AddTypeSummary(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeSummary()), "adding a summary without value worked") - self.assertFalse(category.AddTypeFilter(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeFilter()), "adding a filter without value worked") - self.assertFalse(category.AddTypeSynthetic(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeSynthetic()), "adding a synthetic without value worked") - self.assertFalse(category.AddTypeFormat(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeFormat()), "adding a format without value worked") - - self.assertFalse(category.AddTypeSummary(lldb.SBTypeNameSpecifier(""), lldb.SBTypeSummary.CreateWithSummaryString("")), "adding a summary for an invalid type worked") - self.assertFalse(category.AddTypeFilter(lldb.SBTypeNameSpecifier(""), lldb.SBTypeFilter(0)), "adding a filter for an invalid type worked") - self.assertFalse(category.AddTypeSynthetic(lldb.SBTypeNameSpecifier(""), lldb.SBTypeSynthetic.CreateWithClassName("")), "adding a synthetic for an invalid type worked") - self.assertFalse(category.AddTypeFormat(lldb.SBTypeNameSpecifier(""), lldb.SBTypeFormat(lldb.eFormatHex)), "adding a format for an invalid type worked") + self.assertFalse(True, "adding a format valued None worked") + + self.assertFalse( + category.AddTypeSummary( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeSummary()), + "adding a summary without value worked") + self.assertFalse( + category.AddTypeFilter( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeFilter()), + "adding a filter without value worked") + self.assertFalse( + category.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeSynthetic()), + "adding a synthetic without value worked") + self.assertFalse( + category.AddTypeFormat( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeFormat()), + "adding a format without value worked") + + self.assertFalse( + category.AddTypeSummary( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeSummary.CreateWithSummaryString("")), + "adding a summary for an invalid type worked") + self.assertFalse( + category.AddTypeFilter( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeFilter(0)), + "adding a filter for an invalid type worked") + self.assertFalse( + category.AddTypeSynthetic( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeSynthetic.CreateWithClassName("")), + "adding a synthetic for an invalid type worked") + self.assertFalse( + category.AddTypeFormat( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeFormat( + lldb.eFormatHex)), + "adding a format for an invalid type worked") new_category = self.dbg.CreateCategory("newbar") - new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("JustAStruct"), - lldb.SBTypeSummary.CreateWithScriptCode("return 'hello scripted world';")) + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier("JustAStruct"), + lldb.SBTypeSummary.CreateWithScriptCode("return 'hello scripted world';")) self.expect("frame variable foo", matching=False, - substrs = ['hello scripted world']) + substrs=['hello scripted world']) new_category.enabled = True self.expect("frame variable foo", matching=True, - substrs = ['hello scripted world']) + substrs=['hello scripted world']) self.expect("frame variable foo_ptr", matching=True, - substrs = ['hello scripted world']) - new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("JustAStruct"), - lldb.SBTypeSummary.CreateWithScriptCode("return 'hello scripted world';", - lldb.eTypeOptionSkipPointers)) + substrs=['hello scripted world']) + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier("JustAStruct"), + lldb.SBTypeSummary.CreateWithScriptCode( + "return 'hello scripted world';", + lldb.eTypeOptionSkipPointers)) self.expect("frame variable foo", matching=True, - substrs = ['hello scripted world']) + substrs=['hello scripted world']) - frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() foo_ptr = frame.FindVariable("foo_ptr") summary = foo_ptr.GetTypeSummary() - self.assertFalse(summary.IsValid(), "summary found for foo* when none was planned") + self.assertFalse( + summary.IsValid(), + "summary found for foo* when none was planned") self.expect("frame variable foo_ptr", matching=False, - substrs = ['hello scripted world']) + substrs=['hello scripted world']) - new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("JustAStruct"), - lldb.SBTypeSummary.CreateWithSummaryString("hello static world", - lldb.eTypeOptionNone)) + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier("JustAStruct"), + lldb.SBTypeSummary.CreateWithSummaryString( + "hello static world", + lldb.eTypeOptionNone)) summary = foo_ptr.GetTypeSummary() - self.assertTrue(summary.IsValid(), "no summary found for foo* when one was in place") - self.assertTrue(summary.GetData() == "hello static world", "wrong summary found for foo*") + self.assertTrue( + summary.IsValid(), + "no summary found for foo* when one was in place") + self.assertTrue( + summary.GetData() == "hello static world", + "wrong summary found for foo*") self.expect("frame variable e1", substrs=["I am an empty Empty1 {}"]) self.expect("frame variable e2", substrs=["I am an empty Empty2"]) - self.expect("frame variable e2", substrs=["I am an empty Empty2 {}"], matching=False) - - self.assertTrue(self.dbg.GetCategory(lldb.eLanguageTypeObjC) is not None, "ObjC category is None") + self.expect( + "frame variable e2", + substrs=["I am an empty Empty2 {}"], + matching=False) + + self.assertTrue( + self.dbg.GetCategory( + lldb.eLanguageTypeObjC) is not None, + "ObjC category is None") @add_test_categories(['pyapi']) def test_force_synth_off(self): """Test that one can have the public API return non-synthetic SBValues if desired""" - self.build(dictionary={'EXE':'no_synth'}) + self.build(dictionary={'EXE': 'no_synth'}) self.setTearDownCleanup() self.runCmd("file no_synth", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -326,22 +466,31 @@ class SBFormattersAPITestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() int_vector = frame.FindVariable("int_vector") if self.TraceOn(): - print(int_vector) - self.assertTrue(int_vector.GetNumChildren() == 0, 'synthetic vector is empty') + print(int_vector) + self.assertTrue( + int_vector.GetNumChildren() == 0, + 'synthetic vector is empty') self.runCmd('settings set target.enable-synthetic-value false') - frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() int_vector = frame.FindVariable("int_vector") if self.TraceOn(): - print(int_vector) - self.assertFalse(int_vector.GetNumChildren() == 0, '"physical" vector is not empty') + print(int_vector) + self.assertFalse( + int_vector.GetNumChildren() == 0, + '"physical" vector is not empty') self.runCmd('settings set target.enable-synthetic-value true') - frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame() + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() int_vector = frame.FindVariable("int_vector") if self.TraceOn(): - print(int_vector) - self.assertTrue(int_vector.GetNumChildren() == 0, 'synthetic vector is still empty') + print(int_vector) + self.assertTrue( + int_vector.GetNumChildren() == 0, + 'synthetic vector is still empty') diff --git a/lldb/packages/Python/lldbsuite/test/python_api/formatters/synth.py b/lldb/packages/Python/lldbsuite/test/python_api/formatters/synth.py index 5a30c9a94bb..33a45e9c93d 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/formatters/synth.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/formatters/synth.py @@ -1,23 +1,28 @@ import lldb + class jasSynthProvider: - def __init__(self, valobj, dict): - self.valobj = valobj; - def num_children(self): - return 2; - def get_child_at_index(self, index): - child = None - if index == 0: - child = self.valobj.GetChildMemberWithName('A'); - if index == 1: - child = self.valobj.CreateValueFromExpression('X', '(int)1') - return child; - def get_child_index(self, name): - if name == 'A': - return 0; - if name == 'X': - return 1; - return None; + + def __init__(self, valobj, dict): + self.valobj = valobj + + def num_children(self): + return 2 + + def get_child_at_index(self, index): + child = None + if index == 0: + child = self.valobj.GetChildMemberWithName('A') + if index == 1: + child = self.valobj.CreateValueFromExpression('X', '(int)1') + return child + + def get_child_index(self, name): + if name == 'A': + return 0 + if name == 'X': + return 1 + return None def ccc_summary(sbvalue, internal_dict): @@ -25,11 +30,14 @@ def ccc_summary(sbvalue, internal_dict): # This tests that the SBValue.GetNonSyntheticValue() actually returns a # non-synthetic value. If it does not, then sbvalue.GetChildMemberWithName("a") # in the following statement will call the 'get_child_index' method of the - # synthetic child provider CCCSynthProvider below (which raises an exception). - return "CCC object with leading value " + str(sbvalue.GetChildMemberWithName("a")) + # synthetic child provider CCCSynthProvider below (which raises an + # exception). + return "CCC object with leading value " + \ + str(sbvalue.GetChildMemberWithName("a")) class CCCSynthProvider(object): + def __init__(self, sbvalue, internal_dict): self._sbvalue = sbvalue @@ -53,6 +61,7 @@ def empty1_summary(sbvalue, internal_dict): class Empty1SynthProvider(object): + def __init__(self, sbvalue, internal_dict): self._sbvalue = sbvalue @@ -68,6 +77,7 @@ def empty2_summary(sbvalue, internal_dict): class Empty2SynthProvider(object): + def __init__(self, sbvalue, internal_dict): self._sbvalue = sbvalue @@ -78,28 +88,30 @@ class Empty2SynthProvider(object): return None -def __lldb_init_module(debugger,dict): - debugger.CreateCategory("JASSynth").AddTypeSynthetic(lldb.SBTypeNameSpecifier("JustAStruct"), +def __lldb_init_module(debugger, dict): + debugger.CreateCategory("JASSynth").AddTypeSynthetic( + lldb.SBTypeNameSpecifier("JustAStruct"), lldb.SBTypeSynthetic.CreateWithClassName("synth.jasSynthProvider")) - cat = lldb.debugger.CreateCategory("CCCSynth") - cat.AddTypeSynthetic( - lldb.SBTypeNameSpecifier("CCC"), - lldb.SBTypeSynthetic.CreateWithClassName("synth.CCCSynthProvider", + cat = lldb.debugger.CreateCategory("CCCSynth") + cat.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("CCC"), + lldb.SBTypeSynthetic.CreateWithClassName("synth.CCCSynthProvider", + lldb.eTypeOptionCascade)) + cat.AddTypeSummary( + lldb.SBTypeNameSpecifier("CCC"), + lldb.SBTypeSummary.CreateWithFunctionName("synth.ccc_summary", lldb.eTypeOptionCascade)) - cat.AddTypeSummary( - lldb.SBTypeNameSpecifier("CCC"), - lldb.SBTypeSummary.CreateWithFunctionName("synth.ccc_summary", - lldb.eTypeOptionCascade)) - cat.AddTypeSynthetic( - lldb.SBTypeNameSpecifier("Empty1"), - lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty1SynthProvider")) - cat.AddTypeSummary( - lldb.SBTypeNameSpecifier("Empty1"), - lldb.SBTypeSummary.CreateWithFunctionName("synth.empty1_summary")) - cat.AddTypeSynthetic( - lldb.SBTypeNameSpecifier("Empty2"), - lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty2SynthProvider")) - cat.AddTypeSummary( - lldb.SBTypeNameSpecifier("Empty2"), - lldb.SBTypeSummary.CreateWithFunctionName("synth.empty2_summary", - lldb.eTypeOptionHideEmptyAggregates)) + cat.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("Empty1"), + lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty1SynthProvider")) + cat.AddTypeSummary( + lldb.SBTypeNameSpecifier("Empty1"), + lldb.SBTypeSummary.CreateWithFunctionName("synth.empty1_summary")) + cat.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("Empty2"), + lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty2SynthProvider")) + cat.AddTypeSummary( + lldb.SBTypeNameSpecifier("Empty2"), + lldb.SBTypeSummary.CreateWithFunctionName( + "synth.empty2_summary", + lldb.eTypeOptionHideEmptyAggregates)) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py b/lldb/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py index 0b1e12b08fc..06ca772073a 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py @@ -6,14 +6,15 @@ And other SBFrame API tests. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class FrameAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -37,7 +38,8 @@ class FrameAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, @@ -50,7 +52,8 @@ class FrameAPITestCase(TestBase): from six import StringIO as SixStringIO session = SixStringIO() while process.GetState() == lldb.eStateStopped: - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # Inspect at most 3 frames. numFrames = min(3, thread.GetNumFrames()) @@ -76,27 +79,35 @@ class FrameAPITestCase(TestBase): val.GetName(), val.GetValue())) print("%s(%s)" % (name, ", ".join(argList)), file=session) - + # Also check the generic pc & stack pointer. We can't test their absolute values, - # but they should be valid. Uses get_GPRs() from the lldbutil module. + # but they should be valid. Uses get_GPRs() from the lldbutil + # module. gpr_reg_set = lldbutil.get_GPRs(frame) pc_value = gpr_reg_set.GetChildMemberWithName("pc") - self.assertTrue (pc_value, "We should have a valid PC.") + self.assertTrue(pc_value, "We should have a valid PC.") pc_value_int = int(pc_value.GetValue(), 0) # Make sure on arm targets we dont mismatch PC value on the basis of thumb bit. - # Frame PC will not have thumb bit set in case of a thumb instruction as PC. + # Frame PC will not have thumb bit set in case of a thumb + # instruction as PC. if self.getArchitecture() in ['arm']: pc_value_int &= ~1 - self.assertTrue (pc_value_int == frame.GetPC(), "PC gotten as a value should equal frame's GetPC") + self.assertTrue( + pc_value_int == frame.GetPC(), + "PC gotten as a value should equal frame's GetPC") sp_value = gpr_reg_set.GetChildMemberWithName("sp") - self.assertTrue (sp_value, "We should have a valid Stack Pointer.") - self.assertTrue (int(sp_value.GetValue(), 0) == frame.GetSP(), "SP gotten as a value should equal frame's GetSP") + self.assertTrue( + sp_value, "We should have a valid Stack Pointer.") + self.assertTrue(int(sp_value.GetValue(), 0) == frame.GetSP( + ), "SP gotten as a value should equal frame's GetSP") print("---", file=session) process.Continue() # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) # Expect to find 'a' on the call stacks two times. self.assertTrue(callsOfA == 2, @@ -109,8 +120,8 @@ class FrameAPITestCase(TestBase): print(session.getvalue()) self.expect(session.getvalue(), "Argugment values displayed correctly", exe=False, - substrs = ["a((int)val=1, (char)ch='A')", - "a((int)val=3, (char)ch='A')"]) + substrs=["a((int)val=1, (char)ch='A')", + "a((int)val=3, (char)ch='A')"]) @add_test_categories(['pyapi']) def test_frame_api_boundary_condition(self): @@ -130,13 +141,15 @@ class FrameAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) frame = thread.GetFrameAtIndex(0) if self.TraceOn(): @@ -170,13 +183,15 @@ class FrameAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) frameEntered = thread.GetFrameAtIndex(0) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/TestGetVariables.py b/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/TestGetVariables.py index 914c3d25fd5..86585d8d02e 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/TestGetVariables.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/TestGetVariables.py @@ -5,20 +5,22 @@ Test that SBFrame::GetVariables() calls work correctly. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbplatform from lldbsuite.test import lldbutil + def get_names_from_value_list(value_list): names = list() for value in value_list: names.append(value.GetName()) return names + class TestGetVariables(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -35,12 +37,16 @@ class TestGetVariables(TestBase): if name in copy_names: copy_names.remove(name) else: - self.assertTrue(False, "didn't find '%s' in %s" % (name, copy_names)) - self.assertEqual(len(copy_names), 0, "%s: we didn't find variables: %s in value list (%s)" % (description, copy_names, actual_names)) + self.assertTrue( + False, "didn't find '%s' in %s" % + (name, copy_names)) + self.assertEqual( + len(copy_names), 0, "%s: we didn't find variables: %s in value list (%s)" % + (description, copy_names, actual_names)) + + def test(self): + self.build() - def test (self): - self.build () - # Set debugger into synchronous mode self.dbg.SetAsync(False) @@ -48,36 +54,42 @@ class TestGetVariables(TestBase): exe = os.path.join(os.getcwd(), "a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - + line1 = line_number(self.source, '// breakpoint 1') line2 = line_number(self.source, '// breakpoint 2') line3 = line_number(self.source, '// breakpoint 3') - breakpoint1 = target.BreakpointCreateByLocation (self.source, line1); - breakpoint2 = target.BreakpointCreateByLocation (self.source, line2); - breakpoint3 = target.BreakpointCreateByLocation (self.source, line3); + breakpoint1 = target.BreakpointCreateByLocation(self.source, line1) + breakpoint2 = target.BreakpointCreateByLocation(self.source, line2) + breakpoint3 = target.BreakpointCreateByLocation(self.source, line3) self.assertTrue(breakpoint1.GetNumLocations() >= 1, PROCESS_IS_VALID) self.assertTrue(breakpoint2.GetNumLocations() >= 1, PROCESS_IS_VALID) self.assertTrue(breakpoint3.GetNumLocations() >= 1, PROCESS_IS_VALID) - # Register our shared libraries for remote targets so they get automatically uploaded + # Register our shared libraries for remote targets so they get + # automatically uploaded arguments = None - environment = None + environment = None # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (arguments, environment, self.get_process_working_directory()) + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint1) - self.assertEqual(len(threads), 1, "There should be a thread stopped at breakpoint 1") - + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint1) + self.assertEqual( + len(threads), + 1, + "There should be a thread stopped at breakpoint 1") + thread = threads[0] self.assertTrue(thread.IsValid(), "Thread must be valid") frame = thread.GetFrameAtIndex(0) self.assertTrue(frame.IsValid(), "Frame must be valid") - - arg_names = ['argc', 'argv'] + + arg_names = ['argc', 'argv'] local_names = ['i', 'j', 'k'] static_names = ['static_var', 'g_global_var', 'g_static_var'] breakpoint1_locals = ['i'] @@ -95,96 +107,190 @@ class TestGetVariables(TestBase): ignore_scope = False # Verify if we ask for only arguments that we got what we expect - vars = frame.GetVariables(args_yes, locals_no, statics_no, ignore_scope) - self.assertEqual(vars.GetSize(), num_args, "There should be %i arguments, but we are reporting %i" % (num_args, vars.GetSize())) + vars = frame.GetVariables( + args_yes, locals_no, statics_no, ignore_scope) + self.assertEqual( + vars.GetSize(), + num_args, + "There should be %i arguments, but we are reporting %i" % + (num_args, + vars.GetSize())) self.verify_variable_names("check names of arguments", vars, arg_names) - self.assertEqual(len(arg_names), num_args, "make sure verify_variable_names() didn't mutate list") + self.assertEqual( + len(arg_names), + num_args, + "make sure verify_variable_names() didn't mutate list") # Verify if we ask for only locals that we got what we expect - vars = frame.GetVariables(args_no, locals_yes, statics_no, ignore_scope) - self.assertEqual(vars.GetSize(), num_locals, "There should be %i local variables, but we are reporting %i" % (num_locals, vars.GetSize())) + vars = frame.GetVariables( + args_no, locals_yes, statics_no, ignore_scope) + self.assertEqual( + vars.GetSize(), + num_locals, + "There should be %i local variables, but we are reporting %i" % + (num_locals, + vars.GetSize())) self.verify_variable_names("check names of locals", vars, local_names) # Verify if we ask for only statics that we got what we expect - vars = frame.GetVariables(args_no, locals_no, statics_yes, ignore_scope) + vars = frame.GetVariables( + args_no, locals_no, statics_yes, ignore_scope) print('statics: ', str(vars)) - self.assertEqual(vars.GetSize(), num_statics, "There should be %i static variables, but we are reporting %i" % (num_statics, vars.GetSize())) - self.verify_variable_names("check names of statics", vars, static_names) + self.assertEqual( + vars.GetSize(), + num_statics, + "There should be %i static variables, but we are reporting %i" % + (num_statics, + vars.GetSize())) + self.verify_variable_names( + "check names of statics", vars, static_names) # Verify if we ask for arguments and locals that we got what we expect - vars = frame.GetVariables(args_yes, locals_yes, statics_no, ignore_scope) + vars = frame.GetVariables( + args_yes, locals_yes, statics_no, ignore_scope) desc = 'arguments + locals' names = arg_names + local_names count = len(names) - self.assertEqual(vars.GetSize(), count, "There should be %i %s (%s) but we are reporting %i (%s)" % (count, desc, names, vars.GetSize(), get_names_from_value_list(vars))) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) self.verify_variable_names("check names of %s" % (desc), vars, names) # Verify if we ask for arguments and statics that we got what we expect - vars = frame.GetVariables(args_yes, locals_no, statics_yes, ignore_scope) + vars = frame.GetVariables( + args_yes, locals_no, statics_yes, ignore_scope) desc = 'arguments + statics' names = arg_names + static_names count = len(names) - self.assertEqual(vars.GetSize(), count, "There should be %i %s (%s) but we are reporting %i (%s)" % (count, desc, names, vars.GetSize(), get_names_from_value_list(vars))) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) self.verify_variable_names("check names of %s" % (desc), vars, names) # Verify if we ask for locals and statics that we got what we expect - vars = frame.GetVariables(args_no, locals_yes, statics_yes, ignore_scope) + vars = frame.GetVariables( + args_no, locals_yes, statics_yes, ignore_scope) desc = 'locals + statics' names = local_names + static_names count = len(names) - self.assertEqual(vars.GetSize(), count, "There should be %i %s (%s) but we are reporting %i (%s)" % (count, desc, names, vars.GetSize(), get_names_from_value_list(vars))) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) self.verify_variable_names("check names of %s" % (desc), vars, names) - # Verify if we ask for arguments, locals and statics that we got what we expect - vars = frame.GetVariables(args_yes, locals_yes, statics_yes, ignore_scope) + # Verify if we ask for arguments, locals and statics that we got what + # we expect + vars = frame.GetVariables( + args_yes, locals_yes, statics_yes, ignore_scope) desc = 'arguments + locals + statics' names = arg_names + local_names + static_names count = len(names) - self.assertEqual(vars.GetSize(), count, "There should be %i %s (%s) but we are reporting %i (%s)" % (count, desc, names, vars.GetSize(), get_names_from_value_list(vars))) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) self.verify_variable_names("check names of %s" % (desc), vars, names) # Verify if we ask for in scope locals that we got what we expect - vars = frame.GetVariables(args_no, locals_yes, statics_no, in_scopy_only) + vars = frame.GetVariables( + args_no, locals_yes, statics_no, in_scopy_only) desc = 'in scope locals at breakpoint 1' names = ['i'] count = len(names) - self.assertEqual(vars.GetSize(), count, "There should be %i %s (%s) but we are reporting %i (%s)" % (count, desc, names, vars.GetSize(), get_names_from_value_list(vars))) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) self.verify_variable_names("check names of %s" % (desc), vars, names) - + # Continue to breakpoint 2 process.Continue() - - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint2) - self.assertEqual(len(threads), 1, "There should be a thread stopped at breakpoint 2") - + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint2) + self.assertEqual( + len(threads), + 1, + "There should be a thread stopped at breakpoint 2") + thread = threads[0] self.assertTrue(thread.IsValid(), "Thread must be valid") frame = thread.GetFrameAtIndex(0) self.assertTrue(frame.IsValid(), "Frame must be valid") # Verify if we ask for in scope locals that we got what we expect - vars = frame.GetVariables(args_no, locals_yes, statics_no, in_scopy_only) + vars = frame.GetVariables( + args_no, locals_yes, statics_no, in_scopy_only) desc = 'in scope locals at breakpoint 2' names = ['i', 'j'] count = len(names) - self.assertEqual(vars.GetSize(), count, "There should be %i %s (%s) but we are reporting %i (%s)" % (count, desc, names, vars.GetSize(), get_names_from_value_list(vars))) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) self.verify_variable_names("check names of %s" % (desc), vars, names) # Continue to breakpoint 3 process.Continue() - - threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint3) - self.assertEqual(len(threads), 1, "There should be a thread stopped at breakpoint 3") - + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint3) + self.assertEqual( + len(threads), + 1, + "There should be a thread stopped at breakpoint 3") + thread = threads[0] self.assertTrue(thread.IsValid(), "Thread must be valid") frame = thread.GetFrameAtIndex(0) self.assertTrue(frame.IsValid(), "Frame must be valid") # Verify if we ask for in scope locals that we got what we expect - vars = frame.GetVariables(args_no, locals_yes, statics_no, in_scopy_only) + vars = frame.GetVariables( + args_no, locals_yes, statics_no, in_scopy_only) desc = 'in scope locals at breakpoint 3' names = ['i', 'j', 'k'] count = len(names) - self.assertEqual(vars.GetSize(), count, "There should be %i %s (%s) but we are reporting %i (%s)" % (count, desc, names, vars.GetSize(), get_names_from_value_list(vars))) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) self.verify_variable_names("check names of %s" % (desc), vars, names) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py b/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py index ee6c33f5431..caa2696be7c 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py @@ -5,14 +5,15 @@ Testlldb Python SBFrame APIs IsInlined() and GetFunctionName(). from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class InlinedFrameAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,8 +23,10 @@ class InlinedFrameAPITestCase(TestBase): TestBase.setUp(self) # Find the line number to of function 'c'. self.source = 'inlines.c' - self.first_stop = line_number(self.source, '// This should correspond to the first break stop.') - self.second_stop = line_number(self.source, '// This should correspond to the second break stop.') + self.first_stop = line_number( + self.source, '// This should correspond to the first break stop.') + self.second_stop = line_number( + self.source, '// This should correspond to the second break stop.') @add_test_categories(['pyapi']) def test_stop_at_outer_inline(self): @@ -43,7 +46,8 @@ class InlinedFrameAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, @@ -52,7 +56,8 @@ class InlinedFrameAPITestCase(TestBase): import lldbsuite.test.lldbutil as lldbutil stack_traces1 = lldbutil.print_stacktraces(process, string_buffer=True) if self.TraceOn(): - print("Full stack traces when first stopped on the breakpoint 'inner_inline':") + print( + "Full stack traces when first stopped on the breakpoint 'inner_inline':") print(stack_traces1) # The first breakpoint should correspond to an inlined call frame. @@ -61,23 +66,32 @@ class InlinedFrameAPITestCase(TestBase): # # outer_inline (argc); # - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) frame0 = thread.GetFrameAtIndex(0) if frame0.IsInlined(): filename = frame0.GetLineEntry().GetFileSpec().GetFilename() self.assertTrue(filename == self.source) - self.expect(stack_traces1, "First stop at %s:%d" % (self.source, self.first_stop), exe=False, - substrs = ['%s:%d' % (self.source, self.first_stop)]) + self.expect( + stack_traces1, "First stop at %s:%d" % + (self.source, self.first_stop), exe=False, substrs=[ + '%s:%d' % + (self.source, self.first_stop)]) # Expect to break again for the second time. process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - stack_traces2 = lldbutil.print_stacktraces(process, string_buffer=True) + stack_traces2 = lldbutil.print_stacktraces( + process, string_buffer=True) if self.TraceOn(): - print("Full stack traces when stopped on the breakpoint 'inner_inline' for the second time:") + print( + "Full stack traces when stopped on the breakpoint 'inner_inline' for the second time:") print(stack_traces2) - self.expect(stack_traces2, "Second stop at %s:%d" % (self.source, self.second_stop), exe=False, - substrs = ['%s:%d' % (self.source, self.second_stop)]) + self.expect( + stack_traces2, "Second stop at %s:%d" % + (self.source, self.second_stop), exe=False, substrs=[ + '%s:%d' % + (self.source, self.second_stop)]) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py index 9a763b89c27..4511da94437 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py @@ -5,14 +5,15 @@ Test retrieval of SBAddress from function/symbol, disassembly, and SBAddress API from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class DisasmAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,8 +22,10 @@ class DisasmAPITestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line1 = line_number('main.c', '// Find the line number for breakpoint 1 here.') - self.line2 = line_number('main.c', '// Find the line number for breakpoint 2 here.') + self.line1 = line_number( + 'main.c', '// Find the line number for breakpoint 1 here.') + self.line2 = line_number( + 'main.c', '// Find the line number for breakpoint 2 here.') @add_test_categories(['pyapi']) def test(self): @@ -47,13 +50,17 @@ class DisasmAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() self.assertTrue(lineEntry.GetLine() == self.line1) @@ -62,7 +69,8 @@ class DisasmAPITestCase(TestBase): #print("address1:", address1) # Now call SBTarget.ResolveSymbolContextForAddress() with address1. - context1 = target.ResolveSymbolContextForAddress(address1, lldb.eSymbolContextEverything) + context1 = target.ResolveSymbolContextForAddress( + address1, lldb.eSymbolContextEverything) self.assertTrue(context1) if self.TraceOn(): @@ -71,13 +79,17 @@ class DisasmAPITestCase(TestBase): # Continue the inferior, the breakpoint 2 should be hit. process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() self.assertTrue(lineEntry.GetLine() == self.line2) - # Verify that the symbol and the function has the same address range per function 'a'. + # Verify that the symbol and the function has the same address range + # per function 'a'. symbol = context1.GetSymbol() function = frame0.GetFunction() self.assertTrue(symbol and function) @@ -108,5 +120,6 @@ class DisasmAPITestCase(TestBase): from lldbsuite.test.lldbutil import get_description desc1 = get_description(sa1) desc2 = get_description(sa2) - self.assertTrue(desc1 and desc2 and desc1 == desc2, - "SBAddress.GetDescription() API of sa1 and sa2 should return the same string") + self.assertTrue( + desc1 and desc2 and desc1 == desc2, + "SBAddress.GetDescription() API of sa1 and sa2 should return the same string") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py index 35d73e49427..9919375abb5 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py @@ -5,14 +5,15 @@ Test newly added SBSymbol and SBAddress APIs. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SymbolAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,8 +22,10 @@ class SymbolAPITestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line1 = line_number('main.c', '// Find the line number for breakpoint 1 here.') - self.line2 = line_number('main.c', '// Find the line number for breakpoint 2 here.') + self.line1 = line_number( + 'main.c', '// Find the line number for breakpoint 1 here.') + self.line2 = line_number( + 'main.c', '// Find the line number for breakpoint 2 here.') @add_test_categories(['pyapi']) def test(self): @@ -47,35 +50,45 @@ class SymbolAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) symbol_line1 = frame0.GetSymbol() # We should have a symbol type of code. self.assertTrue(symbol_line1.GetType() == lldb.eSymbolTypeCode) addr_line1 = symbol_line1.GetStartAddress() # And a section type of code, too. - self.assertTrue(addr_line1.GetSection().GetSectionType() == lldb.eSectionTypeCode) + self.assertTrue(addr_line1.GetSection().GetSectionType() + == lldb.eSectionTypeCode) # Continue the inferior, the breakpoint 2 should be hit. process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) symbol_line2 = frame0.GetSymbol() # We should have a symbol type of code. self.assertTrue(symbol_line2.GetType() == lldb.eSymbolTypeCode) addr_line2 = symbol_line2.GetStartAddress() # And a section type of code, too. - self.assertTrue(addr_line2.GetSection().GetSectionType() == lldb.eSectionTypeCode) + self.assertTrue(addr_line2.GetSection().GetSectionType() + == lldb.eSectionTypeCode) # Now verify that both addresses point to the same module. if self.TraceOn(): print("UUID:", addr_line1.GetModule().GetUUIDString()) - self.assertTrue(addr_line1.GetModule().GetUUIDString() == addr_line2.GetModule().GetUUIDString()) + self.assertTrue(addr_line1.GetModule().GetUUIDString() + == addr_line2.GetModule().GetUUIDString()) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py b/lldb/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py index a8beaa90329..44dd4a61850 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py @@ -3,7 +3,6 @@ from __future__ import print_function - import os import sys import time @@ -13,10 +12,11 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class HelloWorldTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - + def setUp(self): # Call super's setUp(). TestBase.setUp(self) @@ -58,7 +58,8 @@ class HelloWorldTestCase(TestBase): # rdar://problem/8364687 # SBTarget.Launch() issue (or is there some race condition)? - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # The following isn't needed anymore, rdar://8364687 is fixed. # # Apply some dances after LaunchProcess() in order to break at "main". @@ -68,7 +69,8 @@ class HelloWorldTestCase(TestBase): process = target.GetProcess() self.assertTrue(process, PROCESS_IS_VALID) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) # The breakpoint should have a hit count of 1. @@ -100,8 +102,8 @@ class HelloWorldTestCase(TestBase): import lldbsuite.test.lldbutil as lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, - substrs = ['main.c:%d' % self.line2, - '(int)argc=3']) + substrs=['main.c:%d' % self.line2, + '(int)argc=3']) @add_test_categories(['pyapi']) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24600") @@ -121,7 +123,8 @@ class HelloWorldTestCase(TestBase): listener = lldb.SBListener("my.attach.listener") error = lldb.SBError() - # Pass 'False' since we don't want to wait for new instance of "hello_world" to be launched. + # Pass 'False' since we don't want to wait for new instance of + # "hello_world" to be launched. name = os.path.basename(self.exe) # While we're at it, make sure that passing a None as the process name @@ -135,12 +138,14 @@ class HelloWorldTestCase(TestBase): self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Verify that after attach, our selected target indeed matches name. - self.expect(self.dbg.GetSelectedTarget().GetExecutable().GetFilename(), exe=False, - startstr = name) + self.expect( + self.dbg.GetSelectedTarget().GetExecutable().GetFilename(), + exe=False, + startstr=name) # Let's check the stack traces of the attached process. import lldbsuite.test.lldbutil as lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, - substrs = ['main.c:%d' % self.line2, - '(int)argc=3']) + substrs=['main.c:%d' % self.line2, + '(int)argc=3']) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py index d39984adb73..7f5781f5cd8 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py @@ -3,13 +3,13 @@ from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class CommandInterpreterAPICase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -72,4 +72,4 @@ class CommandInterpreterAPICase(TestBase): lldbutil.state_type_to_str(process.GetState())) if self.TraceOn(): - lldbutil.print_stacktraces(process) + lldbutil.print_stacktraces(process) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py index 09a5bc12657..bcbaa68ed92 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py @@ -5,13 +5,13 @@ Test utility functions for the frame object. from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class FrameUtilsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -36,7 +36,8 @@ class FrameUtilsTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") @@ -44,17 +45,19 @@ class FrameUtilsTestCase(TestBase): PROCESS_STOPPED) import lldbsuite.test.lldbutil as lldbutil - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue (thread) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread) frame0 = thread.GetFrameAtIndex(0) - self.assertTrue (frame0) + self.assertTrue(frame0) frame1 = thread.GetFrameAtIndex(1) - self.assertTrue (frame1) + self.assertTrue(frame1) parent = lldbutil.get_parent_frame(frame0) self.assertTrue(parent and parent.GetFrameID() == frame1.GetFrameID()) frame0_args = lldbutil.get_args_as_string(frame0) parent_args = lldbutil.get_args_as_string(parent) - self.assertTrue(frame0_args and parent_args and "(int)val=1" in frame0_args) + self.assertTrue( + frame0_args and parent_args and "(int)val=1" in frame0_args) if self.TraceOn(): lldbutil.print_stacktrace(thread) print("Current frame: %s" % frame0_args) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py index 90f879d3761..ae7ec3dfc3c 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py @@ -5,14 +5,15 @@ Test the iteration protocol for some lldb container objects. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LLDBIteratorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,7 +22,8 @@ class LLDBIteratorTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line numbers to break inside main(). - self.line1 = line_number('main.cpp', '// Set break point at this line.') + self.line1 = line_number( + 'main.cpp', '// Set break point at this line.') self.line2 = line_number('main.cpp', '// And that line.') @add_test_categories(['pyapi']) @@ -37,7 +39,8 @@ class LLDBIteratorTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") @@ -55,8 +58,9 @@ class LLDBIteratorTestCase(TestBase): if self.TraceOn(): print("yours[%d]='%s'" % (i, get_description(yours[i]))) print("mine[%d]='%s'" % (i, get_description(mine[i]))) - self.assertTrue(yours[i] == mine[i], - "UUID+FileSpec of yours[{0}] and mine[{0}] matches".format(i)) + self.assertTrue( + yours[i] == mine[i], + "UUID+FileSpec of yours[{0}] and mine[{0}] matches".format(i)) @add_test_categories(['pyapi']) def test_lldb_iter_breakpoint(self): @@ -103,7 +107,8 @@ class LLDBIteratorTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py index 84ef44d2dd7..49a78888ad8 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py @@ -5,14 +5,15 @@ Test the iteration protocol for frame registers. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class RegistersIteratorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -21,7 +22,8 @@ class RegistersIteratorTestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line1 = line_number('main.cpp', '// Set break point at this line.') + self.line1 = line_number( + 'main.cpp', '// Set break point at this line.') @add_test_categories(['pyapi']) @expectedFailureAll(oslist=["windows"]) @@ -37,7 +39,8 @@ class RegistersIteratorTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") @@ -46,14 +49,17 @@ class RegistersIteratorTestCase(TestBase): for thread in process: if thread.GetStopReason() == lldb.eStopReasonBreakpoint: for frame in thread: - # Dump the registers of this frame using lldbutil.get_GPRs() and friends. + # Dump the registers of this frame using + # lldbutil.get_GPRs() and friends. if self.TraceOn(): print(frame) REGs = lldbutil.get_GPRs(frame) num = len(REGs) if self.TraceOn(): - print("\nNumber of general purpose registers: %d" % num) + print( + "\nNumber of general purpose registers: %d" % + num) for reg in REGs: self.assertTrue(reg) if self.TraceOn(): @@ -72,11 +78,15 @@ class RegistersIteratorTestCase(TestBase): if self.platformIsDarwin(): num = len(REGs) if self.TraceOn(): - print("\nNumber of exception state registers: %d" % num) + print( + "\nNumber of exception state registers: %d" % + num) for reg in REGs: self.assertTrue(reg) if self.TraceOn(): - print("%s => %s" % (reg.GetName(), reg.GetValue())) + print( + "%s => %s" % + (reg.GetName(), reg.GetValue())) else: self.assertIsNone(REGs) @@ -86,7 +96,8 @@ class RegistersIteratorTestCase(TestBase): REGs = lldbutil.get_registers(frame, kind) self.assertTrue(REGs) - REGs = lldbutil.get_registers(frame, "Exception State Registers") + REGs = lldbutil.get_registers( + frame, "Exception State Registers") if self.platformIsDarwin(): self.assertIsNotNone(REGs) else: diff --git a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py index fafd05fd92c..b447bb797a0 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py @@ -5,14 +5,15 @@ Test SBprocess and SBThread APIs with printing of the stack traces using lldbuti from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ThreadsStackTracesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,11 +24,12 @@ class ThreadsStackTracesTestCase(TestBase): # Find the line number to break inside main(). self.line = line_number('main.cpp', '// Set break point at this line.') - @expectedFailureAll("llvm.org/pr23043", ["linux"], archs=["i386"]) # We are unable to produce a backtrace of the main thread when the thread is blocked in fgets - - #The __thread_start function in libc doesn't contain any epilogue and prologue instructions - #hence unwinding fail when we are stopped in __thread_start - @expectedFailureAll(triple = 'mips*') + # We are unable to produce a backtrace of the main thread when the thread + # is blocked in fgets + @expectedFailureAll("llvm.org/pr23043", ["linux"], archs=["i386"]) + # The __thread_start function in libc doesn't contain any epilogue and prologue instructions + # hence unwinding fail when we are stopped in __thread_start + @expectedFailureAll(triple='mips*') @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") @expectedFlakeyAndroid("llvm.org/26492", archs=["arm"]) @expectedFlakeyLinux("llvm.org/pr27687") @@ -44,7 +46,8 @@ class ThreadsStackTracesTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (["abc", "xyz"], None, self.get_process_working_directory()) + process = target.LaunchSimple( + ["abc", "xyz"], None, self.get_process_working_directory()) if not process: self.fail("SBTarget.LaunchProcess() failed") @@ -57,4 +60,4 @@ class ThreadsStackTracesTestCase(TestBase): stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, - substrs = ['(int)argc=3']) + substrs=['(int)argc=3']) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py b/lldb/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py index 859edd80ee8..79b988465d7 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py @@ -5,8 +5,8 @@ Test some SBModule and SBSection APIs. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * @@ -14,12 +14,14 @@ from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from lldbsuite.test.lldbutil import symbol_type_to_str + class ModuleAndSectionAPIsTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) - # Py3 asserts due to a bug in SWIG. A fix for this was upstreamed into SWIG 3.0.8. - @skipIf(py_version=['>=', (3,0)], swig_version=['<', (3,0,8)]) + # Py3 asserts due to a bug in SWIG. A fix for this was upstreamed into + # SWIG 3.0.8. + @skipIf(py_version=['>=', (3, 0)], swig_version=['<', (3, 0, 8)]) @add_test_categories(['pyapi']) def test_module_and_section(self): """Test module and section APIs.""" @@ -47,18 +49,29 @@ class ModuleAndSectionAPIsTestCase(TestBase): INDENT2 = INDENT * 2 for sec in exe_module.section_iter(): print(sec) - print(INDENT + "Number of subsections: %d" % sec.GetNumSubSections()) + print( + INDENT + + "Number of subsections: %d" % + sec.GetNumSubSections()) if sec.GetNumSubSections() == 0: for sym in exe_module.symbol_in_section_iter(sec): print(INDENT + str(sym)) - print(INDENT + "symbol type: %s" % symbol_type_to_str(sym.GetType())) + print( + INDENT + + "symbol type: %s" % + symbol_type_to_str( + sym.GetType())) else: for subsec in sec: print(INDENT + str(subsec)) # Now print the symbols belonging to the subsection.... for sym in exe_module.symbol_in_section_iter(subsec): print(INDENT2 + str(sym)) - print(INDENT2 + "symbol type: %s" % symbol_type_to_str(sym.GetType())) + print( + INDENT2 + + "symbol type: %s" % + symbol_type_to_str( + sym.GetType())) @add_test_categories(['pyapi']) def test_module_and_section_boundary_condition(self): @@ -128,4 +141,3 @@ class ModuleAndSectionAPIsTestCase(TestBase): INDENT2 = INDENT * 2 for cu in exe_module.compile_unit_iter(): print(cu) - diff --git a/lldb/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py b/lldb/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py index b81c422863c..89dfebde1af 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py @@ -5,14 +5,15 @@ Test SBType for ObjC classes. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ObjCSBTypeTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -38,22 +39,28 @@ class ObjCSBTypeTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) - - # Get Frame #0. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") aBar = self.frame().FindVariable("aBar") aBarType = aBar.GetType() self.assertTrue(aBarType.IsValid(), "Bar should be a valid data type") - self.assertTrue(aBarType.GetName() == "Bar *", "Bar has the right name") + self.assertTrue( + aBarType.GetName() == "Bar *", + "Bar has the right name") - self.assertTrue(aBarType.GetNumberOfDirectBaseClasses() == 1, "Bar has a superclass") + self.assertTrue( + aBarType.GetNumberOfDirectBaseClasses() == 1, + "Bar has a superclass") aFooType = aBarType.GetDirectBaseClassAtIndex(0) self.assertTrue(aFooType.IsValid(), "Foo should be a valid data type") @@ -62,4 +69,6 @@ class ObjCSBTypeTestCase(TestBase): self.assertTrue(aBarType.GetNumberOfFields() == 1, "Bar has a field") aBarField = aBarType.GetFieldAtIndex(0) - self.assertTrue(aBarField.GetName() == "_iVar", "The field has the right name") + self.assertTrue( + aBarField.GetName() == "_iVar", + "The field has the right name") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py index d5f407155b2..1009536b370 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py @@ -5,13 +5,14 @@ Test SBProcess APIs, including ReadMemory(), WriteMemory(), and others. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbutil import get_stopped_thread, state_type_to_str + class ProcessAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,7 +21,9 @@ class ProcessAPITestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to break inside main(). - self.line = line_number("main.cpp", "// Set break point at this line and check variable 'my_char'.") + self.line = line_number( + "main.cpp", + "// Set break point at this line and check variable 'my_char'.") @add_test_categories(['pyapi']) def test_read_memory(self): @@ -35,10 +38,13 @@ class ProcessAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") frame = thread.GetFrameAtIndex(0) # Get the SBValue for the global variable 'my_char'. @@ -49,45 +55,55 @@ class ProcessAPITestCase(TestBase): # expect to get a Python string as the result object! error = lldb.SBError() self.assertFalse(val.TypeIsPointerType()) - content = process.ReadMemory(val.AddressOf().GetValueAsUnsigned(), 1, error) + content = process.ReadMemory( + val.AddressOf().GetValueAsUnsigned(), 1, error) if not error.Success(): self.fail("SBProcess.ReadMemory() failed") if self.TraceOn(): print("memory content:", content) - self.expect(content, "Result from SBProcess.ReadMemory() matches our expected output: 'x'", - exe=False, - startstr = b'x') + self.expect( + content, + "Result from SBProcess.ReadMemory() matches our expected output: 'x'", + exe=False, + startstr=b'x') # Read (char *)my_char_ptr. val = frame.FindValue("my_char_ptr", lldb.eValueTypeVariableGlobal) self.DebugSBValue(val) - cstring = process.ReadCStringFromMemory(val.GetValueAsUnsigned(), 256, error) + cstring = process.ReadCStringFromMemory( + val.GetValueAsUnsigned(), 256, error) if not error.Success(): self.fail("SBProcess.ReadCStringFromMemory() failed") if self.TraceOn(): print("cstring read is:", cstring) - self.expect(cstring, "Result from SBProcess.ReadCStringFromMemory() matches our expected output", - exe=False, - startstr = 'Does it work?') + self.expect( + cstring, + "Result from SBProcess.ReadCStringFromMemory() matches our expected output", + exe=False, + startstr='Does it work?') # Get the SBValue for the global variable 'my_cstring'. val = frame.FindValue("my_cstring", lldb.eValueTypeVariableGlobal) self.DebugSBValue(val) # Due to the typemap magic (see lldb.swig), we pass in 256 to read at most 256 bytes - # from the address, and expect to get a Python string as the result object! + # from the address, and expect to get a Python string as the result + # object! self.assertFalse(val.TypeIsPointerType()) - cstring = process.ReadCStringFromMemory(val.AddressOf().GetValueAsUnsigned(), 256, error) + cstring = process.ReadCStringFromMemory( + val.AddressOf().GetValueAsUnsigned(), 256, error) if not error.Success(): self.fail("SBProcess.ReadCStringFromMemory() failed") if self.TraceOn(): print("cstring read is:", cstring) - self.expect(cstring, "Result from SBProcess.ReadCStringFromMemory() matches our expected output", - exe=False, - startstr = 'lldb.SBProcess.ReadCStringFromMemory() works!') + self.expect( + cstring, + "Result from SBProcess.ReadCStringFromMemory() matches our expected output", + exe=False, + startstr='lldb.SBProcess.ReadCStringFromMemory() works!') # Get the SBValue for the global variable 'my_uint32'. val = frame.FindValue("my_uint32", lldb.eValueTypeVariableGlobal) @@ -96,14 +112,16 @@ class ProcessAPITestCase(TestBase): # Due to the typemap magic (see lldb.swig), we pass in 4 to read 4 bytes # from the address, and expect to get an int as the result! self.assertFalse(val.TypeIsPointerType()) - my_uint32 = process.ReadUnsignedFromMemory(val.AddressOf().GetValueAsUnsigned(), 4, error) + my_uint32 = process.ReadUnsignedFromMemory( + val.AddressOf().GetValueAsUnsigned(), 4, error) if not error.Success(): self.fail("SBProcess.ReadCStringFromMemory() failed") if self.TraceOn(): print("uint32 read is:", my_uint32) if my_uint32 != 12345: - self.fail("Result from SBProcess.ReadUnsignedFromMemory() does not match our expected output") + self.fail( + "Result from SBProcess.ReadUnsignedFromMemory() does not match our expected output") @add_test_categories(['pyapi']) def test_write_memory(self): @@ -118,17 +136,21 @@ class ProcessAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") frame = thread.GetFrameAtIndex(0) # Get the SBValue for the global variable 'my_char'. val = frame.FindValue("my_char", lldb.eValueTypeVariableGlobal) self.DebugSBValue(val) - # If the variable does not have a load address, there's no sense continuing. + # If the variable does not have a load address, there's no sense + # continuing. if not val.GetLocation().startswith("0x"): return @@ -136,7 +158,8 @@ class ProcessAPITestCase(TestBase): location = int(val.GetLocation(), 16) # The program logic makes the 'my_char' variable to have memory content as 'x'. - # But we want to use the WriteMemory() API to assign 'a' to the variable. + # But we want to use the WriteMemory() API to assign 'a' to the + # variable. # Now use WriteMemory() API to write 'a' into the global variable. error = lldb.SBError() @@ -153,9 +176,11 @@ class ProcessAPITestCase(TestBase): if self.TraceOn(): print("memory content:", content) - self.expect(content, "Result from SBProcess.ReadMemory() matches our expected output: 'a'", - exe=False, - startstr = b'a') + self.expect( + content, + "Result from SBProcess.ReadMemory() matches our expected output: 'a'", + exe=False, + startstr=b'a') @add_test_categories(['pyapi']) def test_access_my_int(self): @@ -170,17 +195,21 @@ class ProcessAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") frame = thread.GetFrameAtIndex(0) # Get the SBValue for the global variable 'my_int'. val = frame.FindValue("my_int", lldb.eValueTypeVariableGlobal) self.DebugSBValue(val) - # If the variable does not have a load address, there's no sense continuing. + # If the variable does not have a load address, there's no sense + # continuing. if not val.GetLocation().startswith("0x"): return @@ -204,7 +233,8 @@ class ProcessAPITestCase(TestBase): return # The program logic makes the 'my_int' variable to have int type and value of 0. - # But we want to use the WriteMemory() API to assign 256 to the variable. + # But we want to use the WriteMemory() API to assign 256 to the + # variable. # Now use WriteMemory() API to write 256 into the global variable. error = lldb.SBError() @@ -212,25 +242,31 @@ class ProcessAPITestCase(TestBase): if not error.Success() or result != byteSize: self.fail("SBProcess.WriteMemory() failed") - # Make sure that the val we got originally updates itself to notice the change: - self.expect(val.GetValue(), - "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'", - exe=False, - startstr = '256') + # Make sure that the val we got originally updates itself to notice the + # change: + self.expect( + val.GetValue(), + "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'", + exe=False, + startstr='256') - # And for grins, get the SBValue for the global variable 'my_int' again, to make sure that also tracks the new value: + # And for grins, get the SBValue for the global variable 'my_int' + # again, to make sure that also tracks the new value: val = frame.FindValue("my_int", lldb.eValueTypeVariableGlobal) - self.expect(val.GetValue(), - "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'", - exe=False, - startstr = '256') - - # Now read the memory content. The bytearray should have (byte)1 as the second element. + self.expect( + val.GetValue(), + "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'", + exe=False, + startstr='256') + + # Now read the memory content. The bytearray should have (byte)1 as + # the second element. content = process.ReadMemory(location, byteSize, error) if not error.Success(): self.fail("SBProcess.ReadMemory() failed") - # The bytearray_to_int utility function expects a little endian bytearray. + # The bytearray_to_int utility function expects a little endian + # bytearray. if byteOrder == lldb.eByteOrderBig: content = bytearray(content, 'ascii') content.reverse() @@ -254,15 +290,19 @@ class ProcessAPITestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) if self.TraceOn(): print("process state:", state_type_to_str(process.GetState())) self.assertTrue(process.GetState() != lldb.eStateConnected) error = lldb.SBError() - success = process.RemoteLaunch(None, None, None, None, None, None, 0, False, error) - self.assertTrue(not success, "RemoteLaunch() should fail for process state != eStateConnected") + success = process.RemoteLaunch( + None, None, None, None, None, None, 0, False, error) + self.assertTrue( + not success, + "RemoteLaunch() should fail for process state != eStateConnected") @add_test_categories(['pyapi']) def test_get_num_supported_hardware_watchpoints(self): @@ -278,10 +318,10 @@ class ProcessAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) - error = lldb.SBError(); + error = lldb.SBError() num = process.GetNumSupportedHardwareWatchpoints(error) if self.TraceOn() and error.Success(): print("Number of supported hardware watchpoints: %d" % num) - diff --git a/lldb/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py b/lldb/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py index 1a194035f4d..5314930ff99 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py @@ -3,13 +3,15 @@ from __future__ import print_function - -import os, sys, time +import os +import sys +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ProcessIOTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -19,16 +21,19 @@ class ProcessIOTestCase(TestBase): TestBase.setUp(self) # Get the full path to our executable to be debugged. self.exe = os.path.join(os.getcwd(), "process_io") - self.local_input_file = os.path.join(os.getcwd(), "input.txt") + self.local_input_file = os.path.join(os.getcwd(), "input.txt") self.local_output_file = os.path.join(os.getcwd(), "output.txt") - self.local_error_file = os.path.join(os.getcwd(), "error.txt") - - self.input_file = os.path.join(self.get_process_working_directory(), "input.txt") - self.output_file = os.path.join(self.get_process_working_directory(), "output.txt") - self.error_file = os.path.join(self.get_process_working_directory(), "error.txt") + self.local_error_file = os.path.join(os.getcwd(), "error.txt") + + self.input_file = os.path.join( + self.get_process_working_directory(), "input.txt") + self.output_file = os.path.join( + self.get_process_working_directory(), "output.txt") + self.error_file = os.path.join( + self.get_process_working_directory(), "error.txt") self.lines = ["Line 1", "Line 2", "Line 3"] - @skipIfWindows # stdio manipulation unsupported on Windows + @skipIfWindows # stdio manipulation unsupported on Windows @add_test_categories(['pyapi']) @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") def test_stdin_by_api(self): @@ -39,7 +44,7 @@ class ProcessIOTestCase(TestBase): output = self.process.GetSTDOUT(1000) self.check_process_output(output, output) - @skipIfWindows # stdio manipulation unsupported on Windows + @skipIfWindows # stdio manipulation unsupported on Windows @add_test_categories(['pyapi']) @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") def test_stdin_redirection(self): @@ -48,10 +53,10 @@ class ProcessIOTestCase(TestBase): self.create_target() self.redirect_stdin() self.run_process(False) - output = self.process.GetSTDOUT(1000) + output = self.process.GetSTDOUT(1000) self.check_process_output(output, output) - @skipIfWindows # stdio manipulation unsupported on Windows + @skipIfWindows # stdio manipulation unsupported on Windows @add_test_categories(['pyapi']) @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") def test_stdout_redirection(self): @@ -64,7 +69,7 @@ class ProcessIOTestCase(TestBase): error = self.process.GetSTDOUT(1000) self.check_process_output(output, error) - @skipIfWindows # stdio manipulation unsupported on Windows + @skipIfWindows # stdio manipulation unsupported on Windows @add_test_categories(['pyapi']) @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") def test_stderr_redirection(self): @@ -77,7 +82,7 @@ class ProcessIOTestCase(TestBase): error = self.read_error_file_and_delete() self.check_process_output(output, error) - @skipIfWindows # stdio manipulation unsupported on Windows + @skipIfWindows # stdio manipulation unsupported on Windows @add_test_categories(['pyapi']) @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") def test_stdout_stderr_redirection(self): @@ -98,29 +103,35 @@ class ProcessIOTestCase(TestBase): self.runCmd('platform get-file "{remote}" "{local}"'.format( remote=target_file, local=local_file)) - self.assertTrue(os.path.exists(local_file), 'Make sure "{local}" file exists'.format(local=local_file)) + self.assertTrue( + os.path.exists(local_file), + 'Make sure "{local}" file exists'.format( + local=local_file)) f = open(local_file, 'r') contents = f.read() f.close() - #TODO: add 'platform delete-file' file command - #if lldb.remote_platform: + # TODO: add 'platform delete-file' file command + # if lldb.remote_platform: # self.runCmd('platform delete-file "{remote}"'.format(remote=target_file)) os.unlink(local_file) return contents def read_output_file_and_delete(self): - return self.read_file_and_delete(self.output_file, self.local_output_file) + return self.read_file_and_delete( + self.output_file, self.local_output_file) def read_error_file_and_delete(self): - return self.read_file_and_delete(self.error_file, self.local_error_file) + return self.read_file_and_delete( + self.error_file, self.local_error_file) def create_target(self): '''Create the target and launch info that will be used by all tests''' - self.target = self.dbg.CreateTarget(self.exe) + self.target = self.dbg.CreateTarget(self.exe) self.launch_info = lldb.SBLaunchInfo([self.exe]) - self.launch_info.SetWorkingDirectory(self.get_process_working_directory()) - + self.launch_info.SetWorkingDirectory( + self.get_process_working_directory()) + def redirect_stdin(self): '''Redirect STDIN (file descriptor 0) to use our input.txt file @@ -140,43 +151,49 @@ class ProcessIOTestCase(TestBase): # clean slate for the next test case. def cleanup(): os.unlink(self.local_input_file) - #TODO: add 'platform delete-file' file command - #if lldb.remote_platform: + # TODO: add 'platform delete-file' file command + # if lldb.remote_platform: # self.runCmd('platform delete-file "{remote}"'.format(remote=self.input_file)) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.launch_info.AddOpenFileAction(0, self.input_file, True, False); - + self.launch_info.AddOpenFileAction(0, self.input_file, True, False) + def redirect_stdout(self): '''Redirect STDOUT (file descriptor 1) to use our output.txt file''' - self.launch_info.AddOpenFileAction(1, self.output_file, False, True); - + self.launch_info.AddOpenFileAction(1, self.output_file, False, True) + def redirect_stderr(self): '''Redirect STDERR (file descriptor 2) to use our error.txt file''' - self.launch_info.AddOpenFileAction(2, self.error_file, False, True); - + self.launch_info.AddOpenFileAction(2, self.error_file, False, True) + def run_process(self, put_stdin): '''Run the process to completion and optionally put lines to STDIN via the API if "put_stdin" is True''' # Set the breakpoints - self.breakpoint = self.target.BreakpointCreateBySourceRegex('Set breakpoint here', lldb.SBFileSpec("main.c")) - self.assertTrue(self.breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT) + self.breakpoint = self.target.BreakpointCreateBySourceRegex( + 'Set breakpoint here', lldb.SBFileSpec("main.c")) + self.assertTrue( + self.breakpoint.GetNumLocations() > 0, + VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. error = lldb.SBError() # This should launch the process and it should exit by the time we get back # because we have synchronous mode enabled - self.process = self.target.Launch (self.launch_info, error) + self.process = self.target.Launch(self.launch_info, error) - self.assertTrue(error.Success(), "Make sure process launched successfully") + self.assertTrue( + error.Success(), + "Make sure process launched successfully") self.assertTrue(self.process, PROCESS_IS_VALID) if self.TraceOn(): print("process launched.") # Frame #0 should be at our breakpoint. - threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, self.breakpoint) - + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, self.breakpoint) + self.assertTrue(len(threads) == 1) self.thread = threads[0] self.frame = self.thread.frames[0] @@ -189,13 +206,13 @@ class ProcessIOTestCase(TestBase): if put_stdin: for line in self.lines: self.process.PutSTDIN(line + "\n") - + # Let process continue so it will exit self.process.Continue() state = self.process.GetState() self.assertTrue(state == lldb.eStateExited, PROCESS_IS_VALID) - - def check_process_output (self, output, error): + + def check_process_output(self, output, error): # Since we launched the process without specifying stdin/out/err, # a pseudo terminal is used for stdout/err, and we are satisfied # once "input line=>1" appears in stdout. @@ -203,10 +220,14 @@ class ProcessIOTestCase(TestBase): if self.TraceOn(): print("output = '%s'" % output) print("error = '%s'" % error) - + for line in self.lines: check_line = 'input line to stdout: %s' % (line) - self.assertTrue(check_line in output, "verify stdout line shows up in STDOUT") + self.assertTrue( + check_line in output, + "verify stdout line shows up in STDOUT") for line in self.lines: check_line = 'input line to stderr: %s' % (line) - self.assertTrue(check_line in error, "verify stderr line shows up in STDERR") + self.assertTrue( + check_line in error, + "verify stderr line shows up in STDERR") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py b/lldb/packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py index f56fd96e466..a84d0004c18 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py @@ -5,12 +5,13 @@ Check that SBValue.GetValueAsSigned() does the right thing for a 32-bit -1. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + class Radar12481949DataFormatterTestCase(TestBase): # test for rdar://problem/12481949 @@ -27,14 +28,15 @@ class Radar12481949DataFormatterTestCase(TestBase): self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) # This is the function to remove the custom formats in order to have a # clean slate for the next test case. @@ -45,10 +47,22 @@ class Radar12481949DataFormatterTestCase(TestBase): # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) - self.assertTrue(self.frame().FindVariable("myvar").GetValueAsSigned() == -1, "GetValueAsSigned() says -1") - self.assertTrue(self.frame().FindVariable("myvar").GetValueAsSigned() != 0xFFFFFFFF, "GetValueAsSigned() does not say 0xFFFFFFFF") - self.assertTrue(self.frame().FindVariable("myvar").GetValueAsSigned() != 0xFFFFFFFFFFFFFFFF, "GetValueAsSigned() does not say 0xFFFFFFFFFFFFFFFF") + self.assertTrue( + self.frame().FindVariable("myvar").GetValueAsSigned() == -1, + "GetValueAsSigned() says -1") + self.assertTrue( + self.frame().FindVariable("myvar").GetValueAsSigned() != 0xFFFFFFFF, + "GetValueAsSigned() does not say 0xFFFFFFFF") + self.assertTrue( + self.frame().FindVariable("myvar").GetValueAsSigned() != 0xFFFFFFFFFFFFFFFF, + "GetValueAsSigned() does not say 0xFFFFFFFFFFFFFFFF") - self.assertTrue(self.frame().FindVariable("myvar").GetValueAsUnsigned() != -1, "GetValueAsUnsigned() does not say -1") - self.assertTrue(self.frame().FindVariable("myvar").GetValueAsUnsigned() == 0xFFFFFFFF, "GetValueAsUnsigned() says 0xFFFFFFFF") - self.assertTrue(self.frame().FindVariable("myvar").GetValueAsUnsigned() != 0xFFFFFFFFFFFFFFFF, "GetValueAsUnsigned() does not says 0xFFFFFFFFFFFFFFFF") + self.assertTrue( + self.frame().FindVariable("myvar").GetValueAsUnsigned() != -1, + "GetValueAsUnsigned() does not say -1") + self.assertTrue( + self.frame().FindVariable("myvar").GetValueAsUnsigned() == 0xFFFFFFFF, + "GetValueAsUnsigned() says 0xFFFFFFFF") + self.assertTrue( + self.frame().FindVariable("myvar").GetValueAsUnsigned() != 0xFFFFFFFFFFFFFFFF, + "GetValueAsUnsigned() does not says 0xFFFFFFFFFFFFFFFF") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py b/lldb/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py index d8e9515973f..e853d6567e7 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py @@ -3,7 +3,6 @@ from __future__ import print_function - from math import fabs import os import lldb @@ -11,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SBDataAPICase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,21 +26,23 @@ class SBDataAPICase(TestBase): """Test the SBData APIs.""" self.build() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - - lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) - + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + self.runCmd("run", RUN_SUCCEEDED) - + # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + target = self.dbg.GetSelectedTarget() - + process = target.GetProcess() - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) self.assertIsNotNone(thread) frame = thread.GetSelectedFrame() @@ -67,8 +69,17 @@ class SBDataAPICase(TestBase): high = data.GetSignedInt16(error, offset) self.assertTrue(error.Success()) offset += 2 - self.assertTrue ((low == 9 and high == 0) or (low == 0 and high == 9), 'foo[0].b == 9') - self.assertTrue( fabs(data.GetFloat(error, offset) - 3.14) < 1, 'foo[0].c == 3.14') + self.assertTrue( + (low == 9 and high == 0) or ( + low == 0 and high == 9), + 'foo[0].b == 9') + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 3.14) < 1, + 'foo[0].c == 3.14') self.assertTrue(error.Success()) offset += 4 self.assert_data(data.GetUnsignedInt32, offset, 8) @@ -90,18 +101,22 @@ class SBDataAPICase(TestBase): offset += 4 self.assert_data(data.GetSignedInt32, offset, 7) offset += 8 - self.assertTrue(data.GetUnsignedInt32(error, offset) == 0, 'do not read beyond end') + self.assertTrue( + data.GetUnsignedInt32( + error, + offset) == 0, + 'do not read beyond end') self.assertTrue(not error.Success()) - error.Clear() # clear the error for the next test + error.Clear() # clear the error for the next test star_foobar = foobar.Dereference() self.assertTrue(star_foobar.IsValid()) - + data = star_foobar.GetData() if self.TraceOn(): print(data) - + offset = 0 self.assert_data(data.GetUnsignedInt32, offset, 1) offset += 4 @@ -113,13 +128,16 @@ class SBDataAPICase(TestBase): # http://llvm.org/bugs/show_bug.cgi?id=11579 # lldb::SBValue::CreateValueFromAddress does not verify SBType::GetPointerType succeeds # This should not crash LLDB. - nothing = foobar.CreateValueFromAddress("nothing", foobar_addr, star_foobar.GetType().GetBasicType(lldb.eBasicTypeInvalid)) + nothing = foobar.CreateValueFromAddress( + "nothing", foobar_addr, star_foobar.GetType().GetBasicType( + lldb.eBasicTypeInvalid)) - new_foobar = foobar.CreateValueFromAddress("f00", foobar_addr, star_foobar.GetType()) + new_foobar = foobar.CreateValueFromAddress( + "f00", foobar_addr, star_foobar.GetType()) self.assertTrue(new_foobar.IsValid()) if self.TraceOn(): print(new_foobar) - + data = new_foobar.GetData() if self.TraceOn(): @@ -127,7 +145,8 @@ class SBDataAPICase(TestBase): self.assertTrue(data.uint32[0] == 8, 'then foo[1].a == 8') self.assertTrue(data.uint32[1] == 7, 'then foo[1].b == 7') - self.assertTrue(fabs(data.float[2] - 3.14) < 1, 'foo[1].c == 3.14') # exploiting that sizeof(uint32) == sizeof(float) + # exploiting that sizeof(uint32) == sizeof(float) + self.assertTrue(fabs(data.float[2] - 3.14) < 1, 'foo[1].c == 3.14') self.runCmd("n") @@ -136,7 +155,13 @@ class SBDataAPICase(TestBase): offset += 4 self.assert_data(data.GetUnsignedInt32, offset, 7) offset += 4 - self.assertTrue(fabs(data.GetFloat(error, offset) - 3.14) < 1, 'foo[1].c == 3.14') + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 3.14) < 1, + 'foo[1].c == 3.14') self.assertTrue(error.Success()) data = new_foobar.GetData() @@ -149,7 +174,13 @@ class SBDataAPICase(TestBase): offset += 4 self.assert_data(data.GetUnsignedInt32, offset, 7) offset += 4 - self.assertTrue(fabs(data.GetFloat(error, offset) - 6.28) < 1, 'foo[1].c == 6.28') + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 6.28) < 1, + 'foo[1].c == 6.28') self.assertTrue(error.Success()) self.runCmd("n") @@ -169,35 +200,61 @@ class SBDataAPICase(TestBase): offset += 4 self.assert_data(data.GetUnsignedInt32, offset, 2) offset += 4 - self.assertTrue(fabs(data.GetFloat(error, offset) - 3) < 1, 'barfoo[0].c == 3') + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 3) < 1, + 'barfoo[0].c == 3') self.assertTrue(error.Success()) offset += 4 self.assert_data(data.GetUnsignedInt32, offset, 4) offset += 4 self.assert_data(data.GetUnsignedInt32, offset, 5) offset += 4 - self.assertTrue(fabs(data.GetFloat(error, offset) - 6) < 1, 'barfoo[1].c == 6') + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 6) < 1, + 'barfoo[1].c == 6') self.assertTrue(error.Success()) - new_object = barfoo.CreateValueFromData("new_object",data,barfoo.GetType().GetBasicType(lldb.eBasicTypeInt)) + new_object = barfoo.CreateValueFromData( + "new_object", data, barfoo.GetType().GetBasicType( + lldb.eBasicTypeInt)) if self.TraceOn(): print(new_object) - + self.assertTrue(new_object.GetValue() == "1", 'new_object == 1') if data.GetByteOrder() == lldb.eByteOrderBig: - data.SetData(error, '\0\0\0A', data.GetByteOrder(), data.GetAddressByteSize()) + data.SetData( + error, + '\0\0\0A', + data.GetByteOrder(), + data.GetAddressByteSize()) else: - data.SetData(error, 'A\0\0\0', data.GetByteOrder(), data.GetAddressByteSize()) + data.SetData( + error, + 'A\0\0\0', + data.GetByteOrder(), + data.GetAddressByteSize()) self.assertTrue(error.Success()) - + data2 = lldb.SBData() - data2.SetData(error, 'BCD', data.GetByteOrder(), data.GetAddressByteSize()) + data2.SetData( + error, + 'BCD', + data.GetByteOrder(), + data.GetAddressByteSize()) self.assertTrue(error.Success()) data.Append(data2) - + if self.TraceOn(): print(data) @@ -213,74 +270,160 @@ class SBDataAPICase(TestBase): offset += 1 # check the new API calls introduced per LLVM llvm.org/prenhancement request - # 11619 (Allow creating SBData values from arrays or primitives in Python) + # 11619 (Allow creating SBData values from arrays or primitives in + # Python) hello_str = "hello!" - data2 = lldb.SBData.CreateDataFromCString(process.GetByteOrder(),process.GetAddressByteSize(),hello_str) + data2 = lldb.SBData.CreateDataFromCString( + process.GetByteOrder(), process.GetAddressByteSize(), hello_str) self.assertTrue(len(data2.uint8) == len(hello_str)) self.assertTrue(data2.uint8[0] == 104, 'h == 104') self.assertTrue(data2.uint8[1] == 101, 'e == 101') self.assertTrue(data2.uint8[2] == 108, 'l == 108') - self.assert_data(data2.GetUnsignedInt8, 3, 108) # l + self.assert_data(data2.GetUnsignedInt8, 3, 108) # l self.assertTrue(data2.uint8[4] == 111, 'o == 111') - self.assert_data(data2.GetUnsignedInt8, 5, 33) # ! + self.assert_data(data2.GetUnsignedInt8, 5, 33) # ! - uint_lists = [ [1,2,3,4,5], [int(i) for i in [1, 2, 3, 4, 5]] ] - int_lists = [ [2, -2], [int(i) for i in [2, -2]] ] + uint_lists = [[1, 2, 3, 4, 5], [int(i) for i in [1, 2, 3, 4, 5]]] + int_lists = [[2, -2], [int(i) for i in [2, -2]]] for l in uint_lists: - data2 = lldb.SBData.CreateDataFromUInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), l) + data2 = lldb.SBData.CreateDataFromUInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) self.assert_data(data2.GetUnsignedInt64, 0, 1) self.assert_data(data2.GetUnsignedInt64, 8, 2) self.assert_data(data2.GetUnsignedInt64, 16, 3) self.assert_data(data2.GetUnsignedInt64, 24, 4) self.assert_data(data2.GetUnsignedInt64, 32, 5) - - self.assertTrue(data2.uint64s == [1,2,3,4,5], 'read_data_helper failure: data2 == [1,2,3,4,5]') + + self.assertTrue( + data2.uint64s == [ + 1, + 2, + 3, + 4, + 5], + 'read_data_helper failure: data2 == [1,2,3,4,5]') for l in int_lists: - data2 = lldb.SBData.CreateDataFromSInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), l) - self.assertTrue(data2.sint32[0:2] == [2,-2], 'signed32 data2 = [2,-2]') - - data2.Append(lldb.SBData.CreateDataFromSInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), int_lists[0])) + data2 = lldb.SBData.CreateDataFromSInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) + self.assertTrue( + data2.sint32[ + 0:2] == [ + 2, -2], 'signed32 data2 = [2,-2]') + + data2.Append( + lldb.SBData.CreateDataFromSInt64Array( + process.GetByteOrder(), + process.GetAddressByteSize(), + int_lists[0])) self.assert_data(data2.GetSignedInt32, 0, 2) self.assert_data(data2.GetSignedInt32, 4, -2) - self.assertTrue(data2.sint64[1:3] == [2,-2], 'signed64 data2 = [2,-2]') + self.assertTrue( + data2.sint64[ + 1:3] == [ + 2, -2], 'signed64 data2 = [2,-2]') for l in int_lists: - data2 = lldb.SBData.CreateDataFromSInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), l) + data2 = lldb.SBData.CreateDataFromSInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) self.assert_data(data2.GetSignedInt64, 0, 2) self.assert_data(data2.GetSignedInt64, 8, -2) - self.assertTrue(data2.sint64[0:2] == [2,-2], 'signed64 data2 = [2,-2]') + self.assertTrue( + data2.sint64[ + 0:2] == [ + 2, -2], 'signed64 data2 = [2,-2]') for l in uint_lists: - data2 = lldb.SBData.CreateDataFromUInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), l) - self.assert_data(data2.GetUnsignedInt32,0, 1) - self.assert_data(data2.GetUnsignedInt32,4, 2) - self.assert_data(data2.GetUnsignedInt32,8, 3) - self.assert_data(data2.GetUnsignedInt32,12, 4) - self.assert_data(data2.GetUnsignedInt32,16, 5) + data2 = lldb.SBData.CreateDataFromUInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) + self.assert_data(data2.GetUnsignedInt32, 0, 1) + self.assert_data(data2.GetUnsignedInt32, 4, 2) + self.assert_data(data2.GetUnsignedInt32, 8, 3) + self.assert_data(data2.GetUnsignedInt32, 12, 4) + self.assert_data(data2.GetUnsignedInt32, 16, 5) bool_list = [True, True, False, False, True, False] - data2 = lldb.SBData.CreateDataFromSInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list) - self.assertTrue(data2.sint32[0:6] == [1, 1, 0, 0, 1, 0], 'signed32 data2 = [1, 1, 0, 0, 1, 0]') - - data2 = lldb.SBData.CreateDataFromUInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list) - self.assertTrue(data2.uint32[0:6] == [1, 1, 0, 0, 1, 0], 'unsigned32 data2 = [1, 1, 0, 0, 1, 0]') - - data2 = lldb.SBData.CreateDataFromSInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list) - self.assertTrue(data2.sint64[0:6] == [1, 1, 0, 0, 1, 0], 'signed64 data2 = [1, 1, 0, 0, 1, 0]') - - data2 = lldb.SBData.CreateDataFromUInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list) - self.assertTrue(data2.uint64[0:6] == [1, 1, 0, 0, 1, 0], 'signed64 data2 = [1, 1, 0, 0, 1, 0]') - - data2 = lldb.SBData.CreateDataFromDoubleArray(process.GetByteOrder(),process.GetAddressByteSize(),[3.14,6.28,2.71]) - self.assertTrue( fabs(data2.GetDouble(error,0) - 3.14) < 0.5, 'double data2[0] = 3.14') + data2 = lldb.SBData.CreateDataFromSInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.sint32[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'signed32 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromUInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.uint32[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'unsigned32 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromSInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.sint64[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'signed64 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromUInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.uint64[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'signed64 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromDoubleArray( + process.GetByteOrder(), process.GetAddressByteSize(), [ + 3.14, 6.28, 2.71]) + self.assertTrue( + fabs( + data2.GetDouble( + error, + 0) - + 3.14) < 0.5, + 'double data2[0] = 3.14') self.assertTrue(error.Success()) - self.assertTrue( fabs(data2.GetDouble(error,8) - 6.28) < 0.5, 'double data2[1] = 6.28') + self.assertTrue( + fabs( + data2.GetDouble( + error, + 8) - + 6.28) < 0.5, + 'double data2[1] = 6.28') self.assertTrue(error.Success()) - self.assertTrue( fabs(data2.GetDouble(error,16) - 2.71) < 0.5, 'double data2[2] = 2.71') + self.assertTrue( + fabs( + data2.GetDouble( + error, + 16) - + 2.71) < 0.5, + 'double data2[2] = 2.71') self.assertTrue(error.Success()) data2 = lldb.SBData() @@ -294,50 +437,90 @@ class SBDataAPICase(TestBase): self.assert_data(data2.GetUnsignedInt8, 4, 111) self.assert_data(data2.GetUnsignedInt8, 5, 33) - data2.SetDataFromUInt64Array([1,2,3,4,5]) + data2.SetDataFromUInt64Array([1, 2, 3, 4, 5]) self.assert_data(data2.GetUnsignedInt64, 0, 1) - self.assert_data(data2.GetUnsignedInt64, 8, 2) + self.assert_data(data2.GetUnsignedInt64, 8, 2) self.assert_data(data2.GetUnsignedInt64, 16, 3) self.assert_data(data2.GetUnsignedInt64, 24, 4) self.assert_data(data2.GetUnsignedInt64, 32, 5) - self.assertTrue(data2.uint64[0] == 1, 'read_data_helper failure: set data2[0] = 1') - self.assertTrue(data2.uint64[1] == 2, 'read_data_helper failure: set data2[1] = 2') - self.assertTrue(data2.uint64[2] == 3, 'read_data_helper failure: set data2[2] = 3') - self.assertTrue(data2.uint64[3] == 4, 'read_data_helper failure: set data2[3] = 4') - self.assertTrue(data2.uint64[4] == 5, 'read_data_helper failure: set data2[4] = 5') - - self.assertTrue(data2.uint64[0:2] == [1,2], 'read_data_helper failure: set data2[0:2] = [1,2]') + self.assertTrue( + data2.uint64[0] == 1, + 'read_data_helper failure: set data2[0] = 1') + self.assertTrue( + data2.uint64[1] == 2, + 'read_data_helper failure: set data2[1] = 2') + self.assertTrue( + data2.uint64[2] == 3, + 'read_data_helper failure: set data2[2] = 3') + self.assertTrue( + data2.uint64[3] == 4, + 'read_data_helper failure: set data2[3] = 4') + self.assertTrue( + data2.uint64[4] == 5, + 'read_data_helper failure: set data2[4] = 5') + + self.assertTrue( + data2.uint64[ + 0:2] == [ + 1, + 2], + 'read_data_helper failure: set data2[0:2] = [1,2]') data2.SetDataFromSInt32Array([2, -2]) self.assert_data(data2.GetSignedInt32, 0, 2) self.assert_data(data2.GetSignedInt32, 4, -2) - + data2.SetDataFromSInt64Array([2, -2]) self.assert_data(data2.GetSignedInt64, 0, 2) self.assert_data(data2.GetSignedInt64, 8, -2) - - data2.SetDataFromUInt32Array([1,2,3,4,5]) + + data2.SetDataFromUInt32Array([1, 2, 3, 4, 5]) self.assert_data(data2.GetUnsignedInt32, 0, 1) self.assert_data(data2.GetUnsignedInt32, 4, 2) self.assert_data(data2.GetUnsignedInt32, 8, 3) self.assert_data(data2.GetUnsignedInt32, 12, 4) self.assert_data(data2.GetUnsignedInt32, 16, 5) - - self.assertTrue(data2.uint32[0] == 1, 'read_data_helper failure: set 32-bit data2[0] = 1') - self.assertTrue(data2.uint32[1] == 2, 'read_data_helper failure: set 32-bit data2[1] = 2') - self.assertTrue(data2.uint32[2] == 3, 'read_data_helper failure: set 32-bit data2[2] = 3') - self.assertTrue(data2.uint32[3] == 4, 'read_data_helper failure: set 32-bit data2[3] = 4') - self.assertTrue(data2.uint32[4] == 5, 'read_data_helper failure: set 32-bit data2[4] = 5') - - data2.SetDataFromDoubleArray([3.14,6.28,2.71]) - self.assertTrue( fabs(data2.GetDouble(error,0) - 3.14) < 0.5, 'set double data2[0] = 3.14') - self.assertTrue( fabs(data2.GetDouble(error,8) - 6.28) < 0.5, 'set double data2[1] = 6.28') - self.assertTrue( fabs(data2.GetDouble(error,16) - 2.71) < 0.5, 'set double data2[2] = 2.71') - - self.assertTrue( fabs(data2.double[0] - 3.14) < 0.5, 'read_data_helper failure: set double data2[0] = 3.14') - self.assertTrue( fabs(data2.double[1] - 6.28) < 0.5, 'read_data_helper failure: set double data2[1] = 6.28') - self.assertTrue( fabs(data2.double[2] - 2.71) < 0.5, 'read_data_helper failure: set double data2[2] = 2.71') + + self.assertTrue( + data2.uint32[0] == 1, + 'read_data_helper failure: set 32-bit data2[0] = 1') + self.assertTrue( + data2.uint32[1] == 2, + 'read_data_helper failure: set 32-bit data2[1] = 2') + self.assertTrue( + data2.uint32[2] == 3, + 'read_data_helper failure: set 32-bit data2[2] = 3') + self.assertTrue( + data2.uint32[3] == 4, + 'read_data_helper failure: set 32-bit data2[3] = 4') + self.assertTrue( + data2.uint32[4] == 5, + 'read_data_helper failure: set 32-bit data2[4] = 5') + + data2.SetDataFromDoubleArray([3.14, 6.28, 2.71]) + self.assertTrue(fabs(data2.GetDouble(error, 0) - 3.14) + < 0.5, 'set double data2[0] = 3.14') + self.assertTrue(fabs(data2.GetDouble(error, 8) - 6.28) + < 0.5, 'set double data2[1] = 6.28') + self.assertTrue(fabs(data2.GetDouble(error, 16) - 2.71) + < 0.5, 'set double data2[2] = 2.71') + + self.assertTrue( + fabs( + data2.double[0] - + 3.14) < 0.5, + 'read_data_helper failure: set double data2[0] = 3.14') + self.assertTrue( + fabs( + data2.double[1] - + 6.28) < 0.5, + 'read_data_helper failure: set double data2[1] = 6.28') + self.assertTrue( + fabs( + data2.double[2] - + 2.71) < 0.5, + 'read_data_helper failure: set double data2[2] = 2.71') def assert_data(self, func, arg, expected): """ Asserts func(SBError error, arg) == expected. """ @@ -346,8 +529,9 @@ class SBDataAPICase(TestBase): if not error.Success(): stream = lldb.SBStream() error.GetDescription(stream) - self.assertTrue(error.Success(), - "%s(error, %s) did not succeed: %s" % (func.__name__, - arg, - stream.GetData())) - self.assertTrue(expected == result, "%s(error, %s) == %s != %s" % (func.__name__, arg, result, expected)) + self.assertTrue( + error.Success(), "%s(error, %s) did not succeed: %s" % + (func.__name__, arg, stream.GetData())) + self.assertTrue( + expected == result, "%s(error, %s) == %s != %s" % + (func.__name__, arg, result, expected)) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py b/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py index 49bc148dd57..9b0c1f5eaef 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py @@ -1,4 +1,6 @@ from lldbsuite.test import decorators from lldbsuite.test import lldbinline -lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIfFreeBSD,decorators.skipIfLinux,decorators.skipIfWindows]) +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, decorators.skipIfWindows]) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py b/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py index e726db7c2d0..eab3cbb30dd 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py @@ -3,13 +3,15 @@ from __future__ import print_function - -import os, sys, time +import os +import sys +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SBValuePersistTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,15 +24,15 @@ class SBValuePersistTestCase(TestBase): self.setTearDownCleanup() self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_source_regexp (self, "break here") + lldbutil.run_break_set_by_source_regexp(self, "break here") self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) - + substrs=['stopped', + 'stop reason = breakpoint']) + # This is the function to remove the custom formats in order to have a # clean slate for the next test case. def cleanup(): @@ -49,7 +51,7 @@ class SBValuePersistTestCase(TestBase): self.assertTrue(foo.IsValid(), "foo is not valid") self.assertTrue(bar.IsValid(), "bar is not valid") self.assertTrue(baz.IsValid(), "baz is not valid") - + fooPersist = foo.Persist() barPersist = bar.Persist() bazPersist = baz.Persist() @@ -58,18 +60,26 @@ class SBValuePersistTestCase(TestBase): self.assertTrue(barPersist.IsValid(), "barPersist is not valid") self.assertTrue(bazPersist.IsValid(), "bazPersist is not valid") - self.assertTrue(fooPersist.GetValueAsUnsigned(0) == 10, "fooPersist != 10") - self.assertTrue(barPersist.GetPointeeData().sint32[0] == 4, "barPersist != 4") + self.assertTrue( + fooPersist.GetValueAsUnsigned(0) == 10, + "fooPersist != 10") + self.assertTrue( + barPersist.GetPointeeData().sint32[0] == 4, + "barPersist != 4") self.assertTrue(bazPersist.GetSummary() == '"85"', "bazPersist != 85") - + self.runCmd("continue") self.assertTrue(fooPersist.IsValid(), "fooPersist is not valid") self.assertTrue(barPersist.IsValid(), "barPersist is not valid") self.assertTrue(bazPersist.IsValid(), "bazPersist is not valid") - self.assertTrue(fooPersist.GetValueAsUnsigned(0) == 10, "fooPersist != 10") - self.assertTrue(barPersist.GetPointeeData().sint32[0] == 4, "barPersist != 4") + self.assertTrue( + fooPersist.GetValueAsUnsigned(0) == 10, + "fooPersist != 10") + self.assertTrue( + barPersist.GetPointeeData().sint32[0] == 4, + "barPersist != 4") self.assertTrue(bazPersist.GetSummary() == '"85"', "bazPersist != 85") - - self.expect("expr *(%s)" % (barPersist.GetName()), substrs = ['= 4']) + + self.expect("expr *(%s)" % (barPersist.GetName()), substrs=['= 4']) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py index 29e089f6b84..5893dfb8f7f 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py @@ -9,6 +9,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SectionAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,7 +23,7 @@ class SectionAPITestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - # find the .data section of the main module + # find the .data section of the main module mod = target.GetModuleAtIndex(0) data_section = None for s in mod.sections: @@ -36,7 +37,7 @@ class SectionAPITestCase(TestBase): sect_type = ss.GetSectionType() if sect_type == lldb.eSectionTypeData: data_section = ss - break + break self.assertIsNotNone(data_section) self.assertEqual(data_section.target_byte_size, 1) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py index 733b0c9d676..76b1d603f55 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py @@ -5,19 +5,20 @@ Test SBProcess APIs, including ReadMemory(), WriteMemory(), and others. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from lldbsuite.test.lldbutil import get_stopped_thread, state_type_to_str + class SignalsAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(['pyapi']) - @skipIfWindows # Windows doesn't have signals + @skipIfWindows # Windows doesn't have signals def test_ignore_signal(self): """Test Python SBUnixSignals.Suppress/Stop/Notify() API.""" self.build() @@ -27,15 +28,20 @@ class SignalsAPITestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - line = line_number("main.cpp", "// Set break point at this line and setup signal ignores.") + line = line_number( + "main.cpp", + "// Set break point at this line and setup signal ignores.") breakpoint = target.BreakpointCreateByLocation("main.cpp", line) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") unix_signals = process.GetUnixSignals() sigint = unix_signals.GetSignalNumberFromName("SIGINT") @@ -44,5 +50,9 @@ class SignalsAPITestCase(TestBase): unix_signals.SetShouldNotify(sigint, False) process.Continue() - self.assertTrue(process.state == lldb.eStateExited, "The process should have exited") - self.assertTrue(process.GetExitStatus() == 0, "The process should have returned 0") + self.assertTrue( + process.state == lldb.eStateExited, + "The process should have exited") + self.assertTrue( + process.GetExitStatus() == 0, + "The process should have returned 0") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py b/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py index 5d0d01d7a2b..85ecb69a91f 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py @@ -5,7 +5,6 @@ Test SBSymbolContext APIs. from __future__ import print_function - import os import re import time @@ -15,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SymbolContextAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,7 +23,8 @@ class SymbolContextAPITestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line = line_number('main.c', '// Find the line number of function "c" here.') + self.line = line_number( + 'main.c', '// Find the line number of function "c" here.') @add_test_categories(['pyapi']) @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") @@ -44,13 +45,16 @@ class SymbolContextAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line. from lldbsuite.test.lldbutil import get_stopped_thread thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") frame0 = thread.GetFrameAtIndex(0) self.assertTrue(frame0.GetLineEntry().GetLine() == self.line) @@ -62,11 +66,17 @@ class SymbolContextAPITestCase(TestBase): module = context.GetModule() desc = lldbutil.get_description(module) self.expect(desc, "The module should match", exe=False, - substrs = [os.path.join(self.mydir, 'a.out')]) + substrs=[os.path.join(self.mydir, 'a.out')]) compileUnit = context.GetCompileUnit() - self.expect(str(compileUnit), "The compile unit should match", exe=False, - substrs = [os.path.join(self.mydir, 'main.c')]) + self.expect( + str(compileUnit), + "The compile unit should match", + exe=False, + substrs=[ + os.path.join( + self.mydir, + 'main.c')]) function = context.GetFunction() self.assertTrue(function) @@ -78,15 +88,21 @@ class SymbolContextAPITestCase(TestBase): lineEntry = context.GetLineEntry() #print("line entry:", lineEntry) - self.expect(lineEntry.GetFileSpec().GetDirectory(), "The line entry should have the correct directory", - exe=False, - substrs = [self.mydir]) - self.expect(lineEntry.GetFileSpec().GetFilename(), "The line entry should have the correct filename", - exe=False, - substrs = ['main.c']) + self.expect( + lineEntry.GetFileSpec().GetDirectory(), + "The line entry should have the correct directory", + exe=False, + substrs=[ + self.mydir]) + self.expect( + lineEntry.GetFileSpec().GetFilename(), + "The line entry should have the correct filename", + exe=False, + substrs=['main.c']) self.assertTrue(lineEntry.GetLine() == self.line, "The line entry's line number should match ") symbol = context.GetSymbol() - self.assertTrue(function.GetName() == symbol.GetName() and symbol.GetName() == 'c', - "The symbol name should be 'c'") + self.assertTrue( + function.GetName() == symbol.GetName() and symbol.GetName() == 'c', + "The symbol name should be 'c'") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py b/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py index 1d8d7011457..b6a26fb3186 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py @@ -11,6 +11,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SymbolContextTwoFilesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -30,7 +31,10 @@ class SymbolContextTwoFilesTestCase(TestBase): for symbol_name in ["struct1::f()", "struct2::f()"]: sc_list = module.FindFunctions(symbol_name, lldb.eSymbolTypeCode) self.assertTrue(1, sc_list.GetSize()) - symbol_address = sc_list.GetContextAtIndex(0).GetSymbol().GetStartAddress() + symbol_address = sc_list.GetContextAtIndex( + 0).GetSymbol().GetStartAddress() self.assertTrue(symbol_address.IsValid()) - sc_by_address = module.ResolveSymbolContextForAddress(symbol_address, lldb.eSymbolContextFunction) - self.assertEqual(symbol_name, sc_by_address.GetFunction().GetName()) + sc_by_address = module.ResolveSymbolContextForAddress( + symbol_address, lldb.eSymbolContextFunction) + self.assertEqual(symbol_name, + sc_by_address.GetFunction().GetName()) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py index 1278742675f..adbdc524949 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py @@ -5,15 +5,16 @@ Test SBTarget APIs. from __future__ import print_function - import unittest2 -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TargetAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,11 +23,14 @@ class TargetAPITestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number to of function 'c'. - self.line1 = line_number('main.c', '// Find the line number for breakpoint 1 here.') - self.line2 = line_number('main.c', '// Find the line number for breakpoint 2 here.') - self.line_main = line_number("main.c", "// Set a break at entry to main.") - - #rdar://problem/9700873 + self.line1 = line_number( + 'main.c', '// Find the line number for breakpoint 1 here.') + self.line2 = line_number( + 'main.c', '// Find the line number for breakpoint 2 here.') + self.line_main = line_number( + "main.c", "// Set a break at entry to main.") + + # rdar://problem/9700873 # Find global variable value fails for dwarf if inferior not started # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94) # @@ -101,20 +105,20 @@ class TargetAPITestCase(TestBase): target = self.create_simple_target('b.out') # find the file address in the .data section of the main - # module + # module data_section = self.find_data_section(target) data_section_addr = data_section.file_addr # resolve the above address, and compare the address produced - # by the resolution against the original address/section + # by the resolution against the original address/section res_file_addr = target.ResolveFileAddress(data_section_addr) self.assertTrue(res_file_addr.IsValid()) - self.assertEqual(data_section_addr, res_file_addr.file_addr) + self.assertEqual(data_section_addr, res_file_addr.file_addr) data_section2 = res_file_addr.section self.assertIsNotNone(data_section2) - self.assertEqual(data_section.name, data_section2.name) + self.assertEqual(data_section.name, data_section2.name) @add_test_categories(['pyapi']) def test_read_memory(self): @@ -123,18 +127,20 @@ class TargetAPITestCase(TestBase): self.setTearDownCleanup(dictionary=d) target = self.create_simple_target('b.out') - breakpoint = target.BreakpointCreateByLocation("main.c", self.line_main) + breakpoint = target.BreakpointCreateByLocation( + "main.c", self.line_main) self.assertTrue(breakpoint, VALID_BREAKPOINT) # Put debugger into synchronous mode so when we target.LaunchSimple returns # it will guaranteed to be at the breakpoint self.dbg.SetAsync(False) - + # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # find the file address in the .data section of the main - # module + # module data_section = self.find_data_section(target) sb_addr = lldb.SBAddress(data_section, 0) error = lldb.SBError() @@ -162,7 +168,7 @@ class TargetAPITestCase(TestBase): sect_type = ss.GetSectionType() if sect_type == lldb.eSectionTypeData: data_section = ss - break + break self.assertIsNotNone(data_section) return data_section @@ -175,7 +181,7 @@ class TargetAPITestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - #rdar://problem/9700873 + # rdar://problem/9700873 # Find global variable value fails for dwarf if inferior not started # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94) # @@ -186,30 +192,37 @@ class TargetAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Make sure we hit our breakpoint: - thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint) - self.assertTrue (len(thread_list) == 1) + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) - value_list = target.FindGlobalVariables('my_global_var_of_char_type', 3) + value_list = target.FindGlobalVariables( + 'my_global_var_of_char_type', 3) self.assertTrue(value_list.GetSize() == 1) my_global_var = value_list.GetValueAtIndex(0) self.DebugSBValue(my_global_var) self.assertTrue(my_global_var) self.expect(my_global_var.GetName(), exe=False, - startstr = "my_global_var_of_char_type") + startstr="my_global_var_of_char_type") self.expect(my_global_var.GetTypeName(), exe=False, - startstr = "char") + startstr="char") self.expect(my_global_var.GetValue(), exe=False, - startstr = "'X'") + startstr="'X'") - # While we are at it, let's also exercise the similar SBModule.FindGlobalVariables() API. + # While we are at it, let's also exercise the similar + # SBModule.FindGlobalVariables() API. for m in target.module_iter(): - if os.path.normpath(m.GetFileSpec().GetDirectory()) == os.getcwd() and m.GetFileSpec().GetFilename() == exe_name: - value_list = m.FindGlobalVariables(target, 'my_global_var_of_char_type', 3) + if os.path.normpath(m.GetFileSpec().GetDirectory()) == os.getcwd( + ) and m.GetFileSpec().GetFilename() == exe_name: + value_list = m.FindGlobalVariables( + target, 'my_global_var_of_char_type', 3) self.assertTrue(value_list.GetSize() == 1) - self.assertTrue(value_list.GetValueAtIndex(0).GetValue() == "'X'") + self.assertTrue( + value_list.GetValueAtIndex(0).GetValue() == "'X'") break def find_functions(self, exe_name): @@ -224,8 +237,9 @@ class TargetAPITestCase(TestBase): self.assertTrue(list.GetSize() == 1) for sc in list: - self.assertTrue(sc.GetModule().GetFileSpec().GetFilename() == exe_name) - self.assertTrue(sc.GetSymbol().GetName() == 'c') + self.assertTrue( + sc.GetModule().GetFileSpec().GetFilename() == exe_name) + self.assertTrue(sc.GetSymbol().GetName() == 'c') def get_description(self): """Exercise SBTaget.GetDescription() API.""" @@ -237,21 +251,22 @@ class TargetAPITestCase(TestBase): from lldbsuite.test.lldbutil import get_description - # get_description() allows no option to mean lldb.eDescriptionLevelBrief. + # get_description() allows no option to mean + # lldb.eDescriptionLevelBrief. desc = get_description(target) #desc = get_description(target, option=lldb.eDescriptionLevelBrief) if not desc: self.fail("SBTarget.GetDescription() failed") self.expect(desc, exe=False, - substrs = ['a.out']) + substrs=['a.out']) self.expect(desc, exe=False, matching=False, - substrs = ['Target', 'Module', 'Breakpoint']) + substrs=['Target', 'Module', 'Breakpoint']) desc = get_description(target, option=lldb.eDescriptionLevelFull) if not desc: self.fail("SBTarget.GetDescription() failed") self.expect(desc, exe=False, - substrs = ['a.out', 'Target', 'Module', 'Breakpoint']) + substrs=['a.out', 'Target', 'Module', 'Breakpoint']) @not_remote_testsuite_ready def launch_new_process_and_redirect_stdout(self): @@ -263,28 +278,44 @@ class TargetAPITestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done. - # We should still see the entire stdout redirected once the process is finished. + # We should still see the entire stdout redirected once the process is + # finished. line = line_number('main.c', '// a(3) -> c(3)') breakpoint = target.BreakpointCreateByLocation('main.c', line) # Now launch the process, do not stop at entry point, and redirect stdout to "stdout.txt" file. - # The inferior should run to completion after "process.Continue()" call. - local_path = "stdout.txt"; + # The inferior should run to completion after "process.Continue()" + # call. + local_path = "stdout.txt" if lldb.remote_platform: - stdout_path = lldbutil.append_to_process_working_directory("lldb-stdout-redirect.txt") + stdout_path = lldbutil.append_to_process_working_directory( + "lldb-stdout-redirect.txt") else: stdout_path = local_path error = lldb.SBError() - process = target.Launch (self.dbg.GetListener(), None, None, None, stdout_path, None, None, 0, False, error) + process = target.Launch( + self.dbg.GetListener(), + None, + None, + None, + stdout_path, + None, + None, + 0, + False, + error) process.Continue() #self.runCmd("process status") if lldb.remote_platform: # copy output file to host - lldb.remote_platform.Get(lldb.SBFileSpec(stdout_path), lldb.SBFileSpec(local_path)) + lldb.remote_platform.Get( + lldb.SBFileSpec(stdout_path), + lldb.SBFileSpec(local_path)) # The 'stdout.txt' file should now exist. - self.assertTrue(os.path.isfile("stdout.txt"), - "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.") + self.assertTrue( + os.path.isfile("stdout.txt"), + "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.") # Read the output file produced by running the program. with open('stdout.txt', 'r') as f: @@ -298,8 +329,7 @@ class TargetAPITestCase(TestBase): pass self.expect(output, exe=False, - substrs = ["a(1)", "b(2)", "a(3)"]) - + substrs=["a(1)", "b(2)", "a(3)"]) def resolve_symbol_context_with_address(self): """Exercise SBTaget.ResolveSymbolContextForAddress() API.""" @@ -322,13 +352,17 @@ class TargetAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.line1. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") #self.runCmd("process status") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() @@ -339,8 +373,11 @@ class TargetAPITestCase(TestBase): # Continue the inferior, the breakpoint 2 should be hit. process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") #self.runCmd("process status") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() @@ -351,9 +388,12 @@ class TargetAPITestCase(TestBase): #print("address1:", address1) #print("address2:", address2) - # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses from our line entry. - context1 = target.ResolveSymbolContextForAddress(address1, lldb.eSymbolContextEverything) - context2 = target.ResolveSymbolContextForAddress(address2, lldb.eSymbolContextEverything) + # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses + # from our line entry. + context1 = target.ResolveSymbolContextForAddress( + address1, lldb.eSymbolContextEverything) + context2 = target.ResolveSymbolContextForAddress( + address2, lldb.eSymbolContextEverything) self.assertTrue(context1 and context2) #print("context1:", context1) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py index 588aa66cf53..a1272cbcbce 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py @@ -5,14 +5,15 @@ Test SBThread APIs. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from lldbsuite.test.lldbutil import get_stopped_thread, get_caller_symbol + class ThreadAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -62,12 +63,17 @@ class ThreadAPITestCase(TestBase): # Call super's setUp(). TestBase.setUp(self) # Find the line number within main.cpp to break inside main(). - self.break_line = line_number("main.cpp", "// Set break point at this line and check variable 'my_char'.") - # Find the line numbers within main2.cpp for step_out_of_malloc_into_function_b() and step_over_3_times(). - self.step_out_of_malloc = line_number("main2.cpp", "// thread step-out of malloc into function b.") - self.after_3_step_overs = line_number("main2.cpp", "// we should reach here after 3 step-over's.") - - # We'll use the test method name as the exe_name for executable comppiled from main2.cpp. + self.break_line = line_number( + "main.cpp", "// Set break point at this line and check variable 'my_char'.") + # Find the line numbers within main2.cpp for + # step_out_of_malloc_into_function_b() and step_over_3_times(). + self.step_out_of_malloc = line_number( + "main2.cpp", "// thread step-out of malloc into function b.") + self.after_3_step_overs = line_number( + "main2.cpp", "// we should reach here after 3 step-over's.") + + # We'll use the test method name as the exe_name for executable + # comppiled from main2.cpp. self.exe_name = self.testMethodName def get_process(self): @@ -77,20 +83,25 @@ class ThreadAPITestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateByLocation("main.cpp", self.break_line) + breakpoint = target.BreakpointCreateByLocation( + "main.cpp", self.break_line) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") self.runCmd("process status") proc_of_thread = thread.GetProcess() #print("proc_of_thread:", proc_of_thread) - self.assertTrue(proc_of_thread.GetProcessID() == process.GetProcessID()) + self.assertTrue(proc_of_thread.GetProcessID() + == process.GetProcessID()) def get_stop_description(self): """Test Python SBThread.GetStopDescription() API.""" @@ -99,15 +110,19 @@ class ThreadAPITestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateByLocation("main.cpp", self.break_line) + breakpoint = target.BreakpointCreateByLocation( + "main.cpp", self.break_line) self.assertTrue(breakpoint, VALID_BREAKPOINT) #self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") #self.runCmd("process status") # Due to the typemap magic (see lldb.swig), we pass in an (int)length to GetStopDescription @@ -115,7 +130,7 @@ class ThreadAPITestCase(TestBase): # The 100 is just an arbitrary number specifying the buffer size. stop_description = thread.GetStopDescription(100) self.expect(stop_description, exe=False, - startstr = 'breakpoint') + startstr='breakpoint') def step_out_of_malloc_into_function_b(self, exe_name): """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b().""" @@ -128,21 +143,26 @@ class ThreadAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) while True: thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") caller_symbol = get_caller_symbol(thread) if not caller_symbol: - self.fail("Test failed: could not locate the caller symbol of malloc") + self.fail( + "Test failed: could not locate the caller symbol of malloc") # Our top frame may be an inlined function in malloc() (e.g., on # FreeBSD). Apply a simple heuristic of stepping out until we find # a non-malloc caller while caller_symbol.startswith("malloc"): thread.StepOut() - self.assertTrue(thread.IsValid(), "Thread valid after stepping to outer malloc") + self.assertTrue(thread.IsValid(), + "Thread valid after stepping to outer malloc") caller_symbol = get_caller_symbol(thread) if caller_symbol == "b(int)": @@ -155,8 +175,9 @@ class ThreadAPITestCase(TestBase): thread.StepOut() self.runCmd("thread backtrace") - self.assertTrue(thread.GetFrameAtIndex(0).GetLineEntry().GetLine() == self.step_out_of_malloc, - "step out of malloc into function b is successful") + self.assertTrue( + thread.GetFrameAtIndex(0).GetLineEntry().GetLine() == self.step_out_of_malloc, + "step out of malloc into function b is successful") def step_over_3_times(self, exe_name): """Test Python SBThread.StepOver() API.""" @@ -165,19 +186,23 @@ class ThreadAPITestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateByLocation('main2.cpp', self.step_out_of_malloc) + breakpoint = target.BreakpointCreateByLocation( + 'main2.cpp', self.step_out_of_malloc) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.step_out_of_malloc. self.assertTrue(process.GetState() == lldb.eStateStopped) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") self.runCmd("thread backtrace") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() @@ -188,7 +213,8 @@ class ThreadAPITestCase(TestBase): thread.StepOver() self.runCmd("thread backtrace") - # Verify that we are stopped at the correct source line number in main2.cpp. + # Verify that we are stopped at the correct source line number in + # main2.cpp. frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) @@ -206,19 +232,23 @@ class ThreadAPITestCase(TestBase): target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) - breakpoint = target.BreakpointCreateByLocation('main2.cpp', self.step_out_of_malloc) + breakpoint = target.BreakpointCreateByLocation( + 'main2.cpp', self.step_out_of_malloc) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.step_out_of_malloc. self.assertTrue(process.GetState() == lldb.eStateStopped) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") self.runCmd("thread backtrace") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() @@ -234,7 +264,7 @@ class ThreadAPITestCase(TestBase): # Disable the breakpoint. self.assertTrue(target.DisableAllBreakpoints()) self.runCmd("breakpoint list") - + thread.StepOver() thread.StepOver() thread.StepOver() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py b/lldb/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py index 20e899beee4..5ab742dac7c 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py @@ -5,7 +5,6 @@ Test SBType and SBTypeList API. from __future__ import print_function - import os import re import time @@ -15,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TypeAndTypeListTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -45,20 +45,27 @@ class TypeAndTypeListTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Get Frame #0. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) # Get the type 'Task'. type_list = target.FindTypes('Task') if self.TraceOn(): - print("Size of type_list from target.FindTypes('Task') query: %d" % type_list.GetSize()) - self.assertTrue(len(type_list) >= 1) # a second Task make be scared up by the Objective-C runtime + print( + "Size of type_list from target.FindTypes('Task') query: %d" % + type_list.GetSize()) + # a second Task make be scared up by the Objective-C runtime + self.assertTrue(len(type_list) >= 1) for type in type_list: self.assertTrue(type) self.DebugSBType(type) @@ -69,9 +76,13 @@ class TypeAndTypeListTestCase(TestBase): self.assertTrue(enum_member) self.DebugSBType(enum_member.type) elif field.name == "my_type_is_nameless": - self.assertTrue(field.type.IsAnonymousType(), "my_type_is_nameless has an anonymous type") + self.assertTrue( + field.type.IsAnonymousType(), + "my_type_is_nameless has an anonymous type") elif field.name == "my_type_is_named": - self.assertFalse(field.type.IsAnonymousType(), "my_type_is_named has a named type") + self.assertFalse( + field.type.IsAnonymousType(), + "my_type_is_named has a named type") # Pass an empty string. LLDB should not crash. :-) fuzz_types = target.FindTypes(None) @@ -87,7 +98,8 @@ class TypeAndTypeListTestCase(TestBase): self.assertTrue(task_ref_type) self.DebugSBType(task_ref_type) - # Get the pointer type of 'Task', which is the same as task_head's type. + # Get the pointer type of 'Task', which is the same as task_head's + # type. task_pointer_type = task_type.GetPointerType() self.assertTrue(task_pointer_type) self.DebugSBType(task_pointer_type) @@ -114,6 +126,7 @@ class TypeAndTypeListTestCase(TestBase): id_type = id.GetType() self.DebugSBType(id_type) - # SBType.GetBasicType() takes an enum 'BasicType' (lldb-enumerations.h). + # SBType.GetBasicType() takes an enum 'BasicType' + # (lldb-enumerations.h). int_type = id_type.GetBasicType(lldb.eBasicTypeInt) self.assertTrue(id_type == int_type) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py index 2a53177d28a..632244e8b9e 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py @@ -13,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ValueAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -43,13 +44,17 @@ class ValueAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Get Frame #0. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) # Get global variable 'days_of_week'. @@ -93,10 +98,11 @@ class ValueAPITestCase(TestBase): self.DebugSBValue(pointed) # While we are at it, verify that 'my_int_ptr' points to 'g_my_int'. - symbol = target.ResolveLoadAddress(int(pointed.GetLocation(), 0)).GetSymbol() + symbol = target.ResolveLoadAddress( + int(pointed.GetLocation(), 0)).GetSymbol() self.assertTrue(symbol) self.expect(symbol.GetName(), exe=False, - startstr = 'g_my_int') + startstr='g_my_int') # Get variable 'str_ptr'. value = frame0.FindVariable('str_ptr') @@ -119,7 +125,7 @@ class ValueAPITestCase(TestBase): self.DebugSBValue(child) self.expect(child.GetSummary(), exe=False, - substrs = ['Friday']) + substrs=['Friday']) # Now try to get at the same variable using GetValueForExpressionPath(). # These two SBValue objects should have the same value. @@ -132,14 +138,31 @@ class ValueAPITestCase(TestBase): val_i = target.EvaluateExpression('i') val_s = target.EvaluateExpression('s') val_a = target.EvaluateExpression('a') - self.assertTrue(val_s.GetChildMemberWithName('a').AddressOf(), VALID_VARIABLE) - self.assertTrue(val_a.Cast(val_i.GetType()).AddressOf(), VALID_VARIABLE) - - self.assertTrue(int(lldb.value(frame0.FindVariable('uinthex'))) == 3768803088, 'uinthex == 3768803088') - self.assertTrue(int(lldb.value(frame0.FindVariable('sinthex'))) == -526164208, 'sinthex == -526164208') - - self.assertTrue(frame0.FindVariable('uinthex').GetValueAsUnsigned() == 3768803088, 'unsigned uinthex == 3768803088') - self.assertTrue(frame0.FindVariable('sinthex').GetValueAsUnsigned() == 3768803088, 'unsigned sinthex == 3768803088') - - self.assertTrue(frame0.FindVariable('uinthex').GetValueAsSigned() == -526164208, 'signed uinthex == -526164208') - self.assertTrue(frame0.FindVariable('sinthex').GetValueAsSigned() == -526164208, 'signed sinthex == -526164208') + self.assertTrue( + val_s.GetChildMemberWithName('a').AddressOf(), + VALID_VARIABLE) + self.assertTrue( + val_a.Cast( + val_i.GetType()).AddressOf(), + VALID_VARIABLE) + + self.assertTrue(int(lldb.value(frame0.FindVariable('uinthex'))) + == 3768803088, 'uinthex == 3768803088') + self.assertTrue(int(lldb.value(frame0.FindVariable('sinthex'))) + == -526164208, 'sinthex == -526164208') + + self.assertTrue( + frame0.FindVariable('uinthex').GetValueAsUnsigned() == 3768803088, + 'unsigned uinthex == 3768803088') + self.assertTrue( + frame0.FindVariable('sinthex').GetValueAsUnsigned() == 3768803088, + 'unsigned sinthex == 3768803088') + + self.assertTrue( + frame0.FindVariable('uinthex').GetValueAsSigned() == - + 526164208, + 'signed uinthex == -526164208') + self.assertTrue( + frame0.FindVariable('sinthex').GetValueAsSigned() == - + 526164208, + 'signed sinthex == -526164208') diff --git a/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py index 52c91e0b262..64c7fde2267 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py @@ -5,14 +5,15 @@ Test some SBValue APIs. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ChangeValueAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,8 +25,10 @@ class ChangeValueAPITestCase(TestBase): self.exe_name = self.testMethodName # Find the line number to of function 'c'. self.line = line_number('main.c', '// Stop here and set values') - self.check_line = line_number('main.c', '// Stop here and check values') - self.end_line = line_number ('main.c', '// Set a breakpoint here at the end') + self.check_line = line_number( + 'main.c', '// Stop here and check values') + self.end_line = line_number( + 'main.c', '// Set a breakpoint here at the end') @add_test_categories(['pyapi']) @expectedFlakeyLinux("llvm.org/pr25652") @@ -46,97 +49,126 @@ class ChangeValueAPITestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Create the breakpoint inside the function 'main' - check_breakpoint = target.BreakpointCreateByLocation('main.c', self.check_line) + check_breakpoint = target.BreakpointCreateByLocation( + 'main.c', self.check_line) self.assertTrue(check_breakpoint, VALID_BREAKPOINT) # Create the breakpoint inside function 'main'. - end_breakpoint = target.BreakpointCreateByLocation('main.c', self.end_line) + end_breakpoint = target.BreakpointCreateByLocation( + 'main.c', self.end_line) self.assertTrue(end_breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Get Frame #0. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) - self.assertTrue (frame0.IsValid(), "Got a valid frame.") + self.assertTrue(frame0.IsValid(), "Got a valid frame.") # Get the val variable and change it: error = lldb.SBError() - val_value = frame0.FindVariable ("val") - self.assertTrue (val_value.IsValid(), "Got the SBValue for val") - actual_value = val_value.GetValueAsSigned (error, 0); - self.assertTrue (error.Success(), "Got a value from val") - self.assertTrue (actual_value == 100, "Got the right value from val") - - result = val_value.SetValueFromCString ("12345") - self.assertTrue (result, "Setting val returned True.") - actual_value = val_value.GetValueAsSigned (error, 0); - self.assertTrue (error.Success(), "Got a changed value from val") - self.assertTrue (actual_value == 12345, "Got the right changed value from val") - + val_value = frame0.FindVariable("val") + self.assertTrue(val_value.IsValid(), "Got the SBValue for val") + actual_value = val_value.GetValueAsSigned(error, 0) + self.assertTrue(error.Success(), "Got a value from val") + self.assertTrue(actual_value == 100, "Got the right value from val") + + result = val_value.SetValueFromCString("12345") + self.assertTrue(result, "Setting val returned True.") + actual_value = val_value.GetValueAsSigned(error, 0) + self.assertTrue(error.Success(), "Got a changed value from val") + self.assertTrue( + actual_value == 12345, + "Got the right changed value from val") + # Now check that we can set a structure element: - mine_value = frame0.FindVariable ("mine") - self.assertTrue (mine_value.IsValid(), "Got the SBValue for mine") - - mine_second_value = mine_value.GetChildMemberWithName ("second_val") - self.assertTrue (mine_second_value.IsValid(), "Got second_val from mine") - actual_value = mine_second_value.GetValueAsUnsigned (error, 0) - self.assertTrue (error.Success(), "Got an unsigned value for second_val") - self.assertTrue (actual_value == 5555) - - result = mine_second_value.SetValueFromCString ("98765") - self.assertTrue (result, "Success setting mine.second_value.") - actual_value = mine_second_value.GetValueAsSigned (error, 0); - self.assertTrue (error.Success(), "Got a changed value from mine.second_val") - self.assertTrue (actual_value == 98765, "Got the right changed value from mine.second_val") - + mine_value = frame0.FindVariable("mine") + self.assertTrue(mine_value.IsValid(), "Got the SBValue for mine") + + mine_second_value = mine_value.GetChildMemberWithName("second_val") + self.assertTrue( + mine_second_value.IsValid(), + "Got second_val from mine") + actual_value = mine_second_value.GetValueAsUnsigned(error, 0) + self.assertTrue( + error.Success(), + "Got an unsigned value for second_val") + self.assertTrue(actual_value == 5555) + + result = mine_second_value.SetValueFromCString("98765") + self.assertTrue(result, "Success setting mine.second_value.") + actual_value = mine_second_value.GetValueAsSigned(error, 0) + self.assertTrue( + error.Success(), + "Got a changed value from mine.second_val") + self.assertTrue(actual_value == 98765, + "Got the right changed value from mine.second_val") + # Next do the same thing with the pointer version. - ptr_value = frame0.FindVariable ("ptr") - self.assertTrue (ptr_value.IsValid(), "Got the SBValue for ptr") - - ptr_second_value = ptr_value.GetChildMemberWithName ("second_val") - self.assertTrue (ptr_second_value.IsValid(), "Got second_val from ptr") - actual_value = ptr_second_value.GetValueAsUnsigned (error, 0) - self.assertTrue (error.Success(), "Got an unsigned value for ptr->second_val") - self.assertTrue (actual_value == 6666) - - result = ptr_second_value.SetValueFromCString ("98765") - self.assertTrue (result, "Success setting ptr->second_value.") - actual_value = ptr_second_value.GetValueAsSigned (error, 0); - self.assertTrue (error.Success(), "Got a changed value from ptr->second_val") - self.assertTrue (actual_value == 98765, "Got the right changed value from ptr->second_val") - + ptr_value = frame0.FindVariable("ptr") + self.assertTrue(ptr_value.IsValid(), "Got the SBValue for ptr") + + ptr_second_value = ptr_value.GetChildMemberWithName("second_val") + self.assertTrue(ptr_second_value.IsValid(), "Got second_val from ptr") + actual_value = ptr_second_value.GetValueAsUnsigned(error, 0) + self.assertTrue( + error.Success(), + "Got an unsigned value for ptr->second_val") + self.assertTrue(actual_value == 6666) + + result = ptr_second_value.SetValueFromCString("98765") + self.assertTrue(result, "Success setting ptr->second_value.") + actual_value = ptr_second_value.GetValueAsSigned(error, 0) + self.assertTrue( + error.Success(), + "Got a changed value from ptr->second_val") + self.assertTrue(actual_value == 98765, + "Got the right changed value from ptr->second_val") + # gcc may set multiple locations for breakpoint breakpoint.SetEnabled(False) - # Now continue, grab the stdout and make sure we changed the real values as well... - process.Continue(); + # Now continue, grab the stdout and make sure we changed the real + # values as well... + process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") expected_value = "Val - 12345 Mine - 55, 98765, 55555555. Ptr - 66, 98765, 66666666" stdout = process.GetSTDOUT(1000) - self.assertTrue (expected_value in stdout, "STDOUT showed changed values.") + self.assertTrue( + expected_value in stdout, + "STDOUT showed changed values.") - # Finally, change the stack pointer to 0, and we should not make it to our end breakpoint. + # Finally, change the stack pointer to 0, and we should not make it to + # our end breakpoint. frame0 = thread.GetFrameAtIndex(0) - self.assertTrue (frame0.IsValid(), "Second time: got a valid frame.") - sp_value = frame0.FindValue ("sp", lldb.eValueTypeRegister); - self.assertTrue (sp_value.IsValid(), "Got a stack pointer value") + self.assertTrue(frame0.IsValid(), "Second time: got a valid frame.") + sp_value = frame0.FindValue("sp", lldb.eValueTypeRegister) + self.assertTrue(sp_value.IsValid(), "Got a stack pointer value") result = sp_value.SetValueFromCString("1") - self.assertTrue (result, "Setting sp returned true.") - actual_value = sp_value.GetValueAsUnsigned (error, 0) - self.assertTrue (error.Success(), "Got a changed value for sp") - self.assertTrue (actual_value == 1, "Got the right changed value for sp.") - + self.assertTrue(result, "Setting sp returned true.") + actual_value = sp_value.GetValueAsUnsigned(error, 0) + self.assertTrue(error.Success(), "Got a changed value for sp") + self.assertTrue( + actual_value == 1, + "Got the right changed value for sp.") + # Boundary condition test the SBValue.CreateValueFromExpression() API. # LLDB should not crash! nosuchval = mine_value.CreateValueFromExpression(None, None) @@ -144,7 +176,10 @@ class ChangeValueAPITestCase(TestBase): process.Continue() self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread == None, "We should not have managed to hit our second breakpoint with sp == 1") - + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread is None, + "We should not have managed to hit our second breakpoint with sp == 1") + process.Kill() diff --git a/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py b/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py index 879efd186d6..d5f53d712e7 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py @@ -6,14 +6,15 @@ supports iteration till the end of list is reached. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class ValueAsLinkedListTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -26,8 +27,9 @@ class ValueAsLinkedListTestCase(TestBase): # Find the line number to break at. self.line = line_number('main.cpp', '// Break at this line') - # Py3 asserts due to a bug in SWIG. A fix for this was upstreamed into SWIG 3.0.8. - @skipIf(py_version=['>=', (3,0)], swig_version=['<', (3,0,8)]) + # Py3 asserts due to a bug in SWIG. A fix for this was upstreamed into + # SWIG 3.0.8. + @skipIf(py_version=['>=', (3, 0)], swig_version=['<', (3, 0, 8)]) @add_test_categories(['pyapi']) def test(self): """Exercise SBValue API linked_list_iter.""" @@ -45,13 +47,17 @@ class ValueAsLinkedListTestCase(TestBase): self.assertTrue(breakpoint, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Get Frame #0. self.assertTrue(process.GetState() == lldb.eStateStopped) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) - self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") frame0 = thread.GetFrameAtIndex(0) # Get variable 'task_head'. @@ -66,7 +72,8 @@ class ValueAsLinkedListTestCase(TestBase): cvf = lldbutil.ChildVisitingFormatter(indent_child=2) for t in task_head.linked_list_iter('next'): self.assertTrue(t, VALID_VARIABLE) - # Make sure that 'next' corresponds to an SBValue with pointer type. + # Make sure that 'next' corresponds to an SBValue with pointer + # type. self.assertTrue(t.TypeIsPointerType()) if self.TraceOn(): print(cvf.format(t)) @@ -96,7 +103,8 @@ class ValueAsLinkedListTestCase(TestBase): list = [] for t in task_head.linked_list_iter('next', eol): self.assertTrue(t, VALID_VARIABLE) - # Make sure that 'next' corresponds to an SBValue with pointer type. + # Make sure that 'next' corresponds to an SBValue with pointer + # type. self.assertTrue(t.TypeIsPointerType()) if self.TraceOn(): print(cvf.format(t)) @@ -106,7 +114,7 @@ class ValueAsLinkedListTestCase(TestBase): if self.TraceOn(): print("visited IDs:", list) self.assertTrue(visitedIDs == list) - + # Get variable 'empty_task_head'. empty_task_head = frame0.FindVariable('empty_task_head') self.assertTrue(empty_task_head, VALID_VARIABLE) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py b/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py index 8620117386f..f4789877f34 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py @@ -3,14 +3,16 @@ from __future__ import print_function - -import os, sys, time +import os +import sys +import time import lldb import time from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class HelloWorldTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,33 +31,41 @@ class HelloWorldTestCase(TestBase): self.setTearDownCleanup(dictionary=self.d) target = self.dbg.CreateTarget(self.exe) - breakpoint = target.BreakpointCreateBySourceRegex("break here", lldb.SBFileSpec("main.c")) + breakpoint = target.BreakpointCreateBySourceRegex( + "break here", lldb.SBFileSpec("main.c")) self.runCmd("run", RUN_SUCCEEDED) - + # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'stop reason = breakpoint']) + substrs=['stopped', + 'stop reason = breakpoint']) i = self.frame().FindVariable("i") i_val = i.GetValueAsUnsigned(0) c = self.frame().FindVariable("c") - # Update any values from the SBValue objects so we can ask them if they changed after a continue + # Update any values from the SBValue objects so we can ask them if they + # changed after a continue i.GetValueDidChange() c.GetChildAtIndex(1).GetValueDidChange() c.GetChildAtIndex(0).GetChildAtIndex(0).GetValueDidChange() - - if self.TraceOn(): self.runCmd("frame variable") - + + if self.TraceOn(): + self.runCmd("frame variable") + self.runCmd("continue") - if self.TraceOn(): self.runCmd("frame variable") - - self.assertTrue(i_val != i.GetValueAsUnsigned(0), "GetValue() is saying a lie") - self.assertTrue(i.GetValueDidChange(), "GetValueDidChange() is saying a lie") + if self.TraceOn(): + self.runCmd("frame variable") + + self.assertTrue( + i_val != i.GetValueAsUnsigned(0), + "GetValue() is saying a lie") + self.assertTrue( + i.GetValueDidChange(), + "GetValueDidChange() is saying a lie") # Check complex type - self.assertTrue(c.GetChildAtIndex(0).GetChildAtIndex(0).GetValueDidChange() and - not c.GetChildAtIndex(1).GetValueDidChange(), "GetValueDidChange() is saying a lie") + self.assertTrue(c.GetChildAtIndex(0).GetChildAtIndex(0).GetValueDidChange( + ) and not c.GetChildAtIndex(1).GetValueDidChange(), "GetValueDidChange() is saying a lie") diff --git a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py index bedf286e199..e4f2c5c7a18 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py @@ -5,14 +5,15 @@ Use lldb Python SBValue API to create a watchpoint for read_write of 'globl' var from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SetWatchpointAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,12 +24,17 @@ class SetWatchpointAPITestCase(TestBase): # Our simple source filename. self.source = 'main.c' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') @add_test_categories(['pyapi']) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_watch_val(self): """Exercise SBValue.Watch() API to set a watchpoint.""" self.build() @@ -45,18 +51,20 @@ class SetWatchpointAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for read and write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) - error = lldb.SBError(); + error = lldb.SBError() watchpoint = value.Watch(True, True, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") @@ -68,28 +76,35 @@ class SetWatchpointAPITestCase(TestBase): print(watchpoint) - # Continue. Expect the program to stop due to the variable being written to. + # Continue. Expect the program to stop due to the variable being + # written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) - # Continue. Expect the program to stop due to the variable being read from. + # Continue. Expect the program to stop due to the variable being read + # from. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) - # Continue the process. We don't expect the program to be stopped again. + # Continue the process. We don't expect the program to be stopped + # again. process.Continue() # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py index d7b45a533e3..1bef9968b4a 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py @@ -5,14 +5,15 @@ Use lldb Python SBWatchpoint API to set the ignore count. from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointIgnoreCountTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,12 +24,17 @@ class WatchpointIgnoreCountTestCase(TestBase): # Our simple source filename. self.source = 'main.c' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') @add_test_categories(['pyapi']) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") - @expectedFailureAll(archs=['s390x']) # Read-write watchpoints not supported on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) def test_set_watch_ignore_count(self): """Test SBWatchpoint.SetIgnoreCount() API.""" self.build() @@ -45,18 +51,20 @@ class WatchpointIgnoreCountTestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for read and write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) - error = lldb.SBError(); + error = lldb.SBError() watchpoint = value.Watch(True, True, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") @@ -82,7 +90,9 @@ class WatchpointIgnoreCountTestCase(TestBase): process.Continue() # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) # Verify some vital statistics. self.assertTrue(watchpoint) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py index 8bbb93af07e..33f1be77ad5 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py @@ -5,7 +5,6 @@ Use lldb Python SBTarget API to iterate on the watchpoint(s) for the target. from __future__ import print_function - import os import re import time @@ -15,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointIteratorTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,11 +25,15 @@ class WatchpointIteratorTestCase(TestBase): # Our simple source filename. self.source = 'main.c' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') @add_test_categories(['pyapi']) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watch_iter(self): """Exercise SBTarget.watchpoint_iter() API to iterate on the available watchpoints.""" self.build() @@ -46,18 +50,20 @@ class WatchpointIteratorTestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for read and write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) - error = lldb.SBError(); + error = lldb.SBError() watchpoint = value.Watch(True, False, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") @@ -73,7 +79,8 @@ class WatchpointIteratorTestCase(TestBase): watch_id = watchpoint.GetID() self.assertTrue(watch_id != 0) - # Continue. Expect the program to stop due to the variable being written to. + # Continue. Expect the program to stop due to the variable being + # written to. process.Continue() # Hide stdout if not running with '-t' option. @@ -83,7 +90,8 @@ class WatchpointIteratorTestCase(TestBase): # Print the stack traces. lldbutil.print_stacktraces(process) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) @@ -107,7 +115,9 @@ class WatchpointIteratorTestCase(TestBase): process.Continue() # At this point, the inferior process should have exited. - self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED) + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) # Verify some vital statistics and exercise the iterator API. for watchpoint in target.watchpoint_iter(): @@ -115,4 +125,3 @@ class WatchpointIteratorTestCase(TestBase): self.assertTrue(watchpoint.GetWatchSize() == 4) self.assertTrue(watchpoint.GetHitCount() == 1) print(watchpoint) - diff --git a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py index b368cc06661..03c94b6d04f 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py @@ -5,13 +5,14 @@ Test watchpoint condition API. from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class WatchpointConditionAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -22,16 +23,23 @@ class WatchpointConditionAPITestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # And the watchpoint variable declaration line number. - self.decl = line_number(self.source, '// Watchpoint variable declaration.') - # Build dictionary to have unique executable names for each test method. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. self.exe_name = self.testMethodName self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["linux"], archs=["aarch64"], bugnumber="llvm.org/pr27710") - @skipIfWindows # Watchpoints not supported on Windows, and this test hangs + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["linux"], + archs=["aarch64"], + bugnumber="llvm.org/pr27710") + @skipIfWindows # Watchpoints not supported on Windows, and this test hangs def test_watchpoint_cond_api(self): """Test watchpoint condition API.""" self.build(dictionary=self.d) @@ -49,18 +57,20 @@ class WatchpointConditionAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Watch 'global' for write. value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) - error = lldb.SBError(); + error = lldb.SBError() watchpoint = value.Watch(True, False, True, error) self.assertTrue(value and watchpoint, "Successfully found the variable and set a watchpoint") @@ -69,7 +79,7 @@ class WatchpointConditionAPITestCase(TestBase): # Now set the condition as "global==5". watchpoint.SetCondition('global==5') self.expect(watchpoint.GetCondition(), exe=False, - startstr = 'global==5') + startstr='global==5') # Hide stdout if not running with '-t' option. if not self.TraceOn(): @@ -77,13 +87,15 @@ class WatchpointConditionAPITestCase(TestBase): print(watchpoint) - # Continue. Expect the program to stop due to the variable being written to. + # Continue. Expect the program to stop due to the variable being + # written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) diff --git a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py index d0a2c2fff12..1cbaf5f46f6 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py @@ -5,7 +5,6 @@ Use lldb Python SBValue.WatchPointee() API to create a watchpoint for write of ' from __future__ import print_function - import os import re import time @@ -15,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SetWatchlocationAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -25,13 +25,17 @@ class SetWatchlocationAPITestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # This is for verifying that watch location works. - self.violating_func = "do_bad_thing_with_location"; + self.violating_func = "do_bad_thing_with_location" @add_test_categories(['pyapi']) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watch_location(self): """Exercise SBValue.WatchPointee() API to set a watchpoint.""" self.build() @@ -48,22 +52,25 @@ class SetWatchlocationAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) value = frame0.FindValue('g_char_ptr', lldb.eValueTypeVariableGlobal) - pointee = value.CreateValueFromAddress("pointee", - value.GetValueAsUnsigned(0), - value.GetType().GetPointeeType()) + pointee = value.CreateValueFromAddress( + "pointee", + value.GetValueAsUnsigned(0), + value.GetType().GetPointeeType()) # Watch for write to *g_char_ptr. - error = lldb.SBError(); + error = lldb.SBError() watchpoint = value.WatchPointee(True, False, True, error) self.assertTrue(value and watchpoint, "Successfully found the pointer and set a watchpoint") @@ -76,18 +83,25 @@ class SetWatchlocationAPITestCase(TestBase): print(watchpoint) - # Continue. Expect the program to stop due to the variable being written to. + # Continue. Expect the program to stop due to the variable being + # written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) self.DebugSBValue(pointee) - self.expect(lldbutil.print_stacktrace(thread, string_buffer=True), exe=False, - substrs = [self.violating_func]) + self.expect( + lldbutil.print_stacktrace( + thread, + string_buffer=True), + exe=False, + substrs=[ + self.violating_func]) # This finishes our test. diff --git a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py index 468f3131f33..5eeffa5d760 100644 --- a/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py +++ b/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py @@ -5,14 +5,15 @@ Use lldb Python SBtarget.WatchAddress() API to create a watchpoint for write of from __future__ import print_function - -import os, time +import os +import time import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TargetWatchAddressAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -23,13 +24,17 @@ class TargetWatchAddressAPITestCase(TestBase): # Our simple source filename. self.source = 'main.cpp' # Find the line number to break inside main(). - self.line = line_number(self.source, '// Set break point at this line.') + self.line = line_number( + self.source, '// Set break point at this line.') # This is for verifying that watch location works. - self.violating_func = "do_bad_thing_with_location"; + self.violating_func = "do_bad_thing_with_location" @add_test_categories(['pyapi']) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows") def test_watch_address(self): """Exercise SBTarget.WatchAddress() API to set a watchpoint.""" self.build() @@ -46,23 +51,27 @@ class TargetWatchAddressAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) value = frame0.FindValue('g_char_ptr', lldb.eValueTypeVariableGlobal) - pointee = value.CreateValueFromAddress("pointee", - value.GetValueAsUnsigned(0), - value.GetType().GetPointeeType()) + pointee = value.CreateValueFromAddress( + "pointee", + value.GetValueAsUnsigned(0), + value.GetType().GetPointeeType()) # Watch for write to *g_char_ptr. - error = lldb.SBError(); - watchpoint = target.WatchAddress(value.GetValueAsUnsigned(), 1, False, True, error) + error = lldb.SBError() + watchpoint = target.WatchAddress( + value.GetValueAsUnsigned(), 1, False, True, error) self.assertTrue(value and watchpoint, "Successfully found the pointer and set a watchpoint") self.DebugSBValue(value) @@ -74,26 +83,35 @@ class TargetWatchAddressAPITestCase(TestBase): print(watchpoint) - # Continue. Expect the program to stop due to the variable being written to. + # Continue. Expect the program to stop due to the variable being + # written to. process.Continue() if (self.TraceOn()): lldbutil.print_stacktraces(process) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) self.assertTrue(thread, "The thread stopped due to watchpoint") self.DebugSBValue(value) self.DebugSBValue(pointee) - self.expect(lldbutil.print_stacktrace(thread, string_buffer=True), exe=False, - substrs = [self.violating_func]) + self.expect( + lldbutil.print_stacktrace( + thread, + string_buffer=True), + exe=False, + substrs=[ + self.violating_func]) # This finishes our test. @add_test_categories(['pyapi']) - @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported - @skipIf(archs=['mips', 'mipsel', 'mips64', 'mips64el']) # No size constraint on MIPS for watches - @skipIf(archs=['s390x']) # Likewise on SystemZ + # Watchpoints not supported + @expectedFailureAndroid(archs=['arm', 'aarch64']) + # No size constraint on MIPS for watches + @skipIf(archs=['mips', 'mipsel', 'mips64', 'mips64el']) + @skipIf(archs=['s390x']) # Likewise on SystemZ def test_watch_address_with_invalid_watch_size(self): """Exercise SBTarget.WatchAddress() API but pass an invalid watch_size.""" self.build() @@ -110,23 +128,27 @@ class TargetWatchAddressAPITestCase(TestBase): VALID_BREAKPOINT) # Now launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # We should be stopped due to the breakpoint. Get frame #0. process = target.GetProcess() self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) - thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) value = frame0.FindValue('g_char_ptr', lldb.eValueTypeVariableGlobal) - pointee = value.CreateValueFromAddress("pointee", - value.GetValueAsUnsigned(0), - value.GetType().GetPointeeType()) + pointee = value.CreateValueFromAddress( + "pointee", + value.GetValueAsUnsigned(0), + value.GetType().GetPointeeType()) # Watch for write to *g_char_ptr. - error = lldb.SBError(); - watchpoint = target.WatchAddress(value.GetValueAsUnsigned(), 365, False, True, error) + error = lldb.SBError() + watchpoint = target.WatchAddress( + value.GetValueAsUnsigned(), 365, False, True, error) self.assertFalse(watchpoint) self.expect(error.GetCString(), exe=False, - substrs = ['watch size of %d is not supported' % 365]) + substrs=['watch size of %d is not supported' % 365]) diff --git a/lldb/packages/Python/lldbsuite/test/redo.py b/lldb/packages/Python/lldbsuite/test/redo.py index e4eba8b2786..03052c3a08c 100644 --- a/lldb/packages/Python/lldbsuite/test/redo.py +++ b/lldb/packages/Python/lldbsuite/test/redo.py @@ -17,7 +17,9 @@ for help. from __future__ import print_function -import os, sys, datetime +import os +import sys +import datetime import re # If True, redo with no '-t' option for the test driver. @@ -42,6 +44,7 @@ comp_specs = set() # The "-A arch" for arch_specs. arch_specs = set() + def usage(): print("""\ Usage: redo.py [-F filename_component] [-n] [session_dir] [-d] @@ -60,6 +63,7 @@ possible session directories with names starting with %Y-%m-%d- (for example, 2012-01-23-) and employs the one with the latest timestamp.""") sys.exit(0) + def where(session_dir, test_dir): """Returns the full path to the session directory; None if non-existent.""" abspath = os.path.abspath(session_dir) @@ -77,6 +81,8 @@ def where(session_dir, test_dir): filter_pattern = re.compile("^\./dotest\.py.*-f (.*)$") comp_pattern = re.compile(" -C ([^ ]+) ") arch_pattern = re.compile(" -A ([^ ]+) ") + + def redo(suffix, dir, names): """Visitor function for os.path.walk(path, visit, arg).""" global redo_specs @@ -108,10 +114,11 @@ def redo(suffix, dir, names): comp_specs.add(comp.group(1)) arch = arch_pattern.search(line) if arch: - arch_specs.add(arch.group(1)) + arch_specs.add(arch.group(1)) else: continue + def main(): """Read the session directory and run the failed test cases one by one.""" global no_trace @@ -128,7 +135,8 @@ def main(): index = 1 while index < len(sys.argv): - if sys.argv[index].startswith('-h') or sys.argv[index].startswith('--help'): + if sys.argv[index].startswith( + '-h') or sys.argv[index].startswith('--help'): usage() if sys.argv[index].startswith('-'): @@ -185,8 +193,8 @@ def main(): for arch in arch_specs: archs += "--arch %s " % (arch) - command = "./dotest.py %s %s -v %s %s -f " % (compilers, archs, "" if no_trace else "-t", "-d" if do_delay else "") - + command = "./dotest.py %s %s -v %s %s -f " % ( + compilers, archs, "" if no_trace else "-t", "-d" if do_delay else "") print("Running %s" % (command + filters)) os.system(command + filters) diff --git a/lldb/packages/Python/lldbsuite/test/settings/TestSettings.py b/lldb/packages/Python/lldbsuite/test/settings/TestSettings.py index 9592fa9d6df..577cac17753 100644 --- a/lldb/packages/Python/lldbsuite/test/settings/TestSettings.py +++ b/lldb/packages/Python/lldbsuite/test/settings/TestSettings.py @@ -5,13 +5,15 @@ Test lldb settings command. from __future__ import print_function - -import os, time, re +import os +import time +import re import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SettingsCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -29,9 +31,9 @@ class SettingsCommandTestCase(TestBase): """Test that 'apropos' command should also search descriptions for the settings variables.""" self.expect("apropos 'environment variable'", - substrs = ["target.env-vars", - "environment variables", - "executable's environment"]) + substrs=["target.env-vars", + "environment variables", + "executable's environment"]) @no_debug_info_test def test_append_target_env_vars(self): @@ -44,7 +46,7 @@ class SettingsCommandTestCase(TestBase): # Check it immediately! self.expect('settings show target.env-vars', - substrs = ['MY_ENV_VAR=YES']) + substrs=['MY_ENV_VAR=YES']) @no_debug_info_test def test_insert_before_and_after_target_run_args(self): @@ -61,12 +63,12 @@ class SettingsCommandTestCase(TestBase): self.runCmd('settings insert-after target.run-args 1 __A__') # Check it immediately! self.expect('settings show target.run-args', - substrs = ['target.run-args', - '[0]: "__a__"', - '[1]: "a"', - '[2]: "__A__"', - '[3]: "b"', - '[4]: "c"']) + substrs=['target.run-args', + '[0]: "__a__"', + '[1]: "a"', + '[2]: "__A__"', + '[3]: "b"', + '[4]: "c"']) @no_debug_info_test def test_replace_target_run_args(self): @@ -81,10 +83,10 @@ class SettingsCommandTestCase(TestBase): self.runCmd('settings replace target.run-args 0 A') # Check it immediately! self.expect('settings show target.run-args', - substrs = ['target.run-args (arguments) =', - '[0]: "A"', - '[1]: "b"', - '[2]: "c"']) + substrs=['target.run-args (arguments) =', + '[0]: "A"', + '[1]: "b"', + '[2]: "c"']) @no_debug_info_test def test_set_prompt(self): @@ -95,11 +97,11 @@ class SettingsCommandTestCase(TestBase): # Immediately test the setting. self.expect("settings show prompt", SETTING_MSG("prompt"), - startstr = 'prompt (string) = "lldb2 "') + startstr='prompt (string) = "lldb2 "') # The overall display should also reflect the new setting. self.expect("settings show", SETTING_MSG("prompt"), - substrs = ['prompt (string) = "lldb2 "']) + substrs=['prompt (string) = "lldb2 "']) # Use '-r' option to reset to the original default prompt. self.runCmd("settings clear prompt") @@ -112,13 +114,13 @@ class SettingsCommandTestCase(TestBase): # Immediately test the setting. self.expect("settings show term-width", SETTING_MSG("term-width"), - startstr = "term-width (int) = 70") + startstr="term-width (int) = 70") # The overall display should also reflect the new setting. self.expect("settings show", SETTING_MSG("term-width"), - substrs = ["term-width (int) = 70"]) + substrs=["term-width (int) = 70"]) - #rdar://problem/10712130 + # rdar://problem/10712130 def test_set_frame_format(self): """Test that 'set frame-format' with a backtick char in the format string works as well as fullpath.""" self.build() @@ -127,30 +129,33 @@ class SettingsCommandTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) def cleanup(): - self.runCmd("settings set frame-format %s" % self.format_string, check=False) + self.runCmd( + "settings set frame-format %s" % + self.format_string, check=False) # Execute the cleanup function during test case tear down. self.addTearDownHook(cleanup) self.runCmd("settings show frame-format") m = re.match( - '^frame-format \(format-string\) = "(.*)\"$', - self.res.GetOutput()) + '^frame-format \(format-string\) = "(.*)\"$', + self.res.GetOutput()) self.assertTrue(m, "Bad settings string") self.format_string = m.group(1) - # Change the default format to print function.name rather than function.name-with-args + # Change the default format to print function.name rather than + # function.name-with-args format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}`${function.name}{${function.pc-offset}}}{ at ${line.file.fullpath}:${line.number}}{, lang=${language}}\n" self.runCmd("settings set frame-format %s" % format_string) # Immediately test the setting. self.expect("settings show frame-format", SETTING_MSG("frame-format"), - substrs = [format_string]) + substrs=[format_string]) self.runCmd("breakpoint set -n main") self.runCmd("run") self.expect("thread backtrace", - substrs = ["`main", os.getcwd()]) + substrs=["`main", os.getcwd()]) def test_set_auto_confirm(self): """Test that after 'set auto-confirm true', manual confirmation should not kick in.""" @@ -163,18 +168,18 @@ class SettingsCommandTestCase(TestBase): # Immediately test the setting. self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"), - startstr = "auto-confirm (boolean) = true") + startstr="auto-confirm (boolean) = true") # Now 'breakpoint delete' should just work fine without confirmation # prompt from the command interpreter. self.runCmd("breakpoint set -n main") self.expect("breakpoint delete", - startstr = "All breakpoints removed") + startstr="All breakpoints removed") # Restore the original setting of auto-confirm. self.runCmd("settings clear auto-confirm") self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"), - startstr = "auto-confirm (boolean) = false") + startstr="auto-confirm (boolean) = false") @skipIf(archs=no_match(['x86_64', 'i386', 'i686'])) def test_disassembler_settings(self): @@ -188,27 +193,27 @@ class SettingsCommandTestCase(TestBase): self.runCmd("settings set target.x86-disassembly-flavor att") self.runCmd("settings set target.use-hex-immediates false") self.expect("disassemble -n numberfn", - substrs = ["$90"]) + substrs=["$90"]) self.runCmd("settings set target.use-hex-immediates true") self.runCmd("settings set target.hex-immediate-style c") self.expect("disassemble -n numberfn", - substrs = ["$0x5a"]) + substrs=["$0x5a"]) self.runCmd("settings set target.hex-immediate-style asm") self.expect("disassemble -n numberfn", - substrs = ["$5ah"]) + substrs=["$5ah"]) # Intel syntax self.runCmd("settings set target.x86-disassembly-flavor intel") self.runCmd("settings set target.use-hex-immediates false") self.expect("disassemble -n numberfn", - substrs = ["90"]) + substrs=["90"]) self.runCmd("settings set target.use-hex-immediates true") self.runCmd("settings set target.hex-immediate-style c") self.expect("disassemble -n numberfn", - substrs = ["0x5a"]) + substrs=["0x5a"]) self.runCmd("settings set target.hex-immediate-style asm") self.expect("disassemble -n numberfn", - substrs = ["5ah"]) + substrs=["5ah"]) def test_run_args_and_env_vars(self): """Test that run-args and env-vars are passed to the launched process.""" @@ -233,13 +238,16 @@ class SettingsCommandTestCase(TestBase): with open('output2.txt', 'r') as f: output = f.read() - self.expect(output, exe=False, - substrs = ["argv[1] matches", - "argv[2] matches", - "argv[3] matches", - "Environment variable 'MY_ENV_VAR' successfully passed."]) + self.expect( + output, + exe=False, + substrs=[ + "argv[1] matches", + "argv[2] matches", + "argv[3] matches", + "Environment variable 'MY_ENV_VAR' successfully passed."]) - @skipIfRemote # it doesn't make sense to send host env to remote target + @skipIfRemote # it doesn't make sense to send host env to remote target def test_pass_host_env_vars(self): """Test that the host env vars are passed to the launched process.""" self.build() @@ -248,8 +256,10 @@ class SettingsCommandTestCase(TestBase): self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) # By default, inherit-env is 'true'. - self.expect('settings show target.inherit-env', "Default inherit-env is 'true'", - startstr = "target.inherit-env (boolean) = true") + self.expect( + 'settings show target.inherit-env', + "Default inherit-env is 'true'", + startstr="target.inherit-env (boolean) = true") # Set some host environment variables now. os.environ["MY_HOST_ENV_VAR1"] = "VAR1" @@ -269,9 +279,12 @@ class SettingsCommandTestCase(TestBase): with open('output1.txt', 'r') as f: output = f.read() - self.expect(output, exe=False, - substrs = ["The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.", - "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."]) + self.expect( + output, + exe=False, + substrs=[ + "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.", + "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."]) def test_set_error_output_path(self): """Test that setting target.error/output-path for the launched process works.""" @@ -291,11 +304,11 @@ class SettingsCommandTestCase(TestBase): self.expect("settings show target.error-path", SETTING_MSG("target.error-path"), - substrs = ['target.error-path (file) = "stderr.txt"']) + substrs=['target.error-path (file) = "stderr.txt"']) self.expect("settings show target.output-path", SETTING_MSG("target.output-path"), - substrs = ['target.output-path (file) = "stdout.txt"']) + substrs=['target.output-path (file) = "stdout.txt"']) self.runCmd("run", RUN_SUCCEEDED) @@ -303,7 +316,6 @@ class SettingsCommandTestCase(TestBase): self.runCmd('platform get-file "stderr.txt" "stderr.txt"') self.runCmd('platform get-file "stdout.txt" "stdout.txt"') - # The 'stderr.txt' file should now exist. self.assertTrue(os.path.isfile("stderr.txt"), "'stderr.txt' exists due to target.error-path.") @@ -314,9 +326,9 @@ class SettingsCommandTestCase(TestBase): message = "This message should go to standard error." if lldbplatformutil.hasChattyStderr(self): - self.expect(output, exe=False, substrs = [message]) + self.expect(output, exe=False, substrs=[message]) else: - self.expect(output, exe=False, startstr = message) + self.expect(output, exe=False, startstr=message) # The 'stdout.txt' file should now exist. self.assertTrue(os.path.isfile("stdout.txt"), @@ -327,173 +339,221 @@ class SettingsCommandTestCase(TestBase): output = f.read() self.expect(output, exe=False, - startstr = "This message should go to standard out.") + startstr="This message should go to standard out.") @no_debug_info_test def test_print_dictionary_setting(self): - self.runCmd ("settings clear target.env-vars") - self.runCmd ("settings set target.env-vars [\"MY_VAR\"]=some-value") - self.expect ("settings show target.env-vars", - substrs = [ "MY_VAR=some-value" ]) - self.runCmd ("settings clear target.env-vars") + self.runCmd("settings clear target.env-vars") + self.runCmd("settings set target.env-vars [\"MY_VAR\"]=some-value") + self.expect("settings show target.env-vars", + substrs=["MY_VAR=some-value"]) + self.runCmd("settings clear target.env-vars") @no_debug_info_test def test_print_array_setting(self): - self.runCmd ("settings clear target.run-args") - self.runCmd ("settings set target.run-args gobbledy-gook") - self.expect ("settings show target.run-args", - substrs = [ '[0]: "gobbledy-gook"' ]) - self.runCmd ("settings clear target.run-args") + self.runCmd("settings clear target.run-args") + self.runCmd("settings set target.run-args gobbledy-gook") + self.expect("settings show target.run-args", + substrs=['[0]: "gobbledy-gook"']) + self.runCmd("settings clear target.run-args") @no_debug_info_test - def test_settings_with_quotes (self): - self.runCmd ("settings clear target.run-args") - self.runCmd ("settings set target.run-args a b c") - self.expect ("settings show target.run-args", - substrs = [ '[0]: "a"', - '[1]: "b"', - '[2]: "c"' ]) - self.runCmd ("settings set target.run-args 'a b c'") - self.expect ("settings show target.run-args", - substrs = [ '[0]: "a b c"' ]) - self.runCmd ("settings clear target.run-args") - self.runCmd ("settings clear target.env-vars") - self.runCmd ('settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"') - self.expect ("settings show target.env-vars", - substrs = [ 'MY_FILE=this is a file name with spaces.txt' ]) - self.runCmd ("settings clear target.env-vars") - # Test and make sure that setting "format-string" settings obeys quotes if they are provided - self.runCmd ("settings set thread-format 'abc def' ") - self.expect ("settings show thread-format", 'thread-format (format-string) = "abc def"') - self.runCmd ('settings set thread-format "abc def" ') - self.expect ("settings show thread-format", 'thread-format (format-string) = "abc def"') - # Make sure when no quotes are provided that we maintain any trailing spaces - self.runCmd ('settings set thread-format abc def ') - self.expect ("settings show thread-format", 'thread-format (format-string) = "abc def "') - self.runCmd ('settings clear thread-format') + def test_settings_with_quotes(self): + self.runCmd("settings clear target.run-args") + self.runCmd("settings set target.run-args a b c") + self.expect("settings show target.run-args", + substrs=['[0]: "a"', + '[1]: "b"', + '[2]: "c"']) + self.runCmd("settings set target.run-args 'a b c'") + self.expect("settings show target.run-args", + substrs=['[0]: "a b c"']) + self.runCmd("settings clear target.run-args") + self.runCmd("settings clear target.env-vars") + self.runCmd( + 'settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"') + self.expect("settings show target.env-vars", + substrs=['MY_FILE=this is a file name with spaces.txt']) + self.runCmd("settings clear target.env-vars") + # Test and make sure that setting "format-string" settings obeys quotes + # if they are provided + self.runCmd("settings set thread-format 'abc def' ") + self.expect("settings show thread-format", + 'thread-format (format-string) = "abc def"') + self.runCmd('settings set thread-format "abc def" ') + self.expect("settings show thread-format", + 'thread-format (format-string) = "abc def"') + # Make sure when no quotes are provided that we maintain any trailing + # spaces + self.runCmd('settings set thread-format abc def ') + self.expect("settings show thread-format", + 'thread-format (format-string) = "abc def "') + self.runCmd('settings clear thread-format') @no_debug_info_test - def test_settings_with_trailing_whitespace (self): - + def test_settings_with_trailing_whitespace(self): + # boolean - self.runCmd ("settings set target.skip-prologue true") # Set to known value - self.runCmd ("settings set target.skip-prologue false ") # Set to new value with trailing whitespace + # Set to known value + self.runCmd("settings set target.skip-prologue true") + # Set to new value with trailing whitespace + self.runCmd("settings set target.skip-prologue false ") # Make sure the setting was correctly set to "false" - self.expect ("settings show target.skip-prologue", SETTING_MSG("target.skip-prologue"), - startstr = "target.skip-prologue (boolean) = false") + self.expect( + "settings show target.skip-prologue", + SETTING_MSG("target.skip-prologue"), + startstr="target.skip-prologue (boolean) = false") self.runCmd("settings clear target.skip-prologue", check=False) # integer - self.runCmd ("settings set term-width 70") # Set to known value - self.runCmd ("settings set term-width 60 \t") # Set to new value with trailing whitespaces - self.expect ("settings show term-width", SETTING_MSG("term-width"), - startstr = "term-width (int) = 60") + self.runCmd("settings set term-width 70") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set term-width 60 \t") + self.expect("settings show term-width", SETTING_MSG("term-width"), + startstr="term-width (int) = 60") self.runCmd("settings clear term-width", check=False) # string - self.runCmd ("settings set target.arg0 abc") # Set to known value - self.runCmd ("settings set target.arg0 cde\t ") # Set to new value with trailing whitespaces - self.expect ("settings show target.arg0", SETTING_MSG("target.arg0"), - startstr = 'target.arg0 (string) = "cde"') + self.runCmd("settings set target.arg0 abc") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.arg0 cde\t ") + self.expect("settings show target.arg0", SETTING_MSG("target.arg0"), + startstr='target.arg0 (string) = "cde"') self.runCmd("settings clear target.arg0", check=False) # file path1 = os.path.join(os.getcwd(), "path1.txt") path2 = os.path.join(os.getcwd(), "path2.txt") - self.runCmd ("settings set target.output-path %s" % path1) # Set to known value - self.expect ("settings show target.output-path", SETTING_MSG("target.output-path"), - startstr = 'target.output-path (file) = ', substrs=[path1]) - self.runCmd ("settings set target.output-path %s " % path2) # Set to new value with trailing whitespaces - self.expect ("settings show target.output-path", SETTING_MSG("target.output-path"), - startstr = 'target.output-path (file) = ', substrs=[path2]) + self.runCmd( + "settings set target.output-path %s" % + path1) # Set to known value + self.expect( + "settings show target.output-path", + SETTING_MSG("target.output-path"), + startstr='target.output-path (file) = ', + substrs=[path1]) + self.runCmd("settings set target.output-path %s " % + path2) # Set to new value with trailing whitespaces + self.expect( + "settings show target.output-path", + SETTING_MSG("target.output-path"), + startstr='target.output-path (file) = ', + substrs=[path2]) self.runCmd("settings clear target.output-path", check=False) # enum - self.runCmd ("settings set stop-disassembly-display never") # Set to known value - self.runCmd ("settings set stop-disassembly-display always ") # Set to new value with trailing whitespaces - self.expect ("settings show stop-disassembly-display", SETTING_MSG("stop-disassembly-display"), - startstr = 'stop-disassembly-display (enum) = always') - self.runCmd("settings clear stop-disassembly-display", check=False) + # Set to known value + self.runCmd("settings set stop-disassembly-display never") + # Set to new value with trailing whitespaces + self.runCmd("settings set stop-disassembly-display always ") + self.expect( + "settings show stop-disassembly-display", + SETTING_MSG("stop-disassembly-display"), + startstr='stop-disassembly-display (enum) = always') + self.runCmd("settings clear stop-disassembly-display", check=False) # language - self.runCmd ("settings set target.language c89") # Set to known value - self.runCmd ("settings set target.language go ") # Set to new value with trailing whitespace - self.expect ("settings show target.language", SETTING_MSG("target.language"), - startstr = "target.language (language) = go") + # Set to known value + self.runCmd("settings set target.language c89") + # Set to new value with trailing whitespace + self.runCmd("settings set target.language go ") + self.expect( + "settings show target.language", + SETTING_MSG("target.language"), + startstr="target.language (language) = go") self.runCmd("settings clear target.language", check=False) # arguments - self.runCmd ("settings set target.run-args 1 2 3") # Set to known value - self.runCmd ("settings set target.run-args 3 4 5 ") # Set to new value with trailing whitespaces - self.expect ("settings show target.run-args", SETTING_MSG("target.run-args"), - substrs = [ 'target.run-args (arguments) =', - '[0]: "3"', - '[1]: "4"', - '[2]: "5"' ]) - self.runCmd ("settings set target.run-args 1 2 3") # Set to known value - self.runCmd ("settings set target.run-args 3 \ \ ") # Set to new value with trailing whitespaces - self.expect ("settings show target.run-args", SETTING_MSG("target.run-args"), - substrs = [ 'target.run-args (arguments) =', - '[0]: "3"', - '[1]: " "', - '[2]: " "' ]) - self.runCmd("settings clear target.run-args", check=False) + self.runCmd("settings set target.run-args 1 2 3") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.run-args 3 4 5 ") + self.expect( + "settings show target.run-args", + SETTING_MSG("target.run-args"), + substrs=[ + 'target.run-args (arguments) =', + '[0]: "3"', + '[1]: "4"', + '[2]: "5"']) + self.runCmd("settings set target.run-args 1 2 3") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.run-args 3 \ \ ") + self.expect( + "settings show target.run-args", + SETTING_MSG("target.run-args"), + substrs=[ + 'target.run-args (arguments) =', + '[0]: "3"', + '[1]: " "', + '[2]: " "']) + self.runCmd("settings clear target.run-args", check=False) # dictionaries - self.runCmd ("settings clear target.env-vars") # Set to known value - self.runCmd ("settings set target.env-vars A=B C=D\t ") # Set to new value with trailing whitespaces - self.expect ("settings show target.env-vars", SETTING_MSG("target.env-vars"), - substrs = [ 'target.env-vars (dictionary of strings) =', - 'A=B', - 'C=D']) - self.runCmd("settings clear target.env-vars", check=False) + self.runCmd("settings clear target.env-vars") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.env-vars A=B C=D\t ") + self.expect( + "settings show target.env-vars", + SETTING_MSG("target.env-vars"), + substrs=[ + 'target.env-vars (dictionary of strings) =', + 'A=B', + 'C=D']) + self.runCmd("settings clear target.env-vars", check=False) # regex - self.runCmd ("settings clear target.process.thread.step-avoid-regexp") # Set to known value - self.runCmd ("settings set target.process.thread.step-avoid-regexp foo\\ ") # Set to new value with trailing whitespaces - self.expect ("settings show target.process.thread.step-avoid-regexp", - SETTING_MSG("target.process.thread.step-avoid-regexp"), - substrs = [ 'target.process.thread.step-avoid-regexp (regex) = foo\\ ']) - self.runCmd("settings clear target.process.thread.step-avoid-regexp", check=False) + # Set to known value + self.runCmd("settings clear target.process.thread.step-avoid-regexp") + # Set to new value with trailing whitespaces + self.runCmd( + "settings set target.process.thread.step-avoid-regexp foo\\ ") + self.expect( + "settings show target.process.thread.step-avoid-regexp", + SETTING_MSG("target.process.thread.step-avoid-regexp"), + substrs=['target.process.thread.step-avoid-regexp (regex) = foo\\ ']) + self.runCmd( + "settings clear target.process.thread.step-avoid-regexp", + check=False) # format-string - self.runCmd ("settings clear disassembly-format") # Set to known value - self.runCmd ("settings set disassembly-format foo ") # Set to new value with trailing whitespaces - self.expect ("settings show disassembly-format", - SETTING_MSG("disassembly-format"), - substrs = [ 'disassembly-format (format-string) = "foo "']) + self.runCmd("settings clear disassembly-format") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set disassembly-format foo ") + self.expect("settings show disassembly-format", + SETTING_MSG("disassembly-format"), + substrs=['disassembly-format (format-string) = "foo "']) self.runCmd("settings clear disassembly-format", check=False) @no_debug_info_test - def test_all_settings_exist (self): - self.expect ("settings show", - substrs = [ "auto-confirm", - "frame-format", - "notify-void", - "prompt", - "script-lang", - "stop-disassembly-count", - "stop-disassembly-display", - "stop-line-count-after", - "stop-line-count-before", - "term-width", - "thread-format", - "use-external-editor", - "target.default-arch", - "target.move-to-nearest-code", - "target.expr-prefix", - "target.language", - "target.prefer-dynamic-value", - "target.enable-synthetic-value", - "target.skip-prologue", - "target.source-map", - "target.exec-search-paths", - "target.max-children-count", - "target.max-string-summary-length", - "target.breakpoints-use-platform-avoid-list", - "target.run-args", - "target.env-vars", - "target.inherit-env", - "target.input-path", - "target.output-path", - "target.error-path", - "target.disable-aslr", - "target.disable-stdio", - "target.x86-disassembly-flavor", - "target.use-hex-immediates", - "target.hex-immediate-style", - "target.process.disable-memory-cache", - "target.process.extra-startup-command", - "target.process.thread.step-avoid-regexp", - "target.process.thread.trace-thread"]) + def test_all_settings_exist(self): + self.expect("settings show", + substrs=["auto-confirm", + "frame-format", + "notify-void", + "prompt", + "script-lang", + "stop-disassembly-count", + "stop-disassembly-display", + "stop-line-count-after", + "stop-line-count-before", + "term-width", + "thread-format", + "use-external-editor", + "target.default-arch", + "target.move-to-nearest-code", + "target.expr-prefix", + "target.language", + "target.prefer-dynamic-value", + "target.enable-synthetic-value", + "target.skip-prologue", + "target.source-map", + "target.exec-search-paths", + "target.max-children-count", + "target.max-string-summary-length", + "target.breakpoints-use-platform-avoid-list", + "target.run-args", + "target.env-vars", + "target.inherit-env", + "target.input-path", + "target.output-path", + "target.error-path", + "target.disable-aslr", + "target.disable-stdio", + "target.x86-disassembly-flavor", + "target.use-hex-immediates", + "target.hex-immediate-style", + "target.process.disable-memory-cache", + "target.process.extra-startup-command", + "target.process.thread.step-avoid-regexp", + "target.process.thread.trace-thread"]) diff --git a/lldb/packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py b/lldb/packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py index 67c535d649f..b193c81e644 100644 --- a/lldb/packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py +++ b/lldb/packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py @@ -5,7 +5,6 @@ Test quoting of arguments to lldb commands from __future__ import print_function - import os import re import time @@ -15,6 +14,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SettingsCommandTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) diff --git a/lldb/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py b/lldb/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py index 93e1789103c..904f0e7b7b2 100644 --- a/lldb/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py +++ b/lldb/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py @@ -12,12 +12,12 @@ o test_modify_source_file_while_debugging: from __future__ import print_function - import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class SourceManagerTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -39,7 +39,8 @@ class SourceManagerTestCase(TestBase): self.assertTrue(target, VALID_TARGET) # Launch the process, and do not stop at the entry point. - process = target.LaunchSimple (None, None, self.get_process_working_directory()) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) # # Exercise Python APIs to display source lines. @@ -52,19 +53,19 @@ class SourceManagerTestCase(TestBase): stream = lldb.SBStream() source_mgr.DisplaySourceLinesWithLineNumbers(filespec, self.line, - 2, # context before - 2, # context after - "=>", # prefix for current line + 2, # context before + 2, # context after + "=>", # prefix for current line stream) - # 2 + # 2 # 3 int main(int argc, char const *argv[]) { # => 4 printf("Hello world.\n"); // Set break point at this line. # 5 return 0; # 6 } self.expect(stream.GetData(), "Source code displayed correctly", exe=False, - patterns = ['=> %d.*Hello world' % self.line]) + patterns=['=> %d.*Hello world' % self.line]) # Boundary condition testings for SBStream(). LLDB should not crash! stream.Print(None) @@ -88,19 +89,23 @@ class SourceManagerTestCase(TestBase): system([["ls"]]) system([["ls", "hidden"]]) - # Set source remapping with invalid replace path and verify we get an error - self.expect("settings set target.source-map /a/b/c/d/e /q/r/s/t/u", error=True, - substrs = ['''error: the replacement path doesn't exist: "/q/r/s/t/u"''']) - + # Set source remapping with invalid replace path and verify we get an + # error + self.expect( + "settings set target.source-map /a/b/c/d/e /q/r/s/t/u", + error=True, + substrs=['''error: the replacement path doesn't exist: "/q/r/s/t/u"''']) + # Set target.source-map settings. - self.runCmd("settings set target.source-map %s %s" % (os.getcwd(), os.path.join(os.getcwd(), "hidden"))) + self.runCmd("settings set target.source-map %s %s" % + (os.getcwd(), os.path.join(os.getcwd(), "hidden"))) # And verify that the settings work. self.expect("settings show target.source-map", - substrs = [os.getcwd(), os.path.join(os.getcwd(), "hidden")]) + substrs=[os.getcwd(), os.path.join(os.getcwd(), "hidden")]) # Display main() and verify that the source mapping has been kicked in. self.expect("source list -n main", SOURCE_DISPLAYED_CORRECTLY, - substrs = ['Hello world']) + substrs=['Hello world']) def test_modify_source_file_while_debugging(self): """Modify a source file while debugging the executable.""" @@ -108,19 +113,23 @@ class SourceManagerTestCase(TestBase): exe = os.path.join(os.getcwd(), "a.out") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'main.c:%d' % self.line, - 'stop reason = breakpoint']) + substrs=['stopped', + 'main.c:%d' % self.line, + 'stop reason = breakpoint']) # Display some source code. - self.expect("source list -f main.c -l %d" % self.line, SOURCE_DISPLAYED_CORRECTLY, - substrs = ['Hello world']) + self.expect( + "source list -f main.c -l %d" % + self.line, + SOURCE_DISPLAYED_CORRECTLY, + substrs=['Hello world']) # The '-b' option shows the line table locations from the debug information # that indicates valid places to set source level breakpoints. @@ -158,8 +167,9 @@ class SourceManagerTestCase(TestBase): # Touch the file just to be sure. os.utime('main.c', None) if self.TraceOn(): - print("os.path.getmtime() after restore:", os.path.getmtime('main.c')) - + print( + "os.path.getmtime() after restore:", + os.path.getmtime('main.c')) # Modify the source code file. with io.open('main.c', 'w', newline='\n') as f: @@ -167,28 +177,35 @@ class SourceManagerTestCase(TestBase): f.write(new_content) if self.TraceOn(): print("new content:", new_content) - print("os.path.getmtime() after writing new content:", os.path.getmtime('main.c')) + print( + "os.path.getmtime() after writing new content:", + os.path.getmtime('main.c')) # Add teardown hook to restore the file to the original content. self.addTearDownHook(restore_file) # Display the source code again. We should see the updated line. - self.expect("source list -f main.c -l %d" % self.line, SOURCE_DISPLAYED_CORRECTLY, - substrs = ['Hello lldb']) + self.expect( + "source list -f main.c -l %d" % + self.line, + SOURCE_DISPLAYED_CORRECTLY, + substrs=['Hello lldb']) def test_set_breakpoint_with_absolute_path(self): self.build() - self.runCmd("settings set target.source-map %s %s" % (os.getcwd(), os.path.join(os.getcwd(), "hidden"))) + self.runCmd("settings set target.source-map %s %s" % + (os.getcwd(), os.path.join(os.getcwd(), "hidden"))) exe = os.path.join(os.getcwd(), "a.out") main = os.path.join(os.getcwd(), "hidden", "main.c") self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, main, self.line, num_expected_locations=1, loc_exact=False) - + lldbutil.run_break_set_by_file_and_line( + self, main, self.line, num_expected_locations=1, loc_exact=False) + self.runCmd("run", RUN_SUCCEEDED) # The stop reason of the thread should be breakpoint. self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, - substrs = ['stopped', - 'main.c:%d' % self.line, - 'stop reason = breakpoint']) + substrs=['stopped', + 'main.c:%d' % self.line, + 'stop reason = breakpoint']) diff --git a/lldb/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py b/lldb/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py index 6644681d2ca..e442509c471 100644 --- a/lldb/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py +++ b/lldb/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py @@ -5,13 +5,13 @@ Test that 'stty -a' displays the same output before and after running the lldb c from __future__ import print_function - import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestSTTYBeforeAndAfter(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -24,13 +24,16 @@ class TestSTTYBeforeAndAfter(TestBase): cls.RemoveTempFile("child_send2.txt") cls.RemoveTempFile("child_read2.txt") - @expectedFailureAll(hostoslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @no_debug_info_test def test_stty_dash_a_before_and_afetr_invoking_lldb_command(self): """Test that 'stty -a' displays the same output before and after running the lldb command.""" import pexpect if not which('expect'): - self.skipTest("The 'expect' program cannot be located, skip the test") + self.skipTest( + "The 'expect' program cannot be located, skip the test") # The expect prompt. expect_prompt = "expect[0-9.]+> " diff --git a/lldb/packages/Python/lldbsuite/test/test_categories.py b/lldb/packages/Python/lldbsuite/test/test_categories.py index 0a85293109e..e2bec304832 100644 --- a/lldb/packages/Python/lldbsuite/test/test_categories.py +++ b/lldb/packages/Python/lldbsuite/test/test_categories.py @@ -20,20 +20,20 @@ debug_info_categories = [ all_categories = { 'dataformatters': 'Tests related to the type command and the data formatters subsystem', - 'dwarf' : 'Tests that can be run with DWARF debug information', - 'dwo' : 'Tests that can be run with DWO debug information', - 'dsym' : 'Tests that can be run with DSYM debug information', - 'gmodules' : 'Tests that can be run with -gmodules debug information', - 'expression' : 'Tests related to the expression parser', - 'objc' : 'Tests related to the Objective-C programming language support', - 'pyapi' : 'Tests related to the Python API', - 'basic_process' : 'Basic process execution sniff tests.', - 'cmdline' : 'Tests related to the LLDB command-line interface', - 'dyntype' : 'Tests related to dynamic type support', - 'stresstest' : 'Tests related to stressing lldb limits', - 'flakey' : 'Flakey test cases, i.e. tests that do not reliably pass at each execution', - 'lldb-mi' : 'lldb-mi tests' -} + 'dwarf': 'Tests that can be run with DWARF debug information', + 'dwo': 'Tests that can be run with DWO debug information', + 'dsym': 'Tests that can be run with DSYM debug information', + 'gmodules': 'Tests that can be run with -gmodules debug information', + 'expression': 'Tests related to the expression parser', + 'objc': 'Tests related to the Objective-C programming language support', + 'pyapi': 'Tests related to the Python API', + 'basic_process': 'Basic process execution sniff tests.', + 'cmdline': 'Tests related to the LLDB command-line interface', + 'dyntype': 'Tests related to dynamic type support', + 'stresstest': 'Tests related to stressing lldb limits', + 'flakey': 'Flakey test cases, i.e. tests that do not reliably pass at each execution', + 'lldb-mi': 'lldb-mi tests'} + def unique_string_match(yourentry, list): candidate = None @@ -63,11 +63,13 @@ def is_supported_on_platform(category, platform, compiler_paths): # allow gmodules on compilers that support it and not on ones that don't. # However, I didn't see an easy way for all the callers of this to know # the compiler being used for a test invocation. As we tend to run with - # a single compiler per test run, this shouldn't be a major issue. + # a single compiler per test run, this shouldn't be a major + # issue. return False return True return True + def validate(categories, exact_match): """ For each category in categories, ensure that it's a valid category (if exact_match is false, @@ -80,10 +82,14 @@ def validate(categories, exact_match): origCategory = category if category not in all_categories and not exact_match: category = unique_string_match(category, all_categories) - if (category not in all_categories) or category == None: - print("fatal error: category '" + origCategory + "' is not a valid category") + if (category not in all_categories) or category is None: + print( + "fatal error: category '" + + origCategory + + "' is not a valid category") print("if you have added a new category, please edit test_categories.py, adding your new category to all_categories") - print("else, please specify one or more of the following: " + str(list(all_categories.keys()))) + print("else, please specify one or more of the following: " + + str(list(all_categories.keys()))) sys.exit(1) result.append(category) return result diff --git a/lldb/packages/Python/lldbsuite/test/test_result.py b/lldb/packages/Python/lldbsuite/test/test_result.py index 01db1f69163..327d170f58d 100644 --- a/lldb/packages/Python/lldbsuite/test/test_result.py +++ b/lldb/packages/Python/lldbsuite/test/test_result.py @@ -23,6 +23,7 @@ from . import configuration from lldbsuite.test_event.event_builder import EventBuilder from lldbsuite.test_event import build_exception + class LLDBTestResult(unittest2.TextTestResult): """ Enforce a singleton pattern to allow introspection of test progress. @@ -39,11 +40,15 @@ class LLDBTestResult(unittest2.TextTestResult): def getTerminalSize(): import os env = os.environ + def ioctl_GWINSZ(fd): try: - import fcntl, termios, struct, os + import fcntl + import termios + import struct + import os cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, - '1234')) + '1234')) except: return return cr @@ -78,15 +83,18 @@ class LLDBTestResult(unittest2.TextTestResult): def _config_string(self, test): compiler = getattr(test, "getCompiler", None) arch = getattr(test, "getArchitecture", None) - return "%s-%s" % (compiler() if compiler else "", arch() if arch else "") + return "%s-%s" % (compiler() if compiler else "", + arch() if arch else "") def _exc_info_to_string(self, err, test): """Overrides superclass TestResult's method in order to append our test config info string to the exception info string.""" if hasattr(test, "getArchitecture") and hasattr(test, "getCompiler"): - return '%sConfig=%s-%s' % (super(LLDBTestResult, self)._exc_info_to_string(err, test), - test.getArchitecture(), - test.getCompiler()) + return '%sConfig=%s-%s' % (super(LLDBTestResult, + self)._exc_info_to_string(err, + test), + test.getArchitecture(), + test.getCompiler()) else: return super(LLDBTestResult, self)._exc_info_to_string(err, test) @@ -103,23 +111,29 @@ class LLDBTestResult(unittest2.TextTestResult): """ test_categories = [] test_method = getattr(test, test._testMethodName) - if test_method != None and hasattr(test_method, "categories"): + if test_method is not None and hasattr(test_method, "categories"): test_categories.extend(test_method.categories) test_categories.extend(test.getCategories()) return test_categories - def hardMarkAsSkipped(self,test): + def hardMarkAsSkipped(self, test): getattr(test, test._testMethodName).__func__.__unittest_skip__ = True - getattr(test, test._testMethodName).__func__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run" + getattr( + test, + test._testMethodName).__func__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run" def startTest(self, test): - if configuration.shouldSkipBecauseOfCategories(self.getCategoriesForTest(test)): + if configuration.shouldSkipBecauseOfCategories( + self.getCategoriesForTest(test)): self.hardMarkAsSkipped(test) - configuration.setCrashInfoHook("%s at %s" % (str(test),inspect.getfile(test.__class__))) + configuration.setCrashInfoHook( + "%s at %s" % + (str(test), inspect.getfile( + test.__class__))) self.counter += 1 - #if self.counter == 4: + # if self.counter == 4: # import crashinfo # crashinfo.testCrashReporterDescription(None) test.test_number = self.counter @@ -133,7 +147,9 @@ class LLDBTestResult(unittest2.TextTestResult): def addSuccess(self, test): super(LLDBTestResult, self).addSuccess(test) if configuration.parsable: - self.stream.write("PASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) + self.stream.write( + "PASS: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) if self.results_formatter: self.results_formatter.handle_event( EventBuilder.event_for_success(test)) @@ -150,7 +166,6 @@ class LLDBTestResult(unittest2.TextTestResult): else: return inspect.getsourcefile(test.__class__) - def _saveBuildErrorTuple(self, test, err): # Adjust the error description so it prints the build command and build error # rather than an uninformative Python backtrace. @@ -172,7 +187,9 @@ class LLDBTestResult(unittest2.TextTestResult): if method: method() if configuration.parsable: - self.stream.write("FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) + self.stream.write( + "FAIL: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) if self.results_formatter: # Handle build errors as a separate event type if self._isBuildError(err): @@ -188,7 +205,9 @@ class LLDBTestResult(unittest2.TextTestResult): if method: method() if configuration.parsable: - self.stream.write("CLEANUP ERROR: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) + self.stream.write( + "CLEANUP ERROR: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) if self.results_formatter: self.results_formatter.handle_event( EventBuilder.event_for_cleanup_error( @@ -201,19 +220,21 @@ class LLDBTestResult(unittest2.TextTestResult): if method: method() if configuration.parsable: - self.stream.write("FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) + self.stream.write( + "FAIL: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) if configuration.useCategories: test_categories = self.getCategoriesForTest(test) for category in test_categories: if category in configuration.failuresPerCategory: - configuration.failuresPerCategory[category] = configuration.failuresPerCategory[category] + 1 + configuration.failuresPerCategory[ + category] = configuration.failuresPerCategory[category] + 1 else: configuration.failuresPerCategory[category] = 1 if self.results_formatter: self.results_formatter.handle_event( EventBuilder.event_for_failure(test, err)) - def addExpectedFailure(self, test, err, bugnumber): configuration.sdir_has_content = True super(LLDBTestResult, self).addExpectedFailure(test, err, bugnumber) @@ -221,11 +242,13 @@ class LLDBTestResult(unittest2.TextTestResult): if method: method(err, bugnumber) if configuration.parsable: - self.stream.write("XFAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) + self.stream.write( + "XFAIL: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) if self.results_formatter: self.results_formatter.handle_event( EventBuilder.event_for_expected_failure( - test, err, bugnumber)) + test, err, bugnumber)) def addSkip(self, test, reason): configuration.sdir_has_content = True @@ -234,7 +257,9 @@ class LLDBTestResult(unittest2.TextTestResult): if method: method() if configuration.parsable: - self.stream.write("UNSUPPORTED: LLDB (%s) :: %s (%s) \n" % (self._config_string(test), str(test), reason)) + self.stream.write( + "UNSUPPORTED: LLDB (%s) :: %s (%s) \n" % + (self._config_string(test), str(test), reason)) if self.results_formatter: self.results_formatter.handle_event( EventBuilder.event_for_skip(test, reason)) @@ -246,7 +271,9 @@ class LLDBTestResult(unittest2.TextTestResult): if method: method(bugnumber) if configuration.parsable: - self.stream.write("XPASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test))) + self.stream.write( + "XPASS: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) if self.results_formatter: self.results_formatter.handle_event( EventBuilder.event_for_unexpected_success( diff --git a/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py b/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py index a7e639e4b8b..e8bc69b7f62 100644 --- a/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py +++ b/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py @@ -23,6 +23,7 @@ import threading class CommunicatorThread(threading.Thread): """Provides a thread class that communicates with a subprocess.""" + def __init__(self, process, event, output_file): super(CommunicatorThread, self).__init__() # Don't let this thread prevent shutdown. @@ -100,6 +101,7 @@ class ProcessHelper(object): @see ProcessHelper.process_helper() """ + def __init__(self): super(ProcessHelper, self).__init__() @@ -281,6 +283,7 @@ class UnixProcessHelper(ProcessHelper): This implementation supports anything that looks Posix-y (e.g. Darwin, Linux, *BSD, etc.) """ + def __init__(self): super(UnixProcessHelper, self).__init__() @@ -302,7 +305,7 @@ class UnixProcessHelper(ProcessHelper): stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 + universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 close_fds=True, preexec_fn=preexec_func) @@ -412,8 +415,10 @@ class UnixProcessHelper(ProcessHelper): signal_name = signal_names_by_number.get(signo, "") return (signo, signal_name) + class WindowsProcessHelper(ProcessHelper): """Provides a Windows implementation of the ProcessHelper class.""" + def __init__(self): super(WindowsProcessHelper, self).__init__() @@ -429,7 +434,7 @@ class WindowsProcessHelper(ProcessHelper): stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 + universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 creationflags=creation_flags) def was_hard_terminate(self, returncode): @@ -447,6 +452,7 @@ class ProcessDriver(object): way. The on_process_exited method is informed if the exit was natural or if it was due to a timeout. """ + def __init__(self, soft_terminate_timeout=10.0): super(ProcessDriver, self).__init__() self.process_helper = ProcessHelper.process_helper() diff --git a/lldb/packages/Python/lldbsuite/test/test_runner/test/test_process_control.py b/lldb/packages/Python/lldbsuite/test/test_runner/test/test_process_control.py index 817c83c4fb5..88ad961be2b 100755 --- a/lldb/packages/Python/lldbsuite/test/test_runner/test/test_process_control.py +++ b/lldb/packages/Python/lldbsuite/test/test_runner/test/test_process_control.py @@ -27,6 +27,7 @@ from test_runner import process_control class TestInferiorDriver(process_control.ProcessDriver): + def __init__(self, soft_terminate_timeout=None): super(TestInferiorDriver, self).__init__( soft_terminate_timeout=soft_terminate_timeout) @@ -58,6 +59,7 @@ class TestInferiorDriver(process_control.ProcessDriver): class ProcessControlTests(unittest.TestCase): + @classmethod def _suppress_soft_terminate(cls, command): # Do the right thing for your platform here. @@ -79,7 +81,8 @@ class ProcessControlTests(unittest.TestCase): # Base command. script_name = "{}/inferior.py".format(os.path.dirname(__file__)) if not os.path.exists(script_name): - raise Exception("test inferior python script not found: {}".format(script_name)) + raise Exception( + "test inferior python script not found: {}".format(script_name)) command = ([sys.executable, script_name]) if ignore_soft_terminate: @@ -97,6 +100,7 @@ class ProcessControlTests(unittest.TestCase): class ProcessControlNoTimeoutTests(ProcessControlTests): """Tests the process_control module.""" + def test_run_completes(self): """Test that running completes and gets expected stdout/stderr.""" driver = TestInferiorDriver() @@ -115,6 +119,7 @@ class ProcessControlNoTimeoutTests(ProcessControlTests): class ProcessControlTimeoutTests(ProcessControlTests): + def test_run_completes(self): """Test that running completes and gets expected return code.""" driver = TestInferiorDriver() @@ -124,7 +129,7 @@ class ProcessControlTimeoutTests(ProcessControlTests): "{}s".format(timeout_seconds), False) self.assertTrue( - driver.completed_event.wait(2*timeout_seconds), + driver.completed_event.wait(2 * timeout_seconds), "process failed to complete") self.assertEqual(driver.returncode, 0) @@ -141,13 +146,13 @@ class ProcessControlTimeoutTests(ProcessControlTests): # Sleep twice as long as the timeout interval. This # should force a timeout. self.inferior_command( - options="--sleep {}".format(timeout_seconds*2)), + options="--sleep {}".format(timeout_seconds * 2)), "{}s".format(timeout_seconds), with_core) # We should complete, albeit with a timeout. self.assertTrue( - driver.completed_event.wait(2*timeout_seconds), + driver.completed_event.wait(2 * timeout_seconds), "process failed to complete") # Ensure we received a timeout. diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py index 6f814c13ec8..0cc50370b16 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py @@ -9,16 +9,19 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiExitTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_gdb_exit(self): """Test that '-gdb-exit' terminates local debug session and exits.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -37,12 +40,14 @@ class MiExitTestCase(lldbmi_testcase.MiTestCaseBase): import pexpect self.expect(pexpect.EOF) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_quit(self): """Test that 'quit' exits immediately.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -60,12 +65,14 @@ class MiExitTestCase(lldbmi_testcase.MiTestCaseBase): import pexpect self.expect(pexpect.EOF) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_q(self): """Test that 'q' exits immediately.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py index 99a06f2711f..7a99ecf7d1e 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py @@ -5,22 +5,22 @@ Test lldb-mi -file-xxx commands. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiFileTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_file_exec_and_symbols_file(self): """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols exe.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -file-exec-and-symbols works for filename self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -31,12 +31,12 @@ class MiFileTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_file_exec_and_symbols_absolute_path(self): """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols fullpath/exe.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -file-exec-and-symbols works for absolute path import os @@ -49,12 +49,12 @@ class MiFileTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_file_exec_and_symbols_relative_path(self): """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols relpath/exe.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -file-exec-and-symbols works for relative path path = "./%s" % self.myexe @@ -66,12 +66,12 @@ class MiFileTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_file_exec_and_symbols_unknown_path(self): """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols badpath/exe.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -file-exec-and-symbols fails on unknown path path = "unknown_dir/%s" % self.myexe diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py index 9898ad4398f..5daf3fe0939 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py @@ -5,23 +5,25 @@ Test lldb-mi -gdb-set and -gdb-show commands. from __future__ import print_function - import unittest2 import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_gdb_set_target_async_default(self): """Test that 'lldb-mi --interpreter' switches to async mode by default.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Switch to sync mode self.runCmd("-gdb-set target-async off") @@ -35,13 +37,15 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-show target-async") self.expect("\^done,value=\"on\"") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @expectedFlakeyLinux("llvm.org/pr26028") # Fails in ~1% of cases + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFlakeyLinux("llvm.org/pr26028") # Fails in ~1% of cases def test_lldbmi_gdb_set_target_async_on(self): """Test that 'lldb-mi --interpreter' can execute commands in async mode.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Switch to sync mode self.runCmd("-gdb-set target-async off") @@ -64,13 +68,17 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\*running") self.expect("@\"argc=1") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @expectedFailureAll(oslist=["linux"], bugnumber="Failing in ~11/600 dosep runs (build 3120-3122)") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["linux"], + bugnumber="Failing in ~11/600 dosep runs (build 3120-3122)") def test_lldbmi_gdb_set_target_async_off(self): """Test that 'lldb-mi --interpreter' can execute commands in sync mode.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -gdb-set can switch to sync mode self.runCmd("-gdb-set target-async off") @@ -84,28 +92,32 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): # Test that program is executed in async mode self.runCmd("-exec-run") - unexpected = [ "\*running" ] # "\*running" is async notification - it = self.expect(unexpected + [ "@\"argc=1\\\\r\\\\n" ]) + unexpected = ["\*running"] # "\*running" is async notification + it = self.expect(unexpected + ["@\"argc=1\\\\r\\\\n"]) if it < len(unexpected): self.fail("unexpected found: %s" % unexpected[it]) - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_gdb_show_target_async(self): """Test that 'lldb-mi --interpreter' in async mode by default.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that default target-async value is "on" self.runCmd("-gdb-show target-async") self.expect("\^done,value=\"on\"") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_gdb_show_language(self): """Test that 'lldb-mi --interpreter' can get current language.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -122,36 +134,41 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-show language") self.expect("\^done,value=\"c\+\+\"") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @unittest2.expectedFailure("-gdb-set ignores unknown properties") def test_lldbmi_gdb_set_unknown(self): """Test that 'lldb-mi --interpreter' fails when setting an unknown property.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -gdb-set fails if property is unknown self.runCmd("-gdb-set unknown some_value") self.expect("\^error") - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") @unittest2.expectedFailure("-gdb-show ignores unknown properties") def test_lldbmi_gdb_show_unknown(self): """Test that 'lldb-mi --interpreter' fails when showing an unknown property.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -gdb-show fails if property is unknown self.runCmd("-gdb-show unknown") self.expect("\^error") - - @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_gdb_set_ouptut_radix(self): """Test that 'lldb-mi --interpreter' works for -gdb-set output-radix.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -162,31 +179,32 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") self.runCmd("-exec-run") - self.expect("\^running"); + self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") # Setup variable - self.runCmd("-var-create var_a * a"); - self.expect("\^done,name=\"var_a\",numchild=\"0\",value=\"10\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.runCmd("-var-create var_a * a") + self.expect( + "\^done,name=\"var_a\",numchild=\"0\",value=\"10\",type=\"int\",thread-id=\"1\",has_more=\"0\"") # Test default output - self.runCmd("-var-evaluate-expression var_a"); - self.expect("\^done,value=\"10\""); + self.runCmd("-var-evaluate-expression var_a") + self.expect("\^done,value=\"10\"") # Test hex output - self.runCmd("-gdb-set output-radix 16"); - self.expect("\^done"); - self.runCmd("-var-evaluate-expression var_a"); - self.expect("\^done,value=\"0xa\""); + self.runCmd("-gdb-set output-radix 16") + self.expect("\^done") + self.runCmd("-var-evaluate-expression var_a") + self.expect("\^done,value=\"0xa\"") # Test octal output - self.runCmd("-gdb-set output-radix 8"); - self.expect("\^done"); - self.runCmd("-var-evaluate-expression var_a"); - self.expect("\^done,value=\"012\""); + self.runCmd("-gdb-set output-radix 8") + self.expect("\^done") + self.runCmd("-var-evaluate-expression var_a") + self.expect("\^done,value=\"012\"") # Test decimal output - self.runCmd("-gdb-set output-radix 10"); - self.expect("\^done"); - self.runCmd("-var-evaluate-expression var_a"); - self.expect("\^done,value=\"10\""); + self.runCmd("-gdb-set output-radix 10") + self.expect("\^done") + self.runCmd("-var-evaluate-expression var_a") + self.expect("\^done,value=\"10\"") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py index 8e1d72aa19c..68d670c9cd1 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py @@ -5,22 +5,22 @@ Test lldb-mi =library-loaded notifications. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_library_loaded(self): """Test that 'lldb-mi --interpreter' shows the =library-loaded notifications.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -29,7 +29,30 @@ class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase): # Test =library-loaded import os path = os.path.join(os.getcwd(), self.myexe) - symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe) - def add_slashes(x): return x.replace("\\", "\\\\").replace("\"", "\\\"").replace("\'", "\\\'").replace("\0", "\\\0") - self.expect([ "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\",size=\"[0-9]+\"" % (add_slashes(path), add_slashes(path), add_slashes(path), add_slashes(symbols_path)), - "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"0\",loaded_addr=\"-\",size=\"[0-9]+\"" % (add_slashes(path), add_slashes(path), add_slashes(path)) ]) + symbols_path = os.path.join( + path + ".dSYM", + "Contents", + "Resources", + "DWARF", + self.myexe) + + def add_slashes(x): return x.replace( + "\\", + "\\\\").replace( + "\"", + "\\\"").replace( + "\'", + "\\\'").replace( + "\0", + "\\\0") + self.expect( + [ + "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\",size=\"[0-9]+\"" % + (add_slashes(path), + add_slashes(path), + add_slashes(path), + add_slashes(symbols_path)), + "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"0\",loaded_addr=\"-\",size=\"[0-9]+\"" % + (add_slashes(path), + add_slashes(path), + add_slashes(path))]) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py index 50e108e9fa2..b853673211b 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py @@ -5,52 +5,53 @@ Test that the lldb-mi driver prints prompt properly. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiPromptTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_prompt(self): """Test that 'lldb-mi --interpreter' echos '(gdb)' after commands and events.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that lldb-mi is ready after unknown command self.runCmd("-unknown-command") - self.expect("\^error,msg=\"Driver\. Received command '-unknown-command'\. It was not handled\. Command 'unknown-command' not in Command Factory\"") - self.expect(self.child_prompt, exactly = True) + self.expect( + "\^error,msg=\"Driver\. Received command '-unknown-command'\. It was not handled\. Command 'unknown-command' not in Command Factory\"") + self.expect(self.child_prompt, exactly=True) # Test that lldb-mi is ready after -file-exec-and-symbols self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Test that lldb-mi is ready after -break-insert self.runCmd("-break-insert -f main") self.expect("\^done,bkpt={number=\"1\"") - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Test that lldb-mi is ready after -exec-run self.runCmd("-exec-run") self.expect("\*running") - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Test that lldb-mi is ready after BP hit self.expect("\*stopped,reason=\"breakpoint-hit\"") - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Test that lldb-mi is ready after -exec-continue self.runCmd("-exec-continue") self.expect("\^running") - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Test that lldb-mi is ready after program exited self.expect("\*stopped,reason=\"exited-normally\"") - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py index 1e0b240d0d6..38c6b1f0b17 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py @@ -11,68 +11,79 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races @expectedFlakeyLinux("llvm.org/pr24717") def test_lldbmi_break_insert_function_pending(self): """Test that 'lldb-mi --interpreter' works for pending function breakpoints.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") self.runCmd("-break-insert -f printf") - #FIXME function name is unknown on Darwin, fullname should be ??, line is -1 - #self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"printf\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") - self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"\?\?\",file=\"\?\?\",fullname=\"\?\?/\?\?\",line=\"0\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") - #FIXME function name is unknown on Darwin, fullname should be ??, line -1 - #self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"printf\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") - self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"\?\?\",file=\"\?\?\",fullname=\"\?\?/\?\?\",line=\"0\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") + # FIXME function name is unknown on Darwin, fullname should be ??, line is -1 + # self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"printf\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") + self.expect( + "\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"\?\?\",file=\"\?\?\",fullname=\"\?\?/\?\?\",line=\"0\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") + # FIXME function name is unknown on Darwin, fullname should be ??, line -1 + # self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"printf\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"\?\?\",file=\"\?\?\",fullname=\"\?\?/\?\?\",line=\"0\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") self.runCmd("-exec-run") self.expect("\^running") - self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_break_insert_function(self): """Test that 'lldb-mi --interpreter' works for function breakpoints.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") self.runCmd("-break-insert -f main") - self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}") - self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}") + self.expect( + "\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}") self.runCmd("-exec-run") self.expect("\^running") - self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}") self.expect("\*stopped,reason=\"breakpoint-hit\"") # Test that -break-insert can set non-pending BP self.runCmd("-break-insert printf") - #FIXME function name is unknown on Darwin - #self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") - self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") - #FIXME function name is unknown on Darwin - #self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") - self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") # FIXME function name is unknown on Darwin - #self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") - self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") + # self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") + self.expect( + "\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") + # FIXME function name is unknown on Darwin + # self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") + # FIXME function name is unknown on Darwin + # self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}") # Test that -break-insert fails if non-pending BP can't be resolved self.runCmd("-break-insert unknown_func") - self.expect("\^error,msg=\"Command 'break-insert'. Breakpoint location 'unknown_func' not found\"") + self.expect( + "\^error,msg=\"Command 'break-insert'. Breakpoint location 'unknown_func' not found\"") # Test that non-pending BP was set correctly self.runCmd("-exec-continue") @@ -84,28 +95,28 @@ class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^done,bkpt={number=\"4\"") self.runCmd("-break-insert main.cpp:ns::foo1") self.expect("\^done,bkpt={number=\"5\"") - #FIXME: quotes on filenames aren't handled correctly in lldb-mi. + # FIXME: quotes on filenames aren't handled correctly in lldb-mi. #self.runCmd("-break-insert \"main.cpp\":main") - #self.expect("\^done,bkpt={number=\"6\"") + # self.expect("\^done,bkpt={number=\"6\"") # We should hit BP #5 on 'main.cpp:ns::foo1' self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\".*bkptno=\"5\"") - #FIXME: this test is disabled due to lldb bug llvm.org/pr24271. + # FIXME: this test is disabled due to lldb bug llvm.org/pr24271. # Test that we can set a BP using the global namespace token #self.runCmd("-break-insert ::main") - #self.expect("\^done,bkpt={number=\"7\"") + # self.expect("\^done,bkpt={number=\"7\"") #self.runCmd("-break-insert main.cpp:::main") - #self.expect("\^done,bkpt={number=\"8\"") + # self.expect("\^done,bkpt={number=\"8\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_break_insert_file_line_pending(self): """Test that 'lldb-mi --interpreter' works for pending file:line breakpoints.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") @@ -114,19 +125,27 @@ class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase): # pending BP line = line_number('main.cpp', '// BP_return') self.runCmd("-break-insert -f main.cpp:%d" % line) - self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",pending=\[\"main.cpp:%d\"\],times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line, line)) - self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",pending=\[\"main.cpp:%d\"\],times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line, line)) + self.expect( + "\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",pending=\[\"main.cpp:%d\"\],times=\"0\",original-location=\"main.cpp:%d\"}" % + (line, + line, + line)) + self.expect( + "=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",pending=\[\"main.cpp:%d\"\],times=\"0\",original-location=\"main.cpp:%d\"}" % + (line, + line, + line)) self.runCmd("-exec-run") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_break_insert_file_line(self): """Test that 'lldb-mi --interpreter' works for file:line breakpoints.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") @@ -141,24 +160,29 @@ class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -break-insert can set non-pending BP line = line_number('main.cpp', '// BP_return') self.runCmd("-break-insert main.cpp:%d" % line) - self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line)) - self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line)) + self.expect( + "\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",times=\"0\",original-location=\"main.cpp:%d\"}" % + (line, line)) + self.expect( + "=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",times=\"0\",original-location=\"main.cpp:%d\"}" % + (line, line)) # Test that -break-insert fails if non-pending BP can't be resolved self.runCmd("-break-insert unknown_file:1") - self.expect("\^error,msg=\"Command 'break-insert'. Breakpoint location 'unknown_file:1' not found\"") + self.expect( + "\^error,msg=\"Command 'break-insert'. Breakpoint location 'unknown_file:1' not found\"") # Test that non-pending BP was set correctly self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_break_insert_file_line_absolute_path(self): """Test that 'lldb-mi --interpreter' works for file:line breakpoints.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") @@ -180,19 +204,21 @@ class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_break_insert_settings(self): """Test that 'lldb-mi --interpreter' can set breakpoints accoridng to global options.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") - # Set target.move-to-nearest-code=off and try to set BP #1 that shouldn't be hit - self.runCmd("-interpreter-exec console \"settings set target.move-to-nearest-code off\"") + # Set target.move-to-nearest-code=off and try to set BP #1 that + # shouldn't be hit + self.runCmd( + "-interpreter-exec console \"settings set target.move-to-nearest-code off\"") self.expect("\^done") line = line_number('main.cpp', '// BP_before_main') self.runCmd("-break-insert -f main.cpp:%d" % line) @@ -201,17 +227,23 @@ class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase): # Test that non-pending BP will not be set on non-existing line if target.move-to-nearest-code=off # Note: this increases the BP number by 1 even though BP #2 is invalid. self.runCmd("-break-insert main.cpp:%d" % line) - self.expect("\^error,msg=\"Command 'break-insert'. Breakpoint location 'main.cpp:%d' not found\"" % line) - - # Set target.move-to-nearest-code=on and target.skip-prologue=on and set BP #3 - self.runCmd("-interpreter-exec console \"settings set target.move-to-nearest-code on\"") - self.runCmd("-interpreter-exec console \"settings set target.skip-prologue on\"") + self.expect( + "\^error,msg=\"Command 'break-insert'. Breakpoint location 'main.cpp:%d' not found\"" % + line) + + # Set target.move-to-nearest-code=on and target.skip-prologue=on and + # set BP #3 + self.runCmd( + "-interpreter-exec console \"settings set target.move-to-nearest-code on\"") + self.runCmd( + "-interpreter-exec console \"settings set target.skip-prologue on\"") self.expect("\^done") self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"3\"") # Set target.skip-prologue=off and set BP #4 - self.runCmd("-interpreter-exec console \"settings set target.skip-prologue off\"") + self.runCmd( + "-interpreter-exec console \"settings set target.skip-prologue off\"") self.expect("\^done") self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"4\"") @@ -219,74 +251,92 @@ class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase): # Test that BP #4 is located before BP #3 self.runCmd("-exec-run") self.expect("\^running") - self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"4\"") + self.expect( + "\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"4\"") # Test that BP #3 is hit self.runCmd("-exec-continue") self.expect("\^running") - self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"3\"") + self.expect( + "\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"3\"") - # Test that the target.language=pascal setting works and that BP #5 is NOT set - self.runCmd("-interpreter-exec console \"settings set target.language c\"") + # Test that the target.language=pascal setting works and that BP #5 is + # NOT set + self.runCmd( + "-interpreter-exec console \"settings set target.language c\"") self.expect("\^done") self.runCmd("-break-insert ns.foo1") self.expect("\^error") # Test that the target.language=c++ setting works and that BP #6 is hit - self.runCmd("-interpreter-exec console \"settings set target.language c++\"") + self.runCmd( + "-interpreter-exec console \"settings set target.language c++\"") self.expect("\^done") self.runCmd("-break-insert ns::foo1") self.expect("\^done,bkpt={number=\"6\"") self.runCmd("-exec-continue") self.expect("\^running") - self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"6\"") + self.expect( + "\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"6\"") # Test that BP #1 and #2 weren't set by running to program exit self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_break_enable_disable(self): """Test that 'lldb-mi --interpreter' works for enabling / disabling breakpoints.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") self.runCmd("-break-insert main") - self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\"") - self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"main\"}") + self.expect( + "\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\"") + self.expect( + "=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"main\"}") self.runCmd("-exec-run") self.expect("\^running") - self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"main\"}") - self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"1\"") + self.expect( + "=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"main\"}") + self.expect( + "\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"1\"") self.runCmd("-break-insert ns::foo1") - self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo1\(\)\"") - self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo1\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo1\"}") + self.expect( + "\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo1\(\)\"") + self.expect( + "=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo1\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo1\"}") self.runCmd("-break-insert ns::foo2") - self.expect("\^done,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\"") - self.expect("=breakpoint-modified,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo2\"}") + self.expect( + "\^done,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\"") + self.expect( + "=breakpoint-modified,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo2\"}") # disable the 2nd breakpoint self.runCmd("-break-disable 2") self.expect("\^done") - self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"n\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo1\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo1\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"n\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo1\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo1\"}") # disable the 3rd breakpoint and re-enable self.runCmd("-break-disable 3") self.expect("\^done") - self.expect("=breakpoint-modified,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"n\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo2\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"n\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo2\"}") self.runCmd("-break-enable 3") self.expect("\^done") - self.expect("=breakpoint-modified,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo2\"}") + self.expect( + "=breakpoint-modified,bkpt={number=\"3\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"ns::foo2\(\)\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",times=\"0\",original-location=\"ns::foo2\"}") self.runCmd("-exec-continue") self.expect("\^running") - self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"3\"") + self.expect( + "\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"3\"") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py index a62b9a25400..0406ede7178 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py @@ -5,23 +5,25 @@ Test lldb-mi -exec-xxx commands. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr25000: lldb-mi does not receive broadcasted notification from Core/Process about process stopped") + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr25000: lldb-mi does not receive broadcasted notification from Core/Process about process stopped") def test_lldbmi_exec_run(self): """Test that 'lldb-mi --interpreter' can stop at entry.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -30,20 +32,22 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test that program is stopped at entry self.runCmd("-exec-run --start") self.expect("\^running") - self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",.*?thread-id=\"1\",stopped-threads=\"all\"") + self.expect( + "\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",.*?thread-id=\"1\",stopped-threads=\"all\"") # Test that lldb-mi is ready to execute next commands - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_exec_abort(self): """Test that 'lldb-mi --interpreter' works for -exec-abort.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -exec-abort fails on invalid process self.runCmd("-exec-abort") - self.expect("\^error,msg=\"Command 'exec-abort'\. Invalid process during debug session\"") + self.expect( + "\^error,msg=\"Command 'exec-abort'\. Invalid process during debug session\"") # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -83,19 +87,20 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^done") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_exec_arguments_set(self): """Test that 'lldb-mi --interpreter' can pass args using -exec-arguments.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") # Set arguments - self.runCmd("-exec-arguments --arg1 \"2nd arg\" third_arg fourth=\"4th arg\"") + self.runCmd( + "-exec-arguments --arg1 \"2nd arg\" third_arg fourth=\"4th arg\"") self.expect("\^done") # Run to main @@ -109,7 +114,7 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-data-evaluate-expression argc") self.expect("\^done,value=\"5\"") #self.runCmd("-data-evaluate-expression argv[1]") - #self.expect("\^done,value=\"--arg1\"") + # self.expect("\^done,value=\"--arg1\"") self.runCmd("-interpreter-exec command \"print argv[1]\"") self.expect("\"--arg1\"") #self.runCmd("-data-evaluate-expression argv[2]") @@ -117,7 +122,7 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-interpreter-exec command \"print argv[2]\"") self.expect("\"2nd arg\"") #self.runCmd("-data-evaluate-expression argv[3]") - #self.expect("\^done,value=\"third_arg\"") + # self.expect("\^done,value=\"third_arg\"") self.runCmd("-interpreter-exec command \"print argv[3]\"") self.expect("\"third_arg\"") #self.runCmd("-data-evaluate-expression argv[4]") @@ -125,12 +130,12 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-interpreter-exec command \"print argv[4]\"") self.expect("\"fourth=\\\\\\\"4th arg\\\\\\\"\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_exec_arguments_reset(self): """Test that 'lldb-mi --interpreter' can reset previously set args using -exec-arguments.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -153,12 +158,12 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-data-evaluate-expression argc") self.expect("\^done,value=\"1\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_exec_next(self): """Test that 'lldb-mi --interpreter' works for stepping.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -176,22 +181,26 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test -exec-next self.runCmd("-exec-next --thread 1 --frame 0") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"29\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"29\"") # Test that --thread is optional self.runCmd("-exec-next --frame 0") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"30\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"30\"") # Test that --frame is optional self.runCmd("-exec-next --thread 1") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"31\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"31\"") # Test that both --thread and --frame are optional self.runCmd("-exec-next") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"32\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"32\"") # Test that an invalid --thread is handled self.runCmd("-exec-next --thread 0") @@ -204,13 +213,15 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-next --frame 10") #self.expect("\^error: Frame index 10 is out of range") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @expectedFailureAll(archs=["i[3-6]86"], bugnumber="xfail to get buildbot green, failing config: i386 binary running on ubuntu 14.04 x86_64") + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + archs=["i[3-6]86"], + bugnumber="xfail to get buildbot green, failing config: i386 binary running on ubuntu 14.04 x86_64") def test_lldbmi_exec_next_instruction(self): """Test that 'lldb-mi --interpreter' works for instruction stepping.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -229,25 +240,29 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test -exec-next-instruction self.runCmd("-exec-next-instruction --thread 1 --frame 0") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"28\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"28\"") # Test that --thread is optional self.runCmd("-exec-next-instruction --frame 0") self.expect("\^running") # Depending on compiler, it can stop at different line - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"(28|29)\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"(28|29)\"") # Test that --frame is optional self.runCmd("-exec-next-instruction --thread 1") self.expect("\^running") # Depending on compiler, it can stop at different line - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"(29|30)\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"(29|30)\"") # Test that both --thread and --frame are optional self.runCmd("-exec-next-instruction") self.expect("\^running") # Depending on compiler, it can stop at different line - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"(29|30|31)\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"(29|30|31)\"") # Test that an invalid --thread is handled self.runCmd("-exec-next-instruction --thread 0") @@ -260,12 +275,12 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-next-instruction --frame 10") #self.expect("\^error: Frame index 10 is out of range") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_exec_step(self): """Test that 'lldb-mi --interpreter' works for stepping into.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -283,39 +298,45 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -exec-step steps into (or not) printf depending on debug info # Note that message is different in Darwin and Linux: # Darwin: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"main\",args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value="0x[0-9a-f]+\"}],file=\"main.cpp\",fullname=\".+main.cpp\",line=\"\d\"},thread-id=\"1\",stopped-threads=\"all\" - # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\" + # Linux: + # "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\" self.runCmd("-exec-step --thread 1 --frame 0") self.expect("\^running") - it = self.expect([ "\*stopped,reason=\"end-stepping-range\".+?func=\"main\"", - "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\"" ]) + it = self.expect(["\*stopped,reason=\"end-stepping-range\".+?func=\"main\"", + "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\""]) # Exit from printf if needed if it == 1: self.runCmd("-exec-finish") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"main\"") # Test that -exec-step steps into g_MyFunction and back out # (and that --thread is optional) self.runCmd("-exec-step --frame 0") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") # Use -exec-finish here to make sure that control reaches the caller. # -exec-step can keep us in the g_MyFunction for gcc self.runCmd("-exec-finish --frame 0") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"30\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"30\"") # Test that -exec-step steps into s_MyFunction # (and that --frame is optional) self.runCmd("-exec-step --thread 1") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\".*?s_MyFunction.*?\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\".*?s_MyFunction.*?\"") # Test that -exec-step steps into g_MyFunction from inside # s_MyFunction (and that both --thread and --frame are optional) self.runCmd("-exec-step") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") # Test that an invalid --thread is handled self.runCmd("-exec-step --thread 0") @@ -328,12 +349,12 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-step --frame 10") #self.expect("\^error: Frame index 10 is out of range") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_exec_step_instruction(self): """Test that 'lldb-mi --interpreter' works for instruction stepping into.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -352,7 +373,8 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -exec-next steps over printf self.runCmd("-exec-next --thread 1 --frame 0") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"29\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"29\"") # Test that -exec-step-instruction steps over non branching # instruction @@ -364,19 +386,22 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): # instruction (and that --thread is optional) self.runCmd("-exec-step-instruction --frame 0") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") # Test that -exec-step-instruction steps over non branching # (and that --frame is optional) self.runCmd("-exec-step-instruction --thread 1") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") # Test that -exec-step-instruction steps into g_MyFunction # (and that both --thread and --frame are optional) self.runCmd("-exec-step-instruction") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"") # Test that an invalid --thread is handled self.runCmd("-exec-step-instruction --thread 0") @@ -389,12 +414,12 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-step-instruction --frame 10") #self.expect("\^error: Frame index 10 is out of range") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_exec_finish(self): """Test that 'lldb-mi --interpreter' works for -exec-finish.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -429,7 +454,8 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): # s_MyFunction (and that --frame is optional) self.runCmd("-exec-finish --thread 1") self.expect("\^running") - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\".*?s_MyFunction.*?\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\".*?s_MyFunction.*?\"") # Test that -exec-finish returns from s_MyFunction # (and that both --thread and --frame are optional) @@ -455,7 +481,7 @@ class MiExecTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - ## Test that -exec-finish returns from printf + # Test that -exec-finish returns from printf self.runCmd("-exec-finish --thread 1 --frame 0") self.expect("\^running") self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py index a19387627c4..7281ae305db 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py @@ -5,23 +5,23 @@ Test lldb-mi -data-xxx commands. from __future__ import print_function - import unittest2 import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_data_disassemble(self): """Test that 'lldb-mi --interpreter' works for -data-disassemble.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -36,16 +36,23 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Get an address for disassembling: use main self.runCmd("-data-evaluate-expression main") - self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"") + self.expect( + "\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"") addr = int(self.child.after.split("\"")[1].split(" ")[0], 16) # Test -data-disassemble: try to disassemble some address - self.runCmd("-data-disassemble -s %#x -e %#x -- 0" % (addr, addr + 0x10)) - self.expect("\^done,asm_insns=\[{address=\"0x0*%x\",func-name=\"main\",offset=\"0\",size=\"[1-9]+\",inst=\".+?\"}," % addr) - + self.runCmd( + "-data-disassemble -s %#x -e %#x -- 0" % + (addr, addr + 0x10)) + self.expect( + "\^done,asm_insns=\[{address=\"0x0*%x\",func-name=\"main\",offset=\"0\",size=\"[1-9]+\",inst=\".+?\"}," % + addr) + # Test -data-disassemble without "--" self.runCmd("-data-disassemble -s %#x -e %#x 0" % (addr, addr + 0x10)) - self.expect("\^done,asm_insns=\[{address=\"0x0*%x\",func-name=\"main\",offset=\"0\",size=\"[1-9]+\",inst=\".+?\"}," % addr) + self.expect( + "\^done,asm_insns=\[{address=\"0x0*%x\",func-name=\"main\",offset=\"0\",size=\"[1-9]+\",inst=\".+?\"}," % + addr) # Run to hello_world self.runCmd("-break-insert -f hello_world") @@ -56,27 +63,31 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Get an address for disassembling: use hello_world self.runCmd("-data-evaluate-expression hello_world") - self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`hello_world\(\) at main.cpp:[0-9]+\)\"") + self.expect( + "\^done,value=\"0x[0-9a-f]+ \(a.out`hello_world\(\) at main.cpp:[0-9]+\)\"") addr = int(self.child.after.split("\"")[1].split(" ")[0], 16) # Test -data-disassemble: try to disassemble some address - self.runCmd("-data-disassemble -s %#x -e %#x -- 0" % (addr, addr + 0x10)) + self.runCmd( + "-data-disassemble -s %#x -e %#x -- 0" % + (addr, addr + 0x10)) # This matches a line similar to: # Darwin: {address="0x0000000100000f18",func-name="hello_world()",offset="8",size="7",inst="leaq 0x65(%rip), %rdi; \"Hello, World!\\n\""}, # Linux: {address="0x0000000000400642",func-name="hello_world()",offset="18",size="5",inst="callq 0x4004d0; symbol stub for: printf"} # To match the escaped characters in the ouptut, we must use four backslashes per matches backslash # See https://docs.python.org/2/howto/regex.html#the-backslash-plague - self.expect([ "{address=\"0x[0-9a-f]+\",func-name=\"hello_world\(\)\",offset=\"[0-9]+\",size=\"[0-9]+\",inst=\".+?; \\\\\"Hello, World!\\\\\\\\n\\\\\"\"}", - "{address=\"0x[0-9a-f]+\",func-name=\"hello_world\(\)\",offset=\"[0-9]+\",size=\"[0-9]+\",inst=\".+?; symbol stub for: printf\"}" ]) + self.expect(["{address=\"0x[0-9a-f]+\",func-name=\"hello_world\(\)\",offset=\"[0-9]+\",size=\"[0-9]+\",inst=\".+?; \\\\\"Hello, World!\\\\\\\\n\\\\\"\"}", + "{address=\"0x[0-9a-f]+\",func-name=\"hello_world\(\)\",offset=\"[0-9]+\",size=\"[0-9]+\",inst=\".+?; symbol stub for: printf\"}"]) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @unittest2.skip("-data-evaluate-expression doesn't work on globals") #FIXME: the global case worked before refactoring + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + # FIXME: the global case worked before refactoring + @unittest2.skip("-data-evaluate-expression doesn't work on globals") def test_lldbmi_data_read_memory_bytes_global(self): """Test that -data-read-memory-bytes can access global buffers.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -97,7 +108,9 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -data-read-memory-bytes works for char[] type (global) self.runCmd("-data-read-memory-bytes %#x %d" % (addr, size)) - self.expect("\^done,memory=\[{begin=\"0x0*%x\",offset=\"0x0+\",end=\"0x0*%x\",contents=\"1112131400\"}\]" % (addr, addr + size)) + self.expect( + "\^done,memory=\[{begin=\"0x0*%x\",offset=\"0x0+\",end=\"0x0*%x\",contents=\"1112131400\"}\]" % + (addr, addr + size)) # Get address of static char[] self.runCmd("-data-evaluate-expression &s_CharArray") @@ -107,14 +120,16 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -data-read-memory-bytes works for static char[] type self.runCmd("-data-read-memory-bytes %#x %d" % (addr, size)) - self.expect("\^done,memory=\[{begin=\"0x0*%x\",offset=\"0x0+\",end=\"0x0*%x\",contents=\"1112131400\"}\]" % (addr, addr + size)) + self.expect( + "\^done,memory=\[{begin=\"0x0*%x\",offset=\"0x0+\",end=\"0x0*%x\",contents=\"1112131400\"}\]" % + (addr, addr + size)) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_data_read_memory_bytes_local(self): """Test that -data-read-memory-bytes can access local buffers.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd('-file-exec-and-symbols %s' % self.myexe) @@ -136,44 +151,65 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Test that an unquoted hex literal address works self.runCmd('-data-read-memory-bytes %#x %d' % (addr, size)) - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % + (addr, addr + size)) # Test that a double-quoted hex literal address works self.runCmd('-data-read-memory-bytes "%#x" %d' % (addr, size)) - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % + (addr, addr + size)) # Test that unquoted expressions work self.runCmd('-data-read-memory-bytes &array %d' % size) - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % + (addr, addr + size)) - # This doesn't work, and perhaps that makes sense, but it does work on GDB + # This doesn't work, and perhaps that makes sense, but it does work on + # GDB self.runCmd('-data-read-memory-bytes array 4') self.expect(r'\^error') #self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) self.runCmd('-data-read-memory-bytes &array[2] 2') - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="0304"\}\]' % (addr + 2, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="0304"\}\]' % + (addr + 2, addr + size)) self.runCmd('-data-read-memory-bytes first_element_ptr %d' % size) - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % + (addr, addr + size)) # Test that double-quoted expressions work self.runCmd('-data-read-memory-bytes "&array" %d' % size) - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % + (addr, addr + size)) self.runCmd('-data-read-memory-bytes "&array[0] + 1" 3') - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % (addr + 1, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % + (addr + 1, addr + size)) self.runCmd('-data-read-memory-bytes "first_element_ptr + 1" 3') - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % (addr + 1, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % + (addr + 1, addr + size)) # Test the -o (offset) option self.runCmd('-data-read-memory-bytes -o 1 &array 3') - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % (addr + 1, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % + (addr + 1, addr + size)) # Test the --thread option self.runCmd('-data-read-memory-bytes --thread 1 &array 4') - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % + (addr, addr + size)) # Test the --thread option with an invalid value self.runCmd('-data-read-memory-bytes --thread 999 &array 4') @@ -181,22 +217,29 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Test the --frame option (current frame) self.runCmd('-data-read-memory-bytes --frame 0 &array 4') - self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size)) + self.expect( + r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % + (addr, addr + size)) # Test the --frame option (outer frame) self.runCmd('-data-read-memory-bytes --frame 1 &array 4') - self.expect(r'\^done,memory=\[\{begin="0x[0-9a-f]+",offset="0x0+",end="0x[0-9a-f]+",contents="05060708"\}\]') + self.expect( + r'\^done,memory=\[\{begin="0x[0-9a-f]+",offset="0x0+",end="0x[0-9a-f]+",contents="05060708"\}\]') # Test the --frame option with an invalid value self.runCmd('-data-read-memory-bytes --frame 999 &array 4') self.expect(r'\^error') # Test all the options at once - self.runCmd('-data-read-memory-bytes --thread 1 --frame 1 -o 2 &array 2') - self.expect(r'\^done,memory=\[\{begin="0x[0-9a-f]+",offset="0x0+",end="0x[0-9a-f]+",contents="0708"\}\]') - - # Test that an expression that references undeclared variables doesn't work - self.runCmd('-data-read-memory-bytes "&undeclared_array1 + undeclared_array2[1]" 2') + self.runCmd( + '-data-read-memory-bytes --thread 1 --frame 1 -o 2 &array 2') + self.expect( + r'\^done,memory=\[\{begin="0x[0-9a-f]+",offset="0x0+",end="0x[0-9a-f]+",contents="0708"\}\]') + + # Test that an expression that references undeclared variables doesn't + # work + self.runCmd( + '-data-read-memory-bytes "&undeclared_array1 + undeclared_array2[1]" 2') self.expect(r'\^error') # Test that the address argument is required @@ -207,23 +250,25 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd('-data-read-memory-bytes &array') self.expect(r'\^error') - # Test that the address and count arguments are required when other options are present + # Test that the address and count arguments are required when other + # options are present self.runCmd('-data-read-memory-bytes --thread 1') self.expect(r'\^error') self.runCmd('-data-read-memory-bytes --thread 1 --frame 0') self.expect(r'\^error') - # Test that the count argument is required when other options are present + # Test that the count argument is required when other options are + # present self.runCmd('-data-read-memory-bytes --thread 1 &array') self.expect(r'\^error') - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_data_list_register_names(self): """Test that 'lldb-mi --interpreter' works for -data-list-register-names.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -244,12 +289,12 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-data-list-register-names 0") self.expect("\^done,register-names=\[\".+?\"\]") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_data_list_register_values(self): """Test that 'lldb-mi --interpreter' works for -data-list-register-values.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -264,18 +309,20 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Test -data-list-register-values: try to get all registers self.runCmd("-data-list-register-values x") - self.expect("\^done,register-values=\[{number=\"0\",value=\"0x[0-9a-f]+\"") + self.expect( + "\^done,register-values=\[{number=\"0\",value=\"0x[0-9a-f]+\"") # Test -data-list-register-values: try to get specified registers self.runCmd("-data-list-register-values x 0") - self.expect("\^done,register-values=\[{number=\"0\",value=\"0x[0-9a-f]+\"}\]") + self.expect( + "\^done,register-values=\[{number=\"0\",value=\"0x[0-9a-f]+\"}\]") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_data_info_line(self): """Test that 'lldb-mi --interpreter' works for -data-info-line.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -290,38 +337,46 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): # Get the address of main and its line self.runCmd("-data-evaluate-expression main") - self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"") + self.expect( + "\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"") addr = int(self.child.after.split("\"")[1].split(" ")[0], 16) line = line_number('main.cpp', '// FUNC_main') # Test that -data-info-line works for address self.runCmd("-data-info-line *%#x" % addr) - self.expect("\^done,start=\"0x0*%x\",end=\"0x[0-9a-f]+\",file=\".+?main.cpp\",line=\"%d\"" % (addr, line)) + self.expect( + "\^done,start=\"0x0*%x\",end=\"0x[0-9a-f]+\",file=\".+?main.cpp\",line=\"%d\"" % + (addr, line)) # Test that -data-info-line works for file:line self.runCmd("-data-info-line main.cpp:%d" % line) - self.expect("\^done,start=\"0x0*%x\",end=\"0x[0-9a-f]+\",file=\".+?main.cpp\",line=\"%d\"" % (addr, line)) + self.expect( + "\^done,start=\"0x0*%x\",end=\"0x[0-9a-f]+\",file=\".+?main.cpp\",line=\"%d\"" % + (addr, line)) # Test that -data-info-line fails when invalid address is specified self.runCmd("-data-info-line *0x0") - self.expect("\^error,msg=\"Command 'data-info-line'\. Error: The LineEntry is absent or has an unknown format\.\"") + self.expect( + "\^error,msg=\"Command 'data-info-line'\. Error: The LineEntry is absent or has an unknown format\.\"") # Test that -data-info-line fails when file is unknown self.runCmd("-data-info-line unknown_file:1") - self.expect("\^error,msg=\"Command 'data-info-line'\. Error: The LineEntry is absent or has an unknown format\.\"") + self.expect( + "\^error,msg=\"Command 'data-info-line'\. Error: The LineEntry is absent or has an unknown format\.\"") # Test that -data-info-line fails when line has invalid format self.runCmd("-data-info-line main.cpp:bad_line") - self.expect("\^error,msg=\"error: invalid line number string 'bad_line'") + self.expect( + "\^error,msg=\"error: invalid line number string 'bad_line'") self.runCmd("-data-info-line main.cpp:0") self.expect("\^error,msg=\"error: zero is an invalid line number") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_data_evaluate_expression(self): """Test that 'lldb-mi --interpreter' works for -data-evaluate-expression.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -334,6 +389,7 @@ class MiDataTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - # Check 2d array + # Check 2d array self.runCmd("-data-evaluate-expression array2d") - self.expect("\^done,value=\"\{\[0\] = \{\[0\] = 1, \[1\] = 2, \[2\] = 3\}, \[1\] = \{\[0\] = 4, \[1\] = 5, \[2\] = 6\}\}\"") + self.expect( + "\^done,value=\"\{\[0\] = \{\[0\] = 1, \[1\] = 2, \[2\] = 3\}, \[1\] = \{\[0\] = 4, \[1\] = 5, \[2\] = 6\}\}\"") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py index d80bc7f94a6..24b3881c1be 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py @@ -5,22 +5,22 @@ Test lldb-mi can interpret CLI commands directly. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_target_create(self): """Test that 'lldb-mi --interpreter' can create target by 'target create' command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that "target create" loads executable self.runCmd("target create \"%s\"" % self.myexe) @@ -33,13 +33,13 @@ class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_breakpoint_set(self): """Test that 'lldb-mi --interpreter' can set breakpoint by 'breakpoint set' command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -56,17 +56,18 @@ class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("=breakpoint-modified,bkpt={number=\"1\"") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_settings_set_target_run_args_before(self): """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command before than target was created.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that "settings set target.run-args" passes arguments to executable - #FIXME: --arg1 causes an error - self.runCmd("setting set target.run-args arg1 \"2nd arg\" third_arg fourth=\"4th arg\"") + # FIXME: --arg1 causes an error + self.runCmd( + "setting set target.run-args arg1 \"2nd arg\" third_arg fourth=\"4th arg\"") self.expect("\^done") # Load executable @@ -80,21 +81,22 @@ class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): # Test that arguments were passed properly self.expect("@\"argc=5\\\\r\\\\n\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_settings_set_target_run_args_after(self): """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command after than target was created.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") # Test that "settings set target.run-args" passes arguments to executable - #FIXME: --arg1 causes an error - self.runCmd("setting set target.run-args arg1 \"2nd arg\" third_arg fourth=\"4th arg\"") + # FIXME: --arg1 causes an error + self.runCmd( + "setting set target.run-args arg1 \"2nd arg\" third_arg fourth=\"4th arg\"") self.expect("\^done") # Run @@ -104,13 +106,13 @@ class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): # Test that arguments were passed properly self.expect("@\"argc=5\\\\r\\\\n\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_process_launch(self): """Test that 'lldb-mi --interpreter' can launch process by "process launch" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -127,13 +129,13 @@ class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): # Test that breakpoint hit self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_thread_step_in(self): """Test that 'lldb-mi --interpreter' can step in by "thread step-in" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -149,21 +151,23 @@ class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): # Test that "thread step-in" steps into (or not) printf depending on debug info # Note that message is different in Darwin and Linux: # Darwin: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"main\",args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value="0x[0-9a-f]+\"}],file=\"main.cpp\",fullname=\".+main.cpp\",line=\"\d\"},thread-id=\"1\",stopped-threads=\"all\" - # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\" + # Linux: + # "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\" self.runCmd("thread step-in") self.expect("\^done") - it = self.expect([ "@\"argc=1\\\\r\\\\n\"", - "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\"" ]) + it = self.expect(["@\"argc=1\\\\r\\\\n\"", + "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\""]) if it == 0: - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"main\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_thread_step_over(self): """Test that 'lldb-mi --interpreter' can step over by "thread step-over" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -182,13 +186,13 @@ class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("@\"argc=1\\\\r\\\\n\"") self.expect("\*stopped,reason=\"end-stepping-range\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_thread_continue(self): """Test that 'lldb-mi --interpreter' can continue execution by "thread continue" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py index 2bcaaad38f4..23da825d591 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py @@ -5,25 +5,27 @@ Test lldb-mi -interpreter-exec command. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_target_create(self): """Test that 'lldb-mi --interpreter' can create target by 'target create' command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that "target create" loads executable - self.runCmd("-interpreter-exec console \"target create \\\"%s\\\"\"" % self.myexe) + self.runCmd( + "-interpreter-exec console \"target create \\\"%s\\\"\"" % + self.myexe) self.expect("\^done") # Test that executable was loaded properly @@ -33,12 +35,12 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_breakpoint_set(self): """Test that 'lldb-mi --interpreter' can set breakpoint by 'breakpoint set' command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -55,17 +57,18 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("=breakpoint-modified,bkpt={number=\"1\"") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races @expectedFlakeyLinux(bugnumber="llvm.org/pr25470") def test_lldbmi_settings_set_target_run_args_before(self): """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command before than target was created.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that "settings set target.run-args" passes arguments to executable - #FIXME: --arg1 causes an error - self.runCmd("-interpreter-exec console \"setting set target.run-args arg1 \\\"2nd arg\\\" third_arg fourth=\\\"4th arg\\\"\"") + # FIXME: --arg1 causes an error + self.runCmd( + "-interpreter-exec console \"setting set target.run-args arg1 \\\"2nd arg\\\" third_arg fourth=\\\"4th arg\\\"\"") self.expect("\^done") # Load executable @@ -87,21 +90,24 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test that program exited normally self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @expectedFailureAll(oslist=["linux"], bugnumber="Failing in ~9/600 dosep runs (build 3120-3122)") + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["linux"], + bugnumber="Failing in ~9/600 dosep runs (build 3120-3122)") def test_lldbmi_settings_set_target_run_args_after(self): """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command after than target was created.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") # Test that "settings set target.run-args" passes arguments to executable - #FIXME: --arg1 causes an error - self.runCmd("-interpreter-exec console \"setting set target.run-args arg1 \\\"2nd arg\\\" third_arg fourth=\\\"4th arg\\\"\"") + # FIXME: --arg1 causes an error + self.runCmd( + "-interpreter-exec console \"setting set target.run-args arg1 \\\"2nd arg\\\" third_arg fourth=\\\"4th arg\\\"\"") self.expect("\^done") # Run to BP_printf @@ -109,7 +115,7 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") self.runCmd("-exec-run") - self.expect("\^running"); + self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") # Run to BP_return @@ -117,7 +123,7 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"2\"") self.runCmd("-exec-continue") - self.expect("\^running"); + self.expect("\^running") # Test that arguments were passed properly self.expect("@\"argc=5\\\\r\\\\n\"") @@ -130,12 +136,12 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): # Hit BP_return self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_process_launch(self): """Test that 'lldb-mi --interpreter' can launch process by "process launch" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -152,12 +158,12 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test that breakpoint hit self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_thread_step_in(self): """Test that 'lldb-mi --interpreter' can step in by "thread step-in" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -173,20 +179,22 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): # Test that "thread step-in" steps into (or not) printf depending on debug info # Note that message is different in Darwin and Linux: # Darwin: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"main\",args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value="0x[0-9a-f]+\"}],file=\"main.cpp\",fullname=\".+main.cpp\",line=\"\d\"},thread-id=\"1\",stopped-threads=\"all\" - # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\" + # Linux: + # "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\" self.runCmd("-interpreter-exec console \"thread step-in\"") self.expect("\^done") - it = self.expect([ "@\"argc=1\\\\r\\\\n\"", - "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\"" ]) + it = self.expect(["@\"argc=1\\\\r\\\\n\"", + "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\""]) if it == 0: - self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"") + self.expect( + "\*stopped,reason=\"end-stepping-range\".+?func=\"main\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_thread_step_over(self): """Test that 'lldb-mi --interpreter' can step over by "thread step-over" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -205,13 +213,13 @@ class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("@\"argc=1\\\\r\\\\n\"") self.expect("\*stopped,reason=\"end-stepping-range\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races @expectedFlakeyLinux("llvm.org/pr25470") def test_lldbmi_thread_continue(self): """Test that 'lldb-mi --interpreter' can continue execution by "thread continue" command.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py index 277ffe70c1c..a862609d697 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py @@ -5,9 +5,9 @@ Base class for lldb-mi test cases. from __future__ import print_function - from lldbsuite.test.lldbtest import * + class MiTestCaseBase(Base): mydir = None @@ -43,7 +43,7 @@ class MiTestCaseBase(Base): self.child.setecho(True) self.child.logfile_read = open(self.mylog, "w") # wait until lldb-mi has started up and is ready to go - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) def runCmd(self, cmd): self.child.sendline(cmd) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py index 197bfa80b3a..e4cd98b2292 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py @@ -5,22 +5,22 @@ Test that the lldb-mi handles signals properly. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Fails on FreeBSD apparently due to thread race conditions + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Fails on FreeBSD apparently due to thread race conditions def test_lldbmi_stopped_when_interrupt(self): """Test that 'lldb-mi --interpreter' interrupt and resume a looping app.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -41,23 +41,25 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -exec-interrupt can interrupt an execution self.runCmd("-exec-interrupt") - self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\",.+?thread-id=\"1\",stopped-threads=\"all\"") + self.expect( + "\*stopped,reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\",.+?thread-id=\"1\",stopped-threads=\"all\"") # Continue (to loop forever) self.runCmd("-exec-continue") self.expect("\^running") # Test that Ctrl+C can interrupt an execution - self.child.sendintr() #FIXME: here uses self.child directly - self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\",.*thread-id=\"1\",stopped-threads=\"all\"") + self.child.sendintr() # FIXME: here uses self.child directly + self.expect( + "\*stopped,reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\",.*thread-id=\"1\",stopped-threads=\"all\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Fails on FreeBSD apparently due to thread race conditions - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Fails on FreeBSD apparently due to thread race conditions + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_stopped_when_stopatentry_local(self): """Test that 'lldb-mi --interpreter' notifies after it was stopped on entry (local).""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -70,9 +72,12 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): # Test that *stopped is printed # Note that message is different in Darwin and Linux: # Darwin: "*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",frame={level=\"0\",addr=\"0x[0-9a-f]+\",func=\"_dyld_start\",file=\"??\",fullname=\"??\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\" - # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"??\",args=[],file=\"??\",fullname=\"??\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\" - self.expect([ "\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"_dyld_start\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"\},thread-id=\"1\",stopped-threads=\"all\"", - "\*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"\?\?\",args=\[\],file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\"" ]) + # Linux: + # "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"??\",args=[],file=\"??\",fullname=\"??\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\" + self.expect( + [ + "\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"_dyld_start\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"\},thread-id=\"1\",stopped-threads=\"all\"", + "\*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"\?\?\",args=\[\],file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\""]) # Run to main to make sure we have not exited the application self.runCmd("-break-insert -f main") @@ -81,7 +86,7 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows @skipUnlessDarwin def test_lldbmi_stopped_when_stopatentry_remote(self): """Test that 'lldb-mi --interpreter' notifies after it was stopped on entry (remote).""" @@ -93,19 +98,25 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): self.skipTest("debugserver exe not found") hostname = "localhost" import random - port = 12000 + random.randint(0,3999) # the same as GdbRemoteTestCaseBase.get_next_port + # the same as GdbRemoteTestCaseBase.get_next_port + port = 12000 + random.randint(0, 3999) import pexpect - debugserver_child = pexpect.spawn("%s %s:%d" % (debugserver_exe, hostname, port)) - self.addTearDownHook(lambda: debugserver_child.terminate(force = True)) + debugserver_child = pexpect.spawn( + "%s %s:%d" % + (debugserver_exe, hostname, port)) + self.addTearDownHook(lambda: debugserver_child.terminate(force=True)) - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Connect to debugserver - self.runCmd("-interpreter-exec command \"platform select remote-macosx --sysroot /\"") + self.runCmd( + "-interpreter-exec command \"platform select remote-macosx --sysroot /\"") self.expect("\^done") self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") - self.runCmd("-interpreter-exec command \"process connect connect://%s:%d\"" % (hostname, port)) + self.runCmd( + "-interpreter-exec command \"process connect connect://%s:%d\"" % + (hostname, port)) self.expect("\^done") # Run with stop-at-entry flag @@ -113,19 +124,20 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^done") # Test that *stopped is printed - self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",.+?thread-id=\"1\",stopped-threads=\"all\"") + self.expect( + "\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",.+?thread-id=\"1\",stopped-threads=\"all\"") # Exit self.runCmd("-gdb-exit") self.expect("\^exit") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_stopped_when_segfault_local(self): """Test that 'lldb-mi --interpreter' notifies after it was stopped when segfault occurred (local).""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -147,9 +159,11 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): # Test that *stopped is printed # Note that message is different in Darwin and Linux: # Darwin: "*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS (code=1, address=0x0)\",thread-id=\"1\",stopped-threads=\"all\"" - # Linux: "*stopped,reason=\"exception-received\",exception=\"invalid address (fault address: 0x0)\",thread-id=\"1\",stopped-threads=\"all\"" - self.expect([ "\*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS \(code=1, address=0x0\)\",thread-id=\"1\",stopped-threads=\"all\"", - "\*stopped,reason=\"exception-received\",exception=\"invalid address \(fault address: 0x0\)\",thread-id=\"1\",stopped-threads=\"all\"" ]) + # Linux: "*stopped,reason=\"exception-received\",exception=\"invalid + # address (fault address: + # 0x0)\",thread-id=\"1\",stopped-threads=\"all\"" + self.expect(["\*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS \(code=1, address=0x0\)\",thread-id=\"1\",stopped-threads=\"all\"", + "\*stopped,reason=\"exception-received\",exception=\"invalid address \(fault address: 0x0\)\",thread-id=\"1\",stopped-threads=\"all\""]) @skipUnlessDarwin def test_lldbmi_stopped_when_segfault_remote(self): @@ -162,27 +176,34 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): self.skipTest("debugserver exe not found") hostname = "localhost" import random - port = 12000 + random.randint(0,3999) # the same as GdbRemoteTestCaseBase.get_next_port + # the same as GdbRemoteTestCaseBase.get_next_port + port = 12000 + random.randint(0, 3999) import pexpect - debugserver_child = pexpect.spawn("%s %s:%d" % (debugserver_exe, hostname, port)) - self.addTearDownHook(lambda: debugserver_child.terminate(force = True)) + debugserver_child = pexpect.spawn( + "%s %s:%d" % + (debugserver_exe, hostname, port)) + self.addTearDownHook(lambda: debugserver_child.terminate(force=True)) - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Connect to debugserver - self.runCmd("-interpreter-exec command \"platform select remote-macosx --sysroot /\"") + self.runCmd( + "-interpreter-exec command \"platform select remote-macosx --sysroot /\"") self.expect("\^done") self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") - self.runCmd("-interpreter-exec command \"process connect connect://%s:%d\"" % (hostname, port)) + self.runCmd( + "-interpreter-exec command \"process connect connect://%s:%d\"" % + (hostname, port)) self.expect("\^done") # Run to main self.runCmd("-break-insert -f main") self.expect("\^done,bkpt={number=\"1\"") - #FIXME -exec-run doesn't work - self.runCmd("-interpreter-exec command \"process launch\"") #FIXME: self.runCmd("-exec-run") - self.expect("\^done") #FIXME: self.expect("\^running") + # FIXME -exec-run doesn't work + # FIXME: self.runCmd("-exec-run") + self.runCmd("-interpreter-exec command \"process launch\"") + self.expect("\^done") # FIXME: self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") # Set do_segfault=1 and run (to cause a segfault error) @@ -192,7 +213,8 @@ class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") # Test that *stopped is printed - self.expect("\*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS \(code=1, address=0x0\)\",thread-id=\"1\",stopped-threads=\"all\"") + self.expect( + "\*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS \(code=1, address=0x0\)\",thread-id=\"1\",stopped-threads=\"all\"") # Exit self.runCmd("-gdb-exit") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py index 54ed9195133..454597c1c5d 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py @@ -5,22 +5,22 @@ Test lldb-mi -stack-xxx commands. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_stack_list_arguments(self): """Test that 'lldb-mi --interpreter' can shows arguments.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -33,55 +33,66 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - # Test that -stack-list-arguments lists empty stack arguments if range is empty + # Test that -stack-list-arguments lists empty stack arguments if range + # is empty self.runCmd("-stack-list-arguments 0 1 0") self.expect("\^done,stack-args=\[\]") # Test that -stack-list-arguments lists stack arguments without values # (and that low-frame and high-frame are optional) self.runCmd("-stack-list-arguments 0") - self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[name=\"argc\",name=\"argv\"\]}") + self.expect( + "\^done,stack-args=\[frame={level=\"0\",args=\[name=\"argc\",name=\"argv\"\]}") self.runCmd("-stack-list-arguments --no-values") - self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[name=\"argc\",name=\"argv\"\]}") + self.expect( + "\^done,stack-args=\[frame={level=\"0\",args=\[name=\"argc\",name=\"argv\"\]}") # Test that -stack-list-arguments lists stack arguments with all values self.runCmd("-stack-list-arguments 1 0 0") - self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\".*\"}\]}\]") + self.expect( + "\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\".*\"}\]}\]") self.runCmd("-stack-list-arguments --all-values 0 0") - self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\".*\"}\]}\]") + self.expect( + "\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\".*\"}\]}\]") - # Test that -stack-list-arguments lists stack arguments with simple values + # Test that -stack-list-arguments lists stack arguments with simple + # values self.runCmd("-stack-list-arguments 2 0 1") - self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",type=\"int\",value=\"1\"},{name=\"argv\",type=\"const char \*\*\",value=\".*\"}\]}") + self.expect( + "\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",type=\"int\",value=\"1\"},{name=\"argv\",type=\"const char \*\*\",value=\".*\"}\]}") self.runCmd("-stack-list-arguments --simple-values 0 1") - self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",type=\"int\",value=\"1\"},{name=\"argv\",type=\"const char \*\*\",value=\".*\"}\]}") + self.expect( + "\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",type=\"int\",value=\"1\"},{name=\"argv\",type=\"const char \*\*\",value=\".*\"}\]}") - # Test that an invalid low-frame is handled + # Test that an invalid low-frame is handled # FIXME: -1 is treated as unsigned int self.runCmd("-stack-list-arguments 0 -1 0") - #self.expect("\^error") + # self.expect("\^error") self.runCmd("-stack-list-arguments 0 0") - self.expect("\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"") + self.expect( + "\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"") # Test that an invalid high-frame is handled # FIXME: -1 is treated as unsigned int self.runCmd("-stack-list-arguments 0 0 -1") - #self.expect("\^error") + # self.expect("\^error") # Test that a missing low-frame or high-frame is handled self.runCmd("-stack-list-arguments 0 0") - self.expect("\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"") + self.expect( + "\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"") - # Test that an invalid low-frame is handled + # Test that an invalid low-frame is handled self.runCmd("-stack-list-arguments 0 0") - self.expect("\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"") + self.expect( + "\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_stack_list_locals(self): """Test that 'lldb-mi --interpreter' can shows local variables.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -111,16 +122,20 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test -stack-list-locals: use 1 or --all-values self.runCmd("-stack-list-locals 1") - self.expect("\^done,locals=\[{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") + self.expect( + "\^done,locals=\[{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") self.runCmd("-stack-list-locals --all-values") - self.expect("\^done,locals=\[{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") + self.expect( + "\^done,locals=\[{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") # Test -stack-list-locals: use 2 or --simple-values self.runCmd("-stack-list-locals 2") - self.expect("\^done,locals=\[{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") + self.expect( + "\^done,locals=\[{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") self.runCmd("-stack-list-locals --simple-values") - self.expect("\^done,locals=\[{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") - + self.expect( + "\^done,locals=\[{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") + # Test struct local variable: # Run to BP_local_struct_test line = line_number('main.cpp', '// BP_local_struct_test') @@ -129,7 +144,7 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Test -stack-list-locals: use 0 or --no-values self.runCmd("-stack-list-locals 0") self.expect("\^done,locals=\[name=\"var_c\"\]") @@ -138,16 +153,18 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test -stack-list-locals: use 1 or --all-values self.runCmd("-stack-list-locals 1") - self.expect("\^done,locals=\[{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") + self.expect( + "\^done,locals=\[{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") self.runCmd("-stack-list-locals --all-values") - self.expect("\^done,locals=\[{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") + self.expect( + "\^done,locals=\[{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") # Test -stack-list-locals: use 2 or --simple-values self.runCmd("-stack-list-locals 2") self.expect("\^done,locals=\[{name=\"var_c\",type=\"my_type\"}\]") self.runCmd("-stack-list-locals --simple-values") self.expect("\^done,locals=\[{name=\"var_c\",type=\"my_type\"}\]") - + # Test array local variable: # Run to BP_local_array_test line = line_number('main.cpp', '// BP_local_array_test') @@ -156,7 +173,7 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Test -stack-list-locals: use 0 or --no-values self.runCmd("-stack-list-locals 0") self.expect("\^done,locals=\[name=\"array\"\]") @@ -165,16 +182,18 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test -stack-list-locals: use 1 or --all-values self.runCmd("-stack-list-locals 1") - self.expect("\^done,locals=\[{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") + self.expect( + "\^done,locals=\[{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") self.runCmd("-stack-list-locals --all-values") - self.expect("\^done,locals=\[{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") + self.expect( + "\^done,locals=\[{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") # Test -stack-list-locals: use 2 or --simple-values self.runCmd("-stack-list-locals 2") self.expect("\^done,locals=\[{name=\"array\",type=\"int \[3\]\"}\]") self.runCmd("-stack-list-locals --simple-values") self.expect("\^done,locals=\[{name=\"array\",type=\"int \[3\]\"}\]") - + # Test pointers as local variable: # Run to BP_local_pointer_test line = line_number('main.cpp', '// BP_local_pointer_test') @@ -183,26 +202,32 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Test -stack-list-locals: use 0 or --no-values self.runCmd("-stack-list-locals 0") - self.expect("\^done,locals=\[name=\"test_str\",name=\"var_e\",name=\"ptr\"\]") + self.expect( + "\^done,locals=\[name=\"test_str\",name=\"var_e\",name=\"ptr\"\]") self.runCmd("-stack-list-locals --no-values") - self.expect("\^done,locals=\[name=\"test_str\",name=\"var_e\",name=\"ptr\"\]") + self.expect( + "\^done,locals=\[name=\"test_str\",name=\"var_e\",name=\"ptr\"\]") # Test -stack-list-locals: use 1 or --all-values self.runCmd("-stack-list-locals 1") - self.expect("\^done,locals=\[{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]") + self.expect( + "\^done,locals=\[{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]") self.runCmd("-stack-list-locals --all-values") - self.expect("\^done,locals=\[{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]") + self.expect( + "\^done,locals=\[{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]") # Test -stack-list-locals: use 2 or --simple-values self.runCmd("-stack-list-locals 2") - self.expect("\^done,locals=\[{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]") + self.expect( + "\^done,locals=\[{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]") self.runCmd("-stack-list-locals --simple-values") - self.expect("\^done,locals=\[{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]") - - # Test -stack-list-locals in a function with catch clause, + self.expect( + "\^done,locals=\[{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]") + + # Test -stack-list-locals in a function with catch clause, # having unnamed parameter # Run to BP_catch_unnamed line = line_number('main.cpp', '// BP_catch_unnamed') @@ -215,12 +240,13 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test -stack-list-locals: use --no-values self.runCmd("-stack-list-locals --no-values") self.expect("\^done,locals=\[name=\"i\",name=\"j\"\]") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_stack_list_variables(self): """Test that 'lldb-mi --interpreter' can shows local variables and arguments.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -244,22 +270,28 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test -stack-list-variables: use 0 or --no-values self.runCmd("-stack-list-variables 0") - self.expect("\^done,variables=\[{arg=\"1\",name=\"c\"},{arg=\"1\",name=\"d\"},{name=\"a\"},{name=\"b\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"c\"},{arg=\"1\",name=\"d\"},{name=\"a\"},{name=\"b\"}\]") self.runCmd("-stack-list-variables --no-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"c\"},{arg=\"1\",name=\"d\"},{name=\"a\"},{name=\"b\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"c\"},{arg=\"1\",name=\"d\"},{name=\"a\"},{name=\"b\"}\]") # Test -stack-list-variables: use 1 or --all-values self.runCmd("-stack-list-variables 1") - self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",value=\"30\"},{arg=\"1\",name=\"d\",value=\"40\"},{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"c\",value=\"30\"},{arg=\"1\",name=\"d\",value=\"40\"},{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") self.runCmd("-stack-list-variables --all-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",value=\"30\"},{arg=\"1\",name=\"d\",value=\"40\"},{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"c\",value=\"30\"},{arg=\"1\",name=\"d\",value=\"40\"},{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]") # Test -stack-list-variables: use 2 or --simple-values self.runCmd("-stack-list-variables 2") - self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",type=\"int\",value=\"30\"},{arg=\"1\",name=\"d\",type=\"int\",value=\"40\"},{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"c\",type=\"int\",value=\"30\"},{arg=\"1\",name=\"d\",type=\"int\",value=\"40\"},{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") self.runCmd("-stack-list-variables --simple-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",type=\"int\",value=\"30\"},{arg=\"1\",name=\"d\",type=\"int\",value=\"40\"},{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") - + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"c\",type=\"int\",value=\"30\"},{arg=\"1\",name=\"d\",type=\"int\",value=\"40\"},{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]") + # Test struct local variable: # Run to BP_local_struct_test line = line_number('main.cpp', '// BP_local_struct_test_with_args') @@ -268,25 +300,31 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Test -stack-list-variables: use 0 or --no-values self.runCmd("-stack-list-variables 0") - self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\"},{name=\"var_c\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"var_e\"},{name=\"var_c\"}\]") self.runCmd("-stack-list-variables --no-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\"},{name=\"var_c\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"var_e\"},{name=\"var_c\"}\]") # Test -stack-list-variables: use 1 or --all-values self.runCmd("-stack-list-variables 1") - self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",value=\"{var_a = 20, var_b = 98 'b', inner_ = {var_d = 40}}\"},{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"var_e\",value=\"{var_a = 20, var_b = 98 'b', inner_ = {var_d = 40}}\"},{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") self.runCmd("-stack-list-variables --all-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",value=\"{var_a = 20, var_b = 98 'b', inner_ = {var_d = 40}}\"},{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"var_e\",value=\"{var_a = 20, var_b = 98 'b', inner_ = {var_d = 40}}\"},{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]") # Test -stack-list-variables: use 2 or --simple-values self.runCmd("-stack-list-variables 2") - self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",type=\"my_type\"},{name=\"var_c\",type=\"my_type\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"var_e\",type=\"my_type\"},{name=\"var_c\",type=\"my_type\"}\]") self.runCmd("-stack-list-variables --simple-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",type=\"my_type\"},{name=\"var_c\",type=\"my_type\"}\]") - + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"var_e\",type=\"my_type\"},{name=\"var_c\",type=\"my_type\"}\]") + # Test array local variable: # Run to BP_local_array_test line = line_number('main.cpp', '// BP_local_array_test_with_args') @@ -295,25 +333,31 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Test -stack-list-variables: use 0 or --no-values self.runCmd("-stack-list-variables 0") - self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\"},{name=\"array\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"other_array\"},{name=\"array\"}\]") self.runCmd("-stack-list-variables --no-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\"},{name=\"array\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"other_array\"},{name=\"array\"}\]") # Test -stack-list-variables: use 1 or --all-values self.runCmd("-stack-list-variables 1") - self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",value=\".*?\"},{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"other_array\",value=\".*?\"},{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") self.runCmd("-stack-list-variables --all-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",value=\".*?\"},{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"other_array\",value=\".*?\"},{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]") # Test -stack-list-variables: use 2 or --simple-values self.runCmd("-stack-list-variables 2") - self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",type=\"int \*\",value=\".*?\"},{name=\"array\",type=\"int \[3\]\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"other_array\",type=\"int \*\",value=\".*?\"},{name=\"array\",type=\"int \[3\]\"}\]") self.runCmd("-stack-list-variables --simple-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",type=\"int \*\",value=\".*?\"},{name=\"array\",type=\"int \[3\]\"}\]") - + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"other_array\",type=\"int \*\",value=\".*?\"},{name=\"array\",type=\"int \[3\]\"}\]") + # Test pointers as local variable: # Run to BP_local_pointer_test line = line_number('main.cpp', '// BP_local_pointer_test_with_args') @@ -322,12 +366,14 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-exec-continue") self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Test -stack-list-variables: use 0 or --no-values self.runCmd("-stack-list-variables 0") - self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\"},{arg=\"1\",name=\"arg_ptr\"},{name=\"test_str\"},{name=\"var_e\"},{name=\"ptr\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"arg_str\"},{arg=\"1\",name=\"arg_ptr\"},{name=\"test_str\"},{name=\"var_e\"},{name=\"ptr\"}\]") self.runCmd("-stack-list-variables --no-values") - self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\"},{arg=\"1\",name=\"arg_ptr\"},{name=\"test_str\"},{name=\"var_e\"},{name=\"ptr\"}\]") + self.expect( + "\^done,variables=\[{arg=\"1\",name=\"arg_str\"},{arg=\"1\",name=\"arg_ptr\"},{name=\"test_str\"},{name=\"var_e\"},{name=\"ptr\"}\]") # Test -stack-list-variables: use 1 or --all-values self.runCmd("-stack-list-variables 1") @@ -340,13 +386,13 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\",type=\"const char \*\",value=\".*?String.*?\"},{arg=\"1\",name=\"arg_ptr\",type=\"int \*\",value=\".*?\"},{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]") self.runCmd("-stack-list-variables --simple-values") self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\",type=\"const char \*\",value=\".*?String.*?\"},{arg=\"1\",name=\"arg_ptr\",type=\"int \*\",value=\".*?\"},{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]") - - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_stack_info_depth(self): """Test that 'lldb-mi --interpreter' can shows depth of the stack.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -365,26 +411,27 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^done,depth=\"[1-9]\"") # Test that max-depth restricts check of stack depth - #FIXME: max-depth argument is ignored + # FIXME: max-depth argument is ignored self.runCmd("-stack-info-depth 1") - #self.expect("\^done,depth=\"1\"") + # self.expect("\^done,depth=\"1\"") # Test that invalid max-depth argument is handled - #FIXME: max-depth argument is ignored + # FIXME: max-depth argument is ignored self.runCmd("-stack-info-depth -1") - #self.expect("\^error") + # self.expect("\^error") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races @skipUnlessDarwin def test_lldbmi_stack_info_frame(self): """Test that 'lldb-mi --interpreter' can show information about current frame.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Test that -stack-info-frame fails when program isn't running self.runCmd("-stack-info-frame") - self.expect("\^error,msg=\"Command 'stack-info-frame'\. Invalid process during debug session\"") + self.expect( + "\^error,msg=\"Command 'stack-info-frame'\. Invalid process during debug session\"") # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -399,7 +446,8 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -stack-info-frame works when program was stopped on BP self.runCmd("-stack-info-frame") - self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") + self.expect( + "\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") # Select frame #1 self.runCmd("-stack-select-frame 1") @@ -407,19 +455,20 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -stack-info-frame works when specified frame was selected self.runCmd("-stack-info-frame") - self.expect("\^done,frame=\{level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+?\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"\}") + self.expect( + "\^done,frame=\{level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+?\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"\}") # Test that -stack-info-frame fails when an argument is specified - #FIXME: unknown argument is ignored + # FIXME: unknown argument is ignored self.runCmd("-stack-info-frame unknown_arg") - #self.expect("\^error") + # self.expect("\^error") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_stack_list_frames(self): """Test that 'lldb-mi --interpreter' can lists the frames on the stack.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -434,14 +483,15 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test stack frame: get frame #0 info self.runCmd("-stack-list-frames 0 0") - self.expect("\^done,stack=\[frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}\]") + self.expect( + "\^done,stack=\[frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}\]") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_stack_select_frame(self): """Test that 'lldb-mi --interpreter' can choose current frame.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -456,15 +506,18 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test that -stack-select-frame requires 1 mandatory argument self.runCmd("-stack-select-frame") - self.expect("\^error,msg=\"Command 'stack-select-frame'\. Command Args\. Validation failed. Mandatory args not found: frame_id\"") + self.expect( + "\^error,msg=\"Command 'stack-select-frame'\. Command Args\. Validation failed. Mandatory args not found: frame_id\"") # Test that -stack-select-frame fails on invalid frame number self.runCmd("-stack-select-frame 99") - self.expect("\^error,msg=\"Command 'stack-select-frame'\. Frame ID invalid\"") + self.expect( + "\^error,msg=\"Command 'stack-select-frame'\. Frame ID invalid\"") # Test that current frame is #0 self.runCmd("-stack-info-frame") - self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") + self.expect( + "\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") # Test that -stack-select-frame can select the selected frame self.runCmd("-stack-select-frame 0") @@ -472,7 +525,8 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test that current frame is still #0 self.runCmd("-stack-info-frame") - self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") + self.expect( + "\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") # Test that -stack-select-frame can select frame #1 (parent frame) self.runCmd("-stack-select-frame 1") @@ -481,9 +535,11 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test that current frame is #1 # Note that message is different in Darwin and Linux: # Darwin: "^done,frame={level=\"1\",addr=\"0x[0-9a-f]+\",func=\"start\",file=\"??\",fullname=\"??\",line=\"-1\"}" - # Linux: "^done,frame={level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+\",file=\".+\",fullname=\".+\",line=\"\d+\"}" + # Linux: + # "^done,frame={level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+\",file=\".+\",fullname=\".+\",line=\"\d+\"}" self.runCmd("-stack-info-frame") - self.expect("\^done,frame=\{level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\"\}") + self.expect( + "\^done,frame=\{level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\"\}") # Test that -stack-select-frame can select frame #0 (child frame) self.runCmd("-stack-select-frame 0") @@ -491,4 +547,5 @@ class MiStackTestCase(lldbmi_testcase.MiTestCaseBase): # Test that current frame is #0 and it has the same information self.runCmd("-stack-info-frame") - self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") + self.expect( + "\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py index 8ddb6b3a150..7673846d6df 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py @@ -9,23 +9,24 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_executable_option_file(self): """Test that 'lldb-mi --interpreter %s' loads executable file.""" - self.spawnLldbMi(args = "%s" % self.myexe) + self.spawnLldbMi(args="%s" % self.myexe) # Test that the executable is loaded when file was specified self.expect("-file-exec-and-symbols \"%s\"" % self.myexe) self.expect("\^done") # Test that lldb-mi is ready when executable was loaded - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Run to main self.runCmd("-break-insert -f main") @@ -39,25 +40,27 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_executable_option_unknown_file(self): """Test that 'lldb-mi --interpreter %s' fails on unknown executable file.""" # Prepare path to executable path = "unknown_file" - self.spawnLldbMi(args = "%s" % path) + self.spawnLldbMi(args="%s" % path) # Test that the executable isn't loaded when unknown file was specified self.expect("-file-exec-and-symbols \"%s\"" % path) - self.expect("\^error,msg=\"Command 'file-exec-and-symbols'. Target binary '%s' is invalid. error: unable to find executable for '%s'\"" % (path, path)) + self.expect( + "\^error,msg=\"Command 'file-exec-and-symbols'. Target binary '%s' is invalid. error: unable to find executable for '%s'\"" % + (path, path)) # Test that lldb-mi is ready when executable was loaded - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_executable_option_absolute_path(self): """Test that 'lldb-mi --interpreter %s' loads executable which is specified via absolute path.""" @@ -65,69 +68,74 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): import os path = os.path.join(os.getcwd(), self.myexe) - self.spawnLldbMi(args = "%s" % path) + self.spawnLldbMi(args="%s" % path) - # Test that the executable is loaded when file was specified using absolute path + # Test that the executable is loaded when file was specified using + # absolute path self.expect("-file-exec-and-symbols \"%s\"" % path) self.expect("\^done") # Test that lldb-mi is ready when executable was loaded - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Run self.runCmd("-exec-run") self.expect("\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_executable_option_relative_path(self): """Test that 'lldb-mi --interpreter %s' loads executable which is specified via relative path.""" # Prepare path to executable path = "./%s" % self.myexe - self.spawnLldbMi(args = "%s" % path) + self.spawnLldbMi(args="%s" % path) - # Test that the executable is loaded when file was specified using relative path + # Test that the executable is loaded when file was specified using + # relative path self.expect("-file-exec-and-symbols \"%s\"" % path) self.expect("\^done") # Test that lldb-mi is ready when executable was loaded - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Run self.runCmd("-exec-run") self.expect("\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_executable_option_unknown_path(self): """Test that 'lldb-mi --interpreter %s' fails on executable file which is specified via unknown path.""" # Prepare path to executable path = "unknown_dir/%s" % self.myexe - self.spawnLldbMi(args = "%s" % path) + self.spawnLldbMi(args="%s" % path) - # Test that the executable isn't loaded when file was specified using unknown path + # Test that the executable isn't loaded when file was specified using + # unknown path self.expect("-file-exec-and-symbols \"%s\"" % path) - self.expect("\^error,msg=\"Command 'file-exec-and-symbols'. Target binary '%s' is invalid. error: unable to find executable for '%s'\"" % (path, path)) + self.expect( + "\^error,msg=\"Command 'file-exec-and-symbols'. Target binary '%s' is invalid. error: unable to find executable for '%s'\"" % + (path, path)) # Test that lldb-mi is ready when executable was loaded - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_source_option_start_script(self): """Test that 'lldb-mi --interpreter' can execute user's commands after initial commands were executed.""" # Prepared source file sourceFile = "start_script" - self.spawnLldbMi(args = "--source %s" % sourceFile) + self.spawnLldbMi(args="--source %s" % sourceFile) # After '-file-exec-and-symbols a.out' self.expect("-file-exec-and-symbols %s" % self.myexe) @@ -153,23 +161,23 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\*stopped,reason=\"breakpoint-hit\"") # Test that lldb-mi is ready after execution of --source start_script - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Try to evaluate 'a' expression self.runCmd("-data-evaluate-expression a") self.expect("\^done,value=\"10\"") - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_source_option_start_script_exit(self): """Test that 'lldb-mi --interpreter' can execute a prepared file which passed via --source option.""" # Prepared source file sourceFile = "start_script_exit" - self.spawnLldbMi(args = "--source %s" % sourceFile) + self.spawnLldbMi(args="--source %s" % sourceFile) # After '-file-exec-and-symbols a.out' self.expect("-file-exec-and-symbols %s" % self.myexe) @@ -203,15 +211,15 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^exit") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_source_option_start_script_error(self): """Test that 'lldb-mi --interpreter' stops execution of initial commands in case of error.""" # Prepared source file sourceFile = "start_script_error" - self.spawnLldbMi(args = "--source %s" % sourceFile) + self.spawnLldbMi(args="--source %s" % sourceFile) # After '-file-exec-and-symbols a.out' self.expect("-file-exec-and-symbols %s" % self.myexe) @@ -222,22 +230,22 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^error") # Test that lldb-mi is ready after execution of --source start_script - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_log_option(self): """Test that 'lldb-mi --log' creates a log file in the current directory.""" - + logDirectory = "." - self.spawnLldbMi(args = "%s --log" % self.myexe) + self.spawnLldbMi(args="%s --log" % self.myexe) # Test that the executable is loaded when file was specified self.expect("-file-exec-and-symbols \"%s\"" % self.myexe) self.expect("\^done") # Test that lldb-mi is ready when executable was loaded - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Run self.runCmd("-exec-run") @@ -245,7 +253,8 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\*stopped,reason=\"exited-normally\"") # Check log file is created - import glob,os + import glob + import os logFile = glob.glob(logDirectory + "/lldb-mi-*.log") if not logFile: @@ -255,23 +264,25 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): for f in logFile: os.remove(f) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_log_directory_option(self): """Test that 'lldb-mi --log --log-dir' creates a log file in the directory specified by --log-dir.""" - + # Create log in temp directory import tempfile logDirectory = tempfile.gettempdir() - self.spawnLldbMi(args = "%s --log --log-dir=%s" % (self.myexe,logDirectory)) + self.spawnLldbMi( + args="%s --log --log-dir=%s" % + (self.myexe, logDirectory)) # Test that the executable is loaded when file was specified self.expect("-file-exec-and-symbols \"%s\"" % self.myexe) self.expect("\^done") # Test that lldb-mi is ready when executable was loaded - self.expect(self.child_prompt, exactly = True) + self.expect(self.child_prompt, exactly=True) # Run self.runCmd("-exec-run") @@ -279,12 +290,13 @@ class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\*stopped,reason=\"exited-normally\"") # Check log file is created - import glob,os + import glob + import os logFile = glob.glob(logDirectory + "/lldb-mi-*.log") if not logFile: - self.fail("log file not found") - + self.fail("log file not found") + # Delete log for f in logFile: os.remove(f) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py index 859c096e336..23374330ba1 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py @@ -5,23 +5,25 @@ Test lldb-mi -symbol-xxx commands. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiSymbolTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @expectedFailureAll(oslist=["linux"], bugnumber="new failure after r256863") + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["linux"], + bugnumber="new failure after r256863") def test_lldbmi_symbol_list_lines_file(self): """Test that 'lldb-mi --interpreter' works for -symbol-list-lines when file exists.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -36,22 +38,31 @@ class MiSymbolTestCase(lldbmi_testcase.MiTestCaseBase): # Get address of main and its line self.runCmd("-data-evaluate-expression main") - self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"") + self.expect( + "\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"") addr = int(self.child.after.split("\"")[1].split(" ")[0], 16) line = line_number('main.cpp', '// FUNC_main') # Test that -symbol-list-lines works on valid data self.runCmd("-symbol-list-lines main.cpp") - self.expect("\^done,lines=\[\{pc=\"0x0*%x\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d+\"\})+\]" % (addr, line)) + self.expect( + "\^done,lines=\[\{pc=\"0x0*%x\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d+\"\})+\]" % + (addr, line)) # Test that -symbol-list-lines doesn't include lines from other sources # by checking the first and last line, and making sure the other lines # are between 30 and 39. - sline = line_number('symbol_list_lines_inline_test2.cpp', '// FUNC_gfunc2') - eline = line_number('symbol_list_lines_inline_test2.cpp', '// END_gfunc2') + sline = line_number( + 'symbol_list_lines_inline_test2.cpp', + '// FUNC_gfunc2') + eline = line_number( + 'symbol_list_lines_inline_test2.cpp', + '// END_gfunc2') self.runCmd("-symbol-list-lines symbol_list_lines_inline_test2.cpp") - self.expect("\^done,lines=\[\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"3\d\"\})*,\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"3\d\"\})*\]" % (sline, eline)) - ##FIXME: This doesn't work for symbol_list_lines_inline_test.cpp due to clang bug llvm.org/pr24716 (fixed in newer versions of clang) + self.expect( + "\^done,lines=\[\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"3\d\"\})*,\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"3\d\"\})*\]" % + (sline, eline)) + # FIXME: This doesn't work for symbol_list_lines_inline_test.cpp due to clang bug llvm.org/pr24716 (fixed in newer versions of clang) ##sline = line_number('symbol_list_lines_inline_test.cpp', '// FUNC_gfunc') ##eline = line_number('symbol_list_lines_inline_test.cpp', '// STRUCT_s') ##self.runCmd("-symbol-list-lines symbol_list_lines_inline_test.cpp") @@ -62,22 +73,31 @@ class MiSymbolTestCase(lldbmi_testcase.MiTestCaseBase): sline = line_number('symbol_list_lines_inline_test.h', '// FUNC_ifunc') eline = line_number('symbol_list_lines_inline_test.h', '// FUNC_mfunc') self.runCmd("-symbol-list-lines symbol_list_lines_inline_test.h") - self.expect("\^done,lines=\[\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d\"\})*(,\{pc=\"0x[0-9a-f]+\",line=\"1\d\"\})*,\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"2\d\"\})*\]" % (sline, eline)) + self.expect( + "\^done,lines=\[\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d\"\})*(,\{pc=\"0x[0-9a-f]+\",line=\"1\d\"\})*,\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"2\d\"\})*\]" % + (sline, eline)) # Test that -symbol-list-lines fails when file doesn't exist self.runCmd("-symbol-list-lines unknown_file") - self.expect("\^error,message=\"error: No source filenames matched 'unknown_file'\. \"") + self.expect( + "\^error,message=\"error: No source filenames matched 'unknown_file'\. \"") - # Test that -symbol-list-lines fails when file is specified using relative path + # Test that -symbol-list-lines fails when file is specified using + # relative path self.runCmd("-symbol-list-lines ./main.cpp") - self.expect("\^error,message=\"error: No source filenames matched '\./main\.cpp'\. \"") + self.expect( + "\^error,message=\"error: No source filenames matched '\./main\.cpp'\. \"") - # Test that -symbol-list-lines works when file is specified using absolute path + # Test that -symbol-list-lines works when file is specified using + # absolute path import os path = os.path.join(os.getcwd(), "main.cpp") self.runCmd("-symbol-list-lines \"%s\"" % path) - self.expect("\^done,lines=\[\{pc=\"0x0*%x\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d+\"\})+\]" % (addr, line)) + self.expect( + "\^done,lines=\[\{pc=\"0x0*%x\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d+\"\})+\]" % + (addr, line)) # Test that -symbol-list-lines fails when file doesn't exist self.runCmd("-symbol-list-lines unknown_dir/main.cpp") - self.expect("\^error,message=\"error: No source filenames matched 'unknown_dir/main\.cpp'\. \"") + self.expect( + "\^error,message=\"error: No source filenames matched 'unknown_dir/main\.cpp'\. \"") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py index a40e49f70e7..9a429adf887 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py @@ -5,22 +5,22 @@ Test that the lldb-mi driver understands MI command syntax. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiSyntaxTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_tokens(self): """Test that 'lldb-mi --interpreter' prints command tokens.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("000-file-exec-and-symbols %s" % self.myexe) @@ -38,8 +38,8 @@ class MiSyntaxTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("0000000000000000000003\^running") self.expect("\*stopped,reason=\"exited-normally\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_specialchars(self): """Test that 'lldb-mi --interpreter' handles complicated strings.""" @@ -48,10 +48,12 @@ class MiSyntaxTestCase(lldbmi_testcase.MiTestCaseBase): os.symlink(self.myexe, complicated_myexe) self.addTearDownHook(lambda: os.unlink(complicated_myexe)) - self.spawnLldbMi(args = "\"%s\"" % complicated_myexe) + self.spawnLldbMi(args="\"%s\"" % complicated_myexe) # Test that the executable was loaded - self.expect("-file-exec-and-symbols \"%s\"" % complicated_myexe, exactly = True) + self.expect( + "-file-exec-and-symbols \"%s\"" % + complicated_myexe, exactly=True) self.expect("\^done") # Check that it was loaded correctly @@ -61,13 +63,15 @@ class MiSyntaxTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\^running") self.expect("\*stopped,reason=\"breakpoint-hit\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @expectedFailureAll(oslist=["linux"], bugnumber="Failing in ~6/600 dosep runs (build 3120-3122)") + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @expectedFailureAll( + oslist=["linux"], + bugnumber="Failing in ~6/600 dosep runs (build 3120-3122)") def test_lldbmi_process_output(self): """Test that 'lldb-mi --interpreter' wraps process output correctly.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py index 2d47db03637..31a05ff402e 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py @@ -9,117 +9,121 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiTargetTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # cannot attach to process on linux + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # cannot attach to process on linux def test_lldbmi_target_attach_wait_for(self): """Test that 'lldb-mi --interpreter' works for -target-attach -n <name> --waitfor.""" - + # Build target executable with unique name exeName = self.testMethodName d = {'EXE': exeName} self.buildProgram("test_attach.cpp", exeName) self.addTearDownCleanup(dictionary=d) - - self.spawnLldbMi(args = None) - + + self.spawnLldbMi(args=None) + # Load executable - # FIXME: -file-exec-and-sybmols is not required for target attach, but the test will not pass without this + # FIXME: -file-exec-and-sybmols is not required for target attach, but + # the test will not pass without this self.runCmd("-file-exec-and-symbols %s" % exeName) self.expect("\^done") - + # Set up attach self.runCmd("-target-attach -n %s --waitfor" % exeName) - time.sleep(4) # Give attach time to setup - + time.sleep(4) # Give attach time to setup + # Start target process - self.spawnSubprocess(os.path.join(os.path.dirname(__file__), exeName)); + self.spawnSubprocess(os.path.join(os.path.dirname(__file__), exeName)) self.addTearDownHook(self.cleanupSubprocesses) self.expect("\^done") - + # Set breakpoint on printf line = line_number('test_attach.cpp', '// BP_i++') self.runCmd("-break-insert -f test_attach.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") - + # Continue to breakpoint self.runCmd("-exec-continue") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Detach self.runCmd("-target-detach") self.expect("\^done") - - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # cannot attach to process on linux + + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # cannot attach to process on linux def test_lldbmi_target_attach_name(self): """Test that 'lldb-mi --interpreter' works for -target-attach -n <name>.""" - + # Build target executable with unique name exeName = self.testMethodName d = {'EXE': exeName} self.buildProgram("test_attach.cpp", exeName) self.addTearDownCleanup(dictionary=d) - + # Start target process - targetProcess = self.spawnSubprocess(os.path.join(os.path.dirname(__file__), exeName)); + targetProcess = self.spawnSubprocess( + os.path.join(os.path.dirname(__file__), exeName)) self.addTearDownHook(self.cleanupSubprocesses) - - self.spawnLldbMi(args = None) - + + self.spawnLldbMi(args=None) + # Set up atatch self.runCmd("-target-attach -n %s" % exeName) self.expect("\^done") - + # Set breakpoint on printf line = line_number('test_attach.cpp', '// BP_i++') self.runCmd("-break-insert -f test_attach.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") - + # Continue to breakpoint self.runCmd("-exec-continue") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Detach self.runCmd("-target-detach") self.expect("\^done") - - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # cannot attach to process on linux + + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # cannot attach to process on linux def test_lldbmi_target_attach_pid(self): """Test that 'lldb-mi --interpreter' works for -target-attach <pid>.""" - + # Build target executable with unique name exeName = self.testMethodName d = {'EXE': exeName} self.buildProgram("test_attach.cpp", exeName) self.addTearDownCleanup(dictionary=d) - + # Start target process - targetProcess = self.spawnSubprocess(os.path.join(os.path.dirname(__file__), exeName)); + targetProcess = self.spawnSubprocess( + os.path.join(os.path.dirname(__file__), exeName)) self.addTearDownHook(self.cleanupSubprocesses) - - self.spawnLldbMi(args = None) - + + self.spawnLldbMi(args=None) + # Set up atatch self.runCmd("-target-attach %d" % targetProcess.pid) self.expect("\^done") - + # Set breakpoint on printf line = line_number('test_attach.cpp', '// BP_i++') self.runCmd("-break-insert -f test_attach.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") - + # Continue to breakpoint self.runCmd("-exec-continue") self.expect("\*stopped,reason=\"breakpoint-hit\"") - + # Detach self.runCmd("-target-detach") self.expect("\^done") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/threadinfo/TestMiThreadInfo.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/threadinfo/TestMiThreadInfo.py index 7226f2e8d32..729674e6e11 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/threadinfo/TestMiThreadInfo.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/threadinfo/TestMiThreadInfo.py @@ -9,16 +9,17 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiThreadInfoTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows # pthreads not supported on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # pthreads not supported on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_thread_info(self): """Test that -thread-info prints thread info and the current-thread-id""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -33,7 +34,7 @@ class MiThreadInfoTestCase(lldbmi_testcase.MiTestCaseBase): self.expect("\*stopped,reason=\"breakpoint-hit\"") self.runCmd("-thread-info") - self.expect("\^done,threads=\[\{id=\"1\",(.*)\},\{id=\"2\",(.*)\],current-thread-id=\"2\"") + self.expect( + "\^done,threads=\[\{id=\"1\",(.*)\},\{id=\"2\",(.*)\],current-thread-id=\"2\"") self.runCmd("-gdb-quit") - diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py index 5ce2b99bbde..61d54cab055 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py @@ -1,4 +1,4 @@ -#coding=utf8 +# coding=utf8 """ Test lldb-mi -gdb-set and -gdb-show commands for 'print option-name'. """ @@ -6,12 +6,12 @@ Test lldb-mi -gdb-set and -gdb-show commands for 'print option-name'. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -19,28 +19,34 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): # evaluates array when char-array-as-string is off def eval_and_check_array(self, var, typ, length): self.runCmd("-var-create - * %s" % var) - self.expect('\^done,name="var\d+",numchild="%d",value="\[%d\]",type="%s \[%d\]",thread-id="1",has_more="0"' % (length, length, typ, length)) + self.expect( + '\^done,name="var\d+",numchild="%d",value="\[%d\]",type="%s \[%d\]",thread-id="1",has_more="0"' % + (length, length, typ, length)) # evaluates any type which can be represented as string of characters def eval_and_match_string(self, var, value, typ): - value=value.replace("\\", "\\\\").replace("\"", "\\\"") + value = value.replace("\\", "\\\\").replace("\"", "\\\"") self.runCmd("-var-create - * " + var) - self.expect('\^done,name="var\d+",numchild="[0-9]+",value="%s",type="%s",thread-id="1",has_more="0"' % (value, typ)) + self.expect( + '\^done,name="var\d+",numchild="[0-9]+",value="%s",type="%s",thread-id="1",has_more="0"' % + (value, typ)) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_gdb_set_show_print_char_array_as_string(self): """Test that 'lldb-mi --interpreter' can print array of chars as string.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") # Run to BP_gdb_set_show_print_char_array_as_string_test - line = line_number('main.cpp', '// BP_gdb_set_show_print_char_array_as_string_test') + line = line_number( + 'main.cpp', + '// BP_gdb_set_show_print_char_array_as_string_test') self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") self.runCmd("-exec-run") @@ -51,23 +57,38 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-show print char-array-as-string") self.expect("\^done,value=\"off\"") - # Test that a char* is expanded to string when print char-array-as-string is "off" - self.eval_and_match_string("cp", r'0x[0-9a-f]+ \"\\t\\\"hello\\\"\\n\"', r'const char \*') - - # Test that a char[] isn't expanded to string when print char-array-as-string is "off" - self.eval_and_check_array("ca", "const char", 10); - - # Test that a char16_t* is expanded to string when print char-array-as-string is "off" - self.eval_and_match_string("u16p", r'0x[0-9a-f]+ u\"\\t\\\"hello\\\"\\n\"', r'const char16_t \*') - - # Test that a char16_t[] isn't expanded to string when print char-array-as-string is "off" - self.eval_and_check_array("u16a", "const char16_t", 10); - - # Test that a char32_t* is expanded to string when print char-array-as-string is "off" - self.eval_and_match_string("u32p", r'0x[0-9a-f]+ U\"\\t\\\"hello\\\"\\n\"', r'const char32_t \*') - - # Test that a char32_t[] isn't expanded to string when print char-array-as-string is "off" - self.eval_and_check_array("u32a", "const char32_t", 10); + # Test that a char* is expanded to string when print + # char-array-as-string is "off" + self.eval_and_match_string( + "cp", + r'0x[0-9a-f]+ \"\\t\\\"hello\\\"\\n\"', + r'const char \*') + + # Test that a char[] isn't expanded to string when print + # char-array-as-string is "off" + self.eval_and_check_array("ca", "const char", 10) + + # Test that a char16_t* is expanded to string when print + # char-array-as-string is "off" + self.eval_and_match_string( + "u16p", + r'0x[0-9a-f]+ u\"\\t\\\"hello\\\"\\n\"', + r'const char16_t \*') + + # Test that a char16_t[] isn't expanded to string when print + # char-array-as-string is "off" + self.eval_and_check_array("u16a", "const char16_t", 10) + + # Test that a char32_t* is expanded to string when print + # char-array-as-string is "off" + self.eval_and_match_string( + "u32p", + r'0x[0-9a-f]+ U\"\\t\\\"hello\\\"\\n\"', + r'const char32_t \*') + + # Test that a char32_t[] isn't expanded to string when print + # char-array-as-string is "off" + self.eval_and_check_array("u32a", "const char32_t", 10) # Test that -gdb-set can set print char-array-as-string flag self.runCmd("-gdb-set print char-array-as-string on") @@ -77,52 +98,94 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-show print char-array-as-string") self.expect("\^done,value=\"on\"") - # Test that a char* with escape chars is expanded to string when print char-array-as-string is "on" - self.eval_and_match_string("cp", r'0x[0-9a-f]+ \"\\t\\\"hello\\\"\\n\"', r'const char \*') - - # Test that a char[] with escape chars is expanded to string when print char-array-as-string is "on" - self.eval_and_match_string("ca", r'\"\\t\\\"hello\\\"\\n\"', r'const char \[10\]') - - # Test that a char16_t* with escape chars is expanded to string when print char-array-as-string is "on" - self.eval_and_match_string("u16p", r'0x[0-9a-f]+ u\"\\t\\\"hello\\\"\\n\"', r'const char16_t \*') - - # Test that a char16_t[] with escape chars is expanded to string when print char-array-as-string is "on" - self.eval_and_match_string("u16a", r'u\"\\t\\\"hello\\\"\\n\"', r'const char16_t \[10\]') - - # Test that a char32_t* with escape chars is expanded to string when print char-array-as-string is "on" - self.eval_and_match_string("u32p", r'0x[0-9a-f]+ U\"\\t\\\"hello\\\"\\n\"', r'const char32_t \*') - - # Test that a char32_t[] with escape chars is expanded to string when print char-array-as-string is "on" - self.eval_and_match_string("u32a", r'U\"\\t\\\"hello\\\"\\n\"', r'const char32_t \[10\]') + # Test that a char* with escape chars is expanded to string when print + # char-array-as-string is "on" + self.eval_and_match_string( + "cp", + r'0x[0-9a-f]+ \"\\t\\\"hello\\\"\\n\"', + r'const char \*') + + # Test that a char[] with escape chars is expanded to string when print + # char-array-as-string is "on" + self.eval_and_match_string( + "ca", + r'\"\\t\\\"hello\\\"\\n\"', + r'const char \[10\]') + + # Test that a char16_t* with escape chars is expanded to string when + # print char-array-as-string is "on" + self.eval_and_match_string( + "u16p", + r'0x[0-9a-f]+ u\"\\t\\\"hello\\\"\\n\"', + r'const char16_t \*') + + # Test that a char16_t[] with escape chars is expanded to string when + # print char-array-as-string is "on" + self.eval_and_match_string( + "u16a", + r'u\"\\t\\\"hello\\\"\\n\"', + r'const char16_t \[10\]') + + # Test that a char32_t* with escape chars is expanded to string when + # print char-array-as-string is "on" + self.eval_and_match_string( + "u32p", + r'0x[0-9a-f]+ U\"\\t\\\"hello\\\"\\n\"', + r'const char32_t \*') + + # Test that a char32_t[] with escape chars is expanded to string when + # print char-array-as-string is "on" + self.eval_and_match_string( + "u32a", + r'U\"\\t\\\"hello\\\"\\n\"', + r'const char32_t \[10\]') # Test russian unicode strings - self.eval_and_match_string("u16p_rus", r'0x[0-9a-f]+ u\"\\\\Аламо-сквер\"', r'const char16_t \*') - self.eval_and_match_string("u16a_rus", r'u\"\\\\Бейвью\"', r'const char16_t \[8\]') - self.eval_and_match_string("u32p_rus", r'0x[0-9a-f]+ U\"\\\\Чайнатаун\"', r'const char32_t \*') - self.eval_and_match_string("u32a_rus", r'U\"\\\\Догпатч\"', r'const char32_t \[9\]') - - # Test that -gdb-set print char-array-as-string fails if "on"/"off" isn't specified + self.eval_and_match_string( + "u16p_rus", + r'0x[0-9a-f]+ u\"\\\\Аламо-сквер\"', + r'const char16_t \*') + self.eval_and_match_string( + "u16a_rus", + r'u\"\\\\Бейвью\"', + r'const char16_t \[8\]') + self.eval_and_match_string( + "u32p_rus", + r'0x[0-9a-f]+ U\"\\\\Чайнатаун\"', + r'const char32_t \*') + self.eval_and_match_string( + "u32a_rus", + r'U\"\\\\Догпатч\"', + r'const char32_t \[9\]') + + # Test that -gdb-set print char-array-as-string fails if "on"/"off" + # isn't specified self.runCmd("-gdb-set print char-array-as-string") - self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") + self.expect( + "\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") - # Test that -gdb-set print char-array-as-string fails when option is unknown + # Test that -gdb-set print char-array-as-string fails when option is + # unknown self.runCmd("-gdb-set print char-array-as-string unknown") - self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") + self.expect( + "\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows + @skipIfWindows # llvm.org/pr24452: Get lldb-mi working on Windows @expectedFailureAll(compiler="gcc", bugnumber="llvm.org/pr23357") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_gdb_set_show_print_expand_aggregates(self): """Test that 'lldb-mi --interpreter' can expand aggregates everywhere.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") # Run to BP_gdb_set_show_print_expand_aggregates - line = line_number('main.cpp', '// BP_gdb_set_show_print_expand_aggregates') + line = line_number( + 'main.cpp', + '// BP_gdb_set_show_print_expand_aggregates') self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") self.runCmd("-exec-run") @@ -133,16 +196,21 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-show print expand-aggregates") self.expect("\^done,value=\"off\"") - # Test that composite type isn't expanded when print expand-aggregates is "off" + # Test that composite type isn't expanded when print expand-aggregates + # is "off" self.runCmd("-var-create var1 * complx") - self.expect("\^done,name=\"var1\",numchild=\"3\",value=\"{\.\.\.}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var1\",numchild=\"3\",value=\"{\.\.\.}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") - # Test that composite type[] isn't expanded when print expand-aggregates is "off" + # Test that composite type[] isn't expanded when print + # expand-aggregates is "off" self.eval_and_check_array("complx_array", "complex_type", 2) - # Test that a struct with a char first element is not formatted as a string + # Test that a struct with a char first element is not formatted as a + # string self.runCmd("-var-create - * &nstr") - self.expect("\^done,name=\"var\d+\",numchild=\"2\",value=\"0x[0-9a-f]+\",type=\"not_str \*\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var\d+\",numchild=\"2\",value=\"0x[0-9a-f]+\",type=\"not_str \*\",thread-id=\"1\",has_more=\"0\"") # Test that -gdb-set can set print expand-aggregates flag self.runCmd("-gdb-set print expand-aggregates on") @@ -152,36 +220,46 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-show print expand-aggregates") self.expect("\^done,value=\"on\"") - # Test that composite type is expanded when print expand-aggregates is "on" + # Test that composite type is expanded when print expand-aggregates is + # "on" self.runCmd("-var-create var3 * complx") - self.expect("\^done,name=\"var3\",numchild=\"3\",value=\"{i = 3, inner = {l = 3}, complex_ptr = 0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var3\",numchild=\"3\",value=\"{i = 3, inner = {l = 3}, complex_ptr = 0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") - # Test that composite type[] is expanded when print expand-aggregates is "on" + # Test that composite type[] is expanded when print expand-aggregates + # is "on" self.runCmd("-var-create var4 * complx_array") - self.expect("\^done,name=\"var4\",numchild=\"2\",value=\"{\[0\] = {i = 4, inner = {l = 4}, complex_ptr = 0x[0-9a-f]+}, \[1\] = {i = 5, inner = {l = 5}, complex_ptr = 0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var4\",numchild=\"2\",value=\"{\[0\] = {i = 4, inner = {l = 4}, complex_ptr = 0x[0-9a-f]+}, \[1\] = {i = 5, inner = {l = 5}, complex_ptr = 0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") - # Test that -gdb-set print expand-aggregates fails if "on"/"off" isn't specified + # Test that -gdb-set print expand-aggregates fails if "on"/"off" isn't + # specified self.runCmd("-gdb-set print expand-aggregates") - self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") + self.expect( + "\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") - # Test that -gdb-set print expand-aggregates fails when option is unknown + # Test that -gdb-set print expand-aggregates fails when option is + # unknown self.runCmd("-gdb-set print expand-aggregates unknown") - self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") + self.expect( + "\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows + @skipIfWindows # llvm.org/pr24452: Get lldb-mi working on Windows @expectedFailureAll(compiler="gcc", bugnumber="llvm.org/pr23357") - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_gdb_set_show_print_aggregate_field_names(self): """Test that 'lldb-mi --interpreter' can expand aggregates everywhere.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) self.expect("\^done") # Run to BP_gdb_set_show_print_aggregate_field_names - line = line_number('main.cpp', '// BP_gdb_set_show_print_aggregate_field_names') + line = line_number( + 'main.cpp', + '// BP_gdb_set_show_print_aggregate_field_names') self.runCmd("-break-insert main.cpp:%d" % line) self.expect("\^done,bkpt={number=\"1\"") self.runCmd("-exec-run") @@ -196,13 +274,17 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-set print expand-aggregates on") self.expect("\^done") - # Test that composite type is expanded with field name when print aggregate-field-names is "on" + # Test that composite type is expanded with field name when print + # aggregate-field-names is "on" self.runCmd("-var-create var1 * complx") - self.expect("\^done,name=\"var1\",numchild=\"3\",value=\"{i = 3, inner = {l = 3}, complex_ptr = 0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var1\",numchild=\"3\",value=\"{i = 3, inner = {l = 3}, complex_ptr = 0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") - # Test that composite type[] is expanded with field name when print aggregate-field-names is "on" + # Test that composite type[] is expanded with field name when print + # aggregate-field-names is "on" self.runCmd("-var-create var2 * complx_array") - self.expect("\^done,name=\"var2\",numchild=\"2\",value=\"{\[0\] = {i = 4, inner = {l = 4}, complex_ptr = 0x[0-9a-f]+}, \[1\] = {i = 5, inner = {l = 5}, complex_ptr = 0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var2\",numchild=\"2\",value=\"{\[0\] = {i = 4, inner = {l = 4}, complex_ptr = 0x[0-9a-f]+}, \[1\] = {i = 5, inner = {l = 5}, complex_ptr = 0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") # Test that -gdb-set can set print aggregate-field-names flag self.runCmd("-gdb-set print aggregate-field-names off") @@ -212,18 +294,26 @@ class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-gdb-show print aggregate-field-names") self.expect("\^done,value=\"off\"") - # Test that composite type is expanded without field name when print aggregate-field-names is "off" + # Test that composite type is expanded without field name when print + # aggregate-field-names is "off" self.runCmd("-var-create var3 * complx") - self.expect("\^done,name=\"var3\",numchild=\"3\",value=\"{3,\{3\},0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var3\",numchild=\"3\",value=\"{3,\{3\},0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") - # Test that composite type[] is expanded without field name when print aggregate-field-names is "off" + # Test that composite type[] is expanded without field name when print + # aggregate-field-names is "off" self.runCmd("-var-create var4 * complx_array") - self.expect("\^done,name=\"var4\",numchild=\"2\",value=\"{{4,\{4\},0x[0-9a-f]+},{5,\{5\},0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var4\",numchild=\"2\",value=\"{{4,\{4\},0x[0-9a-f]+},{5,\{5\},0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") - # Test that -gdb-set print aggregate-field-names fails if "on"/"off" isn't specified + # Test that -gdb-set print aggregate-field-names fails if "on"/"off" + # isn't specified self.runCmd("-gdb-set print aggregate-field-names") - self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") + self.expect( + "\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") - # Test that -gdb-set print aggregate-field-names fails when option is unknown + # Test that -gdb-set print aggregate-field-names fails when option is + # unknown self.runCmd("-gdb-set print aggregate-field-names unknown") - self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") + self.expect( + "\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py index 51f02b9e4a7..c274efe793c 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py @@ -5,22 +5,22 @@ Test lldb-mi -var-xxx commands. from __future__ import print_function - import lldbmi_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): mydir = TestBase.compute_mydir(__file__) - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_eval(self): """Test that 'lldb-mi --interpreter' works for evaluating.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -36,15 +36,18 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Print non-existant variable self.runCmd("-var-create var1 * undef") - self.expect("\^error,msg=\"error: use of undeclared identifier \'undef\'\\\\n\"") + self.expect( + "\^error,msg=\"error: use of undeclared identifier \'undef\'\\\\n\"") self.runCmd("-data-evaluate-expression undef") - self.expect("\^error,msg=\"error: use of undeclared identifier \'undef\'\\\\n\"") + self.expect( + "\^error,msg=\"error: use of undeclared identifier \'undef\'\\\\n\"") # Print global "g_MyVar", modify, delete and create again self.runCmd("-data-evaluate-expression g_MyVar") self.expect("\^done,value=\"3\"") self.runCmd("-var-create var2 * g_MyVar") - self.expect("\^done,name=\"var2\",numchild=\"0\",value=\"3\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var2\",numchild=\"0\",value=\"3\",type=\"int\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-evaluate-expression var2") self.expect("\^done,value=\"3\"") self.runCmd("-var-show-attributes var2") @@ -57,17 +60,20 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-data-evaluate-expression \"g_MyVar=30\"") self.expect("\^done,value=\"30\"") self.runCmd("-var-update --all-values var2") - #self.expect("\^done,changelist=\[\{name=\"var2\",value=\"30\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") #FIXME -var-update doesn't work + # self.expect("\^done,changelist=\[\{name=\"var2\",value=\"30\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") + # #FIXME -var-update doesn't work self.runCmd("-var-delete var2") self.expect("\^done") self.runCmd("-var-create var2 * g_MyVar") - self.expect("\^done,name=\"var2\",numchild=\"0\",value=\"30\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var2\",numchild=\"0\",value=\"30\",type=\"int\",thread-id=\"1\",has_more=\"0\"") # Print static "s_MyVar", modify, delete and create again self.runCmd("-data-evaluate-expression s_MyVar") self.expect("\^done,value=\"30\"") self.runCmd("-var-create var3 * s_MyVar") - self.expect("\^done,name=\"var3\",numchild=\"0\",value=\"30\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var3\",numchild=\"0\",value=\"30\",type=\"int\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-evaluate-expression var3") self.expect("\^done,value=\"30\"") self.runCmd("-var-show-attributes var3") @@ -77,17 +83,20 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-data-evaluate-expression \"s_MyVar=3\"") self.expect("\^done,value=\"3\"") self.runCmd("-var-update --all-values var3") - #self.expect("\^done,changelist=\[\{name=\"var3\",value=\"3\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") #FIXME -var-update doesn't work + # self.expect("\^done,changelist=\[\{name=\"var3\",value=\"3\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") + # #FIXME -var-update doesn't work self.runCmd("-var-delete var3") self.expect("\^done") self.runCmd("-var-create var3 * s_MyVar") - self.expect("\^done,name=\"var3\",numchild=\"0\",value=\"3\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var3\",numchild=\"0\",value=\"3\",type=\"int\",thread-id=\"1\",has_more=\"0\"") # Print local "b", modify, delete and create again self.runCmd("-data-evaluate-expression b") self.expect("\^done,value=\"20\"") self.runCmd("-var-create var4 * b") - self.expect("\^done,name=\"var4\",numchild=\"0\",value=\"20\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var4\",numchild=\"0\",value=\"20\",type=\"int\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-evaluate-expression var4") self.expect("\^done,value=\"20\"") self.runCmd("-var-show-attributes var4") @@ -97,44 +106,55 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-data-evaluate-expression \"b=2\"") self.expect("\^done,value=\"2\"") self.runCmd("-var-update --all-values var4") - #self.expect("\^done,changelist=\[\{name=\"var4\",value=\"2\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") #FIXME -var-update doesn't work + # self.expect("\^done,changelist=\[\{name=\"var4\",value=\"2\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") + # #FIXME -var-update doesn't work self.runCmd("-var-delete var4") self.expect("\^done") self.runCmd("-var-create var4 * b") - self.expect("\^done,name=\"var4\",numchild=\"0\",value=\"2\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var4\",numchild=\"0\",value=\"2\",type=\"int\",thread-id=\"1\",has_more=\"0\"") # Print temp "a + b" self.runCmd("-data-evaluate-expression \"a + b\"") self.expect("\^done,value=\"12\"") self.runCmd("-var-create var5 * \"a + b\"") - self.expect("\^done,name=\"var5\",numchild=\"0\",value=\"12\",type=\"int\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var5\",numchild=\"0\",value=\"12\",type=\"int\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-evaluate-expression var5") self.expect("\^done,value=\"12\"") self.runCmd("-var-show-attributes var5") - self.expect("\^done,status=\"editable\"") #FIXME editable or not? + self.expect("\^done,status=\"editable\"") # FIXME editable or not? self.runCmd("-var-list-children var5") self.expect("\^done,numchild=\"0\",has_more=\"0\"") # Print argument "argv[0]" self.runCmd("-data-evaluate-expression \"argv[0]\"") - self.expect("\^done,value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\"" % self.myexe) + self.expect( + "\^done,value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\"" % + self.myexe) self.runCmd("-var-create var6 * \"argv[0]\"") - self.expect("\^done,name=\"var6\",numchild=\"1\",value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\",type=\"const char \*\",thread-id=\"1\",has_more=\"0\"" % self.myexe) + self.expect( + "\^done,name=\"var6\",numchild=\"1\",value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\",type=\"const char \*\",thread-id=\"1\",has_more=\"0\"" % + self.myexe) self.runCmd("-var-evaluate-expression var6") - self.expect("\^done,value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\"" % self.myexe) + self.expect( + "\^done,value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\"" % + self.myexe) self.runCmd("-var-show-attributes var6") self.expect("\^done,status=\"editable\"") self.runCmd("-var-list-children --all-values var6") # FIXME: The name below is not correct. It should be "var.*argv[0]". - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var6\.\*\$[0-9]+\",exp=\"\*\$[0-9]+\",numchild=\"0\",type=\"const char\",thread-id=\"4294967295\",value=\"47 '/'\",has_more=\"0\"\}\],has_more=\"0\"") #FIXME -var-list-children shows invalid thread-id + # FIXME -var-list-children shows invalid thread-id + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var6\.\*\$[0-9]+\",exp=\"\*\$[0-9]+\",numchild=\"0\",type=\"const char\",thread-id=\"4294967295\",value=\"47 '/'\",has_more=\"0\"\}\],has_more=\"0\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_var_update(self): """Test that 'lldb-mi --interpreter' works for -var-update.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -150,11 +170,14 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Setup variables self.runCmd("-var-create var_l * l") - self.expect("\^done,name=\"var_l\",numchild=\"0\",value=\"1\",type=\"long\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var_l\",numchild=\"0\",value=\"1\",type=\"long\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-create var_complx * complx") - self.expect("\^done,name=\"var_complx\",numchild=\"3\",value=\"\{\.\.\.\}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var_complx\",numchild=\"3\",value=\"\{\.\.\.\}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-create var_complx_array * complx_array") - self.expect("\^done,name=\"var_complx_array\",numchild=\"2\",value=\"\[2\]\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var_complx_array\",numchild=\"2\",value=\"\[2\]\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") # Go to BP_var_update_test_l line = line_number('main.cpp', '// BP_var_update_test_l') @@ -166,7 +189,8 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Test that var_l was updated self.runCmd("-var-update --all-values var_l") - self.expect("\^done,changelist=\[\{name=\"var_l\",value=\"0\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") + self.expect( + "\^done,changelist=\[\{name=\"var_l\",value=\"0\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") # Go to BP_var_update_test_complx line = line_number('main.cpp', '// BP_var_update_test_complx') @@ -178,7 +202,8 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Test that var_complx was updated self.runCmd("-var-update --all-values var_complx") - self.expect("\^done,changelist=\[\{name=\"var_complx\",value=\"\{\.\.\.\}\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") + self.expect( + "\^done,changelist=\[\{name=\"var_complx\",value=\"\{\.\.\.\}\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") # Go to BP_var_update_test_complx_array line = line_number('main.cpp', '// BP_var_update_test_complx_array') @@ -190,14 +215,15 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Test that var_complex_array was updated self.runCmd("-var-update --all-values var_complx_array") - self.expect("\^done,changelist=\[\{name=\"var_complx_array\",value=\"\[2\]\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") + self.expect( + "\^done,changelist=\[\{name=\"var_complx_array\",value=\"\[2\]\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races def test_lldbmi_var_create_register(self): """Test that 'lldb-mi --interpreter' works for -var-create $regname.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -218,26 +244,29 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Create variable for register 0 # Note that message is different in Darwin and Linux: # Darwin: "^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned long\",thread-id=\"1\",has_more=\"0\" - # Linux: "^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned int\",thread-id=\"1\",has_more=\"0\" + # Linux: + # "^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned + # int\",thread-id=\"1\",has_more=\"0\" self.runCmd("-var-create var_reg * $%s" % register_name) - self.expect("\^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned (long|int)\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned (long|int)\",thread-id=\"1\",has_more=\"0\"") # Assign value to variable self.runCmd("-var-assign var_reg \"6\"") - #FIXME: the output has different format for 32bit and 64bit values + # FIXME: the output has different format for 32bit and 64bit values self.expect("\^done,value=\"0x0*?6\"") # Assert register 0 updated self.runCmd("-data-list-register-values d 0") self.expect("\^done,register-values=\[{number=\"0\",value=\"6\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi tests working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_var_list_children(self): """Test that 'lldb-mi --interpreter' works for -var-list-children.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -253,13 +282,17 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Create variable self.runCmd("-var-create var_complx * complx") - self.expect("\^done,name=\"var_complx\",numchild=\"3\",value=\"\{\.\.\.\}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var_complx\",numchild=\"3\",value=\"\{\.\.\.\}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-create var_complx_array * complx_array") - self.expect("\^done,name=\"var_complx_array\",numchild=\"2\",value=\"\[2\]\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var_complx_array\",numchild=\"2\",value=\"\[2\]\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"") self.runCmd("-var-create var_pcomplx * pcomplx") - self.expect("\^done,name=\"var_pcomplx\",numchild=\"2\",value=\"\{\.\.\.\}\",type=\"pcomplex_type\",thread-id=\"1\",has_more=\"0\"") + self.expect( + "\^done,name=\"var_pcomplx\",numchild=\"2\",value=\"\{\.\.\.\}\",type=\"pcomplex_type\",thread-id=\"1\",has_more=\"0\"") - # Test that -var-evaluate-expression can evaluate the children of created varobj + # Test that -var-evaluate-expression can evaluate the children of + # created varobj self.runCmd("-var-list-children var_complx") self.runCmd("-var-evaluate-expression var_complx.i") self.expect("\^done,value=\"3\"") @@ -284,35 +317,46 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-var-list-children --all-values var_complx") self.expect("\^done,numchild=\"3\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",value=\"3\",has_more=\"0\"\},child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\},child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",value=\"0x[0-9a-f]+\",has_more=\"0\"\}\],has_more=\"0\"") self.runCmd("-var-list-children --simple-values var_complx_array") - self.expect("\^done,numchild=\"2\",children=\[child=\{name=\"var_complx_array\.\[0\]\",exp=\"\[0\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\},child=\{name=\"var_complx_array\.\[1\]\",exp=\"\[1\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"") + self.expect( + "\^done,numchild=\"2\",children=\[child=\{name=\"var_complx_array\.\[0\]\",exp=\"\[0\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\},child=\{name=\"var_complx_array\.\[1\]\",exp=\"\[1\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"") self.runCmd("-var-list-children 0 var_pcomplx") self.expect("\^done,numchild=\"2\",children=\[child=\{name=\"var_pcomplx\.complex_type\",exp=\"complex_type\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\},child={name=\"var_pcomplx\.complx\",exp=\"complx\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"") # Test that -var-list-children lists children without values self.runCmd("-var-list-children 0 var_complx 0 1") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") self.runCmd("-var-list-children --no-values var_complx 0 1") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") self.runCmd("-var-list-children --no-values var_complx_array 0 1") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx_array\.\[0\]\",exp=\"\[0\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx_array\.\[0\]\",exp=\"\[0\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") self.runCmd("-var-list-children --no-values var_pcomplx 0 1") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_pcomplx\.complex_type\",exp=\"complex_type\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_pcomplx\.complex_type\",exp=\"complex_type\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"") # Test that -var-list-children lists children with all values self.runCmd("-var-list-children 1 var_complx 1 2") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"1\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"1\"") self.runCmd("-var-list-children --all-values var_complx 1 2") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"1\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"1\"") self.runCmd("-var-list-children --all-values var_complx_array 1 2") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx_array\.\[1\]\",exp=\"\[1\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"0\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx_array\.\[1\]\",exp=\"\[1\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"0\"") self.runCmd("-var-list-children --all-values var_pcomplx 1 2") - self.expect("\^done,numchild=\"1\",children=\[child={name=\"var_pcomplx\.complx\",exp=\"complx\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"0\"") + self.expect( + "\^done,numchild=\"1\",children=\[child={name=\"var_pcomplx\.complx\",exp=\"complx\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"0\"") # Test that -var-list-children lists children with simple values self.runCmd("-var-list-children 2 var_complx 2 4") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"") self.runCmd("-var-list-children --simple-values var_complx 2 4") - self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"") + self.expect( + "\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"") self.runCmd("-var-list-children --simple-values var_complx_array 2 4") self.expect("\^done,numchild=\"0\",has_more=\"0\"") self.runCmd("-var-list-children --simple-values var_pcomplx 2 4") @@ -330,15 +374,16 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Test that a missing low-frame or high-frame is handled self.runCmd("-var-list-children 0 var_complx 0") - self.expect("\^error,msg=\"Command 'var-list-children'. Variable children range invalid\"") + self.expect( + "\^error,msg=\"Command 'var-list-children'. Variable children range invalid\"") - @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + @skipIfWindows # llvm.org/pr24452: Get lldb-mi working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_var_create_for_stl_types(self): """Test that 'lldb-mi --interpreter' print summary for STL types.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -354,15 +399,16 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Test for std::string self.runCmd("-var-create - * std_string") - self.expect('\^done,name="var\d+",numchild="[0-9]+",value="\\\\"hello\\\\"",type="std::[\S]*?string",thread-id="1",has_more="0"') - - @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows - @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races - @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots + self.expect( + '\^done,name="var\d+",numchild="[0-9]+",value="\\\\"hello\\\\"",type="std::[\S]*?string",thread-id="1",has_more="0"') + + @skipIfWindows # llvm.org/pr24452: Get lldb-mi working on Windows + @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races + @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots def test_lldbmi_var_create_for_unnamed_objects(self): """Test that 'lldb-mi --interpreter' can expand unnamed structures and unions.""" - self.spawnLldbMi(args = None) + self.spawnLldbMi(args=None) # Load executable self.runCmd("-file-exec-and-symbols %s" % self.myexe) @@ -378,15 +424,16 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): # Evaluate struct_with_unions type and its children self.runCmd("-var-create v0 * swu") - self.expect('\^done,name="v0",numchild="2",value="\{\.\.\.\}",type="struct_with_unions",thread-id="1",has_more="0"') - + self.expect( + '\^done,name="v0",numchild="2",value="\{\.\.\.\}",type="struct_with_unions",thread-id="1",has_more="0"') + self.runCmd("-var-list-children v0") - + # inspect the first unnamed union self.runCmd("-var-list-children v0.$0") self.runCmd("-var-evaluate-expression v0.$0.u_i") self.expect('\^done,value="1"') - + # inspect the second unnamed union self.runCmd("-var-list-children v0.$1") self.runCmd("-var-evaluate-expression v0.$1.u1") @@ -395,4 +442,3 @@ class MiVarTestCase(lldbmi_testcase.MiTestCaseBase): self.runCmd("-var-list-children v0.$1.$1") self.runCmd("-var-evaluate-expression v0.$1.$1.s1") self.expect('\^done,value="-1"') - diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py index 5460b21382e..e53d80b48f9 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py @@ -1,35 +1,40 @@ from __future__ import print_function - import gdbremote_testcase import lldbgdbserverutils from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteAttach(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) def attach_with_vAttach(self): # Start the inferior, start the debug monitor, nothing is attached yet. - procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:60"]) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["sleep:60"]) self.assertIsNotNone(procs) # Make sure the target process has been launched. inferior = procs.get("inferior") self.assertIsNotNone(inferior) self.assertTrue(inferior.pid > 0) - self.assertTrue(lldbgdbserverutils.process_is_running(inferior.pid, True)) + self.assertTrue( + lldbgdbserverutils.process_is_running( + inferior.pid, True)) # Add attach packets. self.test_sequence.add_log_lines([ # Do the attach. "read packet: $vAttach;{:x}#00".format(inferior.pid), # Expect a stop notification from the attach. - { "direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})[^#]*#[0-9a-fA-F]{2}$", "capture":{1:"stop_signal_hex"} }, - ], True) + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})[^#]*#[0-9a-fA-F]{2}$", + "capture": {1: "stop_signal_hex"}}, + ], True) self.add_process_info_collection_packets() # Run the stream diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py index e70ad5f570a..ffabefc70f8 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py @@ -1,12 +1,12 @@ from __future__ import print_function - import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -15,7 +15,8 @@ class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): def has_auxv_support(self): inferior_args = ["message:main entered", "sleep:5"] - procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) # Don't do anything until we match the launched inferior main entry output. # Then immediately interrupt the process. @@ -25,8 +26,9 @@ class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): # Start the inferior... "read packet: $c#63", # ... match output.... - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"message:main entered\r\n") }, - ], True) + {"type": "output_match", "regex": self.maybe_strict_output_regex( + r"message:main entered\r\n")}, + ], True) # ... then interrupt. self.add_interrupt_packets() self.add_qSupported_packets() @@ -35,7 +37,8 @@ class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertIsNotNone(context) features = self.parse_qSupported_response(context) - return self.AUXV_SUPPORT_FEATURE_NAME in features and features[self.AUXV_SUPPORT_FEATURE_NAME] == "+" + return self.AUXV_SUPPORT_FEATURE_NAME in features and features[ + self.AUXV_SUPPORT_FEATURE_NAME] == "+" def get_raw_auxv_data(self): # Start up llgs and inferior, and check for auxv support. @@ -60,10 +63,20 @@ class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): # Grab the auxv data. self.reset_test_sequence() - self.test_sequence.add_log_lines([ - "read packet: $qXfer:auxv:read::{:x},{:x}:#00".format(OFFSET, LENGTH), - {"direction":"send", "regex":re.compile(r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", re.MULTILINE|re.DOTALL), "capture":{1:"response_type", 2:"content_raw"} } - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: $qXfer:auxv:read::{:x},{:x}:#00".format( + OFFSET, + LENGTH), + { + "direction": "send", + "regex": re.compile( + r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", + re.MULTILINE | re.DOTALL), + "capture": { + 1: "response_type", + 2: "content_raw"}}], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -101,8 +114,9 @@ class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): (word_size, auxv_data) = self.get_raw_auxv_data() self.assertIsNotNone(auxv_data) - # Ensure auxv data is a multiple of 2*word_size (there should be two unsigned long fields per auxv entry). - self.assertEqual(len(auxv_data) % (2*word_size), 0) + # Ensure auxv data is a multiple of 2*word_size (there should be two + # unsigned long fields per auxv entry). + self.assertEqual(len(auxv_data) % (2 * word_size), 0) # print("auxv contains {} entries".format(len(auxv_data) / (2*word_size))) @debugserver_test @@ -179,10 +193,12 @@ class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): auxv_dict = self.build_auxv_dict(endian, word_size, auxv_data) self.assertIsNotNone(auxv_dict) - iterated_auxv_data = self.read_binary_data_in_chunks("qXfer:auxv:read::", 2*word_size) + iterated_auxv_data = self.read_binary_data_in_chunks( + "qXfer:auxv:read::", 2 * word_size) self.assertIsNotNone(iterated_auxv_data) - auxv_dict_iterated = self.build_auxv_dict(endian, word_size, iterated_auxv_data) + auxv_dict_iterated = self.build_auxv_dict( + endian, word_size, iterated_auxv_data) self.assertIsNotNone(auxv_dict_iterated) # Verify both types of data collection returned same content. diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py index 7daae871caf..dc2b99f54bd 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py @@ -1,13 +1,14 @@ from __future__ import print_function - import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestGdbRemoteExpeditedRegisters(gdbremote_testcase.GdbRemoteTestCaseBase): + +class TestGdbRemoteExpeditedRegisters( + gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -19,8 +20,11 @@ class TestGdbRemoteExpeditedRegisters(gdbremote_testcase.GdbRemoteTestCaseBase): "read packet: $c#63", # Immediately tell it to stop. We want to see what it reports. "read packet: {}".format(chr(3)), - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} }, - ], True) + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_result", + 2: "key_vals_text"}}, + ], True) # Run the gdb remote command stream. context = self.expect_gdbremote_sequence() @@ -30,13 +34,16 @@ class TestGdbRemoteExpeditedRegisters(gdbremote_testcase.GdbRemoteTestCaseBase): key_vals_text = context.get("key_vals_text") self.assertIsNotNone(key_vals_text) - expedited_registers = self.extract_registers_from_stop_notification(key_vals_text) + expedited_registers = self.extract_registers_from_stop_notification( + key_vals_text) self.assertIsNotNone(expedited_registers) return expedited_registers - def stop_notification_contains_generic_register(self, generic_register_name): - # Generate a stop reply, parse out expedited registers from stop notification. + def stop_notification_contains_generic_register( + self, generic_register_name): + # Generate a stop reply, parse out expedited registers from stop + # notification. expedited_registers = self.gather_expedited_registers() self.assertIsNotNone(expedited_registers) self.assertTrue(len(expedited_registers) > 0) @@ -45,7 +52,8 @@ class TestGdbRemoteExpeditedRegisters(gdbremote_testcase.GdbRemoteTestCaseBase): reg_infos = self.gather_register_infos() # Find the generic register. - reg_info = self.find_generic_register_with_name(reg_infos, generic_register_name) + reg_info = self.find_generic_register_with_name( + reg_infos, generic_register_name) self.assertIsNotNone(reg_info) # Ensure the expedited registers contained it. @@ -53,7 +61,8 @@ class TestGdbRemoteExpeditedRegisters(gdbremote_testcase.GdbRemoteTestCaseBase): # print("{} reg_info:{}".format(generic_register_name, reg_info)) def stop_notification_contains_any_registers(self): - # Generate a stop reply, parse out expedited registers from stop notification. + # Generate a stop reply, parse out expedited registers from stop + # notification. expedited_registers = self.gather_expedited_registers() # Verify we have at least one expedited register. self.assertTrue(len(expedited_registers) > 0) @@ -73,15 +82,19 @@ class TestGdbRemoteExpeditedRegisters(gdbremote_testcase.GdbRemoteTestCaseBase): self.stop_notification_contains_any_registers() def stop_notification_contains_no_duplicate_registers(self): - # Generate a stop reply, parse out expedited registers from stop notification. + # Generate a stop reply, parse out expedited registers from stop + # notification. expedited_registers = self.gather_expedited_registers() # Verify no expedited register was specified multiple times. for (reg_num, value) in list(expedited_registers.items()): - if (type(value) == list) and (len(value) > 0): - self.fail("expedited register number {} specified more than once ({} times)".format(reg_num, len(value))) + if (isinstance(value, list)) and (len(value) > 0): + self.fail( + "expedited register number {} specified more than once ({} times)".format( + reg_num, len(value))) @debugserver_test - def test_stop_notification_contains_no_duplicate_registers_debugserver(self): + def test_stop_notification_contains_no_duplicate_registers_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py index 560da9d4142..c3ecf5bc24d 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py @@ -1,13 +1,13 @@ from __future__ import print_function - import gdbremote_testcase import lldbgdbserverutils from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteKill(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -16,18 +16,20 @@ class TestGdbRemoteKill(gdbremote_testcase.GdbRemoteTestCaseBase): procs = self.prep_debug_monitor_and_inferior() self.test_sequence.add_log_lines([ "read packet: $k#6b", - {"direction":"send", "regex":r"^\$X[0-9a-fA-F]+([^#]*)#[0-9A-Fa-f]{2}" }, - ], True) + {"direction": "send", "regex": r"^\$X[0-9a-fA-F]+([^#]*)#[0-9A-Fa-f]{2}"}, + ], True) if self.stub_sends_two_stop_notifications_on_kill: - # Add an expectation for a second X result for stubs that send two of these. + # Add an expectation for a second X result for stubs that send two + # of these. self.test_sequence.add_log_lines([ - {"direction":"send", "regex":r"^\$X[0-9a-fA-F]+([^#]*)#[0-9A-Fa-f]{2}" }, - ], True) + {"direction": "send", "regex": r"^\$X[0-9a-fA-F]+([^#]*)#[0-9A-Fa-f]{2}"}, + ], True) self.expect_gdbremote_sequence() - # Wait a moment for completed and now-detached inferior process to clear. + # Wait a moment for completed and now-detached inferior process to + # clear. time.sleep(1) if not lldb.remote_platform: @@ -35,8 +37,11 @@ class TestGdbRemoteKill(gdbremote_testcase.GdbRemoteTestCaseBase): poll_result = procs["inferior"].poll() self.assertIsNotNone(poll_result) - # Where possible, verify at the system level that the process is not running. - self.assertFalse(lldbgdbserverutils.process_is_running(procs["inferior"].pid, False)) + # Where possible, verify at the system level that the process is not + # running. + self.assertFalse( + lldbgdbserverutils.process_is_running( + procs["inferior"].pid, False)) @debugserver_test def test_attach_commandline_kill_after_initial_stop_debugserver(self): @@ -51,4 +56,3 @@ class TestGdbRemoteKill(gdbremote_testcase.GdbRemoteTestCaseBase): self.build() self.set_inferior_startup_attach() self.attach_commandline_kill_after_initial_stop() - diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py index fd89ddfa28f..21af255cfd9 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py @@ -9,6 +9,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteProcessInfo(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -52,7 +53,7 @@ class TestGdbRemoteProcessInfo(gdbremote_testcase.GdbRemoteTestCaseBase): self.add_process_info_collection_packets() # Run the stream - context = self.expect_gdbremote_sequence(timeout_seconds = 8) + context = self.expect_gdbremote_sequence(timeout_seconds=8) self.assertIsNotNone(context) # Gather process info response @@ -66,7 +67,8 @@ class TestGdbRemoteProcessInfo(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertEqual(reported_pid, procs["inferior"].pid) @debugserver_test - def test_attach_commandline_qProcessInfo_reports_correct_pid_debugserver(self): + def test_attach_commandline_qProcessInfo_reports_correct_pid_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_attach() @@ -120,13 +122,17 @@ class TestGdbRemoteProcessInfo(gdbremote_testcase.GdbRemoteTestCaseBase): process_info = self.parse_process_info_response(context) self.assertIsNotNone(process_info) - # Ensure the expected keys are present and non-None within the process info. + # Ensure the expected keys are present and non-None within the process + # info. missing_key_set = set() for expected_key in expected_key_set: if expected_key not in process_info: missing_key_set.add(expected_key) - self.assertEqual(missing_key_set, set(), "the listed keys are missing in the qProcessInfo result") + self.assertEqual( + missing_key_set, + set(), + "the listed keys are missing in the qProcessInfo result") def qProcessInfo_does_not_contain_keys(self, absent_key_set): procs = self.prep_debug_monitor_and_inferior() @@ -146,7 +152,10 @@ class TestGdbRemoteProcessInfo(gdbremote_testcase.GdbRemoteTestCaseBase): if unexpected_key in process_info: unexpected_key_set.add(unexpected_key) - self.assertEqual(unexpected_key_set, set(), "the listed keys were present but unexpected in qProcessInfo result") + self.assertEqual( + unexpected_key_set, + set(), + "the listed keys were present but unexpected in qProcessInfo result") @skipUnlessDarwin @debugserver_test diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py index 63a8995c672..b484bdcc4d5 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py @@ -1,12 +1,12 @@ from __future__ import print_function - import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase): """Test QSaveRegisterState/QRestoreRegisterState support.""" @@ -15,7 +15,8 @@ class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase): def grp_register_save_restore_works(self, with_suffix): # Start up the process, use thread suffix, grab main thread id. inferior_args = ["message:main entered", "sleep:5"] - procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) self.add_process_info_collection_packets() self.add_register_info_collection_packets() @@ -26,8 +27,9 @@ class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase): # Start the inferior... "read packet: $c#63", # ... match output.... - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"message:main entered\r\n") }, - ], True) + {"type": "output_match", "regex": self.maybe_strict_output_regex( + r"message:main entered\r\n")}, + ], True) # ... then interrupt. self.add_interrupt_packets() @@ -44,8 +46,10 @@ class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertIsNotNone(reg_infos) self.add_lldb_register_index(reg_infos) - # Pull out the register infos that we think we can bit flip successfully. - gpr_reg_infos = [reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)] + # Pull out the register infos that we think we can bit flip + # successfully. + gpr_reg_infos = [ + reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)] self.assertTrue(len(gpr_reg_infos) > 0) # Gather thread info. @@ -71,15 +75,18 @@ class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase): # print("saved register state id: {}".format(state_id)) # Remember initial register values. - initial_reg_values = self.read_register_values(gpr_reg_infos, endian, thread_id=thread_id) + initial_reg_values = self.read_register_values( + gpr_reg_infos, endian, thread_id=thread_id) # print("initial_reg_values: {}".format(initial_reg_values)) # Flip gpr register values. - (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value(gpr_reg_infos, endian, thread_id=thread_id) + (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value( + gpr_reg_infos, endian, thread_id=thread_id) # print("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes)) self.assertTrue(successful_writes > 0) - flipped_reg_values = self.read_register_values(gpr_reg_infos, endian, thread_id=thread_id) + flipped_reg_values = self.read_register_values( + gpr_reg_infos, endian, thread_id=thread_id) # print("flipped_reg_values: {}".format(flipped_reg_values)) # Restore register values. @@ -90,7 +97,8 @@ class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertIsNotNone(context) # Verify registers match initial register values. - final_reg_values = self.read_register_values(gpr_reg_infos, endian, thread_id=thread_id) + final_reg_values = self.read_register_values( + gpr_reg_infos, endian, thread_id=thread_id) # print("final_reg_values: {}".format(final_reg_values)) self.assertIsNotNone(final_reg_values) self.assertEqual(final_reg_values, initial_reg_values) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py index 31d53bed259..f3a18786b03 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py @@ -1,12 +1,12 @@ from __future__ import print_function - import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteSingleStep(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -16,13 +16,24 @@ class TestGdbRemoteSingleStep(gdbremote_testcase.GdbRemoteTestCaseBase): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() - self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="s") + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="s") @llgs_test - @expectedFailureAndroid(bugnumber="llvm.org/pr24739", archs=["arm", "aarch64"]) - @expectedFailureAll(oslist=["linux"], archs=["arm", "aarch64"], bugnumber="llvm.org/pr24739") + @expectedFailureAndroid( + bugnumber="llvm.org/pr24739", + archs=[ + "arm", + "aarch64"]) + @expectedFailureAll( + oslist=["linux"], + archs=[ + "arm", + "aarch64"], + bugnumber="llvm.org/pr24739") def test_single_step_only_steps_one_instruction_with_s_llgs(self): self.init_llgs_test() self.build() self.set_inferior_startup_launch() - self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="s") + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="s") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py index d55416569ac..57d4d5ab4bb 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py @@ -5,7 +5,9 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil -class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): + +class TestGdbRemoteThreadsInStopReply( + gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -16,11 +18,12 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): def gather_stop_reply_threads(self, post_startup_log_lines, thread_count): # Set up the inferior args. - inferior_args=[] + inferior_args = [] for i in range(thread_count - 1): inferior_args.append("thread:new") inferior_args.append("sleep:10") - procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) # Assumes test_sequence has anything added needed to setup the initial state. # (Like optionally enabling QThreadsInStopReply.) @@ -28,17 +31,25 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): self.test_sequence.add_log_lines(post_startup_log_lines, True) self.test_sequence.add_log_lines([ "read packet: $c#63" - ], True) + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Give threads time to start up, then break. time.sleep(1) self.reset_test_sequence() - self.test_sequence.add_log_lines([ - "read packet: {}".format(chr(3)), - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} }, - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: {}".format( + chr(3)), + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": { + 1: "stop_result", + 2: "key_vals_text"}}, + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -49,11 +60,14 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): # Run, then stop the process, grab the stop reply content. self.reset_test_sequence() - self.test_sequence.add_log_lines([ - "read packet: $c#63", - "read packet: {}".format(chr(3)), - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} }, - ], True) + self.test_sequence.add_log_lines(["read packet: $c#63", + "read packet: {}".format(chr(3)), + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_result", + 2: "key_vals_text"}}, + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -66,13 +80,15 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): # Pull out threads from stop response. stop_reply_threads_text = kv_dict.get("threads") if stop_reply_threads_text: - return [int(thread_id, 16) for thread_id in stop_reply_threads_text.split(",")] + return [int(thread_id, 16) + for thread_id in stop_reply_threads_text.split(",")] else: return [] def QListThreadsInStopReply_supported(self): procs = self.prep_debug_monitor_and_inferior() - self.test_sequence.add_log_lines(self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True) + self.test_sequence.add_log_lines( + self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -92,8 +108,10 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): self.QListThreadsInStopReply_supported() def stop_reply_reports_multiple_threads(self, thread_count): - # Gather threads from stop notification when QThreadsInStopReply is enabled. - stop_reply_threads = self.gather_stop_reply_threads(self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count) + # Gather threads from stop notification when QThreadsInStopReply is + # enabled. + stop_reply_threads = self.gather_stop_reply_threads( + self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count) self.assertEqual(len(stop_reply_threads), thread_count) @debugserver_test @@ -111,7 +129,8 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): self.stop_reply_reports_multiple_threads(5) def no_QListThreadsInStopReply_supplies_no_threads(self, thread_count): - # Gather threads from stop notification when QThreadsInStopReply is not enabled. + # Gather threads from stop notification when QThreadsInStopReply is not + # enabled. stop_reply_threads = self.gather_stop_reply_threads(None, thread_count) self.assertEqual(len(stop_reply_threads), 0) @@ -130,8 +149,10 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): self.no_QListThreadsInStopReply_supplies_no_threads(5) def stop_reply_reports_correct_threads(self, thread_count): - # Gather threads from stop notification when QThreadsInStopReply is enabled. - stop_reply_threads = self.gather_stop_reply_threads(self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count) + # Gather threads from stop notification when QThreadsInStopReply is + # enabled. + stop_reply_threads = self.gather_stop_reply_threads( + self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count) self.assertEqual(len(stop_reply_threads), thread_count) # Gather threads from q{f,s}ThreadInfo. @@ -144,7 +165,7 @@ class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase): threads = self.parse_threadinfo_packets(context) self.assertIsNotNone(threads) self.assertEqual(len(threads), thread_count) - + # Ensure each thread in q{f,s}ThreadInfo appears in stop reply threads for tid in threads: self.assertTrue(tid in stop_reply_threads) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py index b2b54e3f039..74e4849b0cb 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py @@ -1,7 +1,6 @@ from __future__ import print_function - import sys import unittest2 @@ -10,6 +9,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -17,27 +17,36 @@ class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): def gather_stop_replies_via_qThreadStopInfo(self, thread_count): # Set up the inferior args. - inferior_args=[] + inferior_args = [] for i in range(thread_count - 1): inferior_args.append("thread:new") inferior_args.append("sleep:10") - procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) # Assumes test_sequence has anything added needed to setup the initial state. # (Like optionally enabling QThreadsInStopReply.) self.test_sequence.add_log_lines([ "read packet: $c#63" - ], True) + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Give threads time to start up, then break. time.sleep(1) self.reset_test_sequence() - self.test_sequence.add_log_lines([ - "read packet: {}".format(chr(3)), - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} }, - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: {}".format( + chr(3)), + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": { + 1: "stop_result", + 2: "key_vals_text"}}, + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -52,10 +61,17 @@ class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): for thread in threads: # Run the qThreadStopInfo command. self.reset_test_sequence() - self.test_sequence.add_log_lines([ - "read packet: $qThreadStopInfo{:x}#00".format(thread), - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} }, - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: $qThreadStopInfo{:x}#00".format(thread), + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": { + 1: "stop_result", + 2: "key_vals_text"}}, + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -65,7 +81,8 @@ class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): kv_dict = self.parse_key_val_dict(key_vals_text) self.assertIsNotNone(kv_dict) - # Verify there is a thread and that it matches the expected thread id. + # Verify there is a thread and that it matches the expected thread + # id. kv_thread = kv_dict.get("thread") self.assertIsNotNone(kv_thread) kv_thread_id = int(kv_thread, 16) @@ -99,12 +116,17 @@ class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): self.set_inferior_startup_launch() self.qThreadStopInfo_works_for_multiple_threads(self.THREAD_COUNT) - def qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt(self, thread_count): + def qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt( + self, thread_count): (stop_replies, _) = self.gather_stop_replies_via_qThreadStopInfo(thread_count) self.assertIsNotNone(stop_replies) - no_stop_reason_count = sum(1 for stop_reason in list(stop_replies.values()) if stop_reason == 0) - with_stop_reason_count = sum(1 for stop_reason in list(stop_replies.values()) if stop_reason != 0) + no_stop_reason_count = sum( + 1 for stop_reason in list( + stop_replies.values()) if stop_reason == 0) + with_stop_reason_count = sum( + 1 for stop_reason in list( + stop_replies.values()) if stop_reason != 0) # All but one thread should report no stop reason. self.assertEqual(no_stop_reason_count, thread_count - 1) @@ -113,20 +135,25 @@ class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertEqual(with_stop_reason_count, 1) @debugserver_test - def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_debugserver(self): + def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() - self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt(self.THREAD_COUNT) + self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt( + self.THREAD_COUNT) @llgs_test - def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_llgs(self): + def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_llgs( + self): self.init_llgs_test() self.build() self.set_inferior_startup_launch() - self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt(self.THREAD_COUNT) + self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt( + self.THREAD_COUNT) - def qThreadStopInfo_has_valid_thread_names(self, thread_count, expected_thread_name): + def qThreadStopInfo_has_valid_thread_names( + self, thread_count, expected_thread_name): (_, thread_dicts) = self.gather_stop_replies_via_qThreadStopInfo(thread_count) self.assertIsNotNone(thread_dicts) @@ -143,7 +170,8 @@ class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): self.set_inferior_startup_launch() self.qThreadStopInfo_has_valid_thread_names(self.THREAD_COUNT, "a.out") - @skipUnlessPlatform(["linux"]) # test requires OS with set, equal thread names by default. + # test requires OS with set, equal thread names by default. + @skipUnlessPlatform(["linux"]) @llgs_test def test_qThreadStopInfo_has_valid_thread_names_llgs(self): self.init_llgs_test() diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py index 335d96c2b07..1d98b9279f4 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py @@ -5,13 +5,15 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemote_vCont(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) def vCont_supports_mode(self, mode, inferior_args=None): # Setup the stub and set the gdb remote command stream. - procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) self.add_vCont_query_packets() # Run the gdb remote command stream. @@ -86,33 +88,58 @@ class TestGdbRemote_vCont(gdbremote_testcase.GdbRemoteTestCaseBase): self.vCont_supports_S() @debugserver_test - def test_single_step_only_steps_one_instruction_with_Hc_vCont_s_debugserver(self): + def test_single_step_only_steps_one_instruction_with_Hc_vCont_s_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() - self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="vCont;s") + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="vCont;s") @llgs_test - @expectedFailureAndroid(bugnumber="llvm.org/pr24739", archs=["arm", "aarch64"]) - @expectedFailureAll(oslist=["linux"], archs=["arm", "aarch64"], bugnumber="llvm.org/pr24739") + @expectedFailureAndroid( + bugnumber="llvm.org/pr24739", + archs=[ + "arm", + "aarch64"]) + @expectedFailureAll( + oslist=["linux"], + archs=[ + "arm", + "aarch64"], + bugnumber="llvm.org/pr24739") def test_single_step_only_steps_one_instruction_with_Hc_vCont_s_llgs(self): self.init_llgs_test() self.build() self.set_inferior_startup_launch() - self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="vCont;s") + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="vCont;s") @debugserver_test - def test_single_step_only_steps_one_instruction_with_vCont_s_thread_debugserver(self): + def test_single_step_only_steps_one_instruction_with_vCont_s_thread_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() - self.single_step_only_steps_one_instruction(use_Hc_packet=False, step_instruction="vCont;s:{thread}") + self.single_step_only_steps_one_instruction( + use_Hc_packet=False, step_instruction="vCont;s:{thread}") @llgs_test - @expectedFailureAndroid(bugnumber="llvm.org/pr24739", archs=["arm", "aarch64"]) - @expectedFailureAll(oslist=["linux"], archs=["arm", "aarch64"], bugnumber="llvm.org/pr24739") - def test_single_step_only_steps_one_instruction_with_vCont_s_thread_llgs(self): + @expectedFailureAndroid( + bugnumber="llvm.org/pr24739", + archs=[ + "arm", + "aarch64"]) + @expectedFailureAll( + oslist=["linux"], + archs=[ + "arm", + "aarch64"], + bugnumber="llvm.org/pr24739") + def test_single_step_only_steps_one_instruction_with_vCont_s_thread_llgs( + self): self.init_llgs_test() self.build() self.set_inferior_startup_launch() - self.single_step_only_steps_one_instruction(use_Hc_packet=False, step_instruction="vCont;s:{thread}") + self.single_step_only_steps_one_instruction( + use_Hc_packet=False, step_instruction="vCont;s:{thread}") diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py index 9cc20c11f74..1ba49f33940 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py @@ -13,7 +13,6 @@ the initial set of tests implemented. from __future__ import print_function - import unittest2 import gdbremote_testcase import lldbgdbserverutils @@ -23,6 +22,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -137,7 +137,7 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.add_verified_launch_packets(launch_args) self.test_sequence.add_log_lines( ["read packet: $vCont;c#a8", - {"type":"output_match", "regex": self.maybe_strict_output_regex(r"hello, world\r\n")}, + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"hello, world\r\n")}, "send packet: $W00#00"], True) @@ -168,12 +168,15 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.add_no_ack_remote_stream() self.add_verified_launch_packets(launch_args) - self.test_sequence.add_log_lines( - ["read packet: $qC#00", - { "direction":"send", "regex":r"^\$QC([0-9a-fA-F]+)#", "capture":{1:"thread_id"} }, - "read packet: $?#00", - { "direction":"send", "regex":r"^\$T[0-9a-fA-F]{2}thread:([0-9a-fA-F]+)", "expect_captures":{1:"thread_id"} }], - True) + self.test_sequence.add_log_lines(["read packet: $qC#00", + {"direction": "send", + "regex": r"^\$QC([0-9a-fA-F]+)#", + "capture": {1: "thread_id"}}, + "read packet: $?#00", + {"direction": "send", + "regex": r"^\$T[0-9a-fA-F]{2}thread:([0-9a-fA-F]+)", + "expect_captures": {1: "thread_id"}}], + True) self.expect_gdbremote_sequence() @debugserver_test @@ -196,7 +199,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): True) self.expect_gdbremote_sequence() - # Wait a moment for completed and now-detached inferior process to clear. + # Wait a moment for completed and now-detached inferior process to + # clear. time.sleep(1) if not lldb.remote_platform: @@ -204,8 +208,11 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): poll_result = procs["inferior"].poll() self.assertIsNotNone(poll_result) - # Where possible, verify at the system level that the process is not running. - self.assertFalse(lldbgdbserverutils.process_is_running(procs["inferior"].pid, False)) + # Where possible, verify at the system level that the process is not + # running. + self.assertFalse( + lldbgdbserverutils.process_is_running( + procs["inferior"].pid, False)) @debugserver_test def test_attach_commandline_continue_app_exits_debugserver(self): @@ -232,7 +239,7 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.add_verified_launch_packets(launch_args) self.test_sequence.add_log_lines( ["read packet: $qRegisterInfo0#00", - { "direction":"send", "regex":r"^\$(.+);#[0-9A-Fa-f]{2}", "capture":{1:"reginfo_0"} }], + {"direction": "send", "regex": r"^\$(.+);#[0-9A-Fa-f]{2}", "capture": {1: "reginfo_0"}}], True) # Run the stream @@ -241,7 +248,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): reg_info_packet = context.get("reginfo_0") self.assertIsNotNone(reg_info_packet) - self.assert_valid_reg_info(lldbgdbserverutils.parse_reg_info_response(reg_info_packet)) + self.assert_valid_reg_info( + lldbgdbserverutils.parse_reg_info_response(reg_info_packet)) @debugserver_test @expectedFailureDarwin("llvm.org/pr25486") @@ -307,7 +315,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): reg_infos = self.parse_register_info_packets(context) # Collect all generic registers found. - generic_regs = { reg_info['generic']:1 for reg_info in reg_infos if 'generic' in reg_info } + generic_regs = { + reg_info['generic']: 1 for reg_info in reg_infos if 'generic' in reg_info} # Ensure we have a program counter register. self.assertTrue('pc' in generic_regs) @@ -352,11 +361,13 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): reg_infos = self.parse_register_info_packets(context) # Collect all register sets found. - register_sets = { reg_info['set']:1 for reg_info in reg_infos if 'set' in reg_info } + register_sets = { + reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info} self.assertTrue(len(register_sets) >= 1) @debugserver_test - def test_qRegisterInfo_contains_at_least_one_register_set_debugserver(self): + def test_qRegisterInfo_contains_at_least_one_register_set_debugserver( + self): self.init_debugserver_test() self.build() self.qRegisterInfo_contains_at_least_one_register_set() @@ -406,8 +417,11 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): reg_infos = self.parse_register_info_packets(context) # Collect all generics found. - register_sets = { reg_info['set']:1 for reg_info in reg_infos if 'set' in reg_info } - self.assertEqual(self.targetHasAVX(), "Advanced Vector Extensions" in register_sets) + register_sets = { + reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info} + self.assertEqual( + self.targetHasAVX(), + "Advanced Vector Extensions" in register_sets) @llgs_test def test_qRegisterInfo_contains_avx_registers_llgs(self): @@ -464,7 +478,7 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.add_threadinfo_collection_packets() self.test_sequence.add_log_lines( ["read packet: $qC#00", - { "direction":"send", "regex":r"^\$QC([0-9a-fA-F]+)#", "capture":{1:"thread_id"} } + {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}} ], True) # Run the packet stream. @@ -532,7 +546,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): for reg_info in reg_infos: # Skip registers that don't have a register set. For x86, these are # the DRx registers, which have no LLDB-kind register number and thus - # cannot be read via normal NativeRegisterContext::ReadRegister(reg_info,...) calls. + # cannot be read via normal + # NativeRegisterContext::ReadRegister(reg_info,...) calls. if not "set" in reg_info: continue @@ -542,7 +557,7 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Run the register query self.test_sequence.add_log_lines( ["read packet: $p{0:x}#00".format(reg_index), - { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }], + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -556,28 +571,32 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): reg_index += 1 @debugserver_test - def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_debugserver(self): + def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() self.p_returns_correct_data_size_for_each_qRegisterInfo() @llgs_test - def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_llgs(self): + def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_llgs( + self): self.init_llgs_test() self.build() self.set_inferior_startup_launch() self.p_returns_correct_data_size_for_each_qRegisterInfo() @debugserver_test - def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_debugserver(self): + def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_attach() self.p_returns_correct_data_size_for_each_qRegisterInfo() @llgs_test - def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_llgs(self): + def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_llgs( + self): self.init_llgs_test() self.build() self.set_inferior_startup_attach() @@ -585,9 +604,12 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): def Hg_switches_to_3_threads(self): # Startup the inferior with three threads (main + 2 new ones). - procs = self.prep_debug_monitor_and_inferior(inferior_args=["thread:new", "thread:new"]) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["thread:new", "thread:new"]) - # Let the inferior process have a few moments to start up the thread when launched. (The launch scenario has no time to run, so threads won't be there yet.) + # Let the inferior process have a few moments to start up the thread + # when launched. (The launch scenario has no time to run, so threads + # won't be there yet.) self.run_process_then_stop(run_seconds=1) # Wait at most x seconds for 3 threads to be present. @@ -602,7 +624,7 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): ["read packet: $Hg{0:x}#00".format(thread), # Set current thread. "send packet: $OK#00", "read packet: $qC#00", - { "direction":"send", "regex":r"^\$QC([0-9a-fA-F]+)#", "capture":{1:"thread_id"} }], + {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}}], True) context = self.expect_gdbremote_sequence() @@ -648,7 +670,7 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Startup the inferior with three threads (main + NUM_THREADS-1 worker threads). # inferior_args=["thread:print-ids"] - inferior_args=["thread:segfault"] + inferior_args = ["thread:segfault"] for i in range(NUM_THREADS - 1): # if i > 0: # Give time between thread creation/segfaulting for the handler to work. @@ -656,8 +678,10 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): inferior_args.append("thread:new") inferior_args.append("sleep:10") - # Launch/attach. (In our case, this should only ever be launched since we need inferior stdout/stderr). - procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args) + # Launch/attach. (In our case, this should only ever be launched since + # we need inferior stdout/stderr). + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) self.test_sequence.add_log_lines(["read packet: $c#63"], True) context = self.expect_gdbremote_sequence() @@ -675,9 +699,11 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): for i in range(NUM_THREADS - 1): # Run until SIGSEGV comes in. self.reset_test_sequence() - self.test_sequence.add_log_lines( - [{"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"signo", 2:"thread_id"} } - ], True) + self.test_sequence.add_log_lines([{"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "signo", + 2: "thread_id"}}], + True) context = self.expect_gdbremote_sequence(timeout_seconds=10) self.assertIsNotNone(context) @@ -693,23 +719,24 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.reset_test_sequence() self.test_sequence.add_log_lines( [ - # Set the continue thread. - "read packet: $Hc{0:x}#00".format(thread_id), # Set current thread. - "send packet: $OK#00", - - # Continue sending the signal number to the continue thread. - # The commented out packet is a way to do this same operation without using - # a $Hc (but this test is testing $Hc, so we'll stick with the former). - "read packet: $C{0:x}#00".format(lldbutil.get_signal_number('SIGUSR1')), - # "read packet: $vCont;C{0:x}:{1:x};c#00".format(lldbutil.get_signal_number('SIGUSR1'), thread_id), - - # FIXME: Linux does not report the thread stop on the delivered signal (SIGUSR1 here). MacOSX debugserver does. - # But MacOSX debugserver isn't guaranteeing the thread the signal handler runs on, so currently its an XFAIL. - # Need to rectify behavior here. The linux behavior is more intuitive to me since we're essentially swapping out - # an about-to-be-delivered signal (for which we already sent a stop packet) to a different signal. - # {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }, - # "read packet: $c#63", - { "type":"output_match", "regex":r"^received SIGUSR1 on thread id: ([0-9a-fA-F]+)\r\nthread ([0-9a-fA-F]+): past SIGSEGV\r\n", "capture":{ 1:"print_thread_id", 2:"post_handle_thread_id" } }, + # Set the continue thread. + # Set current thread. + "read packet: $Hc{0:x}#00".format(thread_id), + "send packet: $OK#00", + + # Continue sending the signal number to the continue thread. + # The commented out packet is a way to do this same operation without using + # a $Hc (but this test is testing $Hc, so we'll stick with the former). + "read packet: $C{0:x}#00".format(lldbutil.get_signal_number('SIGUSR1')), + # "read packet: $vCont;C{0:x}:{1:x};c#00".format(lldbutil.get_signal_number('SIGUSR1'), thread_id), + + # FIXME: Linux does not report the thread stop on the delivered signal (SIGUSR1 here). MacOSX debugserver does. + # But MacOSX debugserver isn't guaranteeing the thread the signal handler runs on, so currently its an XFAIL. + # Need to rectify behavior here. The linux behavior is more intuitive to me since we're essentially swapping out + # an about-to-be-delivered signal (for which we already sent a stop packet) to a different signal. + # {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }, + # "read packet: $c#63", + {"type": "output_match", "regex": r"^received SIGUSR1 on thread id: ([0-9a-fA-F]+)\r\nthread ([0-9a-fA-F]+): past SIGSEGV\r\n", "capture": {1: "print_thread_id", 2: "post_handle_thread_id"}}, ], True) @@ -727,16 +754,20 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # self.assertIsNotNone(stop_thread_id) # self.assertEquals(int(stop_thread_id,16), thread_id) - # Ensure we haven't seen this thread id yet. The inferior's self-obtained thread ids are not guaranteed to match the stub tids (at least on MacOSX). + # Ensure we haven't seen this thread id yet. The inferior's + # self-obtained thread ids are not guaranteed to match the stub + # tids (at least on MacOSX). print_thread_id = context.get("print_thread_id") self.assertIsNotNone(print_thread_id) print_thread_id = int(print_thread_id, 16) self.assertFalse(print_thread_id in print_thread_ids) - - # Now remember this print (i.e. inferior-reflected) thread id and ensure we don't hit it again. + + # Now remember this print (i.e. inferior-reflected) thread id and + # ensure we don't hit it again. print_thread_ids[print_thread_id] = 1 - # Ensure post signal-handle thread id matches the thread that initially raised the SIGSEGV. + # Ensure post signal-handle thread id matches the thread that + # initially raised the SIGSEGV. post_handle_thread_id = context.get("post_handle_thread_id") self.assertIsNotNone(post_handle_thread_id) post_handle_thread_id = int(post_handle_thread_id, 16) @@ -748,7 +779,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() - # Darwin debugserver translates some signals like SIGSEGV into some gdb expectations about fixed signal numbers. + # Darwin debugserver translates some signals like SIGSEGV into some gdb + # expectations about fixed signal numbers. self.Hc_then_Csignal_signals_correct_thread(self.TARGET_EXC_BAD_ACCESS) @llgs_test @@ -756,29 +788,35 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.init_llgs_test() self.build() self.set_inferior_startup_launch() - self.Hc_then_Csignal_signals_correct_thread(lldbutil.get_signal_number('SIGSEGV')) + self.Hc_then_Csignal_signals_correct_thread( + lldbutil.get_signal_number('SIGSEGV')) def m_packet_reads_memory(self): - # This is the memory we will write into the inferior and then ensure we can read back with $m. + # This is the memory we will write into the inferior and then ensure we + # can read back with $m. MEMORY_CONTENTS = "Test contents 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz" # Start up the inferior. procs = self.prep_debug_monitor_and_inferior( - inferior_args=["set-message:%s" % MEMORY_CONTENTS, "get-data-address-hex:g_message", "sleep:5"]) + inferior_args=[ + "set-message:%s" % + MEMORY_CONTENTS, + "get-data-address-hex:g_message", + "sleep:5"]) # Run the process self.test_sequence.add_log_lines( [ - # Start running after initial stop. - "read packet: $c#63", - # Match output line that prints the memory address of the message buffer within the inferior. - # Note we require launch-only testing so we can get inferior otuput. - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"), - "capture":{ 1:"message_address"} }, - # Now stop the inferior. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }], + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "message_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], True) # Run the packet stream. @@ -793,7 +831,7 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.reset_test_sequence() self.test_sequence.add_log_lines( ["read packet: $m{0:x},{1:x}#00".format(message_address, len(MEMORY_CONTENTS)), - {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"read_contents"} }], + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "read_contents"}}], True) # Run the packet stream. @@ -852,16 +890,16 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Run the process self.test_sequence.add_log_lines( [ - # Start running after initial stop. - "read packet: $c#63", - # Match output line that prints the memory address of the message buffer within the inferior. - # Note we require launch-only testing so we can get inferior otuput. - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"), - "capture":{ 1:"code_address"} }, - # Now stop the inferior. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }], + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "code_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], True) # Run the packet stream. @@ -893,7 +931,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.assert_address_within_memory_region(code_address, mem_region_dict) @debugserver_test - def test_qMemoryRegionInfo_reports_code_address_as_executable_debugserver(self): + def test_qMemoryRegionInfo_reports_code_address_as_executable_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() @@ -914,16 +953,16 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Run the process self.test_sequence.add_log_lines( [ - # Start running after initial stop. - "read packet: $c#63", - # Match output line that prints the memory address of the message buffer within the inferior. - # Note we require launch-only testing so we can get inferior otuput. - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"stack address: 0x([0-9a-fA-F]+)\r\n"), - "capture":{ 1:"stack_address"} }, - # Now stop the inferior. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }], + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"stack address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "stack_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], True) # Run the packet stream. @@ -952,17 +991,20 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertTrue("w" in mem_region_dict["permissions"]) # Ensure the start address and size encompass the address we queried. - self.assert_address_within_memory_region(stack_address, mem_region_dict) + self.assert_address_within_memory_region( + stack_address, mem_region_dict) @debugserver_test - def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_debugserver(self): + def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable() @llgs_test - def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_llgs(self): + def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_llgs( + self): self.init_llgs_test() self.build() self.set_inferior_startup_launch() @@ -976,16 +1018,16 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Run the process self.test_sequence.add_log_lines( [ - # Start running after initial stop. - "read packet: $c#63", - # Match output line that prints the memory address of the message buffer within the inferior. - # Note we require launch-only testing so we can get inferior otuput. - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"heap address: 0x([0-9a-fA-F]+)\r\n"), - "capture":{ 1:"heap_address"} }, - # Now stop the inferior. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }], + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"heap address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "heap_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], True) # Run the packet stream. @@ -1016,16 +1058,17 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Ensure the start address and size encompass the address we queried. self.assert_address_within_memory_region(heap_address, mem_region_dict) - @debugserver_test - def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_debugserver(self): + def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_debugserver( + self): self.init_debugserver_test() self.build() self.set_inferior_startup_launch() self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable() @llgs_test - def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_llgs(self): + def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_llgs( + self): self.init_llgs_test() self.build() self.set_inferior_startup_launch() @@ -1034,29 +1077,33 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): def software_breakpoint_set_and_remove_work(self): # Start up the inferior. procs = self.prep_debug_monitor_and_inferior( - inferior_args=["get-code-address-hex:hello", "sleep:1", "call-function:hello"]) + inferior_args=[ + "get-code-address-hex:hello", + "sleep:1", + "call-function:hello"]) # Run the process self.add_register_info_collection_packets() self.add_process_info_collection_packets() self.test_sequence.add_log_lines( - [# Start running after initial stop. - "read packet: $c#63", - # Match output line that prints the memory address of the function call entry point. - # Note we require launch-only testing so we can get inferior otuput. - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"), - "capture":{ 1:"function_address"} }, - # Now stop the inferior. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }], + [ # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the function call entry point. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "function_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], True) # Run the packet stream. context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) - # Gather process info - we need endian of target to handle register value conversions. + # Gather process info - we need endian of target to handle register + # value conversions. process_info = self.parse_process_info_response(context) endian = process_info.get("endian") self.assertIsNotNone(endian) @@ -1078,7 +1125,10 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): else: BREAKPOINT_KIND = 1 self.reset_test_sequence() - self.add_set_breakpoint_packets(function_address, do_continue=True, breakpoint_kind=BREAKPOINT_KIND) + self.add_set_breakpoint_packets( + function_address, + do_continue=True, + breakpoint_kind=BREAKPOINT_KIND) # Run the packet stream. context = self.expect_gdbremote_sequence() @@ -1087,7 +1137,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Verify the stop signal reported was the breakpoint signal number. stop_signo = context.get("stop_signo") self.assertIsNotNone(stop_signo) - self.assertEqual(int(stop_signo,16), lldbutil.get_signal_number('SIGTRAP')) + self.assertEqual(int(stop_signo, 16), + lldbutil.get_signal_number('SIGTRAP')) # Ensure we did not receive any output. If the breakpoint was not set, we would # see output (from a launched process with captured stdio) printing a hello, world message. @@ -1099,37 +1150,43 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.reset_test_sequence() self.test_sequence.add_log_lines( [ - # Print the PC. This should match the breakpoint address. - "read packet: $p{0:x}#00".format(pc_lldb_reg_index), - # Capture $p results. - { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }, - ], True) - + # Print the PC. This should match the breakpoint address. + "read packet: $p{0:x}#00".format(pc_lldb_reg_index), + # Capture $p results. + {"direction": "send", + "regex": r"^\$([0-9a-fA-F]+)#", + "capture": {1: "p_response"}}, + ], True) + context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) - - # Verify the PC is where we expect. Note response is in endianness of the inferior. + + # Verify the PC is where we expect. Note response is in endianness of + # the inferior. p_response = context.get("p_response") self.assertIsNotNone(p_response) # Convert from target endian to int. - returned_pc = lldbgdbserverutils.unpack_register_hex_unsigned(endian, p_response) + returned_pc = lldbgdbserverutils.unpack_register_hex_unsigned( + endian, p_response) self.assertEqual(returned_pc, function_address) - # Verify that a breakpoint remove and continue gets us the expected output. + # Verify that a breakpoint remove and continue gets us the expected + # output. self.reset_test_sequence() self.test_sequence.add_log_lines( [ - # Remove the breakpoint. - "read packet: $z0,{0:x},{1}#00".format(function_address, BREAKPOINT_KIND), - # Verify the stub could unset it. - "send packet: $OK#00", - # Continue running. - "read packet: $c#63", - # We should now receive the output from the call. - { "type":"output_match", "regex":r"^hello, world\r\n$" }, - # And wait for program completion. - {"direction":"send", "regex":r"^\$W00(.*)#[0-9a-fA-F]{2}$" }, + # Remove the breakpoint. + "read packet: $z0,{0:x},{1}#00".format( + function_address, BREAKPOINT_KIND), + # Verify the stub could unset it. + "send packet: $OK#00", + # Continue running. + "read packet: $c#63", + # We should now receive the output from the call. + {"type": "output_match", "regex": r"^hello, world\r\n$"}, + # And wait for program completion. + {"direction": "send", "regex": r"^\$W00(.*)#[0-9a-fA-F]{2}$"}, ], True) context = self.expect_gdbremote_sequence() @@ -1190,19 +1247,24 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): TEST_MESSAGE = "Hello, memory" # Start up the stub and start/prep the inferior. - procs = self.prep_debug_monitor_and_inferior(inferior_args=["set-message:xxxxxxxxxxxxxX", "get-data-address-hex:g_message", "sleep:1", "print-message:"]) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=[ + "set-message:xxxxxxxxxxxxxX", + "get-data-address-hex:g_message", + "sleep:1", + "print-message:"]) self.test_sequence.add_log_lines( [ - # Start running after initial stop. - "read packet: $c#63", - # Match output line that prints the memory address of the message buffer within the inferior. - # Note we require launch-only testing so we can get inferior otuput. - { "type":"output_match", "regex":self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"), - "capture":{ 1:"message_address"} }, - # Now stop the inferior. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }], + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "message_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1229,9 +1291,9 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): "read packet: $x{0:x},4#00".format(message_address), "send packet: ${0}#00".format(TEST_MESSAGE[0:4]), "read packet: $c#63", - { "type":"output_match", "regex":r"^message: (.+)\r\n$", "capture":{ 1:"printed_message"} }, + {"type": "output_match", "regex": r"^message: (.+)\r\n$", "capture": {1: "printed_message"}}, "send packet: $W00#00", - ], True) + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1274,17 +1336,21 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): endian = process_info.get("endian") self.assertIsNotNone(endian) - # Pull out the register infos that we think we can bit flip successfully,. - gpr_reg_infos = [reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)] + # Pull out the register infos that we think we can bit flip + # successfully,. + gpr_reg_infos = [ + reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)] self.assertTrue(len(gpr_reg_infos) > 0) # Write flipped bit pattern of existing value to each register. - (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value(gpr_reg_infos, endian) + (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value( + gpr_reg_infos, endian) # print("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes)) self.assertTrue(successful_writes > 0) # Note: as of this moment, a hefty number of the GPR writes are failing with E32 (everything except rax-rdx, rdi, rsi, rbp). - # Come back to this. I have the test rigged to verify that at least some of the bit-flip writes work. + # Come back to this. I have the test rigged to verify that at least some + # of the bit-flip writes work. @debugserver_test def test_P_writes_all_gpr_registers_debugserver(self): self.init_debugserver_test() @@ -1301,7 +1367,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): def P_and_p_thread_suffix_work(self): # Startup the inferior with three threads. - procs = self.prep_debug_monitor_and_inferior(inferior_args=["thread:new", "thread:new"]) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["thread:new", "thread:new"]) self.add_thread_suffix_request_packets() self.add_register_info_collection_packets() self.add_process_info_collection_packets() @@ -1323,7 +1390,8 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): reg_byte_size = int(reg_infos[reg_index]["bitsize"]) / 8 self.assertTrue(reg_byte_size > 0) - # Run the process a bit so threads can start up, and collect register info. + # Run the process a bit so threads can start up, and collect register + # info. context = self.run_process_then_stop(run_seconds=1) self.assertIsNotNone(context) @@ -1338,59 +1406,75 @@ class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): # Set the same register in each of 3 threads to a different value. # Verify each one has the unique value. for thread in threads: - # If we don't have a next value yet, start it with the initial read value + 1 + # If we don't have a next value yet, start it with the initial read + # value + 1 if not next_value: # Read pre-existing register value. self.reset_test_sequence() self.test_sequence.add_log_lines( ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread), - { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }, - ], True) + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) - # Set the next value to use for writing as the increment plus current value. + # Set the next value to use for writing as the increment plus + # current value. p_response = context.get("p_response") self.assertIsNotNone(p_response) - next_value = lldbgdbserverutils.unpack_register_hex_unsigned(endian, p_response) + next_value = lldbgdbserverutils.unpack_register_hex_unsigned( + endian, p_response) # Set new value using P and thread suffix. self.reset_test_sequence() self.test_sequence.add_log_lines( - ["read packet: $P{0:x}={1};thread:{2:x}#00".format(reg_index, lldbgdbserverutils.pack_register_hex(endian, next_value, byte_size=reg_byte_size), thread), - "send packet: $OK#00", - ], True) + [ + "read packet: $P{0:x}={1};thread:{2:x}#00".format( + reg_index, + lldbgdbserverutils.pack_register_hex( + endian, + next_value, + byte_size=reg_byte_size), + thread), + "send packet: $OK#00", + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Save the value we set. expected_reg_values.append(next_value) - # Increment value for next thread to use (we want them all different so we can verify they wrote to each thread correctly next.) + # Increment value for next thread to use (we want them all + # different so we can verify they wrote to each thread correctly + # next.) next_value += register_increment - # Revisit each thread and verify they have the expected value set for the register we wrote. + # Revisit each thread and verify they have the expected value set for + # the register we wrote. thread_index = 0 for thread in threads: # Read pre-existing register value. self.reset_test_sequence() self.test_sequence.add_log_lines( ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread), - { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }, - ], True) + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Get the register value. p_response = context.get("p_response") self.assertIsNotNone(p_response) - read_value = lldbgdbserverutils.unpack_register_hex_unsigned(endian, p_response) + read_value = lldbgdbserverutils.unpack_register_hex_unsigned( + endian, p_response) # Make sure we read back what we wrote. self.assertEqual(read_value, expected_reg_values[thread_index]) thread_index += 1 - # Note: as of this moment, a hefty number of the GPR writes are failing with E32 (everything except rax-rdx, rdi, rsi, rbp). + # Note: as of this moment, a hefty number of the GPR writes are failing + # with E32 (everything except rax-rdx, rdi, rsi, rbp). @debugserver_test def test_P_and_p_thread_suffix_work_debugserver(self): self.init_debugserver_test() diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py index 6894d1ceacc..c1a63af5424 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py @@ -10,6 +10,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestStubReverseConnect(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -30,7 +31,7 @@ class TestStubReverseConnect(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertIsNotNone(sock) sock.settimeout(timeout_seconds) - sock.bind(("127.0.0.1",0)) + sock.bind(("127.0.0.1", 0)) sock.listen(1) def tear_down_listener(): @@ -56,18 +57,25 @@ class TestStubReverseConnect(gdbremote_testcase.GdbRemoteTestCaseBase): triple = self.dbg.GetSelectedPlatform().GetTriple() if re.match(".*-.*-.*-android", triple): - self.forward_adb_port(self.port, self.port, "reverse", self.stub_device) + self.forward_adb_port( + self.port, + self.port, + "reverse", + self.stub_device) # Start the stub. server = self.launch_debug_monitor(logfile=sys.stdout) self.assertIsNotNone(server) - self.assertTrue(lldbgdbserverutils.process_is_running(server.pid, True)) + self.assertTrue( + lldbgdbserverutils.process_is_running( + server.pid, True)) # Listen for the stub's connection to us. (stub_socket, address) = self.listener_socket.accept() self.assertIsNotNone(stub_socket) self.assertIsNotNone(address) - print("connected to stub {} on {}".format(address, stub_socket.getsockname())) + print("connected to stub {} on {}".format( + address, stub_socket.getsockname())) # Verify we can do the handshake. If that works, we'll call it good. self.do_handshake(stub_socket, timeout_seconds=self._DEFAULT_TIMEOUT) @@ -82,7 +90,7 @@ class TestStubReverseConnect(gdbremote_testcase.GdbRemoteTestCaseBase): self.reverse_connect_works() @llgs_test - @skipIfRemote # reverse connect is not a supported use case for now + @skipIfRemote # reverse connect is not a supported use case for now def test_reverse_connect_works_llgs(self): self.init_llgs_test(use_named_pipe=False) self.set_inferior_startup_launch() diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py index bda93155d27..27daf30f189 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py @@ -1,7 +1,6 @@ from __future__ import print_function - import gdbremote_testcase import lldbgdbserverutils import os @@ -12,6 +11,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestStubSetSIDTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -23,7 +23,9 @@ class TestStubSetSIDTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): server = self.launch_debug_monitor() self.assertIsNotNone(server) - self.assertTrue(lldbgdbserverutils.process_is_running(server.pid, True)) + self.assertTrue( + lldbgdbserverutils.process_is_running( + server.pid, True)) # Get the process id for the stub. return os.getsid(server.pid) @@ -41,14 +43,14 @@ class TestStubSetSIDTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.assertNotEqual(stub_sid, os.getsid(0)) @debugserver_test - @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target def test_sid_is_same_without_setsid_debugserver(self): self.init_debugserver_test() self.set_inferior_startup_launch() self.sid_is_same_without_setsid() @llgs_test - @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target @expectedFailureAll(oslist=['freebsd']) def test_sid_is_same_without_setsid_llgs(self): self.init_llgs_test() @@ -56,28 +58,28 @@ class TestStubSetSIDTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): self.sid_is_same_without_setsid() @debugserver_test - @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target def test_sid_is_different_with_setsid_debugserver(self): self.init_debugserver_test() self.set_inferior_startup_launch() self.sid_is_different_with_setsid() @llgs_test - @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target def test_sid_is_different_with_setsid_llgs(self): self.init_llgs_test() self.set_inferior_startup_launch() self.sid_is_different_with_setsid() @debugserver_test - @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target def test_sid_is_different_with_S_debugserver(self): self.init_debugserver_test() self.set_inferior_startup_launch() self.sid_is_different_with_S() @llgs_test - @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target def test_sid_is_different_with_S_llgs(self): self.init_llgs_test() self.set_inferior_startup_launch() diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py index 12c1033cba1..7fc25807435 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py @@ -5,7 +5,6 @@ Base class for gdb-remote test cases. from __future__ import print_function - import errno import os import os.path @@ -24,9 +23,11 @@ from lldbsuite.test.lldbtest import * from lldbgdbserverutils import * import logging + class _ConnectionRefused(IOError): pass + class GdbRemoteTestCaseBase(TestBase): NO_DEBUG_INFO_TESTCASE = True @@ -35,29 +36,34 @@ class GdbRemoteTestCaseBase(TestBase): _GDBREMOTE_KILL_PACKET = "$k#6b" - # Start the inferior separately, attach to the inferior on the stub command line. + # Start the inferior separately, attach to the inferior on the stub + # command line. _STARTUP_ATTACH = "attach" - # Start the inferior separately, start the stub without attaching, allow the test to attach to the inferior however it wants (e.g. $vAttach;pid). + # Start the inferior separately, start the stub without attaching, allow + # the test to attach to the inferior however it wants (e.g. $vAttach;pid). _STARTUP_ATTACH_MANUALLY = "attach_manually" - # Start the stub, and launch the inferior with an $A packet via the initial packet stream. + # Start the stub, and launch the inferior with an $A packet via the + # initial packet stream. _STARTUP_LAUNCH = "launch" - # GDB Signal numbers that are not target-specific used for common exceptions - TARGET_EXC_BAD_ACCESS = 0x91 + # GDB Signal numbers that are not target-specific used for common + # exceptions + TARGET_EXC_BAD_ACCESS = 0x91 TARGET_EXC_BAD_INSTRUCTION = 0x92 - TARGET_EXC_ARITHMETIC = 0x93 - TARGET_EXC_EMULATION = 0x94 - TARGET_EXC_SOFTWARE = 0x95 - TARGET_EXC_BREAKPOINT = 0x96 + TARGET_EXC_ARITHMETIC = 0x93 + TARGET_EXC_EMULATION = 0x94 + TARGET_EXC_SOFTWARE = 0x95 + TARGET_EXC_BREAKPOINT = 0x96 _verbose_log_handler = None - _log_formatter = logging.Formatter(fmt='%(asctime)-15s %(levelname)-8s %(message)s') + _log_formatter = logging.Formatter( + fmt='%(asctime)-15s %(levelname)-8s %(message)s') def setUpBaseLogging(self): self.logger = logging.getLogger(__name__) if len(self.logger.handlers) > 0: - return # We have set up this handler already + return # We have set up this handler already self.logger.propagate = False self.logger.setLevel(logging.DEBUG) @@ -68,11 +74,11 @@ class GdbRemoteTestCaseBase(TestBase): handler.setFormatter(self._log_formatter) self.logger.addHandler(handler) - def isVerboseLoggingRequested(self): # We will report our detailed logs if the user requested that the "gdb-remote" channel is # logged. - return any(("gdb-remote" in channel) for channel in lldbtest_config.channels) + return any(("gdb-remote" in channel) + for channel in lldbtest_config.channels) def setUp(self): TestBase.setUp(self) @@ -83,7 +89,8 @@ class GdbRemoteTestCaseBase(TestBase): if self.isVerboseLoggingRequested(): # If requested, full logs go to a log file - self._verbose_log_handler = logging.FileHandler(self.log_basename + "-host.log") + self._verbose_log_handler = logging.FileHandler( + self.log_basename + "-host.log") self._verbose_log_handler.setFormatter(self._log_formatter) self._verbose_log_handler.setLevel(logging.DEBUG) self.logger.addHandler(self._verbose_log_handler) @@ -100,7 +107,8 @@ class GdbRemoteTestCaseBase(TestBase): url_pattern = '(.+)://\[?(.+?)\]?/.*' else: url_pattern = '(.+)://(.+):\d+' - scheme, host = re.match(url_pattern, configuration.lldb_platform_url).groups() + scheme, host = re.match( + url_pattern, configuration.lldb_platform_url).groups() if configuration.lldb_platform_name == 'remote-android' and host != 'localhost': self.stub_device = host self.stub_hostname = 'localhost' @@ -122,21 +130,24 @@ class GdbRemoteTestCaseBase(TestBase): def setUpServerLogging(self, is_llgs): if len(lldbtest_config.channels) == 0: - return # No logging requested + return # No logging requested if lldb.remote_platform: - log_file = lldbutil.join_remote_paths(lldb.remote_platform.GetWorkingDirectory(), "server.log") + log_file = lldbutil.join_remote_paths( + lldb.remote_platform.GetWorkingDirectory(), "server.log") else: log_file = self.getLocalServerLogFile() if is_llgs: self.debug_monitor_extra_args.append("--log-file=" + log_file) - self.debug_monitor_extra_args.append("--log-channels={}".format(":".join(lldbtest_config.channels))) + self.debug_monitor_extra_args.append( + "--log-channels={}".format(":".join(lldbtest_config.channels))) else: - self.debug_monitor_extra_args = ["--log-file=" + log_file, "--log-flags=0x800000"] + self.debug_monitor_extra_args = [ + "--log-file=" + log_file, "--log-flags=0x800000"] def get_next_port(self): - return 12000 + random.randint(0,3999) + return 12000 + random.randint(0, 3999) def reset_test_sequence(self): self.test_sequence = GdbRemoteTestSequence(self.logger) @@ -149,7 +160,8 @@ class GdbRemoteTestCaseBase(TestBase): # Create the named pipe. os.mkfifo(named_pipe_path) - # Open the read side of the pipe in non-blocking mode. This will return right away, ready or not. + # Open the read side of the pipe in non-blocking mode. This will + # return right away, ready or not. named_pipe_fd = os.open(named_pipe_path, os.O_RDONLY | os.O_NONBLOCK) # Create the file for the named pipe. Note this will follow semantics of @@ -177,7 +189,9 @@ class GdbRemoteTestCaseBase(TestBase): try: os.rmdir(temp_dir) except: - print("failed to delete temp dir: {}, directory contents: '{}'".format(temp_dir, os.listdir(temp_dir))) + print( + "failed to delete temp dir: {}, directory contents: '{}'".format( + temp_dir, os.listdir(temp_dir))) None # Add the shutdown hook to clean up the named pipe. @@ -190,14 +204,23 @@ class GdbRemoteTestCaseBase(TestBase): def get_stub_port_from_named_socket(self, read_timeout_seconds=5): # Wait for something to read with a max timeout. - (ready_readers, _, _) = select.select([self.named_pipe_fd], [], [], read_timeout_seconds) - self.assertIsNotNone(ready_readers, "write side of pipe has not written anything - stub isn't writing to pipe.") - self.assertNotEqual(len(ready_readers), 0, "write side of pipe has not written anything - stub isn't writing to pipe.") + (ready_readers, _, _) = select.select( + [self.named_pipe_fd], [], [], read_timeout_seconds) + self.assertIsNotNone( + ready_readers, + "write side of pipe has not written anything - stub isn't writing to pipe.") + self.assertNotEqual( + len(ready_readers), + 0, + "write side of pipe has not written anything - stub isn't writing to pipe.") # Read the port from the named pipe. stub_port_raw = self.named_pipe.read() self.assertIsNotNone(stub_port_raw) - self.assertNotEqual(len(stub_port_raw), 0, "no content to read on pipe") + self.assertNotEqual( + len(stub_port_raw), + 0, + "no content to read on pipe") # Trim null byte, convert to int. stub_port_raw = stub_port_raw[:-1] @@ -212,15 +235,24 @@ class GdbRemoteTestCaseBase(TestBase): use_named_pipe = False # Grab the ppid from /proc/[shell pid]/stat - err, retcode, shell_stat = self.run_platform_command("cat /proc/$$/stat") - self.assertTrue(err.Success() and retcode == 0, - "Failed to read file /proc/$$/stat: %s, retcode: %d" % (err.GetCString(), retcode)) + err, retcode, shell_stat = self.run_platform_command( + "cat /proc/$$/stat") + self.assertTrue( + err.Success() and retcode == 0, + "Failed to read file /proc/$$/stat: %s, retcode: %d" % + (err.GetCString(), + retcode)) # [pid] ([executable]) [state] [*ppid*] pid = re.match(r"^\d+ \(.+\) . (\d+)", shell_stat).group(1) - err, retcode, ls_output = self.run_platform_command("ls -l /proc/%s/exe" % pid) - self.assertTrue(err.Success() and retcode == 0, - "Failed to read file /proc/%s/exe: %s, retcode: %d" % (pid, err.GetCString(), retcode)) + err, retcode, ls_output = self.run_platform_command( + "ls -l /proc/%s/exe" % pid) + self.assertTrue( + err.Success() and retcode == 0, + "Failed to read file /proc/%s/exe: %s, retcode: %d" % + (pid, + err.GetCString(), + retcode)) exe = ls_output.split()[-1] # If the binary has been deleted, the link name has " (deleted)" appended. @@ -235,7 +267,8 @@ class GdbRemoteTestCaseBase(TestBase): self.setUpServerLogging(is_llgs=True) if use_named_pipe: - (self.named_pipe_path, self.named_pipe, self.named_pipe_fd) = self.create_named_pipe() + (self.named_pipe_path, self.named_pipe, + self.named_pipe_fd) = self.create_named_pipe() def init_debugserver_test(self, use_named_pipe=True): self.debug_monitor_exe = get_debugserver_exe() @@ -243,17 +276,19 @@ class GdbRemoteTestCaseBase(TestBase): self.skipTest("debugserver exe not found") self.setUpServerLogging(is_llgs=False) if use_named_pipe: - (self.named_pipe_path, self.named_pipe, self.named_pipe_fd) = self.create_named_pipe() + (self.named_pipe_path, self.named_pipe, + self.named_pipe_fd) = self.create_named_pipe() # The debugserver stub has a race on handling the 'k' command, so it sends an X09 right away, then sends the real X notification # when the process truly dies. self.stub_sends_two_stop_notifications_on_kill = True def forward_adb_port(self, source, target, direction, device): - adb = [ 'adb' ] + ([ '-s', device ] if device else []) + [ direction ] + adb = ['adb'] + (['-s', device] if device else []) + [direction] + def remove_port_forward(): - subprocess.call(adb + [ "--remove", "tcp:%d" % source]) + subprocess.call(adb + ["--remove", "tcp:%d" % source]) - subprocess.call(adb + [ "tcp:%d" % source, "tcp:%d" % target]) + subprocess.call(adb + ["tcp:%d" % source, "tcp:%d" % target]) self.addTearDownHook(remove_port_forward) def _verify_socket(self, sock): @@ -265,12 +300,12 @@ class GdbRemoteTestCaseBase(TestBase): # connection again. triple = self.dbg.GetSelectedPlatform().GetTriple() if not re.match(".*-.*-.*-android", triple): - return # Not android. + return # Not android. can_read, _, _ = select.select([sock], [], [], 0.1) if sock not in can_read: - return # Data is not available, but the connection is alive. + return # Data is not available, but the connection is alive. if len(sock.recv(1, socket.MSG_PEEK)) == 0: - raise _ConnectionRefused() # Got EOF, connection dropped. + raise _ConnectionRefused() # Got EOF, connection dropped. def create_socket(self): sock = socket.socket() @@ -278,9 +313,16 @@ class GdbRemoteTestCaseBase(TestBase): triple = self.dbg.GetSelectedPlatform().GetTriple() if re.match(".*-.*-.*-android", triple): - self.forward_adb_port(self.port, self.port, "forward", self.stub_device) - - logger.info("Connecting to debug monitor on %s:%d", self.stub_hostname, self.port) + self.forward_adb_port( + self.port, + self.port, + "forward", + self.stub_device) + + logger.info( + "Connecting to debug monitor on %s:%d", + self.stub_hostname, + self.port) connect_info = (self.stub_hostname, self.port) try: sock.connect(connect_info) @@ -295,12 +337,16 @@ class GdbRemoteTestCaseBase(TestBase): # send the kill packet so lldb-server shuts down gracefully sock.sendall(GdbRemoteTestCaseBase._GDBREMOTE_KILL_PACKET) except: - logger.warning("failed to send kill packet to debug monitor: {}; ignoring".format(sys.exc_info()[0])) + logger.warning( + "failed to send kill packet to debug monitor: {}; ignoring".format( + sys.exc_info()[0])) try: sock.close() except: - logger.warning("failed to close socket to debug monitor: {}; ignoring".format(sys.exc_info()[0])) + logger.warning( + "failed to close socket to debug monitor: {}; ignoring".format( + sys.exc_info()[0])) self.addTearDownHook(shutdown_socket) @@ -319,9 +365,11 @@ class GdbRemoteTestCaseBase(TestBase): def get_debug_monitor_command_line_args(self, attach_pid=None): if lldb.remote_platform: - commandline_args = self.debug_monitor_extra_args + ["*:{}".format(self.port)] + commandline_args = self.debug_monitor_extra_args + \ + ["*:{}".format(self.port)] else: - commandline_args = self.debug_monitor_extra_args + ["localhost:{}".format(self.port)] + commandline_args = self.debug_monitor_extra_args + \ + ["localhost:{}".format(self.port)] if attach_pid: commandline_args += ["--attach=%d" % attach_pid] @@ -331,14 +379,19 @@ class GdbRemoteTestCaseBase(TestBase): def launch_debug_monitor(self, attach_pid=None, logfile=None): # Create the command line. - commandline_args = self.get_debug_monitor_command_line_args(attach_pid=attach_pid) + commandline_args = self.get_debug_monitor_command_line_args( + attach_pid=attach_pid) # Start the server. - server = self.spawnSubprocess(self.debug_monitor_exe, commandline_args, install_remote=False) + server = self.spawnSubprocess( + self.debug_monitor_exe, + commandline_args, + install_remote=False) self.addTearDownHook(self.cleanupSubprocesses) self.assertIsNotNone(server) - # If we're receiving the stub's listening port from the named pipe, do that here. + # If we're receiving the stub's listening port from the named pipe, do + # that here. if self.named_pipe: self.port = self.get_stub_port_from_named_socket() @@ -354,7 +407,9 @@ class GdbRemoteTestCaseBase(TestBase): try: server.terminate() except: - logger.warning("failed to terminate server for debug monitor: {}; ignoring".format(sys.exc_info()[0])) + logger.warning( + "failed to terminate server for debug monitor: {}; ignoring".format( + sys.exc_info()[0])) self.addTearDownHook(shutdown_debug_monitor) # Schedule debug monitor to be shut down during teardown. @@ -374,11 +429,14 @@ class GdbRemoteTestCaseBase(TestBase): # Schedule debug monitor to be shut down during teardown. logger = self.logger + def shutdown_debug_monitor(): try: server.terminate() except: - logger.warning("failed to terminate server for debug monitor: {}; ignoring".format(sys.exc_info()[0])) + logger.warning( + "failed to terminate server for debug monitor: {}; ignoring".format( + sys.exc_info()[0])) self.addTearDownHook(shutdown_debug_monitor) connect_attemps = 0 @@ -387,7 +445,7 @@ class GdbRemoteTestCaseBase(TestBase): while connect_attemps < MAX_CONNECT_ATTEMPTS: # Create a socket to talk to the server try: - logger.info("Connect attempt %d", connect_attemps+1) + logger.info("Connect attempt %d", connect_attemps + 1) self.sock = self.create_socket() return server except _ConnectionRefused as serr: @@ -400,18 +458,27 @@ class GdbRemoteTestCaseBase(TestBase): server.terminate() # Increment attempts. - print("connect to debug monitor on port %d failed, attempt #%d of %d" % (self.port, attempts + 1, MAX_ATTEMPTS)) + print( + "connect to debug monitor on port %d failed, attempt #%d of %d" % + (self.port, attempts + 1, MAX_ATTEMPTS)) attempts += 1 - # And wait a random length of time before next attempt, to avoid collisions. - time.sleep(random.randint(1,5)) - + # And wait a random length of time before next attempt, to avoid + # collisions. + time.sleep(random.randint(1, 5)) + # Now grab a new port number. self.port = self.get_next_port() - raise Exception("failed to create a socket to the launched debug monitor after %d tries" % attempts) + raise Exception( + "failed to create a socket to the launched debug monitor after %d tries" % + attempts) - def launch_process_for_attach(self, inferior_args=None, sleep_seconds=3, exe_path=None): + def launch_process_for_attach( + self, + inferior_args=None, + sleep_seconds=3, + exe_path=None): # We're going to start a child process that the debug monitor stub can later attach to. # This process needs to be started so that it just hangs around for a while. We'll # have it sleep. @@ -425,15 +492,22 @@ class GdbRemoteTestCaseBase(TestBase): args.append("sleep:%d" % sleep_seconds) inferior = self.spawnSubprocess(exe_path, args) + def shutdown_process_for_attach(): try: inferior.terminate() except: - logger.warning("failed to terminate inferior process for attach: {}; ignoring".format(sys.exc_info()[0])) + logger.warning( + "failed to terminate inferior process for attach: {}; ignoring".format( + sys.exc_info()[0])) self.addTearDownHook(shutdown_process_for_attach) return inferior - def prep_debug_monitor_and_inferior(self, inferior_args=None, inferior_sleep_seconds=3, inferior_exe_path=None): + def prep_debug_monitor_and_inferior( + self, + inferior_args=None, + inferior_sleep_seconds=3, + inferior_exe_path=None): """Prep the debug monitor, the inferior, and the expected packet stream. Handle the separate cases of using the debug monitor in attach-to-inferior mode @@ -458,11 +532,15 @@ class GdbRemoteTestCaseBase(TestBase): if self._inferior_startup == self._STARTUP_ATTACH or self._inferior_startup == self._STARTUP_ATTACH_MANUALLY: # Launch the process that we'll use as the inferior. - inferior = self.launch_process_for_attach(inferior_args=inferior_args, sleep_seconds=inferior_sleep_seconds, exe_path=inferior_exe_path) + inferior = self.launch_process_for_attach( + inferior_args=inferior_args, + sleep_seconds=inferior_sleep_seconds, + exe_path=inferior_exe_path) self.assertIsNotNone(inferior) self.assertTrue(inferior.pid > 0) if self._inferior_startup == self._STARTUP_ATTACH: - # In this case, we want the stub to attach via the command line, so set the command line attach pid here. + # In this case, we want the stub to attach via the command + # line, so set the command line attach pid here. attach_pid = inferior.pid if self._inferior_startup == self._STARTUP_LAUNCH: @@ -471,11 +549,15 @@ class GdbRemoteTestCaseBase(TestBase): inferior_exe_path = os.path.abspath("a.out") if lldb.remote_platform: - remote_path = lldbutil.append_to_process_working_directory(os.path.basename(inferior_exe_path)) + remote_path = lldbutil.append_to_process_working_directory( + os.path.basename(inferior_exe_path)) remote_file_spec = lldb.SBFileSpec(remote_path, False) - err = lldb.remote_platform.Install(lldb.SBFileSpec(inferior_exe_path, True), remote_file_spec) + err = lldb.remote_platform.Install(lldb.SBFileSpec( + inferior_exe_path, True), remote_file_spec) if err.Fail(): - raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (inferior_exe_path, remote_path, err)) + raise Exception( + "remote_platform.Install('%s', '%s') failed: %s" % + (inferior_exe_path, remote_path, err)) inferior_exe_path = remote_path launch_args = [inferior_exe_path] @@ -491,13 +573,18 @@ class GdbRemoteTestCaseBase(TestBase): if self._inferior_startup == self._STARTUP_LAUNCH: self.add_verified_launch_packets(launch_args) - return {"inferior":inferior, "server":server} + return {"inferior": inferior, "server": server} - def expect_socket_recv(self, sock, expected_content_regex, timeout_seconds): + def expect_socket_recv( + self, + sock, + expected_content_regex, + timeout_seconds): response = "" timeout_time = time.time() + timeout_seconds - while not expected_content_regex.match(response) and time.time() < timeout_time: + while not expected_content_regex.match( + response) and time.time() < timeout_time: can_read, _, _ = select.select([sock], [], [], timeout_seconds) if can_read and sock in can_read: recv_bytes = sock.recv(4096) @@ -514,7 +601,8 @@ class GdbRemoteTestCaseBase(TestBase): _, can_write, _ = select.select([], [sock], [], timeout_seconds) if can_write and sock in can_write: written_byte_count = sock.send(request_bytes_remaining) - request_bytes_remaining = request_bytes_remaining[written_byte_count:] + request_bytes_remaining = request_bytes_remaining[ + written_byte_count:] self.assertEqual(len(request_bytes_remaining), 0) def do_handshake(self, stub_socket, timeout_seconds=5): @@ -527,7 +615,8 @@ class GdbRemoteTestCaseBase(TestBase): self.assertEqual(bytes_sent, len(NO_ACK_MODE_REQUEST)) # Receive the ack and "OK" - self.expect_socket_recv(stub_socket, re.compile(r"^\+\$OK#[0-9a-fA-F]{2}$"), timeout_seconds) + self.expect_socket_recv(stub_socket, re.compile( + r"^\+\$OK#[0-9a-fA-F]{2}$"), timeout_seconds) # Send the final ack. self.expect_socket_send(stub_socket, "+", timeout_seconds) @@ -553,12 +642,12 @@ class GdbRemoteTestCaseBase(TestBase): self.test_sequence.add_log_lines( ["read packet: $QThreadSuffixSupported#e4", "send packet: $OK#00", - ], True) + ], True) def add_process_info_collection_packets(self): self.test_sequence.add_log_lines( ["read packet: $qProcessInfo#dc", - { "direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"process_info_raw"} }], + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "process_info_raw"}}], True) _KNOWN_PROCESS_INFO_KEYS = [ @@ -575,7 +664,7 @@ class GdbRemoteTestCaseBase(TestBase): "vendor", "endian", "ptrsize" - ] + ] def parse_process_info_response(self, context): # Ensure we have a process info response. @@ -584,7 +673,9 @@ class GdbRemoteTestCaseBase(TestBase): self.assertIsNotNone(process_info_raw) # Pull out key:value; pairs. - process_info_dict = { match.group(1):match.group(2) for match in re.finditer(r"([^:]+):([^;]+);", process_info_raw) } + process_info_dict = { + match.group(1): match.group(2) for match in re.finditer( + r"([^:]+):([^;]+);", process_info_raw)} # Validate keys are known. for (key, val) in list(process_info_dict.items()): @@ -595,9 +686,9 @@ class GdbRemoteTestCaseBase(TestBase): def add_register_info_collection_packets(self): self.test_sequence.add_log_lines( - [ { "type":"multi_response", "query":"qRegisterInfo", "append_iteration_suffix":True, - "end_regex":re.compile(r"^\$(E\d+)?#[0-9a-fA-F]{2}$"), - "save_key":"reg_info_responses" } ], + [{"type": "multi_response", "query": "qRegisterInfo", "append_iteration_suffix": True, + "end_regex": re.compile(r"^\$(E\d+)?#[0-9a-fA-F]{2}$"), + "save_key": "reg_info_responses"}], True) def parse_register_info_packets(self, context): @@ -606,13 +697,19 @@ class GdbRemoteTestCaseBase(TestBase): self.assertIsNotNone(reg_info_responses) # Parse register infos. - return [parse_reg_info_response(reg_info_response) for reg_info_response in reg_info_responses] + return [parse_reg_info_response(reg_info_response) + for reg_info_response in reg_info_responses] def expect_gdbremote_sequence(self, timeout_seconds=None): if not timeout_seconds: timeout_seconds = self._TIMEOUT_SECONDS - return expect_lldb_gdbserver_replay(self, self.sock, self.test_sequence, - self._pump_queues, timeout_seconds, self.logger) + return expect_lldb_gdbserver_replay( + self, + self.sock, + self.test_sequence, + self._pump_queues, + timeout_seconds, + self.logger) _KNOWN_REGINFO_KEYS = [ "name", @@ -667,7 +764,7 @@ class GdbRemoteTestCaseBase(TestBase): def add_query_memory_region_packets(self, address): self.test_sequence.add_log_lines( ["read packet: $qMemoryRegionInfo:{0:x}#00".format(address), - {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"memory_region_response"} }], + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "memory_region_response"}}], True) def parse_key_val_dict(self, key_val_text, allow_dupes=True): @@ -678,13 +775,15 @@ class GdbRemoteTestCaseBase(TestBase): val = match.group(2) if key in kv_dict: if allow_dupes: - if type(kv_dict[key]) == list: + if isinstance(kv_dict[key], list): kv_dict[key].append(val) else: # Promote to list kv_dict[key] = [kv_dict[key], val] else: - self.fail("key '{}' already present when attempting to add value '{}' (text='{}', dict={})".format(key, val, key_val_text, kv_dict)) + self.fail( + "key '{}' already present when attempting to add value '{}' (text='{}', dict={})".format( + key, val, key_val_text, kv_dict)) else: kv_dict[key] = val return kv_dict @@ -694,17 +793,25 @@ class GdbRemoteTestCaseBase(TestBase): self.assertIsNotNone(context.get("memory_region_response")) # Pull out key:value; pairs. - mem_region_dict = self.parse_key_val_dict(context.get("memory_region_response")) + mem_region_dict = self.parse_key_val_dict( + context.get("memory_region_response")) # Validate keys are known. for (key, val) in list(mem_region_dict.items()): - self.assertTrue(key in ["start", "size", "permissions", "name", "error"]) + self.assertTrue( + key in [ + "start", + "size", + "permissions", + "name", + "error"]) self.assertIsNotNone(val) # Return the dictionary of key-value pairs for the memory region. return mem_region_dict - def assert_address_within_memory_region(self, test_address, mem_region_dict): + def assert_address_within_memory_region( + self, test_address, mem_region_dict): self.assertIsNotNone(mem_region_dict) self.assertTrue("start" in mem_region_dict) self.assertTrue("size" in mem_region_dict) @@ -714,15 +821,25 @@ class GdbRemoteTestCaseBase(TestBase): range_end = range_start + range_size if test_address < range_start: - self.fail("address 0x{0:x} comes before range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format(test_address, range_start, range_end, range_size)) + self.fail( + "address 0x{0:x} comes before range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( + test_address, + range_start, + range_end, + range_size)) elif test_address >= range_end: - self.fail("address 0x{0:x} comes after range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format(test_address, range_start, range_end, range_size)) + self.fail( + "address 0x{0:x} comes after range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( + test_address, + range_start, + range_end, + range_size)) def add_threadinfo_collection_packets(self): self.test_sequence.add_log_lines( - [ { "type":"multi_response", "first_query":"qfThreadInfo", "next_query":"qsThreadInfo", - "append_iteration_suffix":False, "end_regex":re.compile(r"^\$(l)?#[0-9a-fA-F]{2}$"), - "save_key":"threadinfo_responses" } ], + [{"type": "multi_response", "first_query": "qfThreadInfo", "next_query": "qsThreadInfo", + "append_iteration_suffix": False, "end_regex": re.compile(r"^\$(l)?#[0-9a-fA-F]{2}$"), + "save_key": "threadinfo_responses"}], True) def parse_threadinfo_packets(self, context): @@ -760,35 +877,44 @@ class GdbRemoteTestCaseBase(TestBase): return threads - def add_set_breakpoint_packets(self, address, do_continue=True, breakpoint_kind=1): + def add_set_breakpoint_packets( + self, + address, + do_continue=True, + breakpoint_kind=1): self.test_sequence.add_log_lines( - [# Set the breakpoint. - "read packet: $Z0,{0:x},{1}#00".format(address, breakpoint_kind), - # Verify the stub could set it. - "send packet: $OK#00", - ], True) + [ # Set the breakpoint. + "read packet: $Z0,{0:x},{1}#00".format( + address, breakpoint_kind), + # Verify the stub could set it. + "send packet: $OK#00", + ], True) if (do_continue): self.test_sequence.add_log_lines( - [# Continue the inferior. - "read packet: $c#63", - # Expect a breakpoint stop report. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }, - ], True) + [ # Continue the inferior. + "read packet: $c#63", + # Expect a breakpoint stop report. + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "stop_signo", + 2: "stop_thread_id"}}, + ], True) def add_remove_breakpoint_packets(self, address, breakpoint_kind=1): self.test_sequence.add_log_lines( - [# Remove the breakpoint. - "read packet: $z0,{0:x},{1}#00".format(address, breakpoint_kind), - # Verify the stub could unset it. - "send packet: $OK#00", + [ # Remove the breakpoint. + "read packet: $z0,{0:x},{1}#00".format( + address, breakpoint_kind), + # Verify the stub could unset it. + "send packet: $OK#00", ], True) def add_qSupported_packets(self): self.test_sequence.add_log_lines( ["read packet: $qSupported#00", - {"direction":"send", "regex":r"^\$(.*)#[0-9a-fA-F]{2}", "capture":{1: "qSupported_response"}}, - ], True) + {"direction": "send", "regex": r"^\$(.*)#[0-9a-fA-F]{2}", "capture": {1: "qSupported_response"}}, + ], True) _KNOWN_QSUPPORTED_STUB_FEATURES = [ "augmented-libraries-svr4-read", @@ -821,23 +947,27 @@ class GdbRemoteTestCaseBase(TestBase): supported_dict[key] = val else: if len(key) < 2: - raise Exception("singular stub feature is too short: must be stub_feature{+,-,?}") + raise Exception( + "singular stub feature is too short: must be stub_feature{+,-,?}") supported_type = key[-1] key = key[:-1] if not supported_type in ["+", "-", "?"]: - raise Exception("malformed stub feature: final character {} not in expected set (+,-,?)".format(supported_type)) - supported_dict[key] = supported_type + raise Exception( + "malformed stub feature: final character {} not in expected set (+,-,?)".format(supported_type)) + supported_dict[key] = supported_type # Ensure we know the supported element - if not key in self._KNOWN_QSUPPORTED_STUB_FEATURES: - raise Exception("unknown qSupported stub feature reported: %s" % key) + if key not in self._KNOWN_QSUPPORTED_STUB_FEATURES: + raise Exception( + "unknown qSupported stub feature reported: %s" % + key) return supported_dict def run_process_then_stop(self, run_seconds=1): # Tell the stub to continue. self.test_sequence.add_log_lines( - ["read packet: $vCont;c#a8"], - True) + ["read packet: $vCont;c#a8"], + True) context = self.expect_gdbremote_sequence() # Wait for run_seconds. @@ -847,7 +977,7 @@ class GdbRemoteTestCaseBase(TestBase): self.reset_test_sequence() self.test_sequence.add_log_lines( ["read packet: {}".format(chr(3)), - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result"} }], + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture": {1: "stop_result"}}], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -857,18 +987,21 @@ class GdbRemoteTestCaseBase(TestBase): def select_modifiable_register(self, reg_infos): """Find a register that can be read/written freely.""" - PREFERRED_REGISTER_NAMES = set(["rax",]) + PREFERRED_REGISTER_NAMES = set(["rax", ]) - # First check for the first register from the preferred register name set. + # First check for the first register from the preferred register name + # set. alternative_register_index = None self.assertIsNotNone(reg_infos) for reg_info in reg_infos: - if ("name" in reg_info) and (reg_info["name"] in PREFERRED_REGISTER_NAMES): + if ("name" in reg_info) and ( + reg_info["name"] in PREFERRED_REGISTER_NAMES): # We found a preferred register. Use it. return reg_info["lldb_register_index"] if ("generic" in reg_info) and (reg_info["generic"] == "fp"): - # A frame pointer register will do as a register to modify temporarily. + # A frame pointer register will do as a register to modify + # temporarily. alternative_register_index = reg_info["lldb_register_index"] # We didn't find a preferred register. Return whatever alternative register @@ -901,7 +1034,8 @@ class GdbRemoteTestCaseBase(TestBase): def find_generic_register_with_name(self, reg_infos, generic_name): self.assertIsNotNone(reg_infos) for reg_info in reg_infos: - if ("generic" in reg_info) and (reg_info["generic"] == generic_name): + if ("generic" in reg_info) and ( + reg_info["generic"] == generic_name): return reg_info return None @@ -912,13 +1046,13 @@ class GdbRemoteTestCaseBase(TestBase): if encoded_bytes[i] == "}": # Handle escaped char. self.assertTrue(i + 1 < len(encoded_bytes)) - decoded_bytes += chr(ord(encoded_bytes[i+1]) ^ 0x20) - i +=2 + decoded_bytes += chr(ord(encoded_bytes[i + 1]) ^ 0x20) + i += 2 elif encoded_bytes[i] == "*": # Handle run length encoding. self.assertTrue(len(decoded_bytes) > 0) self.assertTrue(i + 1 < len(encoded_bytes)) - repeat_count = ord(encoded_bytes[i+1]) - 29 + repeat_count = ord(encoded_bytes[i + 1]) - 29 decoded_bytes += decoded_bytes[-1] * repeat_count i += 2 else: @@ -955,7 +1089,8 @@ class GdbRemoteTestCaseBase(TestBase): self.assertFalse(key in auxv_dict) auxv_dict[key] = value - self.fail("should not reach here - implies required double zero entry not found") + self.fail( + "should not reach here - implies required double zero entry not found") return auxv_dict def read_binary_data_in_chunks(self, command_prefix, chunk_length): @@ -967,10 +1102,21 @@ class GdbRemoteTestCaseBase(TestBase): while not done: # Grab the next iteration of data. self.reset_test_sequence() - self.test_sequence.add_log_lines([ - "read packet: ${}{:x},{:x}:#00".format(command_prefix, offset, chunk_length), - {"direction":"send", "regex":re.compile(r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", re.MULTILINE|re.DOTALL), "capture":{1:"response_type", 2:"content_raw"} } - ], True) + self.test_sequence.add_log_lines( + [ + "read packet: ${}{:x},{:x}:#00".format( + command_prefix, + offset, + chunk_length), + { + "direction": "send", + "regex": re.compile( + r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", + re.MULTILINE | re.DOTALL), + "capture": { + 1: "response_type", + 2: "content_raw"}}], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -997,25 +1143,32 @@ class GdbRemoteTestCaseBase(TestBase): # Send the intterupt. "read packet: {}".format(chr(3)), # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", "capture":{1:"stop_signo", 2:"stop_key_val_text" } }, - ], True) + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_signo", + 2: "stop_key_val_text"}}, + ], True) def parse_interrupt_packets(self, context): self.assertIsNotNone(context.get("stop_signo")) self.assertIsNotNone(context.get("stop_key_val_text")) - return (int(context["stop_signo"], 16), self.parse_key_val_dict(context["stop_key_val_text"])) + return (int(context["stop_signo"], 16), self.parse_key_val_dict( + context["stop_key_val_text"])) def add_QSaveRegisterState_packets(self, thread_id): if thread_id: # Use the thread suffix form. - request = "read packet: $QSaveRegisterState;thread:{:x}#00".format(thread_id) + request = "read packet: $QSaveRegisterState;thread:{:x}#00".format( + thread_id) else: request = "read packet: $QSaveRegisterState#00" - - self.test_sequence.add_log_lines([ - request, - {"direction":"send", "regex":r"^\$(E?.*)#[0-9a-fA-F]{2}$", "capture":{1:"save_response" } }, - ], True) + + self.test_sequence.add_log_lines([request, + {"direction": "send", + "regex": r"^\$(E?.*)#[0-9a-fA-F]{2}$", + "capture": {1: "save_response"}}, + ], + True) def parse_QSaveRegisterState_response(self, context): self.assertIsNotNone(context) @@ -1032,16 +1185,19 @@ class GdbRemoteTestCaseBase(TestBase): def add_QRestoreRegisterState_packets(self, save_id, thread_id=None): if thread_id: # Use the thread suffix form. - request = "read packet: $QRestoreRegisterState:{};thread:{:x}#00".format(save_id, thread_id) + request = "read packet: $QRestoreRegisterState:{};thread:{:x}#00".format( + save_id, thread_id) else: - request = "read packet: $QRestoreRegisterState:{}#00".format(save_id) + request = "read packet: $QRestoreRegisterState:{}#00".format( + save_id) self.test_sequence.add_log_lines([ request, "send packet: $OK#00" - ], True) + ], True) - def flip_all_bits_in_each_register_value(self, reg_infos, endian, thread_id=None): + def flip_all_bits_in_each_register_value( + self, reg_infos, endian, thread_id=None): self.assertIsNotNone(reg_infos) successful_writes = 0 @@ -1049,16 +1205,18 @@ class GdbRemoteTestCaseBase(TestBase): for reg_info in reg_infos: # Use the lldb register index added to the reg info. We're not necessarily - # working off a full set of register infos, so an inferred register index could be wrong. + # working off a full set of register infos, so an inferred register + # index could be wrong. reg_index = reg_info["lldb_register_index"] self.assertIsNotNone(reg_index) - reg_byte_size = int(reg_info["bitsize"])/8 + reg_byte_size = int(reg_info["bitsize"]) / 8 self.assertTrue(reg_byte_size > 0) # Handle thread suffix. if thread_id: - p_request = "read packet: $p{:x};thread:{:x}#00".format(reg_index, thread_id) + p_request = "read packet: $p{:x};thread:{:x}#00".format( + reg_index, thread_id) else: p_request = "read packet: $p{:x}#00".format(reg_index) @@ -1066,15 +1224,16 @@ class GdbRemoteTestCaseBase(TestBase): self.reset_test_sequence() self.test_sequence.add_log_lines([ p_request, - { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }, - ], True) + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Verify the response length. p_response = context.get("p_response") self.assertIsNotNone(p_response) - initial_reg_value = unpack_register_hex_unsigned(endian, p_response) + initial_reg_value = unpack_register_hex_unsigned( + endian, p_response) # Flip the value by xoring with all 1s all_one_bits_raw = "ff" * (int(reg_info["bitsize"]) / 8) @@ -1083,16 +1242,22 @@ class GdbRemoteTestCaseBase(TestBase): # Handle thread suffix for P. if thread_id: - P_request = "read packet: $P{:x}={};thread:{:x}#00".format(reg_index, pack_register_hex(endian, flipped_bits_int, byte_size=reg_byte_size), thread_id) + P_request = "read packet: $P{:x}={};thread:{:x}#00".format( + reg_index, pack_register_hex( + endian, flipped_bits_int, byte_size=reg_byte_size), thread_id) else: - P_request = "read packet: $P{:x}={}#00".format(reg_index, pack_register_hex(endian, flipped_bits_int, byte_size=reg_byte_size)) + P_request = "read packet: $P{:x}={}#00".format( + reg_index, pack_register_hex( + endian, flipped_bits_int, byte_size=reg_byte_size)) # Write the flipped value to the register. self.reset_test_sequence() - self.test_sequence.add_log_lines([ - P_request, - { "direction":"send", "regex":r"^\$(OK|E[0-9a-fA-F]+)#[0-9a-fA-F]{2}", "capture":{1:"P_response"} }, - ], True) + self.test_sequence.add_log_lines([P_request, + {"direction": "send", + "regex": r"^\$(OK|E[0-9a-fA-F]+)#[0-9a-fA-F]{2}", + "capture": {1: "P_response"}}, + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1107,25 +1272,27 @@ class GdbRemoteTestCaseBase(TestBase): failed_writes += 1 # print("reg (index={}, name={}) write FAILED (error: {})".format(reg_index, reg_info["name"], P_response)) - # Read back the register value, ensure it matches the flipped value. + # Read back the register value, ensure it matches the flipped + # value. if P_response == "OK": self.reset_test_sequence() self.test_sequence.add_log_lines([ p_request, - { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }, - ], True) + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) verify_p_response_raw = context.get("p_response") self.assertIsNotNone(verify_p_response_raw) - verify_bits = unpack_register_hex_unsigned(endian, verify_p_response_raw) + verify_bits = unpack_register_hex_unsigned( + endian, verify_p_response_raw) if verify_bits != flipped_bits_int: # Some registers, like mxcsrmask and others, will permute what's written. Adjust succeed/fail counts. # print("reg (index={}, name={}): read verify FAILED: wrote {:x}, verify read back {:x}".format(reg_index, reg_info["name"], flipped_bits_int, verify_bits)) successful_writes -= 1 - failed_writes +=1 + failed_writes += 1 return (successful_writes, failed_writes) @@ -1136,7 +1303,8 @@ class GdbRemoteTestCaseBase(TestBase): return False if reg_info["set"] != "General Purpose Registers": return False - if ("container-regs" in reg_info) and (len(reg_info["container-regs"]) > 0): + if ("container-regs" in reg_info) and ( + len(reg_info["container-regs"]) > 0): # Don't try to bit flip registers contained in another register. return False if re.match("^.s$", reg_info["name"]): @@ -1154,13 +1322,15 @@ class GdbRemoteTestCaseBase(TestBase): values = {} for reg_info in reg_infos: - # We append a register index when load reg infos so we can work with subsets. + # We append a register index when load reg infos so we can work + # with subsets. reg_index = reg_info.get("lldb_register_index") self.assertIsNotNone(reg_index) # Handle thread suffix. if thread_id: - p_request = "read packet: $p{:x};thread:{:x}#00".format(reg_index, thread_id) + p_request = "read packet: $p{:x};thread:{:x}#00".format( + reg_index, thread_id) else: p_request = "read packet: $p{:x}#00".format(reg_index) @@ -1168,8 +1338,8 @@ class GdbRemoteTestCaseBase(TestBase): self.reset_test_sequence() self.test_sequence.add_log_lines([ p_request, - { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }, - ], True) + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1178,58 +1348,75 @@ class GdbRemoteTestCaseBase(TestBase): self.assertIsNotNone(p_response) self.assertTrue(len(p_response) > 0) self.assertFalse(p_response[0] == "E") - - values[reg_index] = unpack_register_hex_unsigned(endian, p_response) - + + values[reg_index] = unpack_register_hex_unsigned( + endian, p_response) + return values def add_vCont_query_packets(self): - self.test_sequence.add_log_lines([ - "read packet: $vCont?#49", - {"direction":"send", "regex":r"^\$(vCont)?(.*)#[0-9a-fA-F]{2}$", "capture":{2:"vCont_query_response" } }, - ], True) + self.test_sequence.add_log_lines(["read packet: $vCont?#49", + {"direction": "send", + "regex": r"^\$(vCont)?(.*)#[0-9a-fA-F]{2}$", + "capture": {2: "vCont_query_response"}}, + ], + True) def parse_vCont_query_response(self, context): self.assertIsNotNone(context) vCont_query_response = context.get("vCont_query_response") - # Handle case of no vCont support at all - in which case the capture group will be none or zero length. + # Handle case of no vCont support at all - in which case the capture + # group will be none or zero length. if not vCont_query_response or len(vCont_query_response) == 0: return {} - return {key:1 for key in vCont_query_response.split(";") if key and len(key) > 0} - - def count_single_steps_until_true(self, thread_id, predicate, args, max_step_count=100, use_Hc_packet=True, step_instruction="s"): + return {key: 1 for key in vCont_query_response.split( + ";") if key and len(key) > 0} + + def count_single_steps_until_true( + self, + thread_id, + predicate, + args, + max_step_count=100, + use_Hc_packet=True, + step_instruction="s"): """Used by single step test that appears in a few different contexts.""" single_step_count = 0 while single_step_count < max_step_count: self.assertIsNotNone(thread_id) - # Build the packet for the single step instruction. We replace {thread}, if present, with the thread_id. - step_packet = "read packet: ${}#00".format(re.sub(r"{thread}", "{:x}".format(thread_id), step_instruction)) + # Build the packet for the single step instruction. We replace + # {thread}, if present, with the thread_id. + step_packet = "read packet: ${}#00".format( + re.sub(r"{thread}", "{:x}".format(thread_id), step_instruction)) # print("\nstep_packet created: {}\n".format(step_packet)) # Single step. self.reset_test_sequence() if use_Hc_packet: self.test_sequence.add_log_lines( - [# Set the continue thread. - "read packet: $Hc{0:x}#00".format(thread_id), - "send packet: $OK#00", - ], True) + [ # Set the continue thread. + "read packet: $Hc{0:x}#00".format(thread_id), + "send packet: $OK#00", + ], True) self.test_sequence.add_log_lines([ - # Single step. - step_packet, - # "read packet: $vCont;s:{0:x}#00".format(thread_id), - # Expect a breakpoint stop report. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }, - ], True) + # Single step. + step_packet, + # "read packet: $vCont;s:{0:x}#00".format(thread_id), + # Expect a breakpoint stop report. + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "stop_signo", + 2: "stop_thread_id"}}, + ], True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) self.assertIsNotNone(context.get("stop_signo")) self.assertEqual(int(context.get("stop_signo"), 16), - lldbutil.get_signal_number('SIGTRAP')) + lldbutil.get_signal_number('SIGTRAP')) single_step_count += 1 @@ -1251,9 +1438,9 @@ class GdbRemoteTestCaseBase(TestBase): self.reset_test_sequence() self.test_sequence.add_log_lines( ["read packet: $m{0:x},{1:x}#00".format(g_c1_address, 1), - {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"g_c1_contents"} }, + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "g_c1_contents"}}, "read packet: $m{0:x},{1:x}#00".format(g_c2_address, 1), - {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"g_c2_contents"} }], + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "g_c2_contents"}}], True) # Run the packet stream. @@ -1264,26 +1451,34 @@ class GdbRemoteTestCaseBase(TestBase): self.assertIsNotNone(context.get("g_c1_contents")) self.assertIsNotNone(context.get("g_c2_contents")) - return (context.get("g_c1_contents").decode("hex") == expected_g_c1) and (context.get("g_c2_contents").decode("hex") == expected_g_c2) + return (context.get("g_c1_contents").decode("hex") == expected_g_c1) and ( + context.get("g_c2_contents").decode("hex") == expected_g_c2) - def single_step_only_steps_one_instruction(self, use_Hc_packet=True, step_instruction="s"): + def single_step_only_steps_one_instruction( + self, use_Hc_packet=True, step_instruction="s"): """Used by single step test that appears in a few different contexts.""" # Start up the inferior. procs = self.prep_debug_monitor_and_inferior( - inferior_args=["get-code-address-hex:swap_chars", "get-data-address-hex:g_c1", "get-data-address-hex:g_c2", "sleep:1", "call-function:swap_chars", "sleep:5"]) + inferior_args=[ + "get-code-address-hex:swap_chars", + "get-data-address-hex:g_c1", + "get-data-address-hex:g_c2", + "sleep:1", + "call-function:swap_chars", + "sleep:5"]) # Run the process self.test_sequence.add_log_lines( - [# Start running after initial stop. - "read packet: $c#63", - # Match output line that prints the memory address of the function call entry point. - # Note we require launch-only testing so we can get inferior otuput. - { "type":"output_match", "regex":r"^code address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\n$", - "capture":{ 1:"function_address", 2:"g_c1_address", 3:"g_c2_address"} }, - # Now stop the inferior. - "read packet: {}".format(chr(3)), - # And wait for the stop notification. - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }], + [ # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the function call entry point. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": r"^code address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\n$", + "capture": {1: "function_address", 2: "g_c1_address", 3: "g_c2_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], True) # Run the packet stream. @@ -1312,13 +1507,17 @@ class GdbRemoteTestCaseBase(TestBase): else: BREAKPOINT_KIND = 1 self.reset_test_sequence() - self.add_set_breakpoint_packets(function_address, do_continue=True, breakpoint_kind=BREAKPOINT_KIND) + self.add_set_breakpoint_packets( + function_address, + do_continue=True, + breakpoint_kind=BREAKPOINT_KIND) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) # Remove the breakpoint. self.reset_test_sequence() - self.add_remove_breakpoint_packets(function_address, breakpoint_kind=BREAKPOINT_KIND) + self.add_remove_breakpoint_packets( + function_address, breakpoint_kind=BREAKPOINT_KIND) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -1331,44 +1530,72 @@ class GdbRemoteTestCaseBase(TestBase): self.assertTrue(self.g_c1_c2_contents_are(args)) - # Verify we take only a small number of steps to hit the first state. Might need to work through function entry prologue code. + # Verify we take only a small number of steps to hit the first state. + # Might need to work through function entry prologue code. args["expected_g_c1"] = "1" args["expected_g_c2"] = "1" - (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=25, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction) + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=25, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) self.assertTrue(state_reached) # Verify we hit the next state. args["expected_g_c1"] = "1" args["expected_g_c2"] = "0" - (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=5, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction) + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) self.assertTrue(state_reached) expected_step_count = 1 arch = self.getArchitecture() - #MIPS required "3" (ADDIU, SB, LD) machine instructions for updation of variable value - if re.match("mips",arch): - expected_step_count = 3 - #S390X requires "2" (LARL, MVI) machine instructions for updation of variable value - if re.match("s390x",arch): - expected_step_count = 2 + # MIPS required "3" (ADDIU, SB, LD) machine instructions for updation + # of variable value + if re.match("mips", arch): + expected_step_count = 3 + # S390X requires "2" (LARL, MVI) machine instructions for updation of + # variable value + if re.match("s390x", arch): + expected_step_count = 2 self.assertEqual(step_count, expected_step_count) # Verify we hit the next state. args["expected_g_c1"] = "0" args["expected_g_c2"] = "0" - (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=5, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction) + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) self.assertTrue(state_reached) self.assertEqual(step_count, expected_step_count) # Verify we hit the next state. args["expected_g_c1"] = "0" args["expected_g_c2"] = "1" - (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=5, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction) + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) self.assertTrue(state_reached) self.assertEqual(step_count, expected_step_count) def maybe_strict_output_regex(self, regex): - return '.*'+regex+'.*' if lldbplatformutil.hasChattyStderr(self) else '^'+regex+'$' + return '.*' + regex + \ + '.*' if lldbplatformutil.hasChattyStderr(self) else '^' + regex + '$' def install_and_create_launch_args(self): exe_path = os.path.abspath('a.out') diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py index 8bd00a3f1b2..b417b3292e7 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py @@ -1,13 +1,13 @@ from __future__ import print_function - import gdbremote_testcase import signal from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteAbort(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -15,10 +15,12 @@ class TestGdbRemoteAbort(gdbremote_testcase.GdbRemoteTestCaseBase): procs = self.prep_debug_monitor_and_inferior(inferior_args=["abort"]) self.assertIsNotNone(procs) - self.test_sequence.add_log_lines([ - "read packet: $vCont;c#a8", - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", "capture":{ 1:"hex_exit_code"} }, - ], True) + self.test_sequence.add_log_lines(["read packet: $vCont;c#a8", + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", + "capture": {1: "hex_exit_code"}}, + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) @@ -26,7 +28,7 @@ class TestGdbRemoteAbort(gdbremote_testcase.GdbRemoteTestCaseBase): hex_exit_code = context.get("hex_exit_code") self.assertIsNotNone(hex_exit_code) self.assertEqual(int(hex_exit_code, 16), - lldbutil.get_signal_number('SIGABRT')) + lldbutil.get_signal_number('SIGABRT')) @debugserver_test def test_inferior_abort_received_debugserver(self): @@ -41,4 +43,3 @@ class TestGdbRemoteAbort(gdbremote_testcase.GdbRemoteTestCaseBase): self.init_llgs_test() self.build() self.inferior_abort_received() - diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py index 949b00b0f61..5bbca3c146d 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py @@ -1,26 +1,29 @@ from __future__ import print_function - import gdbremote_testcase import signal from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestGdbRemoteSegFault(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) GDB_REMOTE_STOP_CODE_BAD_ACCESS = 0x91 def inferior_seg_fault_received(self, expected_signo): - procs = self.prep_debug_monitor_and_inferior(inferior_args=["segfault"]) + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["segfault"]) self.assertIsNotNone(procs) - self.test_sequence.add_log_lines([ - "read packet: $vCont;c#a8", - {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", "capture":{ 1:"hex_exit_code"} }, - ], True) + self.test_sequence.add_log_lines(["read packet: $vCont;c#a8", + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", + "capture": {1: "hex_exit_code"}}, + ], + True) context = self.expect_gdbremote_sequence() self.assertIsNotNone(context) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py index 0c73bed9ea0..c89cd301899 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py @@ -4,7 +4,6 @@ from __future__ import print_function - import os import os.path import platform @@ -17,6 +16,7 @@ from lldbsuite.test.lldbtest import * from six.moves import queue + def _get_debug_monitor_from_lldb(lldb_exe, debug_monitor_basename): """Return the debug monitor exe path given the lldb exe path. @@ -55,7 +55,10 @@ def _get_debug_monitor_from_lldb(lldb_exe, debug_monitor_basename): if os.path.exists(debug_monitor_exe): return debug_monitor_exe - new_base = regex.sub( 'LLDB.framework/Versions/A/Resources/' + debug_monitor_basename, exe_base) + new_base = regex.sub( + 'LLDB.framework/Versions/A/Resources/' + + debug_monitor_basename, + exe_base) debug_monitor_exe = os.path.join(exe_dir, new_base) if os.path.exists(debug_monitor_exe): return debug_monitor_exe @@ -73,7 +76,9 @@ def get_lldb_server_exe(): if "LLDB_DEBUGSERVER_PATH" in os.environ: return os.environ["LLDB_DEBUGSERVER_PATH"] - return _get_debug_monitor_from_lldb(lldbtest_config.lldbExec, "lldb-server") + return _get_debug_monitor_from_lldb( + lldbtest_config.lldbExec, "lldb-server") + def get_debugserver_exe(): """Return the debugserver exe path. @@ -85,10 +90,11 @@ def get_debugserver_exe(): if "LLDB_DEBUGSERVER_PATH" in os.environ: return os.environ["LLDB_DEBUGSERVER_PATH"] - return _get_debug_monitor_from_lldb(lldbtest_config.lldbExec, "debugserver") + return _get_debug_monitor_from_lldb( + lldbtest_config.lldbExec, "debugserver") _LOG_LINE_REGEX = re.compile(r'^(lldb-server|debugserver)\s+<\s*(\d+)>' + - '\s+(read|send)\s+packet:\s+(.+)$') + '\s+(read|send)\s+packet:\s+(.+)$') def _is_packet_lldb_gdbserver_input(packet_type, llgs_input_is_read): @@ -131,10 +137,12 @@ def handle_O_packet(context, packet_contents, logger): new_text = gdbremote_hex_decode_string(packet_contents[1:]) context["O_content"] += new_text context["O_count"] += 1 - + if logger: - logger.debug("text: new \"{}\", cumulative: \"{}\"".format(new_text, context["O_content"])) - + logger.debug( + "text: new \"{}\", cumulative: \"{}\"".format( + new_text, context["O_content"])) + return True _STRIP_CHECKSUM_REGEX = re.compile(r'#[0-9a-fA-F]{2}$') @@ -150,13 +158,14 @@ def assert_packets_equal(asserter, actual_packet, expected_packet): expected_stripped = _STRIP_CHECKSUM_REGEX.sub('', expected_packet) asserter.assertEqual(actual_stripped, expected_stripped) + def expect_lldb_gdbserver_replay( - asserter, - sock, - test_sequence, - pump_queues, - timeout_seconds, - logger=None): + asserter, + sock, + test_sequence, + pump_queues, + timeout_seconds, + logger=None): """Replay socket communication with lldb-gdbserver and verify responses. Args: @@ -188,16 +197,16 @@ def expect_lldb_gdbserver_replay( context["O_count"] will contain an integer of the number of O packets received. """ - + # Ensure we have some work to do. if len(test_sequence.entries) < 1: return {} - context = {"O_count":0, "O_content":""} + context = {"O_count": 0, "O_content": ""} with socket_packet_pump.SocketPacketPump(sock, pump_queues, logger) as pump: # Grab the first sequence entry. sequence_entry = test_sequence.entries.pop(0) - + # While we have an active sequence entry, send messages # destined for the stub and collect/match/process responses # expected from the stub. @@ -210,10 +219,12 @@ def expect_lldb_gdbserver_replay( packet_desc = "^C" else: packet_desc = send_packet - logger.info("sending packet to remote: {}".format(packet_desc)) + logger.info( + "sending packet to remote: {}".format(packet_desc)) sock.sendall(send_packet) else: - # This is an entry expecting to receive content from the remote debug monitor. + # This is an entry expecting to receive content from the remote + # debug monitor. # We'll pull from (and wait on) the queue appropriate for the type of matcher. # We keep separate queues for process output (coming from non-deterministic @@ -224,51 +235,65 @@ def expect_lldb_gdbserver_replay( content = pump_queues.output_queue().get(True, timeout_seconds) except queue.Empty: if logger: - logger.warning("timeout waiting for stub output (accumulated output:{})".format(pump.get_accumulated_output())) - raise Exception("timed out while waiting for output match (accumulated output: {})".format(pump.get_accumulated_output())) + logger.warning( + "timeout waiting for stub output (accumulated output:{})".format( + pump.get_accumulated_output())) + raise Exception( + "timed out while waiting for output match (accumulated output: {})".format( + pump.get_accumulated_output())) else: try: content = pump_queues.packet_queue().get(True, timeout_seconds) except queue.Empty: if logger: - logger.warning("timeout waiting for packet match (receive buffer: {})".format(pump.get_receive_buffer())) - raise Exception("timed out while waiting for packet match (receive buffer: {})".format(pump.get_receive_buffer())) - + logger.warning( + "timeout waiting for packet match (receive buffer: {})".format( + pump.get_receive_buffer())) + raise Exception( + "timed out while waiting for packet match (receive buffer: {})".format( + pump.get_receive_buffer())) + # Give the sequence entry the opportunity to match the content. # Output matchers might match or pass after more output accumulates. # Other packet types generally must match. asserter.assertIsNotNone(content) - context = sequence_entry.assert_match(asserter, content, context=context) + context = sequence_entry.assert_match( + asserter, content, context=context) # Move on to next sequence entry as needed. Some sequence entries support executing multiple - # times in different states (for looping over query/response packets). + # times in different states (for looping over query/response + # packets). if sequence_entry.is_consumed(): if len(test_sequence.entries) > 0: sequence_entry = test_sequence.entries.pop(0) else: sequence_entry = None - + # Fill in the O_content entries. context["O_count"] = 1 context["O_content"] = pump.get_accumulated_output() - + return context + def gdbremote_hex_encode_string(str): output = '' for c in str: output += '{0:02x}'.format(ord(c)) return output + def gdbremote_hex_decode_string(str): return str.decode("hex") + def gdbremote_packet_encode_string(str): checksum = 0 for c in str: checksum += ord(c) return '$' + str + '#{0:02x}'.format(checksum % 256) + def build_gdbremote_A_packet(args_list): """Given a list of args, create a properly-formed $A packet containing each arg. """ @@ -322,7 +347,9 @@ def parse_threadinfo_response(response_packet): response_packet = _STRIP_CHECKSUM_REGEX.sub("", response_packet) # Return list of thread ids - return [int(thread_id_hex,16) for thread_id_hex in response_packet.split(",") if len(thread_id_hex) > 0] + return [int(thread_id_hex, 16) for thread_id_hex in response_packet.split( + ",") if len(thread_id_hex) > 0] + def unpack_endian_binary_string(endian, value_string): """Unpack a gdb-remote binary (post-unescaped, i.e. not escaped) response to an unsigned int given endianness of the inferior.""" @@ -349,6 +376,7 @@ def unpack_endian_binary_string(endian, value_string): # pdp is valid but need to add parse code once needed. raise Exception("unsupported endian:{}".format(endian)) + def unpack_register_hex_unsigned(endian, value_string): """Unpack a gdb-remote $p-style response to an unsigned int given endianness of inferior.""" if not endian: @@ -370,6 +398,7 @@ def unpack_register_hex_unsigned(endian, value_string): # pdp is valid but need to add parse code once needed. raise Exception("unsupported endian:{}".format(endian)) + def pack_register_hex(endian, value, byte_size=None): """Unpack a gdb-remote $p-style response to an unsigned int given endianness of inferior.""" if not endian: @@ -383,7 +412,7 @@ def pack_register_hex(endian, value, byte_size=None): value = value >> 8 if byte_size: # Add zero-fill to the right/end (MSB side) of the value. - retval += "00" * (byte_size - len(retval)/2) + retval += "00" * (byte_size - len(retval) / 2) return retval elif endian == 'big': @@ -393,20 +422,29 @@ def pack_register_hex(endian, value, byte_size=None): value = value >> 8 if byte_size: # Add zero-fill to the left/front (MSB side) of the value. - retval = ("00" * (byte_size - len(retval)/2)) + retval + retval = ("00" * (byte_size - len(retval) / 2)) + retval return retval else: # pdp is valid but need to add parse code once needed. raise Exception("unsupported endian:{}".format(endian)) + class GdbRemoteEntryBase(object): + def is_output_matcher(self): return False + class GdbRemoteEntry(GdbRemoteEntryBase): - def __init__(self, is_send_to_remote=True, exact_payload=None, regex=None, capture=None, expect_captures=None): + def __init__( + self, + is_send_to_remote=True, + exact_payload=None, + regex=None, + capture=None, + expect_captures=None): """Create an entry representing one piece of the I/O to/from a gdb remote debug monitor. Args: @@ -469,9 +507,11 @@ class GdbRemoteEntry(GdbRemoteEntryBase): def get_send_packet(self): if not self.is_send_to_remote(): - raise Exception("get_send_packet() called on GdbRemoteEntry that is not a send-to-remote packet") + raise Exception( + "get_send_packet() called on GdbRemoteEntry that is not a send-to-remote packet") if not self.exact_payload: - raise Exception("get_send_packet() called on GdbRemoteEntry but it doesn't have an exact payload") + raise Exception( + "get_send_packet() called on GdbRemoteEntry but it doesn't have an exact payload") return self.exact_payload def _assert_exact_payload_match(self, asserter, actual_packet): @@ -482,14 +522,17 @@ class GdbRemoteEntry(GdbRemoteEntryBase): # Ensure the actual packet matches from the start of the actual packet. match = self.regex.match(actual_packet) if not match: - asserter.fail("regex '{}' failed to match against content '{}'".format(self.regex.pattern, actual_packet)) + asserter.fail( + "regex '{}' failed to match against content '{}'".format( + self.regex.pattern, actual_packet)) if self.capture: # Handle captures. for group_index, var_name in list(self.capture.items()): capture_text = match.group(group_index) # It is okay for capture text to be None - which it will be if it is a group that can match nothing. - # The user must be okay with it since the regex itself matched above. + # The user must be okay with it since the regex itself matched + # above. context[var_name] = capture_text if self.expect_captures: @@ -497,7 +540,8 @@ class GdbRemoteEntry(GdbRemoteEntryBase): for group_index, var_name in list(self.expect_captures.items()): capture_text = match.group(group_index) if not capture_text: - raise Exception("No content to expect for group index {}".format(group_index)) + raise Exception( + "No content to expect for group index {}".format(group_index)) asserter.assertEqual(capture_text, context[var_name]) return context @@ -506,7 +550,8 @@ class GdbRemoteEntry(GdbRemoteEntryBase): # This only makes sense for matching lines coming from the # remote debug monitor. if self.is_send_to_remote(): - raise Exception("Attempted to match a packet being sent to the remote debug monitor, doesn't make sense.") + raise Exception( + "Attempted to match a packet being sent to the remote debug monitor, doesn't make sense.") # Create a new context if needed. if not context: @@ -521,16 +566,18 @@ class GdbRemoteEntry(GdbRemoteEntryBase): elif self.regex: return self._assert_regex_match(asserter, actual_packet, context) else: - raise Exception("Don't know how to match a remote-sent packet when exact_payload isn't specified.") + raise Exception( + "Don't know how to match a remote-sent packet when exact_payload isn't specified.") + class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): """Represents a query/response style packet. - + Assumes the first item is sent to the gdb remote. An end sequence regex indicates the end of the query/response packet sequence. All responses up through (but not including) the end response are stored in a context variable. - + Settings accepted from params: next_query or query: required. The typical query packet without the $ prefix or #xx suffix. @@ -557,17 +604,20 @@ class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): assume there is something wrong with either the response collection or the ending detection regex and throw an exception. """ + def __init__(self, params): self._next_query = params.get("next_query", params.get("query")) if not self._next_query: raise "either next_query or query key must be specified for MultiResponseGdbRemoteEntry" - + self._first_query = params.get("first_query", self._next_query) - self._append_iteration_suffix = params.get("append_iteration_suffix", False) + self._append_iteration_suffix = params.get( + "append_iteration_suffix", False) self._iteration = 0 self._end_regex = params["end_regex"] self._save_key = params["save_key"] - self._runaway_response_count = params.get("runaway_response_count", 10000) + self._runaway_response_count = params.get( + "runaway_response_count", 10000) self._is_send_to_remote = True self._end_matched = False @@ -576,9 +626,11 @@ class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): def get_send_packet(self): if not self.is_send_to_remote(): - raise Exception("get_send_packet() called on MultiResponseGdbRemoteEntry that is not in the send state") + raise Exception( + "get_send_packet() called on MultiResponseGdbRemoteEntry that is not in the send state") if self._end_matched: - raise Exception("get_send_packet() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") + raise Exception( + "get_send_packet() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") # Choose the first or next query for the base payload. if self._iteration == 0 and self._first_query: @@ -593,7 +645,8 @@ class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): # Keep track of the iteration. self._iteration += 1 - # Now that we've given the query packet, flip the mode to receive/match. + # Now that we've given the query packet, flip the mode to + # receive/match. self._is_send_to_remote = False # Return the result, converted to packet form. @@ -603,12 +656,15 @@ class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): return self._end_matched def assert_match(self, asserter, actual_packet, context=None): - # This only makes sense for matching lines coming from the remote debug monitor. + # This only makes sense for matching lines coming from the remote debug + # monitor. if self.is_send_to_remote(): - raise Exception("assert_match() called on MultiResponseGdbRemoteEntry but state is set to send a query packet.") + raise Exception( + "assert_match() called on MultiResponseGdbRemoteEntry but state is set to send a query packet.") if self._end_matched: - raise Exception("assert_match() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") + raise Exception( + "assert_match() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") # Set up a context as needed. if not context: @@ -627,21 +683,27 @@ class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): # Check for a runaway response cycle. if len(context[self._save_key]) >= self._runaway_response_count: - raise Exception("runaway query/response cycle detected: %d responses captured so far. Last response: %s" % - (len(context[self._save_key]), context[self._save_key][-1])) + raise Exception( + "runaway query/response cycle detected: %d responses captured so far. Last response: %s" % + (len( + context[ + self._save_key]), context[ + self._save_key][ + -1])) # Flip the mode to send for generating the query. self._is_send_to_remote = True return context + class MatchRemoteOutputEntry(GdbRemoteEntryBase): """Waits for output from the debug monitor to match a regex or time out. - + This entry type tries to match each time new gdb remote output is accumulated using a provided regex. If the output does not match the regex within the given timeframe, the command fails the playback session. If the regex does match, any capture fields are recorded in the context. - + Settings accepted from params: regex: required. Specifies a compiled regex object that must either succeed @@ -653,7 +715,7 @@ class MatchRemoteOutputEntry(GdbRemoteEntryBase): must match starting somewhere within the output text accumulated thus far. Default: "match" (i.e. the regex must match the entirety of the accumulated output buffer, so unexpected text will generally fail the match). - + capture: optional. If specified, is a dictionary of regex match group indices (should start with 1) to variable names that will store the capture group indicated by the index. For example, {1:"thread_id"} will store capture group 1's content in the @@ -661,6 +723,7 @@ class MatchRemoteOutputEntry(GdbRemoteEntryBase): the value. The value stored off can be used later in a expect_captures expression. This arg only makes sense when regex is specified. """ + def __init__(self, regex=None, regex_mode="match", capture=None): self._regex = regex self._regex_mode = regex_mode @@ -671,7 +734,9 @@ class MatchRemoteOutputEntry(GdbRemoteEntryBase): raise Exception("regex cannot be None") if not self._regex_mode in ["match", "search"]: - raise Exception("unsupported regex mode \"{}\": must be \"match\" or \"search\"".format(self._regex_mode)) + raise Exception( + "unsupported regex mode \"{}\": must be \"match\" or \"search\"".format( + self._regex_mode)) def is_output_matcher(self): return True @@ -692,7 +757,8 @@ class MatchRemoteOutputEntry(GdbRemoteEntryBase): # Validate that we haven't already matched. if self._matched: - raise Exception("invalid state - already matched, attempting to match again") + raise Exception( + "invalid state - already matched, attempting to match again") # If we don't have any content yet, we don't match. if len(accumulated_output) < 1: @@ -704,9 +770,12 @@ class MatchRemoteOutputEntry(GdbRemoteEntryBase): elif self._regex_mode == "search": match = self._regex.search(accumulated_output) else: - raise Exception("Unexpected regex mode: {}".format(self._regex_mode)) + raise Exception( + "Unexpected regex mode: {}".format( + self._regex_mode)) - # If we don't match, wait to try again after next $O content, or time out. + # If we don't match, wait to try again after next $O content, or time + # out. if not match: # print("re pattern \"{}\" did not match against \"{}\"".format(self._regex.pattern, accumulated_output)) return context @@ -721,7 +790,8 @@ class MatchRemoteOutputEntry(GdbRemoteEntryBase): for group_index, var_name in list(self._capture.items()): capture_text = match.group(group_index) if not capture_text: - raise Exception("No content for group index {}".format(group_index)) + raise Exception( + "No content for group index {}".format(group_index)) context[var_name] = capture_text return context @@ -737,7 +807,7 @@ class GdbRemoteTestSequence(object): def add_log_lines(self, log_lines, remote_input_is_read): for line in log_lines: - if type(line) == str: + if isinstance(line, str): # Handle log line import # if self.logger: # self.logger.debug("processing log line: {}".format(line)) @@ -745,19 +815,27 @@ class GdbRemoteTestSequence(object): if match: playback_packet = match.group(2) direction = match.group(1) - if _is_packet_lldb_gdbserver_input(direction, remote_input_is_read): + if _is_packet_lldb_gdbserver_input( + direction, remote_input_is_read): # Handle as something to send to the remote debug monitor. # if self.logger: # self.logger.info("processed packet to send to remote: {}".format(playback_packet)) - self.entries.append(GdbRemoteEntry(is_send_to_remote=True, exact_payload=playback_packet)) + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=True, + exact_payload=playback_packet)) else: # Log line represents content to be expected from the remote debug monitor. # if self.logger: # self.logger.info("receiving packet from llgs, should match: {}".format(playback_packet)) - self.entries.append(GdbRemoteEntry(is_send_to_remote=False,exact_payload=playback_packet)) + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=False, + exact_payload=playback_packet)) else: - raise Exception("failed to interpret log line: {}".format(line)) - elif type(line) == dict: + raise Exception( + "failed to interpret log line: {}".format(line)) + elif isinstance(line, dict): entry_type = line.get("type", "regex_capture") if entry_type == "regex_capture": # Handle more explicit control over details via dictionary. @@ -767,34 +845,50 @@ class GdbRemoteTestSequence(object): expect_captures = line.get("expect_captures", None) # Compile the regex. - if regex and (type(regex) == str): + if regex and (isinstance(regex, str)): regex = re.compile(regex) - if _is_packet_lldb_gdbserver_input(direction, remote_input_is_read): + if _is_packet_lldb_gdbserver_input( + direction, remote_input_is_read): # Handle as something to send to the remote debug monitor. # if self.logger: # self.logger.info("processed dict sequence to send to remote") - self.entries.append(GdbRemoteEntry(is_send_to_remote=True, regex=regex, capture=capture, expect_captures=expect_captures)) + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=True, + regex=regex, + capture=capture, + expect_captures=expect_captures)) else: # Log line represents content to be expected from the remote debug monitor. # if self.logger: # self.logger.info("processed dict sequence to match receiving from remote") - self.entries.append(GdbRemoteEntry(is_send_to_remote=False, regex=regex, capture=capture, expect_captures=expect_captures)) + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=False, + regex=regex, + capture=capture, + expect_captures=expect_captures)) elif entry_type == "multi_response": self.entries.append(MultiResponseGdbRemoteEntry(line)) elif entry_type == "output_match": regex = line.get("regex", None) # Compile the regex. - if regex and (type(regex) == str): + if regex and (isinstance(regex, str)): regex = re.compile(regex, re.DOTALL) regex_mode = line.get("regex_mode", "match") capture = line.get("capture", None) - self.entries.append(MatchRemoteOutputEntry(regex=regex, regex_mode=regex_mode, capture=capture)) + self.entries.append( + MatchRemoteOutputEntry( + regex=regex, + regex_mode=regex_mode, + capture=capture)) else: raise Exception("unknown entry type \"%s\"" % entry_type) + def process_is_running(pid, unknown_value=True): """If possible, validate that the given pid represents a running process on the local system. @@ -814,7 +908,9 @@ def process_is_running(pid, unknown_value=True): return the value provided by the unknown_value arg. """ if not isinstance(pid, six.integer_types): - raise Exception("pid must be an integral type (actual type: %s)" % str(type(pid))) + raise Exception( + "pid must be an integral type (actual type: %s)" % str( + type(pid))) process_ids = [] @@ -824,10 +920,12 @@ def process_is_running(pid, unknown_value=True): return unknown_value elif platform.system() in ['Darwin', 'Linux', 'FreeBSD', 'NetBSD']: # Build the list of running process ids - output = subprocess.check_output("ps ax | awk '{ print $1; }'", shell=True) + output = subprocess.check_output( + "ps ax | awk '{ print $1; }'", shell=True) text_process_ids = output.split('\n')[1:] # Convert text pids to ints - process_ids = [int(text_pid) for text_pid in text_process_ids if text_pid != ''] + process_ids = [int(text_pid) + for text_pid in text_process_ids if text_pid != ''] # elif {your_platform_here}: # fill in process_ids as a list of int type process IDs running on # the local system. diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py index 5c28d288db5..7e4190b7fe9 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py @@ -7,6 +7,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class TestPlatformProcessConnect(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) @@ -19,10 +20,16 @@ class TestPlatformProcessConnect(gdbremote_testcase.GdbRemoteTestCaseBase): self.init_llgs_test(False) working_dir = lldb.remote_platform.GetWorkingDirectory() - err = lldb.remote_platform.Put(lldb.SBFileSpec(os.path.join(os.getcwd(), "a.out")), - lldb.SBFileSpec(os.path.join(working_dir, "a.out"))) + err = lldb.remote_platform.Put( + lldb.SBFileSpec( + os.path.join( + os.getcwd(), "a.out")), lldb.SBFileSpec( + os.path.join( + working_dir, "a.out"))) if err.Fail(): - raise RuntimeError("Unable copy '%s' to '%s'.\n>>> %s" % (f, wd, err.GetCString())) + raise RuntimeError( + "Unable copy '%s' to '%s'.\n>>> %s" % + (f, wd, err.GetCString())) m = re.search("^(.*)://([^:/]*)", configuration.lldb_platform_url) protocol = m.group(1) @@ -30,19 +37,34 @@ class TestPlatformProcessConnect(gdbremote_testcase.GdbRemoteTestCaseBase): unix_protocol = protocol.startswith("unix-") if unix_protocol: p = re.search("^(.*)-connect", protocol) - listen_url = "%s://%s" % (p.group(1), os.path.join(working_dir, "platform-%d.sock" % int(time.time()))) + listen_url = "%s://%s" % (p.group(1), + os.path.join(working_dir, + "platform-%d.sock" % int(time.time()))) else: listen_url = "*:0" port_file = "%s/port" % working_dir - commandline_args = ["platform", "--listen", listen_url, "--socket-file", port_file, "--", "%s/a.out" % working_dir, "foo"] - self.spawnSubprocess(self.debug_monitor_exe, commandline_args, install_remote=False) + commandline_args = [ + "platform", + "--listen", + listen_url, + "--socket-file", + port_file, + "--", + "%s/a.out" % + working_dir, + "foo"] + self.spawnSubprocess( + self.debug_monitor_exe, + commandline_args, + install_remote=False) self.addTearDownHook(self.cleanupSubprocesses) socket_id = lldbutil.wait_for_file_on_target(self, port_file) new_debugger = lldb.SBDebugger.Create() new_debugger.SetAsync(False) + def del_debugger(new_debugger=new_debugger): del new_debugger self.addTearDownHook(del_debugger) @@ -59,7 +81,10 @@ class TestPlatformProcessConnect(gdbremote_testcase.GdbRemoteTestCaseBase): command = "platform connect %s" % (connect_url) result = lldb.SBCommandReturnObject() new_interpreter.HandleCommand(command, result) - self.assertTrue(result.Succeeded(), "platform process connect failed: %s" % result.GetOutput()) + self.assertTrue( + result.Succeeded(), + "platform process connect failed: %s" % + result.GetOutput()) target = new_debugger.GetSelectedTarget() process = target.GetProcess() diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py index 9f594b7df73..6f32dcacd35 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py @@ -2,7 +2,6 @@ from __future__ import print_function - import re import select import threading @@ -11,6 +10,7 @@ import codecs from six.moves import queue + def _handle_output_packet_string(packet_contents): if (not packet_contents) or (len(packet_contents) < 1): return None @@ -21,12 +21,15 @@ def _handle_output_packet_string(packet_contents): else: return packet_contents[1:].decode("hex") + def _dump_queue(the_queue): while not the_queue.empty(): print(codecs.encode(the_queue.get(True), "string_escape")) print("\n") + class PumpQueues(object): + def __init__(self): self._output_queue = queue.Queue() self._packet_queue = queue.Queue() @@ -179,7 +182,8 @@ class SocketPacketPump(object): # Likely a closed socket. Done with the pump thread. if self._logger: self._logger.debug( - "socket read failed, stopping pump read thread\n" + traceback.format_exc(3)) + "socket read failed, stopping pump read thread\n" + + traceback.format_exc(3)) break self._process_new_bytes(new_bytes) diff --git a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py index 8b3b6b68cf0..dc52f244aa4 100644 --- a/lldb/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py +++ b/lldb/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py @@ -1,7 +1,6 @@ from __future__ import print_function - import unittest2 import os.path import re @@ -11,6 +10,7 @@ from lldbgdbserverutils import * class TestLldbGdbServerUtils(unittest2.TestCase): + def test_entry_exact_payload_match(self): entry = GdbRemoteEntry(is_send_to_remote=False, exact_payload="$OK#9a") entry.assert_match(self, "$OK#9a") @@ -25,22 +25,38 @@ class TestLldbGdbServerUtils(unittest2.TestCase): self.assertIsNotNone(context) def test_entry_regex_matches(self): - entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), capture={ 1:"thread_id" }) + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), + capture={ + 1: "thread_id"}) context = entry.assert_match(self, "$QC980#00") def test_entry_regex_saves_match(self): - entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), capture={ 1:"thread_id" }) + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), + capture={ + 1: "thread_id"}) context = entry.assert_match(self, "$QC980#00") self.assertEqual(context["thread_id"], "980") def test_entry_regex_expect_captures_success(self): - context = { "thread_id":"980" } - entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), expect_captures={ 2:"thread_id" }) + context = {"thread_id": "980"} + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), + expect_captures={ + 2: "thread_id"}) entry.assert_match(self, "$T11thread:980;", context=context) def test_entry_regex_expect_captures_raises_on_fail(self): - context = { "thread_id":"980" } - entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), expect_captures={ 2:"thread_id" }) + context = {"thread_id": "980"} + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), + expect_captures={ + 2: "thread_id"}) try: entry.assert_match(self, "$T11thread:970;", context=context) self.fail() diff --git a/lldb/packages/Python/lldbsuite/test/types/AbstractBase.py b/lldb/packages/Python/lldbsuite/test/types/AbstractBase.py index dd09c91f4d0..044a085e020 100644 --- a/lldb/packages/Python/lldbsuite/test/types/AbstractBase.py +++ b/lldb/packages/Python/lldbsuite/test/types/AbstractBase.py @@ -4,15 +4,18 @@ Abstract base class of basic types provides a generic type tester method. from __future__ import print_function -import os, time +import os +import time import re import lldb from lldbsuite.test.lldbtest import * import lldbsuite.test.lldbutil as lldbutil + def Msg(var, val, using_frame_variable): return "'%s %s' matches the output (from compiled code): %s" % ( - 'frame variable --show-types' if using_frame_variable else 'expression' ,var, val) + 'frame variable --show-types' if using_frame_variable else 'expression', var, val) + class GenericTester(TestBase): @@ -59,38 +62,56 @@ class GenericTester(TestBase): #==========================================================================# def build_and_run(self, source, atoms, bc=False, qd=False): - self.build_and_run_with_source_atoms_expr(source, atoms, expr=False, bc=bc, qd=qd) + self.build_and_run_with_source_atoms_expr( + source, atoms, expr=False, bc=bc, qd=qd) def build_and_run_expr(self, source, atoms, bc=False, qd=False): - self.build_and_run_with_source_atoms_expr(source, atoms, expr=True, bc=bc, qd=qd) + self.build_and_run_with_source_atoms_expr( + source, atoms, expr=True, bc=bc, qd=qd) - def build_and_run_with_source_atoms_expr(self, source, atoms, expr, bc=False, qd=False): + def build_and_run_with_source_atoms_expr( + self, source, atoms, expr, bc=False, qd=False): # See also Makefile and basic_type.cpp:177. if bc: - d = {'CXX_SOURCES': source, 'EXE': self.exe_name, 'CFLAGS_EXTRAS': '-DTEST_BLOCK_CAPTURED_VARS'} + d = {'CXX_SOURCES': source, 'EXE': self.exe_name, + 'CFLAGS_EXTRAS': '-DTEST_BLOCK_CAPTURED_VARS'} else: d = {'CXX_SOURCES': source, 'EXE': self.exe_name} self.build(dictionary=d) self.setTearDownCleanup(dictionary=d) if expr: - self.generic_type_expr_tester(self.exe_name, atoms, blockCaptured=bc, quotedDisplay=qd) + self.generic_type_expr_tester( + self.exe_name, atoms, blockCaptured=bc, quotedDisplay=qd) else: - self.generic_type_tester(self.exe_name, atoms, blockCaptured=bc, quotedDisplay=qd) + self.generic_type_tester( + self.exe_name, + atoms, + blockCaptured=bc, + quotedDisplay=qd) def process_launch_o(self, localPath): - # process launch command output redirect always goes to host the process is running on + # process launch command output redirect always goes to host the + # process is running on if lldb.remote_platform: # process launch -o requires a path that is valid on the target self.assertIsNotNone(lldb.remote_platform.GetWorkingDirectory()) - remote_path = lldbutil.append_to_process_working_directory("lldb-stdout-redirect.txt") - self.runCmd('process launch -o {remote}'.format(remote=remote_path)) + remote_path = lldbutil.append_to_process_working_directory( + "lldb-stdout-redirect.txt") + self.runCmd( + 'process launch -o {remote}'.format(remote=remote_path)) # copy remote_path to local host self.runCmd('platform get-file {remote} "{local}"'.format( remote=remote_path, local=self.golden_filename)) else: - self.runCmd('process launch -o "{local}"'.format(local=self.golden_filename)) - - def generic_type_tester(self, exe_name, atoms, quotedDisplay=False, blockCaptured=False): + self.runCmd( + 'process launch -o "{local}"'.format(local=self.golden_filename)) + + def generic_type_tester( + self, + exe_name, + atoms, + quotedDisplay=False, + blockCaptured=False): """Test that variables with basic types are displayed correctly.""" self.runCmd("file %s" % exe_name, CURRENT_EXECUTABLE_SET) @@ -125,21 +146,30 @@ class GenericTester(TestBase): # always setting inlined breakpoints. self.runCmd('settings set target.inline-breakpoint-strategy always') # And add hooks to restore the settings during tearDown(). - self.addTearDownHook( - lambda: self.runCmd("settings set target.inline-breakpoint-strategy headers")) + self.addTearDownHook(lambda: self.runCmd( + "settings set target.inline-breakpoint-strategy headers")) # Bring the program to the point where we can issue a series of # 'frame variable --show-types' command. if blockCaptured: - break_line = line_number ("basic_type.cpp", "// Break here to test block captured variables.") + break_line = line_number( + "basic_type.cpp", + "// Break here to test block captured variables.") else: - break_line = line_number ("basic_type.cpp", "// Here is the line we will break on to check variables.") - lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", break_line, num_expected_locations=1, loc_exact=True) + break_line = line_number( + "basic_type.cpp", + "// Here is the line we will break on to check variables.") + lldbutil.run_break_set_by_file_and_line( + self, + "basic_type.cpp", + break_line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, - substrs = [" at basic_type.cpp:%d" % break_line, - "stop reason = breakpoint"]) + substrs=[" at basic_type.cpp:%d" % break_line, + "stop reason = breakpoint"]) #self.runCmd("frame variable --show-types") @@ -162,19 +192,22 @@ class GenericTester(TestBase): self.fail(self.DATA_TYPE_GROKKED) # Expect the display type string to contain each and every atoms. - self.expect(dt, - "Display type: '%s' must contain the type atoms: '%s'" % - (dt, atoms), - exe=False, - substrs = list(atoms)) + self.expect( + dt, "Display type: '%s' must contain the type atoms: '%s'" % + (dt, atoms), exe=False, substrs=list(atoms)) # The (var, val) pair must match, too. nv = ("%s = '%s'" if quotedDisplay else "%s = %s") % (var, val) self.expect(output, Msg(var, val, True), exe=False, - substrs = [nv]) + substrs=[nv]) pass - def generic_type_expr_tester(self, exe_name, atoms, quotedDisplay=False, blockCaptured=False): + def generic_type_expr_tester( + self, + exe_name, + atoms, + quotedDisplay=False, + blockCaptured=False): """Test that variable expressions with basic types are evaluated correctly.""" self.runCmd("file %s" % exe_name, CURRENT_EXECUTABLE_SET) @@ -209,21 +242,30 @@ class GenericTester(TestBase): # always setting inlined breakpoints. self.runCmd('settings set target.inline-breakpoint-strategy always') # And add hooks to restore the settings during tearDown(). - self.addTearDownHook( - lambda: self.runCmd("settings set target.inline-breakpoint-strategy headers")) + self.addTearDownHook(lambda: self.runCmd( + "settings set target.inline-breakpoint-strategy headers")) # Bring the program to the point where we can issue a series of # 'expr' command. if blockCaptured: - break_line = line_number ("basic_type.cpp", "// Break here to test block captured variables.") + break_line = line_number( + "basic_type.cpp", + "// Break here to test block captured variables.") else: - break_line = line_number ("basic_type.cpp", "// Here is the line we will break on to check variables.") - lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", break_line, num_expected_locations=1, loc_exact=True) + break_line = line_number( + "basic_type.cpp", + "// Here is the line we will break on to check variables.") + lldbutil.run_break_set_by_file_and_line( + self, + "basic_type.cpp", + break_line, + num_expected_locations=1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, - substrs = [" at basic_type.cpp:%d" % break_line, - "stop reason = breakpoint"]) + substrs=[" at basic_type.cpp:%d" % break_line, + "stop reason = breakpoint"]) #self.runCmd("frame variable --show-types") @@ -246,14 +288,12 @@ class GenericTester(TestBase): self.fail(self.DATA_TYPE_GROKKED) # Expect the display type string to contain each and every atoms. - self.expect(dt, - "Display type: '%s' must contain the type atoms: '%s'" % - (dt, atoms), - exe=False, - substrs = list(atoms)) + self.expect( + dt, "Display type: '%s' must contain the type atoms: '%s'" % + (dt, atoms), exe=False, substrs=list(atoms)) # The val part must match, too. valPart = ("'%s'" if quotedDisplay else "%s") % val self.expect(output, Msg(var, val, False), exe=False, - substrs = [valPart]) + substrs=[valPart]) pass diff --git a/lldb/packages/Python/lldbsuite/test/types/HideTestFailures.py b/lldb/packages/Python/lldbsuite/test/types/HideTestFailures.py index 5818166ef5e..662665b85a0 100644 --- a/lldb/packages/Python/lldbsuite/test/types/HideTestFailures.py +++ b/lldb/packages/Python/lldbsuite/test/types/HideTestFailures.py @@ -5,14 +5,16 @@ Test that variables of integer basic types are displayed correctly. from __future__ import print_function - import AbstractBase import sys import lldb from lldbsuite.test.lldbtest import * # rdar://problem/9649573 -# Capture the lldb and gdb-remote log files for test failures when run with no "-w" option +# Capture the lldb and gdb-remote log files for test failures when run +# with no "-w" option + + class DebugIntegerTypesFailures(TestBase): mydir = TestBase.compute_mydir(__file__) diff --git a/lldb/packages/Python/lldbsuite/test/types/TestFloatTypes.py b/lldb/packages/Python/lldbsuite/test/types/TestFloatTypes.py index 9fb555943b8..1b8555daa87 100644 --- a/lldb/packages/Python/lldbsuite/test/types/TestFloatTypes.py +++ b/lldb/packages/Python/lldbsuite/test/types/TestFloatTypes.py @@ -5,7 +5,6 @@ Test that variables of floating point types are displayed correctly. from __future__ import print_function - import AbstractBase import sys @@ -14,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class FloatTypesTestCase(AbstractBase.GenericTester): mydir = AbstractBase.GenericTester.compute_mydir(__file__) @@ -23,7 +23,8 @@ class FloatTypesTestCase(AbstractBase.GenericTester): AbstractBase.GenericTester.setUp(self) # disable "There is a running process, kill it and restart?" prompt self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def test_float_type(self): """Test that float-type variables are displayed correctly.""" diff --git a/lldb/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py b/lldb/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py index 188033fffa3..2fd1d39f553 100644 --- a/lldb/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py +++ b/lldb/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py @@ -13,19 +13,22 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class FloatTypesExprTestCase(AbstractBase.GenericTester): mydir = AbstractBase.GenericTester.compute_mydir(__file__) # rdar://problem/8493023 - # test/types failures for Test*TypesExpr.py: element offset computed wrong and sign error? + # test/types failures for Test*TypesExpr.py: element offset computed wrong + # and sign error? def setUp(self): # Call super's setUp(). AbstractBase.GenericTester.setUp(self) # disable "There is a running process, kill it and restart?" prompt self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def test_float_type(self): """Test that float-type variable expressions are evaluated correctly.""" diff --git a/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypes.py b/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypes.py index c1eab718307..88a89e83f40 100644 --- a/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypes.py +++ b/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypes.py @@ -12,6 +12,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class IntegerTypesTestCase(AbstractBase.GenericTester): mydir = AbstractBase.GenericTester.compute_mydir(__file__) @@ -21,7 +22,8 @@ class IntegerTypesTestCase(AbstractBase.GenericTester): AbstractBase.GenericTester.setUp(self) # disable "There is a running process, kill it and restart?" prompt self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def test_char_type(self): """Test that char-type variables are displayed correctly.""" @@ -34,12 +36,14 @@ class IntegerTypesTestCase(AbstractBase.GenericTester): def test_unsigned_char_type(self): """Test that 'unsigned_char'-type variables are displayed correctly.""" - self.build_and_run('unsigned_char.cpp', set(['unsigned', 'char']), qd=True) + self.build_and_run('unsigned_char.cpp', set( + ['unsigned', 'char']), qd=True) @skipUnlessDarwin def test_unsigned_char_type_from_block(self): """Test that 'unsigned char'-type variables are displayed correctly from a block.""" - self.build_and_run('unsigned_char.cpp', set(['unsigned', 'char']), bc=True, qd=True) + self.build_and_run('unsigned_char.cpp', set( + ['unsigned', 'char']), bc=True, qd=True) def test_short_type(self): """Test that short-type variables are displayed correctly.""" @@ -57,7 +61,8 @@ class IntegerTypesTestCase(AbstractBase.GenericTester): @skipUnlessDarwin def test_unsigned_short_type_from_block(self): """Test that 'unsigned short'-type variables are displayed correctly from a block.""" - self.build_and_run('unsigned_short.cpp', set(['unsigned', 'short']), bc=True) + self.build_and_run('unsigned_short.cpp', set( + ['unsigned', 'short']), bc=True) def test_int_type(self): """Test that int-type variables are displayed correctly.""" @@ -75,7 +80,8 @@ class IntegerTypesTestCase(AbstractBase.GenericTester): @skipUnlessDarwin def test_unsigned_int_type_from_block(self): """Test that 'unsigned int'-type variables are displayed correctly from a block.""" - self.build_and_run('unsigned_int.cpp', set(['unsigned', 'int']), bc=True) + self.build_and_run('unsigned_int.cpp', set( + ['unsigned', 'int']), bc=True) def test_long_type(self): """Test that long-type variables are displayed correctly.""" @@ -93,7 +99,8 @@ class IntegerTypesTestCase(AbstractBase.GenericTester): @skipUnlessDarwin def test_unsigned_long_type_from_block(self): """Test that 'unsigned_long'-type variables are displayed correctly from a block.""" - self.build_and_run('unsigned_long.cpp', set(['unsigned', 'long']), bc=True) + self.build_and_run('unsigned_long.cpp', set( + ['unsigned', 'long']), bc=True) def test_long_long_type(self): """Test that 'long long'-type variables are displayed correctly.""" @@ -106,9 +113,11 @@ class IntegerTypesTestCase(AbstractBase.GenericTester): def test_unsigned_long_long_type(self): """Test that 'unsigned long long'-type variables are displayed correctly.""" - self.build_and_run('unsigned_long_long.cpp', set(['unsigned', 'long long'])) + self.build_and_run('unsigned_long_long.cpp', + set(['unsigned', 'long long'])) @skipUnlessDarwin def test_unsigned_long_long_type_from_block(self): """Test that 'unsigned_long_long'-type variables are displayed correctly from a block.""" - self.build_and_run('unsigned_long_long.cpp', set(['unsigned', 'long long']), bc=True) + self.build_and_run('unsigned_long_long.cpp', set( + ['unsigned', 'long long']), bc=True) diff --git a/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py b/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py index 2c3edea7ada..a6ada4a2031 100644 --- a/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py +++ b/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py @@ -13,6 +13,7 @@ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + class IntegerTypesExprTestCase(AbstractBase.GenericTester): mydir = AbstractBase.GenericTester.compute_mydir(__file__) @@ -22,7 +23,8 @@ class IntegerTypesExprTestCase(AbstractBase.GenericTester): AbstractBase.GenericTester.setUp(self) # disable "There is a running process, kill it and restart?" prompt self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) def test_char_type(self): """Test that char-type variable expressions are evaluated correctly.""" @@ -35,12 +37,14 @@ class IntegerTypesExprTestCase(AbstractBase.GenericTester): def test_unsigned_char_type(self): """Test that 'unsigned_char'-type variable expressions are evaluated correctly.""" - self.build_and_run_expr('unsigned_char.cpp', set(['unsigned', 'char']), qd=True) + self.build_and_run_expr('unsigned_char.cpp', set( + ['unsigned', 'char']), qd=True) @skipUnlessDarwin def test_unsigned_char_type_from_block(self): """Test that 'unsigned char'-type variables are displayed correctly from a block.""" - self.build_and_run_expr('unsigned_char.cpp', set(['unsigned', 'char']), bc=True, qd=True) + self.build_and_run_expr('unsigned_char.cpp', set( + ['unsigned', 'char']), bc=True, qd=True) def test_short_type(self): """Test that short-type variable expressions are evaluated correctly.""" @@ -53,12 +57,14 @@ class IntegerTypesExprTestCase(AbstractBase.GenericTester): def test_unsigned_short_type(self): """Test that 'unsigned_short'-type variable expressions are evaluated correctly.""" - self.build_and_run_expr('unsigned_short.cpp', set(['unsigned', 'short'])) + self.build_and_run_expr('unsigned_short.cpp', + set(['unsigned', 'short'])) @skipUnlessDarwin def test_unsigned_short_type_from_block(self): """Test that 'unsigned short'-type variables are displayed correctly from a block.""" - self.build_and_run_expr('unsigned_short.cpp', set(['unsigned', 'short']), bc=True) + self.build_and_run_expr('unsigned_short.cpp', set( + ['unsigned', 'short']), bc=True) def test_int_type(self): """Test that int-type variable expressions are evaluated correctly.""" @@ -76,7 +82,8 @@ class IntegerTypesExprTestCase(AbstractBase.GenericTester): @skipUnlessDarwin def test_unsigned_int_type_from_block(self): """Test that 'unsigned int'-type variables are displayed correctly from a block.""" - self.build_and_run_expr('unsigned_int.cpp', set(['unsigned', 'int']), bc=True) + self.build_and_run_expr( + 'unsigned_int.cpp', set(['unsigned', 'int']), bc=True) def test_long_type(self): """Test that long-type variable expressions are evaluated correctly.""" @@ -94,7 +101,8 @@ class IntegerTypesExprTestCase(AbstractBase.GenericTester): @skipUnlessDarwin def test_unsigned_long_type_from_block(self): """Test that 'unsigned_long'-type variables are displayed correctly from a block.""" - self.build_and_run_expr('unsigned_long.cpp', set(['unsigned', 'long']), bc=True) + self.build_and_run_expr('unsigned_long.cpp', set( + ['unsigned', 'long']), bc=True) def test_long_long_type(self): """Test that 'long long'-type variable expressions are evaluated correctly.""" @@ -107,9 +115,11 @@ class IntegerTypesExprTestCase(AbstractBase.GenericTester): def test_unsigned_long_long_type(self): """Test that 'unsigned long long'-type variable expressions are evaluated correctly.""" - self.build_and_run_expr('unsigned_long_long.cpp', set(['unsigned', 'long long'])) + self.build_and_run_expr('unsigned_long_long.cpp', + set(['unsigned', 'long long'])) @skipUnlessDarwin def test_unsigned_long_long_type_from_block(self): """Test that 'unsigned_long_long'-type variables are displayed correctly from a block.""" - self.build_and_run_expr('unsigned_long_long.cpp', set(['unsigned', 'long long']), bc=True) + self.build_and_run_expr('unsigned_long_long.cpp', set( + ['unsigned', 'long long']), bc=True) diff --git a/lldb/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py b/lldb/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py index 0b60b5a4d63..4735bcee512 100644 --- a/lldb/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py +++ b/lldb/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py @@ -5,12 +5,12 @@ Test that recursive types are handled correctly. from __future__ import print_function - import lldb import lldbsuite.test.lldbutil as lldbutil import sys from lldbsuite.test.lldbtest import * + class RecursiveTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @@ -20,13 +20,16 @@ class RecursiveTypesTestCase(TestBase): TestBase.setUp(self) # disable "There is a running process, kill it and restart?" prompt self.runCmd("settings set auto-confirm true") - self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm")) + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) # Find the line number to break for main.c. self.line = line_number('recursive_type_main.cpp', '// Test at this line.') - self.d1 = {'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_1.cpp'} - self.d2 = {'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_2.cpp'} + self.d1 = { + 'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_1.cpp'} + self.d2 = { + 'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_2.cpp'} def test_recursive_type_1(self): """Test that recursive structs are displayed correctly.""" @@ -43,7 +46,12 @@ class RecursiveTypesTestCase(TestBase): def print_struct(self): self.runCmd("file a.out", CURRENT_EXECUTABLE_SET) - lldbutil.run_break_set_by_file_and_line (self, "recursive_type_main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "recursive_type_main.cpp", + self.line, + num_expected_locations=-1, + loc_exact=True) self.runCmd("run", RUN_SUCCEEDED) diff --git a/lldb/packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py b/lldb/packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py index 5010309e894..5df4c701ad9 100644 --- a/lldb/packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py +++ b/lldb/packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py @@ -3,13 +3,14 @@ from __future__ import print_function - -import os, time +import os +import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil + @skipUnlessDarwin class AddDsymCommandCase(TestBase): @@ -29,7 +30,8 @@ class AddDsymCommandCase(TestBase): self.generate_main_cpp(version=1) self.buildDsym(clean=True) - # Insert some delay and then call the program generator to produce main.cpp, version 2. + # Insert some delay and then call the program generator to produce + # main.cpp, version 2. time.sleep(5) self.generate_main_cpp(version=101) # Now call make again, but this time don't generate the dSYM. @@ -60,15 +62,16 @@ class AddDsymCommandCase(TestBase): self.exe_name = 'a.out' self.do_add_dsym_with_dSYM_bundle(self.exe_name) - def generate_main_cpp(self, version=0): """Generate main.cpp from main.cpp.template.""" temp = os.path.join(os.getcwd(), self.template) with open(temp, 'r') as f: content = f.read() - new_content = content.replace('%ADD_EXTRA_CODE%', - 'printf("This is version %d\\n");' % version) + new_content = content.replace( + '%ADD_EXTRA_CODE%', + 'printf("This is version %d\\n");' % + version) src = os.path.join(os.getcwd(), self.source) with open(src, 'w') as f: f.write(new_content) @@ -84,20 +87,33 @@ class AddDsymCommandCase(TestBase): wrong_path = os.path.join("%s.dSYM" % exe_name, "Contents") self.expect("add-dsym " + wrong_path, error=True, - substrs = ['invalid module path']) - - right_path = os.path.join("%s.dSYM" % exe_name, "Contents", "Resources", "DWARF", exe_name) + substrs=['invalid module path']) + + right_path = os.path.join( + "%s.dSYM" % + exe_name, + "Contents", + "Resources", + "DWARF", + exe_name) self.expect("add-dsym " + right_path, error=True, - substrs = ['symbol file', 'does not match']) + substrs=['symbol file', 'does not match']) def do_add_dsym_with_success(self, exe_name): """Test that the 'add-dsym' command informs the user about success.""" self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET) - # This time, the UUID should match and we expect some feedback from lldb. - right_path = os.path.join("%s.dSYM" % exe_name, "Contents", "Resources", "DWARF", exe_name) + # This time, the UUID should match and we expect some feedback from + # lldb. + right_path = os.path.join( + "%s.dSYM" % + exe_name, + "Contents", + "Resources", + "DWARF", + exe_name) self.expect("add-dsym " + right_path, - substrs = ['symbol file', 'has been added to']) + substrs=['symbol file', 'has been added to']) def do_add_dsym_with_dSYM_bundle(self, exe_name): """Test that the 'add-dsym' command informs the user about success when loading files in bundles.""" @@ -106,4 +122,4 @@ class AddDsymCommandCase(TestBase): # This time, the UUID should be found inside the bundle right_path = "%s.dSYM" % exe_name self.expect("add-dsym " + right_path, - substrs = ['symbol file', 'has been added to']) + substrs=['symbol file', 'has been added to']) diff --git a/lldb/packages/Python/lldbsuite/test_event/build_exception.py b/lldb/packages/Python/lldbsuite/test_event/build_exception.py index 4a7c5f4a9d3..5b00b92d473 100644 --- a/lldb/packages/Python/lldbsuite/test_event/build_exception.py +++ b/lldb/packages/Python/lldbsuite/test_event/build_exception.py @@ -1,8 +1,11 @@ class BuildError(Exception): + def __init__(self, called_process_error): super(BuildError, self).__init__("Error when building test subject") - self.command = called_process_error.lldb_extensions.get("command", "<command unavailable>") - self.build_error = called_process_error.lldb_extensions.get("stderr_content", "<error output unavailable>") + self.command = called_process_error.lldb_extensions.get( + "command", "<command unavailable>") + self.build_error = called_process_error.lldb_extensions.get( + "stderr_content", "<error output unavailable>") def __str__(self): return self.format_build_error(self.command, self.build_error) @@ -10,5 +13,4 @@ class BuildError(Exception): @staticmethod def format_build_error(command, command_output): return "Error when building test subject.\n\nBuild Command:\n{}\n\nBuild Command Output:\n{}".format( - command, - command_output) + command, command_output) diff --git a/lldb/packages/Python/lldbsuite/test_event/dotest_channels.py b/lldb/packages/Python/lldbsuite/test_event/dotest_channels.py index d69720e4f66..4f79193514b 100644 --- a/lldb/packages/Python/lldbsuite/test_event/dotest_channels.py +++ b/lldb/packages/Python/lldbsuite/test_event/dotest_channels.py @@ -42,6 +42,7 @@ class UnpicklingForwardingReaderChannel(asyncore.dispatcher): The bulk of this class is devoted to reading and parsing out the payload bytes. """ + def __init__(self, file_object, async_map, forwarding_func): asyncore.dispatcher.__init__(self, sock=file_object, map=async_map) @@ -181,6 +182,7 @@ class UnpicklingForwardingListenerChannel(asyncore.dispatcher): one of the reasons for implementing with asyncore. This listener shuts down once a single connection is made to it. """ + def __init__(self, async_map, host, port, backlog_count, forwarding_func): asyncore.dispatcher.__init__(self, map=async_map) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) diff --git a/lldb/packages/Python/lldbsuite/test_event/event_builder.py b/lldb/packages/Python/lldbsuite/test_event/event_builder.py index aabbd986bd7..a7cb57c7f9c 100644 --- a/lldb/packages/Python/lldbsuite/test_event/event_builder.py +++ b/lldb/packages/Python/lldbsuite/test_event/event_builder.py @@ -20,6 +20,7 @@ import traceback # LLDB modules from . import build_exception + class EventBuilder(object): """Helper class to build test result event dictionaries.""" @@ -95,7 +96,8 @@ class EventBuilder(object): def _assert_is_python_sourcefile(test_filename): if test_filename is not None: if not test_filename.endswith(".py"): - raise Exception("source python filename has unexpected extension: {}".format(test_filename)) + raise Exception( + "source python filename has unexpected extension: {}".format(test_filename)) return test_filename @staticmethod @@ -113,9 +115,11 @@ class EventBuilder(object): # Determine the filename for the test case. If there is an attribute # for it, use it. Otherwise, determine from the TestCase class path. if hasattr(test, "test_filename"): - test_filename = EventBuilder._assert_is_python_sourcefile(test.test_filename) + test_filename = EventBuilder._assert_is_python_sourcefile( + test.test_filename) else: - test_filename = EventBuilder._assert_is_python_sourcefile(inspect.getsourcefile(test.__class__)) + test_filename = EventBuilder._assert_is_python_sourcefile( + inspect.getsourcefile(test.__class__)) event = EventBuilder.bare_event(event_type) event.update({ @@ -352,7 +356,8 @@ class EventBuilder(object): event = EventBuilder.bare_event(EventBuilder.TYPE_JOB_RESULT) event["status"] = EventBuilder.STATUS_ERROR if test_filename is not None: - event["test_filename"] = EventBuilder._assert_is_python_sourcefile(test_filename) + event["test_filename"] = EventBuilder._assert_is_python_sourcefile( + test_filename) if exception is not None and "__class__" in dir(exception): event["issue_class"] = exception.__class__ event["issue_message"] = exception @@ -390,7 +395,8 @@ class EventBuilder(object): if exception_description is not None: event["exception_description"] = exception_description if test_filename is not None: - event["test_filename"] = EventBuilder._assert_is_python_sourcefile(test_filename) + event["test_filename"] = EventBuilder._assert_is_python_sourcefile( + test_filename) if command_line is not None: event["command_line"] = command_line return event @@ -414,7 +420,8 @@ class EventBuilder(object): if worker_index is not None: event["worker_index"] = int(worker_index) if test_filename is not None: - event["test_filename"] = EventBuilder._assert_is_python_sourcefile(test_filename) + event["test_filename"] = EventBuilder._assert_is_python_sourcefile( + test_filename) if command_line is not None: event["command_line"] = command_line return event diff --git a/lldb/packages/Python/lldbsuite/test_event/formatter/__init__.py b/lldb/packages/Python/lldbsuite/test_event/formatter/__init__.py index 556370ebb9d..2481e326e94 100644 --- a/lldb/packages/Python/lldbsuite/test_event/formatter/__init__.py +++ b/lldb/packages/Python/lldbsuite/test_event/formatter/__init__.py @@ -76,7 +76,8 @@ def create_results_formatter(config): # we lose the test result info. read_bytes = sock.recv(1) if read_bytes is None or (len(read_bytes) < 1) or (read_bytes != b'*'): - raise Exception("listening socket did not respond with ack byte: response={}".format(read_bytes)) + raise Exception( + "listening socket did not respond with ack byte: response={}".format(read_bytes)) return sock, lambda: socket_closer(sock) diff --git a/lldb/packages/Python/lldbsuite/test_event/formatter/curses.py b/lldb/packages/Python/lldbsuite/test_event/formatter/curses.py index 4e89fa9bf01..f415575ded8 100644 --- a/lldb/packages/Python/lldbsuite/test_event/formatter/curses.py +++ b/lldb/packages/Python/lldbsuite/test_event/formatter/curses.py @@ -38,7 +38,10 @@ class Curses(results_formatter.ResultsFormatter): self.results = list() try: self.main_window = lldbcurses.intialize_curses() - self.main_window.add_key_action('\t', self.main_window.select_next_first_responder, "Switch between views that can respond to keyboard input") + self.main_window.add_key_action( + '\t', + self.main_window.select_next_first_responder, + "Switch between views that can respond to keyboard input") self.main_window.refresh() self.job_panel = None self.results_panel = None @@ -87,10 +90,15 @@ class Curses(results_formatter.ResultsFormatter): selected_idx = self.results_panel.get_selected_idx() if selected_idx >= 0 and selected_idx < len(self.results): if self.info_panel is None: - info_frame = self.results_panel.get_contained_rect(top_inset=10, left_inset=10, right_inset=10, height=30) - self.info_panel = lldbcurses.BoxedPanel(info_frame, "Result Details") - # Add a key action for any key that will hide this panel when any key is pressed - self.info_panel.add_key_action(-1, self.hide_info_panel, 'Hide the info panel') + info_frame = self.results_panel.get_contained_rect( + top_inset=10, left_inset=10, right_inset=10, height=30) + self.info_panel = lldbcurses.BoxedPanel( + info_frame, "Result Details") + # Add a key action for any key that will hide this panel when + # any key is pressed + self.info_panel.add_key_action(-1, + self.hide_info_panel, + 'Hide the info panel') self.info_panel.top() else: self.info_panel.show() @@ -98,9 +106,15 @@ class Curses(results_formatter.ResultsFormatter): self.main_window.push_first_responder(self.info_panel) test_start = self.results[selected_idx][0] test_result = self.results[selected_idx][1] - self.info_panel.set_line(0, "File: %s" % (test_start['test_filename'])) - self.info_panel.set_line(1, "Test: %s.%s" % (test_start['test_class'], test_start['test_name'])) - self.info_panel.set_line(2, "Time: %s" % (test_result['elapsed_time'])) + self.info_panel.set_line( + 0, "File: %s" % + (test_start['test_filename'])) + self.info_panel.set_line( + 1, "Test: %s.%s" % + (test_start['test_class'], test_start['test_name'])) + self.info_panel.set_line( + 2, "Time: %s" % + (test_result['elapsed_time'])) self.info_panel.set_line(3, "Status: %s" % (test_result['status'])) def hide_info_panel(self): @@ -110,7 +124,8 @@ class Curses(results_formatter.ResultsFormatter): def toggle_status(self, status): if status: - # Toggle showing and hiding results whose status matches "status" in "Results" window + # Toggle showing and hiding results whose status matches "status" + # in "Results" window if status in self.hide_status_list: self.hide_status_list.remove(status) else: @@ -127,7 +142,13 @@ class Curses(results_formatter.ResultsFormatter): if status in self.hide_status_list: continue name = test_result['test_class'] + '.' + test_result['test_name'] - self.results_panel.append_line('%s (%6.2f sec) %s' % (self.status_to_short_str(status, test_result), test_result['elapsed_time'], name)) + self.results_panel.append_line( + '%s (%6.2f sec) %s' % + (self.status_to_short_str( + status, + test_result), + test_result['elapsed_time'], + name)) if update: self.main_window.refresh() @@ -145,9 +166,14 @@ class Curses(results_formatter.ResultsFormatter): #print(str(test_event), file=self.events_file) event = test_event['event'] if self.status_panel: - self.status_panel.update_status('time', str(datetime.timedelta(seconds=math.floor(time.time() - self.start_time)))) + self.status_panel.update_status( + 'time', str( + datetime.timedelta( + seconds=math.floor( + time.time() - self.start_time)))) if event == 'test_start': - name = test_event['test_class'] + '.' + test_event['test_name'] + name = test_event['test_class'] + \ + '.' + test_event['test_name'] self.job_tests[worker_index] = test_event if 'pid' in test_event: line = 'pid: %5d ' % (test_event['pid']) + name @@ -163,14 +189,20 @@ class Curses(results_formatter.ResultsFormatter): else: line = '' self.job_panel.set_line(worker_index, line) - name = test_event['test_class'] + '.' + test_event['test_name'] - elapsed_time = test_event['event_time'] - self.job_tests[worker_index]['event_time'] - if not status in self.hide_status_list: - self.results_panel.append_line('%s (%6.2f sec) %s' % (self.status_to_short_str(status, test_event), elapsed_time, name)) + name = test_event['test_class'] + \ + '.' + test_event['test_name'] + elapsed_time = test_event[ + 'event_time'] - self.job_tests[worker_index]['event_time'] + if status not in self.hide_status_list: + self.results_panel.append_line( + '%s (%6.2f sec) %s' % + (self.status_to_short_str( + status, test_event), elapsed_time, name)) self.main_window.refresh() # Append the result pairs test_event['elapsed_time'] = elapsed_time - self.results.append([self.job_tests[worker_index], test_event]) + self.results.append( + [self.job_tests[worker_index], test_event]) self.job_tests[worker_index] = '' elif event == 'job_begin': self.jobs[worker_index] = test_event @@ -185,40 +217,121 @@ class Curses(results_formatter.ResultsFormatter): elif event == 'initialize': self.initialize_event = test_event num_jobs = test_event['worker_count'] - job_frame = self.main_window.get_contained_rect(height=num_jobs+2) - results_frame = self.main_window.get_contained_rect(top_inset=num_jobs+2, bottom_inset=1) - status_frame = self.main_window.get_contained_rect(height=1, top_inset=self.main_window.get_size().h-1) - self.job_panel = lldbcurses.BoxedPanel(frame=job_frame, title="Jobs") - self.results_panel = lldbcurses.BoxedPanel(frame=results_frame, title="Results") - - self.results_panel.add_key_action(curses.KEY_UP, self.results_panel.select_prev , "Select the previous list entry") - self.results_panel.add_key_action(curses.KEY_DOWN, self.results_panel.select_next , "Select the next list entry") - self.results_panel.add_key_action(curses.KEY_HOME, self.results_panel.scroll_begin , "Scroll to the start of the list") - self.results_panel.add_key_action(curses.KEY_END, self.results_panel.scroll_end , "Scroll to the end of the list") - self.results_panel.add_key_action(curses.KEY_ENTER, self.show_info_panel , "Display info for the selected result item") - self.results_panel.add_key_action('.', lambda : self.toggle_status(EventBuilder.STATUS_SUCCESS) , "Toggle showing/hiding tests whose status is 'success'") - self.results_panel.add_key_action('e', lambda : self.toggle_status(EventBuilder.STATUS_ERROR) , "Toggle showing/hiding tests whose status is 'error'") - self.results_panel.add_key_action('f', lambda : self.toggle_status(EventBuilder.STATUS_FAILURE) , "Toggle showing/hiding tests whose status is 'failure'") - self.results_panel.add_key_action('s', lambda : self.toggle_status(EventBuilder.STATUS_SKIP) , "Toggle showing/hiding tests whose status is 'skip'") - self.results_panel.add_key_action('x', lambda : self.toggle_status(EventBuilder.STATUS_EXPECTED_FAILURE) , "Toggle showing/hiding tests whose status is 'expected_failure'") - self.results_panel.add_key_action('?', lambda : self.toggle_status(EventBuilder.STATUS_UNEXPECTED_SUCCESS), "Toggle showing/hiding tests whose status is 'unexpected_success'") - self.status_panel = lldbcurses.StatusPanel(frame=status_frame) + job_frame = self.main_window.get_contained_rect( + height=num_jobs + 2) + results_frame = self.main_window.get_contained_rect( + top_inset=num_jobs + 2, bottom_inset=1) + status_frame = self.main_window.get_contained_rect( + height=1, top_inset=self.main_window.get_size().h - 1) + self.job_panel = lldbcurses.BoxedPanel( + frame=job_frame, title="Jobs") + self.results_panel = lldbcurses.BoxedPanel( + frame=results_frame, title="Results") + + self.results_panel.add_key_action( + curses.KEY_UP, + self.results_panel.select_prev, + "Select the previous list entry") + self.results_panel.add_key_action( + curses.KEY_DOWN, self.results_panel.select_next, "Select the next list entry") + self.results_panel.add_key_action( + curses.KEY_HOME, + self.results_panel.scroll_begin, + "Scroll to the start of the list") + self.results_panel.add_key_action( + curses.KEY_END, self.results_panel.scroll_end, "Scroll to the end of the list") + self.results_panel.add_key_action( + curses.KEY_ENTER, + self.show_info_panel, + "Display info for the selected result item") + self.results_panel.add_key_action( + '.', + lambda: self.toggle_status( + EventBuilder.STATUS_SUCCESS), + "Toggle showing/hiding tests whose status is 'success'") + self.results_panel.add_key_action( + 'e', + lambda: self.toggle_status( + EventBuilder.STATUS_ERROR), + "Toggle showing/hiding tests whose status is 'error'") + self.results_panel.add_key_action( + 'f', + lambda: self.toggle_status( + EventBuilder.STATUS_FAILURE), + "Toggle showing/hiding tests whose status is 'failure'") + self.results_panel.add_key_action('s', lambda: self.toggle_status( + EventBuilder.STATUS_SKIP), "Toggle showing/hiding tests whose status is 'skip'") + self.results_panel.add_key_action( + 'x', + lambda: self.toggle_status( + EventBuilder.STATUS_EXPECTED_FAILURE), + "Toggle showing/hiding tests whose status is 'expected_failure'") + self.results_panel.add_key_action( + '?', + lambda: self.toggle_status( + EventBuilder.STATUS_UNEXPECTED_SUCCESS), + "Toggle showing/hiding tests whose status is 'unexpected_success'") + self.status_panel = lldbcurses.StatusPanel( + frame=status_frame) self.main_window.add_child(self.job_panel) self.main_window.add_child(self.results_panel) self.main_window.add_child(self.status_panel) - self.main_window.set_first_responder(self.results_panel) - - self.status_panel.add_status_item(name="time", title="Elapsed", format="%s", width=20, value="0:00:00", update=False) - self.status_panel.add_status_item(name=EventBuilder.STATUS_SUCCESS, title="Success", format="%u", width=20, value=0, update=False) - self.status_panel.add_status_item(name=EventBuilder.STATUS_FAILURE, title="Failure", format="%u", width=20, value=0, update=False) - self.status_panel.add_status_item(name=EventBuilder.STATUS_ERROR, title="Error", format="%u", width=20, value=0, update=False) - self.status_panel.add_status_item(name=EventBuilder.STATUS_SKIP, title="Skipped", format="%u", width=20, value=0, update=True) - self.status_panel.add_status_item(name=EventBuilder.STATUS_EXPECTED_FAILURE, title="Expected Failure", format="%u", width=30, value=0, update=False) - self.status_panel.add_status_item(name=EventBuilder.STATUS_UNEXPECTED_SUCCESS, title="Unexpected Success", format="%u", width=30, value=0, update=False) + self.main_window.set_first_responder( + self.results_panel) + + self.status_panel.add_status_item( + name="time", + title="Elapsed", + format="%s", + width=20, + value="0:00:00", + update=False) + self.status_panel.add_status_item( + name=EventBuilder.STATUS_SUCCESS, + title="Success", + format="%u", + width=20, + value=0, + update=False) + self.status_panel.add_status_item( + name=EventBuilder.STATUS_FAILURE, + title="Failure", + format="%u", + width=20, + value=0, + update=False) + self.status_panel.add_status_item( + name=EventBuilder.STATUS_ERROR, + title="Error", + format="%u", + width=20, + value=0, + update=False) + self.status_panel.add_status_item( + name=EventBuilder.STATUS_SKIP, + title="Skipped", + format="%u", + width=20, + value=0, + update=True) + self.status_panel.add_status_item( + name=EventBuilder.STATUS_EXPECTED_FAILURE, + title="Expected Failure", + format="%u", + width=30, + value=0, + update=False) + self.status_panel.add_status_item( + name=EventBuilder.STATUS_UNEXPECTED_SUCCESS, + title="Unexpected Success", + format="%u", + width=30, + value=0, + update=False) self.main_window.refresh() elif event == 'terminate': - #self.main_window.key_event_loop() + # self.main_window.key_event_loop() lldbcurses.terminate_curses() check_for_one_key = False self.using_terminal = False diff --git a/lldb/packages/Python/lldbsuite/test_event/formatter/pickled.py b/lldb/packages/Python/lldbsuite/test_event/formatter/pickled.py index 6d800f6c8ba..588614e2f7b 100644 --- a/lldb/packages/Python/lldbsuite/test_event/formatter/pickled.py +++ b/lldb/packages/Python/lldbsuite/test_event/formatter/pickled.py @@ -31,21 +31,29 @@ class RawPickledFormatter(ResultsFormatter): return parser class StreamSerializer(object): + @staticmethod def serialize(test_event, out_file): - # Send it as {serialized_length_of_serialized_bytes}{serialized_bytes} + # Send it as + # {serialized_length_of_serialized_bytes}{serialized_bytes} import struct msg = cPickle.dumps(test_event) packet = struct.pack("!I%ds" % len(msg), len(msg), msg) out_file.send(packet) class BlockSerializer(object): + @staticmethod def serialize(test_event, out_file): cPickle.dump(test_event, out_file) def __init__(self, out_file, options, file_is_stream): - super(RawPickledFormatter, self).__init__(out_file, options, file_is_stream) + super( + RawPickledFormatter, + self).__init__( + out_file, + options, + file_is_stream) self.pid = os.getpid() if file_is_stream: self.serializer = self.StreamSerializer() diff --git a/lldb/packages/Python/lldbsuite/test_event/formatter/results_formatter.py b/lldb/packages/Python/lldbsuite/test_event/formatter/results_formatter.py index 3bf389b9726..e2c1d8ce396 100644 --- a/lldb/packages/Python/lldbsuite/test_event/formatter/results_formatter.py +++ b/lldb/packages/Python/lldbsuite/test_event/formatter/results_formatter.py @@ -341,7 +341,8 @@ class ResultsFormatter(object): # started test for the given worker index. status = test_event["status"] self.result_status_counts[status] += 1 - # Clear the most recently started test for the related worker. + # Clear the most recently started test for the related + # worker. worker_index = test_event.get("worker_index", None) if worker_index is not None: self.started_tests_by_worker.pop(worker_index, None) @@ -688,7 +689,7 @@ class ResultsFormatter(object): # prevent buildbots from thinking it is an issue when scanning # for TIMEOUT. "Expected Timeout", True, "EXPECTED TIME-OUT"] - ] + ] # Partition all the events by test result status result_events_by_status = self._partition_results_by_status( diff --git a/lldb/packages/Python/lldbsuite/test_event/formatter/xunit.py b/lldb/packages/Python/lldbsuite/test_event/formatter/xunit.py index b3682f8fb10..d3ea8677f0a 100644 --- a/lldb/packages/Python/lldbsuite/test_event/formatter/xunit.py +++ b/lldb/packages/Python/lldbsuite/test_event/formatter/xunit.py @@ -180,7 +180,7 @@ class XunitFormatter(ResultsFormatter): "unexpected_successes": [], "expected_failures": [], "all": [] - } + } self.status_handlers = { EventBuilder.STATUS_SUCCESS: self._handle_success, @@ -197,9 +197,11 @@ class XunitFormatter(ResultsFormatter): self._handle_exceptional_exit, EventBuilder.STATUS_TIMEOUT: self._handle_timeout - } + } - RESULT_TYPES = {EventBuilder.TYPE_TEST_RESULT, EventBuilder.TYPE_JOB_RESULT} + RESULT_TYPES = { + EventBuilder.TYPE_TEST_RESULT, + EventBuilder.TYPE_JOB_RESULT} def handle_event(self, test_event): super(XunitFormatter, self).handle_event(test_event) diff --git a/lldb/packages/Python/lldbsuite/test_event/test/src/TestCatchInvalidDecorator.py b/lldb/packages/Python/lldbsuite/test_event/test/src/TestCatchInvalidDecorator.py index 56814416c33..5b199defc5d 100644 --- a/lldb/packages/Python/lldbsuite/test_event/test/src/TestCatchInvalidDecorator.py +++ b/lldb/packages/Python/lldbsuite/test_event/test/src/TestCatchInvalidDecorator.py @@ -63,7 +63,7 @@ def _filter_error_results(events): for event in events if event.get("event", None) in ["job_result", "test_result"] and event.get("status", None) == "error" - ] + ] if __name__ == "__main__": diff --git a/lldb/packages/Python/lldbsuite/test_event/test/src/event_collector.py b/lldb/packages/Python/lldbsuite/test_event/test/src/event_collector.py index 35d13206689..6b64cc71ac6 100644 --- a/lldb/packages/Python/lldbsuite/test_event/test/src/event_collector.py +++ b/lldb/packages/Python/lldbsuite/test_event/test/src/event_collector.py @@ -65,9 +65,9 @@ def collect_events_whole_file(test_filename): "--inferior", "--results-formatter=lldbsuite.test_event.formatter.pickled.RawPickledFormatter", "--results-file={}".format(events_filename), - "-p", os.path.basename(test_filename), - os.path.dirname(test_filename) - ] + "-p", + os.path.basename(test_filename), + os.path.dirname(test_filename)] return _collect_events_with_command(command, events_filename) @@ -79,7 +79,7 @@ def collect_events_for_directory_with_filter(test_filename, filter_desc): "--inferior", "--results-formatter=lldbsuite.test_event.formatter.pickled.RawPickledFormatter", "--results-file={}".format(events_filename), - "-f", filter_desc, - os.path.dirname(test_filename) - ] + "-f", + filter_desc, + os.path.dirname(test_filename)] return _collect_events_with_command(command, events_filename) |