Esempio n. 1
0
 def setUp(self):
     lldbtest.TestBase.setUp(self)
     self.main_source = "main.swift"
     self.main_source_spec = lldb.SBFileSpec(self.main_source)
     self.line_breakpoint = lldbtest.line_number(self.main_source,
                                                 '// breakpoint')
    def do_test_depths(self):
        """This test uses a class variable in resolver.Resolver which gets set to 1 if we saw
           compile unit and 2 if we only saw modules.  If the search depth is module, you get passed just
           the modules with no comp_unit.  If the depth is comp_unit you get comp_units.  So we can use
           this to test that our callback gets called at the right depth."""

        target = self.make_target_and_import()
        extra_args = self.make_extra_args()

        file_list = lldb.SBFileSpecList()
        module_list = lldb.SBFileSpecList()
        module_list.Append(lldb.SBFileSpec("a.out"))

        # Make a breakpoint that has no __get_depth__, check that that is converted to eSearchDepthModule:
        bkpt = target.BreakpointCreateFromScript("resolver.Resolver",
                                                 extra_args, module_list,
                                                 file_list)
        self.assertTrue(bkpt.GetNumLocations() > 0,
                        "Resolver got no locations.")
        self.expect("script print(resolver.Resolver.got_files)",
                    substrs=["2"],
                    msg="Was only passed modules")

        # Make a breakpoint that asks for modules, check that we didn't get any files:
        bkpt = target.BreakpointCreateFromScript(
            "resolver.ResolverModuleDepth", extra_args, module_list, file_list)
        self.assertTrue(bkpt.GetNumLocations() > 0,
                        "ResolverModuleDepth got no locations.")
        self.expect("script print(resolver.Resolver.got_files)",
                    substrs=["2"],
                    msg="Was only passed modules")

        # Make a breakpoint that asks for compile units, check that we didn't get any files:
        bkpt = target.BreakpointCreateFromScript("resolver.ResolverCUDepth",
                                                 extra_args, module_list,
                                                 file_list)
        self.assertTrue(bkpt.GetNumLocations() > 0,
                        "ResolverCUDepth got no locations.")
        self.expect("script print(resolver.Resolver.got_files)",
                    substrs=["1"],
                    msg="Was passed compile units")

        # Make a breakpoint that returns a bad value - we should convert that to "modules" so check that:
        bkpt = target.BreakpointCreateFromScript("resolver.ResolverBadDepth",
                                                 extra_args, module_list,
                                                 file_list)
        self.assertTrue(bkpt.GetNumLocations() > 0,
                        "ResolverBadDepth got no locations.")
        self.expect("script print(resolver.Resolver.got_files)",
                    substrs=["2"],
                    msg="Was only passed modules")

        # Make a breakpoint that searches at function depth:
        bkpt = target.BreakpointCreateFromScript("resolver.ResolverFuncDepth",
                                                 extra_args, module_list,
                                                 file_list)
        self.assertTrue(bkpt.GetNumLocations() > 0,
                        "ResolverFuncDepth got no locations.")
        self.expect("script print(resolver.Resolver.got_files)",
                    substrs=["3"],
                    msg="Was only passed modules")
        self.expect("script print(resolver.Resolver.func_list)",
                    substrs=['test_func', 'break_on_me', 'main'],
                    msg="Saw all the functions")
Esempio n. 3
0
    def test_with_python_api(self):
        """Test stepping and setting breakpoints in indirect and re-exported symbols."""
        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)

        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)
        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())

        self.assertTrue(process, PROCESS_IS_VALID)

        # The stop reason of the thread should be breakpoint.
        threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1)
        if len(threads) != 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.
        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.")
        curr_function = thread.GetFrameAtIndex(0).GetFunctionName()
        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())

        # 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:
        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.")
        curr_function = thread.GetFrameAtIndex(0).GetFunctionName()
        self.assertTrue(curr_function == "call_through_indirect_hidden",
                        "Stepped into indirect symbols.")
Esempio n. 4
0
    def address_breakpoints(self):
        """Test address breakpoints set with shared library of SBAddress work correctly."""
        exe = os.path.join(os.getcwd(), "a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        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"))
        self.assertTrue(breakpoint and breakpoint.GetNumLocations() >= 1,
                        VALID_BREAKPOINT)

        # Get the breakpoint location from breakpoint after we verified that,
        # indeed, it has one location.
        location = breakpoint.GetLocationAtIndex(0)
        self.assertTrue(location and location.IsEnabled(),
                        VALID_BREAKPOINT_LOCATION)

        # Next get the address from the location, and create an address breakpoint using
        # that address:

        address = location.GetAddress()
        target.BreakpointDelete(breakpoint.GetID())

        breakpoint = target.BreakpointCreateBySBAddress(address)

        # Disable ASLR.  This will allow us to actually test (on platforms that support this flag)
        # that the breakpoint was able to track the module.

        launch_info = lldb.SBLaunchInfo(None)
        flags = launch_info.GetLaunchFlags()
        flags &= ~lldb.eLaunchFlagDisableASLR
        launch_info.SetLaunchFlags(flags)

        error = lldb.SBError()

        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")

        # The hit count for the breakpoint should be 1.
        self.assertTrue(breakpoint.GetHitCount() == 1)

        process.Kill()

        # Now re-launch and see that we hit the breakpoint again:
        launch_info.Clear()
        launch_info.SetLaunchFlags(flags)

        process = target.Launch(launch_info, error)
        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")

        # The hit count for the breakpoint should now be 2.
        self.assertTrue(breakpoint.GetHitCount() == 2)
 def setUp(self):
     TestBase.setUp(self)
     self.main_source = "main.swift"
     self.main_source_spec = lldb.SBFileSpec(self.main_source)
Esempio n. 6
0
 def test_python_os_plugin(self):
     """Test that stepping works when the OS Plugin doesn't report all
        threads at every stop"""
     self.build()
     self.main_file = lldb.SBFileSpec('main.cpp')
     self.run_python_os_step_missing_thread(False)
    def test_swift_deployment_target(self):
        self.build()

        lldbutil.run_to_source_breakpoint(self, "break here",
                                          lldb.SBFileSpec('main.swift'))
        self.expect("p f", substrs=['i = 23'])
Esempio n. 8
0
    def setUp(self):
        # Call super's setUp().
        TestBase.setUp(self)

        self.main_source = "wait-a-while.cpp"
        self.main_source_spec = lldb.SBFileSpec(self.main_source)
Esempio n. 9
0
    def test_evaluate_expression_python(self):
        """Test SBFrame.EvaluateExpression() API for evaluating an expression."""
        self.buildDefault()

        exe = os.path.join(os.getcwd(), "a.out")

        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        # Create the breakpoint.
        filespec = lldb.SBFileSpec("main.cpp", False)
        breakpoint = target.BreakpointCreateByLocation(filespec, self.line)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)

        # Verify the breakpoint just created.
        self.expect(str(breakpoint),
                    BREAKPOINT_CREATED,
                    exe=False,
                    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())

        if not process:
            self.fail("SBTarget.LaunchProcess() failed")

        if process.GetState() != lldb.eStateStopped:
            self.fail("Process should be in the 'stopped' state, "
                      "instead the actual state is: '%s'" %
                      lldbutil.state_type_to_str(process.GetState()))

        # The stop reason of the thread should be breakpoint.
        thread = process.GetThreadAtIndex(0)
        if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
            from lldbutil import stop_reason_to_str
            self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
                      stop_reason_to_str(thread.GetStopReason()))

        # 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")
        self.expect(lldbutil.get_function_names(thread)[0],
                    "Break correctly at main()",
                    exe=False,
                    startstr="main")

        # We should be stopped on the breakpoint with a hit count of 1.
        self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE)

        #
        # Use Python API to evaluate expressions while stopped in a stack frame.
        #
        frame = thread.GetFrameAtIndex(0)

        val = frame.EvaluateExpression("2.234")
        self.expect(val.GetValue(),
                    "2.345 evaluated correctly",
                    exe=False,
                    startstr="2.234")
        self.expect(val.GetTypeName(),
                    "2.345 evaluated correctly",
                    exe=False,
                    startstr="double")
        self.DebugSBValue(val)

        val = frame.EvaluateExpression("argc")
        self.expect(val.GetValue(),
                    "Argc evaluated correctly",
                    exe=False,
                    startstr="4")
        self.DebugSBValue(val)

        val = frame.EvaluateExpression("*argv[1]")
        self.expect(val.GetValue(),
                    "Argv[1] evaluated correctly",
                    exe=False,
                    startstr="'X'")
        self.DebugSBValue(val)

        val = frame.EvaluateExpression("*argv[2]")
        self.expect(val.GetValue(),
                    "Argv[2] evaluated correctly",
                    exe=False,
                    startstr="'Y'")
        self.DebugSBValue(val)

        val = frame.EvaluateExpression("*argv[3]")
        self.expect(val.GetValue(),
                    "Argv[3] evaluated correctly",
                    exe=False,
                    startstr="'Z'")
        self.DebugSBValue(val)

        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)

        # 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)
Esempio n. 10
0
 def test_thread_state_after_expr(self):
     self.build()
     self.main_source_file = lldb.SBFileSpec("main.cpp")
     self.do_test()
Esempio n. 11
0
    def do_test(self, use_target_create):
        self.absent_file = '/nosuch_dir/nosuch_subdir/nosuch_executable'
        self.a_packet_file = None
        class MyResponder(MockGDBServerResponder):
            def __init__(self, testcase):
                MockGDBServerResponder.__init__(self)
                self.after_launch = False
                self.testcase = testcase
                self.current_thread = 0
                
            def A(self, packet):
                # This is the main test, we want to see that lldb DID send the
                # A packet to get debugserver to load the file.
                # Skip the length and second length:
                print("Got A packet: {0}".format(packet))
                a_arr = packet.split(",")
                self.testcase.a_packet_file = bytearray.fromhex(a_arr[2]).decode()
                return "OK"

            def qXferRead(self, obj, annex, offset, length):
                if annex == "target.xml":
                    return """<?xml version="1.0"?>
                        <target version="1.0">
                          <architecture>i386:x86-64</architecture>
                          <feature name="org.gnu.gdb.i386.core">
                            <reg name="rip" bitsize="64" regnum="0" type="code_ptr" group="general"/>
                          </feature>
                        </target>""", False
                else:
                    return None, False

            def qC(self):
                if not self.after_launch:
                    return "QC0"
                return "0"

            def qfThreadInfo(self):
                if not self.after_launch:
                    return "OK"
                return "m0"

            def qsThreadInfo(self):
                if not self.after_launch:
                    return "OK"
                return "l"

            def qLaunchSuccess(self):
                return "OK"

            def qProcessInfo(self):
                return "$pid:10b70;parent-pid:10b20;real-uid:1f6;real-gid:14;effective-uid:1f6;effective-gid:14;cputype:1000007;cpusubtype:8;ptrsize:8;ostype:macosx;vendor:apple;endian:little;"

            
        error = lldb.SBError()
        self.server.responder = MyResponder(self)
        target = lldb.SBTarget()
        if (use_target_create):
            create_cmd = "target create --arch x86_64-apple-macosx --platform remote-macosx --remote-file {0}".format(self.absent_file)
            self.runCmd(create_cmd)
            target = self.dbg.GetSelectedTarget()
            self.assertTrue(target.IsValid(), "Made a valid target")
        else:
            target = self.dbg.CreateTarget(None, "x86_64-apple-macosx", "remote-macosx", False, error)
            self.assertSuccess(error, "Made a valid target")

        launch_info = target.GetLaunchInfo()
        if (not use_target_create):
            launch_info.SetExecutableFile(lldb.SBFileSpec(self.absent_file), True)
        flags = launch_info.GetLaunchFlags()
        flags |= lldb.eLaunchFlagStopAtEntry
        launch_info.SetLaunchFlags(flags)

        process = self.connect(target)
        self.assertTrue(process.IsValid(), "Process is valid")

        # We need to fetch the connected event:
        lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected])

        self.server.responder.after_launch = True

        process = target.Launch(launch_info, error)

        self.assertSuccess(error, "Successfully launched.")
        self.assertEqual(process.GetState(), lldb.eStateStopped, "Should be stopped at entry")
        self.assertIsNotNone(self.a_packet_file, "A packet was sent")
        self.assertEqual(self.absent_file, self.a_packet_file, "The A packet file was correct")
    def do_test(self):
        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))
        self.assertTrue(breakpoint, VALID_BREAKPOINT)

        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)

        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.expect("frame variable argv[1]", substrs=['file1.txt'])
        self.expect("frame variable argv[2]", substrs=['file2.txt'])
        self.expect("frame variable argv[3]", substrs=['file3.txt'])
        self.expect("frame variable argv[4]", substrs=['file4.txy'])
        self.expect("frame variable argv[5]",
                    substrs=['file5.tyx'],
                    matching=False)

        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)

        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.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)

        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.expect("frame variable argv[1]", substrs=['foo bar'])
Esempio n. 13
0
 def test_allow_jit_options(self):
     """Test the SetAllowJIT SBExpressionOption setting"""
     self.build()
     self.main_source_file = lldb.SBFileSpec("main.c")
     self.expr_options_test()
Esempio n. 14
0
 def test_allow_jit_expr_command(self):
     """Test the --allow-jit command line flag"""
     self.build()
     self.main_source_file = lldb.SBFileSpec("main.c")
     self.expr_cmd_test()
Esempio n. 15
0
    def test(self):
        self.build()
        exe = self.getBuildArtifact("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))
        self.assertTrue(breakpoint, VALID_BREAKPOINT)

        # Ensure we do the expansion with /bin/sh on POSIX.
        os.environ["SHELL"] = '/bin/sh'

        self.runCmd("process launch -X true -w %s -- fi*.tx? () > <" %
                    (self.getSourceDir()))

        process = self.process()

        self.assertEquals(process.GetState(), lldb.eStateStopped,
                          STOPPED_DUE_TO_BREAKPOINT)

        thread = process.GetThreadAtIndex(0)

        self.assertTrue(
            thread.IsValid(),
            "Process stopped at 'main' should have a valid thread")

        stop_reason = thread.GetStopReason()

        self.assertEqual(
            stop_reason, lldb.eStopReasonBreakpoint,
            "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint"
        )

        self.expect_var_path("argv[1]", summary='"file1.txt"')
        self.expect_var_path("argv[2]", summary='"file2.txt"')
        self.expect_var_path("argv[3]", summary='"file3.txt"')
        self.expect_var_path("argv[4]", summary='"file4.txy"')
        self.expect_var_path("argv[5]", summary='"()"')
        self.expect_var_path("argv[6]", summary='">"')
        self.expect_var_path("argv[7]", summary='"<"')
        self.expect_var_path("argc", value='8')

        self.runCmd("process kill")

        self.runCmd('process launch -X true -w %s -- "foo bar"' %
                    (self.getSourceDir()))

        process = self.process()

        self.assertEquals(process.GetState(), lldb.eStateStopped,
                          STOPPED_DUE_TO_BREAKPOINT)

        thread = process.GetThreadAtIndex(0)

        self.assertTrue(
            thread.IsValid(),
            "Process stopped at 'main' should have a valid thread")

        stop_reason = thread.GetStopReason()

        self.assertEqual(
            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' %
                    (self.getBuildDir()))

        process = self.process()

        self.assertEquals(process.GetState(), lldb.eStateStopped,
                          STOPPED_DUE_TO_BREAKPOINT)

        thread = process.GetThreadAtIndex(0)

        self.assertTrue(
            thread.IsValid(),
            "Process stopped at 'main' should have a valid thread")

        stop_reason = thread.GetStopReason()

        self.assertEqual(
            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'])
Esempio n. 16
0
    def test_with_python_api(self):
        """Test that adding, deleting and modifying watchpoints sends the appropriate events."""
        self.build()

        exe = self.getBuildArtifact("a.out")

        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        self.main_source_spec = lldb.SBFileSpec(self.main_source)

        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())

        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)

        if len(threads) != 1:
            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())

        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)

        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.GetWatchpointEvent(lldb.eWatchpointEventTypeAdded)
        # Now change some of the features of this watchpoint and make sure we
        # get events:
        local_watch.SetEnabled(False)
        self.GetWatchpointEvent(lldb.eWatchpointEventTypeDisabled)

        local_watch.SetEnabled(True)
        self.GetWatchpointEvent(lldb.eWatchpointEventTypeEnabled)

        local_watch.SetIgnoreCount(10)
        self.GetWatchpointEvent(lldb.eWatchpointEventTypeIgnoreChanged)

        condition = "1 == 2"
        local_watch.SetCondition(condition)
        self.GetWatchpointEvent(lldb.eWatchpointEventTypeConditionChanged)

        self.assertTrue(
            local_watch.GetCondition() == condition,
            'make sure watchpoint condition is "' + condition + '"')
Esempio n. 17
0
    def test_breakpint_in_member_func_w_non_primitie_params(self):
        self.build()
        lldbutil.run_to_source_breakpoint(self, '// break here',
                                          lldb.SBFileSpec("main.cpp", False))

        self.runCmd("b a.cpp:11")
Esempio n. 18
0
    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."
            )

        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.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())

        self.assertTrue(process, PROCESS_IS_VALID)

        # The stop reason of the thread should be breakpoint.
        threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1)
        if len(threads) != 1:
            self.fail("Failed to stop at breakpoint 1.")

        libbtr_module_filespec = lldb.SBFileSpec("libBacktraceRecording.dylib")
        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.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")
Esempio n. 19
0
 def test_python_os_plugin_prune(self):
     """Test that pruning the unreported PlanStacks works"""
     self.build()
     self.main_file = lldb.SBFileSpec('main.cpp')
     self.run_python_os_step_missing_thread(True)
Esempio n. 20
0
    def queues(self):
        """Test queues inspection SB APIs without libBacktraceRecording."""
        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)
        break1 = target.BreakpointCreateByName("stopper", 'a.out')
        self.assertTrue(break1, VALID_BREAKPOINT)
        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)
        if len(threads) != 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)

        # We have threads running with all the different dispatch QoS service
        # levels - find those threads and check that we can get the correct
        # QoS name for each of them.

        user_initiated_thread = lldb.SBThread()
        user_interactive_thread = lldb.SBThread()
        utility_thread = lldb.SBThread()
        unspecified_thread = lldb.SBThread()
        background_thread = lldb.SBThread()
        for th in process.threads:
            if th.GetName() == "user initiated QoS":
                user_initiated_thread = th
            if th.GetName() == "user interactive QoS":
                user_interactive_thread = th
            if th.GetName() == "utility QoS":
                utility_thread = th
            if th.GetName() == "unspecified QoS":
                unspecified_thread = th
            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(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")

        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")
        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")
        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")
        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")
        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")
Esempio n. 21
0
    def test_and_python_api(self):
        """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms."""
        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)

        breakpoints_to_disable = []

        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)

        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)

        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)

        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)

        # Now launch the process, and do not stop at entry point.
        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)

        if len(threads) != 1:
            self.fail ("Failed to stop at first breakpoint in main.")

        thread = threads[0]

        # Get the stop id and for fun make sure it increases:
        old_stop_id = process.GetStopID()

        # Now step over, which should cause us to hit the breakpoint in "a"
        thread.StepOver()

        # The stop reason of the thread should be breakpoint.
        threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_a)
        if len(threads) != 1:
            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.")

        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)
        if len(threads) != 1:
            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
        # and with the same stop reason.
        frame = thread.GetFrameAtIndex(0)
        current_line = frame.GetLineEntry().GetLine()
        current_file = frame.GetLineEntry().GetFileSpec()
        current_bp = []
        current_bp.append(thread.GetStopReasonDataAtIndex(0))
        current_bp.append(thread.GetStopReasonDataAtIndex(1))

        stop_id_before_expression = process.GetStopID()
        stop_id_before_including_expressions = process.GetStopID(True)

        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.")
        
        # 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_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.

        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.")

        # 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
        # breakpoint a "b" and we don't want to hit that.
        for bkpt in breakpoints_to_disable:
            bkpt.SetEnabled(False)

        process.Continue()

        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)

        # 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()
        current_file = frame.GetLineEntry().GetFileSpec()

        break_in_b.SetEnabled(True)
        frame.EvaluateExpression ("b (4)", lldb.eNoDynamicValues, False)

        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.")
        thread = threads[0]

        # So do a step over here to make sure we can still do that:

        thread.StepOver()

        # See that we are still in b:
        func_name = thread.GetFrameAtIndex(0).GetFunctionName()
        self.assertTrue (func_name == "b", "Should be in 'b', were in {0!s}".format((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 ()

        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_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)
        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)
        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)
        self.assertTrue(break_before_complex_4, VALID_BREAKPOINT)

        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")

        # 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 = threads[0]
        break_before_complex_3.SetEnabled(False)

        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);

        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())

        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)
        thread = threads[0]
        break_before_complex_4.SetEnabled(False)

        thread.StepInto("NoSuchFunction")
        self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "main")
Esempio n. 22
0
 def do_check_consistency(self):
     """Check formatting for T? and T!"""
     self.build()
     lldbutil.run_to_source_breakpoint(self, 'Set breakpoint here',
                                       lldb.SBFileSpec('main.swift'))
Esempio n. 23
0
    def test_with_multiple_retries(self):
        """Test calling expressions with errors that can be fixed by the FixIts."""
        self.build()
        (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self,
                                        'Stop here to evaluate expressions',
                                         lldb.SBFileSpec("main.cpp"))

        # Test repeatedly applying Fix-Its to expressions and reparsing them.
        multiple_runs_options = lldb.SBExpressionOptions()
        multiple_runs_options.SetAutoApplyFixIts(True)
        multiple_runs_options.SetTopLevel(True)

        frame = self.thread.GetFrameAtIndex(0)

        # An expression that needs two parse attempts with one Fix-It each
        # to be successfully parsed.
        two_runs_expr = """
        struct Data { int m; };

        template<typename T>
        struct S1 : public T {
          using T::TypeDef;
          int f() {
            Data data;
            data.m = 123;
            // The first error as the using above requires a 'typename '.
            // Will trigger a Fix-It that puts 'typename' in the right place.
            typename S1<T>::TypeDef i = &data;
            // i has the type "Data *", so this should be i.m.
            // The second run will change the . to -> via the Fix-It.
            return i.m;
          }
        };

        struct ClassWithTypeDef {
          typedef Data *TypeDef;
        };

        int test_X(int i) {
          S1<ClassWithTypeDef> s1;
          return s1.f();
        }
        """

        # Disable retries which will fail.
        multiple_runs_options.SetRetriesWithFixIts(0)
        value = frame.EvaluateExpression(two_runs_expr, multiple_runs_options)
        errmsg = value.GetError().GetCString()
        self.assertIn("expression failed to parse", errmsg)
        self.assertIn("using declaration resolved to type without 'typename'",
                      errmsg)
        self.assertIn("fixed expression suggested:", errmsg)
        self.assertIn("using typename T::TypeDef", errmsg)
        # The second Fix-It shouldn't be suggested here as Clang should have
        # aborted the parsing process.
        self.assertNotIn("i->m", errmsg)

        # Retry once, but the expression needs two retries.
        multiple_runs_options.SetRetriesWithFixIts(1)
        value = frame.EvaluateExpression(two_runs_expr, multiple_runs_options)
        errmsg = value.GetError().GetCString()
        self.assertIn("expression failed to parse", errmsg)
        self.assertIn("fixed expression suggested:", errmsg)
        # Both our fixed expressions should be in the suggested expression.
        self.assertIn("using typename T::TypeDef", errmsg)
        self.assertIn("i->m", errmsg)

        # Retry twice, which will get the expression working.
        multiple_runs_options.SetRetriesWithFixIts(2)
        value = frame.EvaluateExpression(two_runs_expr, multiple_runs_options)
        # This error signals success for top level expressions.
        self.assertEquals(value.GetError().GetCString(), "error: No value")

        # Test that the code above compiles to the right thing.
        self.expect_expr("test_X(1)", result_type="int", result_value="123")
    def test_with_run_command(self):
        """Test that that file and class static variables display correctly."""
        self.build()
        (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint(
            self, "Set break point at this line.",
            lldb.SBFileSpec("main.cpp", False))

        # 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('type filter clear', check=False)
            self.runCmd('type synth clear', 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)

        ii_type = self.getVariableType("ii")
        self.assertTrue(ii_type.startswith(self.namespace + "::multiset"),
                        "Type: " + ii_type)

        self.expect("frame variable ii", substrs=["size=0", "{}"])
        lldbutil.continue_to_breakpoint(process, bkpt)
        self.expect("frame variable ii",
                    substrs=[
                        "size=6", "[0] = 0", "[1] = 1", "[2] = 2", "[3] = 3",
                        "[4] = 4", "[5] = 5"
                    ])
        lldbutil.continue_to_breakpoint(process, bkpt)

        self.check_ii("ii")

        lldbutil.continue_to_breakpoint(process, bkpt)
        self.expect("frame variable ii", substrs=["size=0", "{}"])
        lldbutil.continue_to_breakpoint(process, bkpt)
        self.expect("frame variable ii", substrs=["size=0", "{}"])
        ss_type = self.getVariableType("ss")
        self.assertTrue(ss_type.startswith(self.namespace + "::multiset"),
                        "Type: " + ss_type)
        self.expect("frame variable ss", substrs=["size=0", "{}"])
        lldbutil.continue_to_breakpoint(process, bkpt)
        self.expect("frame variable ss",
                    substrs=[
                        "size=2", '[0] = "a"',
                        '[1] = "a very long string is right here"'
                    ])
        lldbutil.continue_to_breakpoint(process, bkpt)
        self.expect("frame variable ss",
                    substrs=[
                        "size=4",
                        '[0] = "a"',
                        '[1] = "a very long string is right here"',
                        '[2] = "b"',
                        '[3] = "c"',
                    ])
        self.expect("p ss",
                    substrs=[
                        "size=4",
                        '[0] = "a"',
                        '[1] = "a very long string is right here"',
                        '[2] = "b"',
                        '[3] = "c"',
                    ])
        self.expect("frame variable ss[2]", substrs=[' = "b"'])
        lldbutil.continue_to_breakpoint(process, bkpt)
        self.expect("frame variable ss",
                    substrs=[
                        "size=3", '[0] = "a"',
                        '[1] = "a very long string is right here"', '[2] = "c"'
                    ])
Esempio n. 25
0
    def test_objc_exceptions_at_throw(self):
        self.build()

        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
        self.assertTrue(target, VALID_TARGET)

        launch_info = lldb.SBLaunchInfo(["a.out", "0"])
        launch_info.SetLaunchFlags(lldb.eLaunchFlagInheritTCCFromParent)
        lldbutil.run_to_name_breakpoint(self,
                                        "objc_exception_throw",
                                        launch_info=launch_info)

        self.expect(
            "thread list",
            substrs=['stopped', 'stop reason = hit Objective-C exception'])

        self.expect('thread exception',
                    substrs=[
                        '(NSException *) exception = ',
                        '"SomeReason"',
                    ])

        target = self.dbg.GetSelectedTarget()
        thread = target.GetProcess().GetSelectedThread()
        frame = thread.GetSelectedFrame()

        opts = lldb.SBVariablesOptions()
        opts.SetIncludeRecognizedArguments(True)
        variables = frame.GetVariables(opts)

        self.assertEqual(variables.GetSize(), 1)
        self.assertEqual(variables.GetValueAtIndex(0).name, "exception")
        self.assertEqual(
            variables.GetValueAtIndex(0).GetValueType(),
            lldb.eValueTypeVariableArgument)

        lldbutil.run_to_source_breakpoint(self,
                                          "// Set break point at this line.",
                                          lldb.SBFileSpec("main.mm"),
                                          launch_info=launch_info)

        self.expect("thread list",
                    STOPPED_DUE_TO_BREAKPOINT,
                    substrs=['stopped', 'stop reason = breakpoint'])

        target = self.dbg.GetSelectedTarget()
        thread = target.GetProcess().GetSelectedThread()
        frame = thread.GetSelectedFrame()

        # No exception being currently thrown/caught at this point
        self.assertFalse(thread.GetCurrentException().IsValid())
        self.assertFalse(thread.GetCurrentExceptionBacktrace().IsValid())

        self.expect('frame variable e1',
                    substrs=['(NSException *) e1 = ', '"SomeReason"'])

        self.expect('frame variable --dynamic-type no-run-target *e1',
                    substrs=[
                        '(NSException) *e1 = ',
                        'name = ',
                        '"ExceptionName"',
                        'reason = ',
                        '"SomeReason"',
                        'userInfo = ',
                        '1 key/value pair',
                        'reserved = ',
                        'nil',
                    ])

        e1 = frame.FindVariable("e1")
        self.assertTrue(e1)
        self.assertEqual(e1.type.name, "NSException *")
        self.assertEqual(e1.GetSummary(), '"SomeReason"')
        self.assertEqual(
            e1.GetChildMemberWithName("name").description, "ExceptionName")
        self.assertEqual(
            e1.GetChildMemberWithName("reason").description, "SomeReason")
        userInfo = e1.GetChildMemberWithName("userInfo").dynamic
        self.assertEqual(userInfo.summary, "1 key/value pair")
        self.assertEqual(
            userInfo.GetChildAtIndex(0).GetChildAtIndex(0).description,
            "some_key")
        self.assertEqual(
            userInfo.GetChildAtIndex(0).GetChildAtIndex(1).description,
            "some_value")
        self.assertEqual(
            e1.GetChildMemberWithName("reserved").description, "<nil>")

        self.expect('frame variable e2',
                    substrs=['(NSException *) e2 = ', '"SomeReason"'])

        self.expect('frame variable --dynamic-type no-run-target *e2',
                    substrs=[
                        '(NSException) *e2 = ',
                        'name = ',
                        '"ThrownException"',
                        'reason = ',
                        '"SomeReason"',
                        'userInfo = ',
                        '1 key/value pair',
                        'reserved = ',
                    ])

        e2 = frame.FindVariable("e2")
        self.assertTrue(e2)
        self.assertEqual(e2.type.name, "NSException *")
        self.assertEqual(e2.GetSummary(), '"SomeReason"')
        self.assertEqual(
            e2.GetChildMemberWithName("name").description, "ThrownException")
        self.assertEqual(
            e2.GetChildMemberWithName("reason").description, "SomeReason")
        userInfo = e2.GetChildMemberWithName("userInfo").dynamic
        self.assertEqual(userInfo.summary, "1 key/value pair")
        self.assertEqual(
            userInfo.GetChildAtIndex(0).GetChildAtIndex(0).description,
            "some_key")
        self.assertEqual(
            userInfo.GetChildAtIndex(0).GetChildAtIndex(1).description,
            "some_value")
        reserved = e2.GetChildMemberWithName("reserved").dynamic
        self.assertGreater(reserved.num_children, 0)
        callStackReturnAddresses = [
            reserved.GetChildAtIndex(i).GetChildAtIndex(1)
            for i in range(0, reserved.GetNumChildren())
            if reserved.GetChildAtIndex(i).GetChildAtIndex(0).description ==
            "callStackReturnAddresses"
        ][0].dynamic
        children = [
            callStackReturnAddresses.GetChildAtIndex(i)
            for i in range(0, callStackReturnAddresses.num_children)
        ]

        pcs = [i.unsigned for i in children]
        names = [
            target.ResolveSymbolContextForAddress(lldb.SBAddress(
                pc, target), lldb.eSymbolContextSymbol).GetSymbol().name
            for pc in pcs
        ]
        for n in ["objc_exception_throw", "foo(int)", "main"]:
            self.assertIn(n, names,
                          "%s is in the exception backtrace (%s)" % (n, names))
Esempio n. 26
0
    def do_test(self, skip_exec):
        self.build()
        exe = self.getBuildArtifact("a.out")
        secondprog = self.getBuildArtifact("secondprog")

        # Create the target
        target = self.dbg.CreateTarget(exe)

        # Create any breakpoints we need
        breakpoint1 = target.BreakpointCreateBySourceRegex(
            'Set breakpoint 1 here', lldb.SBFileSpec("main.cpp", False))
        self.assertTrue(breakpoint1, VALID_BREAKPOINT)
        breakpoint2 = target.BreakpointCreateBySourceRegex(
            'Set breakpoint 2 here', lldb.SBFileSpec("secondprog.cpp", False))
        self.assertTrue(breakpoint2, VALID_BREAKPOINT)

        # Launch the process
        process = target.LaunchSimple(None, None,
                                      self.get_process_working_directory())
        self.assertTrue(process, PROCESS_IS_VALID)

        if self.TraceOn():
            self.runCmd("settings show target.process.stop-on-exec",
                        check=False)
        if skip_exec:
            self.dbg.HandleCommand(
                "settings set target.process.stop-on-exec false")

            def cleanup():
                self.runCmd("settings set target.process.stop-on-exec false",
                            check=False)

            # Execute the cleanup function during test case tear down.
            self.addTearDownHook(cleanup)

        # 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, breakpoint1)
        self.assertTrue(len(threads) == 1)

        # We had a deadlock tearing down the TypeSystemMap on exec, but only if some
        # expression had been evaluated.  So make sure we do that here so the teardown
        # is not trivial.

        thread = threads[0]
        value = thread.frames[0].EvaluateExpression("1 + 2")
        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()

        if not skip_exec:
            self.assertFalse(process.GetState() == lldb.eStateExited,
                             "Process should not have exited!")
            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_threads_stopped_at_breakpoint(
            process, breakpoint2)
        if self.TraceOn():
            for t in process.threads:
                print(t)
                if t.GetStopReason() != lldb.eStopReasonBreakpoint:
                    self.runCmd("bt")
        self.assertTrue(
            len(threads) == 1, "Stopped at breakpoint in exec'ed process.")
    def do_test(self):
        """This reads in a python file and sets a breakpoint using it."""

        target = self.make_target_and_import()
        extra_args = self.make_extra_args()

        file_list = lldb.SBFileSpecList()
        module_list = lldb.SBFileSpecList()

        # Make breakpoints with this resolver using different filters, first ones that will take:
        right = []
        # one with no file or module spec - this one should fire:
        right.append(
            target.BreakpointCreateFromScript("resolver.Resolver", extra_args,
                                              module_list, file_list))

        # one with the right source file and no module - should also fire:
        file_list.Append(lldb.SBFileSpec("main.c"))
        right.append(
            target.BreakpointCreateFromScript("resolver.Resolver", extra_args,
                                              module_list, file_list))
        # Make sure the help text shows up in the "break list" output:
        self.expect("break list",
                    substrs=["I am a python breakpoint resolver"],
                    msg="Help is listed in break list")

        # one with the right source file and right module - should also fire:
        module_list.Append(lldb.SBFileSpec("a.out"))
        right.append(
            target.BreakpointCreateFromScript("resolver.Resolver", extra_args,
                                              module_list, file_list))

        # And one with no source file but the right module:
        file_list.Clear()
        right.append(
            target.BreakpointCreateFromScript("resolver.Resolver", extra_args,
                                              module_list, file_list))

        # Make sure these all got locations:
        for i in range(0, len(right)):
            self.assertTrue(right[i].GetNumLocations() >= 1,
                            "Breakpoint %d has no locations." % (i))

        # Now some ones that won't take:

        module_list.Clear()
        file_list.Clear()
        wrong = []

        # one with the wrong module - should not fire:
        module_list.Append(lldb.SBFileSpec("noSuchModule"))
        wrong.append(
            target.BreakpointCreateFromScript("resolver.Resolver", extra_args,
                                              module_list, file_list))

        # one with the wrong file - also should not fire:
        file_list.Clear()
        module_list.Clear()
        file_list.Append(lldb.SBFileSpec("noFileOfThisName.xxx"))
        wrong.append(
            target.BreakpointCreateFromScript("resolver.Resolver", extra_args,
                                              module_list, file_list))

        # Now make sure the CU level iteration obeys the file filters:
        file_list.Clear()
        module_list.Clear()
        file_list.Append(lldb.SBFileSpec("no_such_file.xxx"))
        wrong.append(
            target.BreakpointCreateFromScript("resolver.ResolverCUDepth",
                                              extra_args, module_list,
                                              file_list))

        # And the Module filters:
        file_list.Clear()
        module_list.Clear()
        module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib"))
        wrong.append(
            target.BreakpointCreateFromScript("resolver.ResolverCUDepth",
                                              extra_args, module_list,
                                              file_list))

        # Now make sure the Function level iteration obeys the file filters:
        file_list.Clear()
        module_list.Clear()
        file_list.Append(lldb.SBFileSpec("no_such_file.xxx"))
        wrong.append(
            target.BreakpointCreateFromScript("resolver.ResolverFuncDepth",
                                              extra_args, module_list,
                                              file_list))

        # And the Module filters:
        file_list.Clear()
        module_list.Clear()
        module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib"))
        wrong.append(
            target.BreakpointCreateFromScript("resolver.ResolverFuncDepth",
                                              extra_args, module_list,
                                              file_list))

        # Make sure these didn't get locations:
        for i in range(0, len(wrong)):
            self.assertEqual(wrong[i].GetNumLocations(), 0,
                             "Breakpoint %d has locations." % (i))

        # Now run to main and ensure we hit the breakpoints we should have:

        lldbutil.run_to_breakpoint_do_run(self, target, right[0])

        # Test the hit counts:
        for i in range(0, len(right)):
            self.assertEqual(right[i].GetHitCount(), 1,
                             "Breakpoint %d has the wrong hit count" % (i))

        for i in range(0, len(wrong)):
            self.assertEqual(wrong[i].GetHitCount(), 0,
                             "Breakpoint %d has the wrong hit count" % (i))
Esempio n. 28
0
    def do_test(self):
        target = self.createTestTarget()

        # Now create a breakpoint in main.c at the source matching
        # "Set a breakpoint here"
        breakpoint = target.BreakpointCreateBySourceRegex(
            "Set a breakpoint here", lldb.SBFileSpec("main.c"))
        self.assertTrue(breakpoint and breakpoint.GetNumLocations() >= 1,
                        VALID_BREAKPOINT)

        error = lldb.SBError()
        # This is the launch info.  If you want to launch with arguments or
        # environment variables, add them using SetArguments or
        # SetEnvironmentEntries

        launch_info = target.GetLaunchInfo()
        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.assertEqual(len(threads), 1,
                         "There should be a thread stopped at our breakpoint")

        # The hit count for the breakpoint should be 1.
        self.assertEquals(breakpoint.GetHitCount(), 1)

        frame = threads[0].GetFrameAtIndex(0)
        command_result = lldb.SBCommandReturnObject()
        interp = self.dbg.GetCommandInterpreter()

        # Just get args:
        result = interp.HandleCommand("frame var -l", command_result)
        self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult,
                         "frame var -a didn't succeed")
        output = command_result.GetOutput()
        self.assertIn("argc", output, "Args didn't find argc")
        self.assertIn("argv", output, "Args didn't find argv")
        self.assertNotIn("test_var", output, "Args found a local")
        self.assertNotIn("g_var", output, "Args found a global")

        # Just get locals:
        result = interp.HandleCommand("frame var -a", command_result)
        self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult,
                         "frame var -a didn't succeed")
        output = command_result.GetOutput()
        self.assertNotIn("argc", output, "Locals found argc")
        self.assertNotIn("argv", output, "Locals found argv")
        self.assertIn("test_var", output, "Locals didn't find test_var")
        self.assertNotIn("g_var", output, "Locals found a global")

        # Get the file statics:
        result = interp.HandleCommand("frame var -l -a -g", command_result)
        self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult,
                         "frame var -a didn't succeed")
        output = command_result.GetOutput()
        self.assertNotIn("argc", output, "Globals found argc")
        self.assertNotIn("argv", output, "Globals found argv")
        self.assertNotIn("test_var", output, "Globals found test_var")
        self.assertIn("g_var", output, "Globals didn't find g_var")
Esempio n. 29
0
 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")
Esempio n. 30
0
 def setUp(self):
     TestBase.setUp(self)
     self.main_source_file = lldb.SBFileSpec("main.c")
     self.runCmd("command script import Steps.py")