def test (self):
        self.build()

        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."] )
示例#2
0
    def test(self):
        """Test that we can backtrace correctly from Non ABI  functions on the stack"""
        self.build()
        self.setTearDownCleanup()

        exe = os.path.join(os.getcwd(), "a.out")
        target = self.dbg.CreateTarget(exe)

        self.assertTrue(target, VALID_TARGET)

        lldbutil.run_break_set_by_symbol(self, "func")

        process = target.LaunchSimple(
            ["abc", "xyz"], None, self.get_process_working_directory())

        if not process:
            self.fail("SBTarget.Launch() 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()))

        stacktraces = lldbutil.print_stacktraces(process, string_buffer=True)
        self.expect(stacktraces, exe=False,
                    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'])
    def test_and_run_command(self):
        """Display *bar_ptr when stopped on a function with forward declaration of struct bar."""
        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_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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
            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'])

        # And so should this.
        self.expect("expression --show-types -- *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY,
            substrs = ['(bar)',
                       '(int) a = 1',
                       '(int) b = 2'])
    def test_break(self):
        """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'."""
        if self.getArchitecture() != 'x86_64':
            self.skipTest("This only applies to the v2 runtime")

        self.build()
        exe = os.path.join(os.getcwd(), "a.out")
        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)

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

        # 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\)"])

        # Static methods on NSString should work.
        self.expect("expr [NSString stringWithCString:\"foo\" encoding:1]", VALID_TYPE,
            substrs = ["(id)", "$1"])

        self.expect("po $1", VARIABLES_DISPLAYED_CORRECTLY,
            substrs = ["foo"])
示例#5
0
    def test_break(self):
        """Test 'expr member' continues to work for optimized build."""
        self.build()
        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)

        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("expression member", startstr="(int) $0 = 5")

        # <rdar://problem/12693963>
        interp = self.dbg.GetCommandInterpreter()
        result = lldb.SBCommandReturnObject()
        interp.HandleCommand("frame variable self", result)
        output = result.GetOutput()

        desired_pointer = "0x0"

        mo = re.search("0x[0-9a-f]+", output)

        if mo:
            desired_pointer = mo.group(0)

        self.expect("expression (self)", substrs=[("(%s *) $1 = " % self.myclass), desired_pointer])

        self.expect("expression self->non_member", error=True, substrs=["does not have a member named 'non_member'"])
示例#6
0
    def test(self):
        """Break inside a() and b() defined within libfoo.a."""
        self.build()

        exe = self.getBuildArtifact("a.out")
        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        # Break on a() and b() symbols
        lldbutil.run_break_set_by_symbol(
            self, "a", sym_exact=True)
        lldbutil.run_break_set_by_symbol(
            self, "b", 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'])

        # Break at a(int) first.
        self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['(int) arg = 1'])
        self.expect("frame variable __a_global", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['(int) __a_global = 1'])

        # 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'])
        self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['(int) arg = 2'])
        self.expect("frame variable __b_global", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['(int) __b_global = 2'])
示例#7
0
    def test_load_unload(self):
        """Test breakpoint by name works correctly with dlopen'ing."""

        # Invoke the default build rule.
        self.build()
        self.copy_shlibs_to_remote()

        exe = os.path.join(os.getcwd(), "a.out")
        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)

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

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, 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.
        self.runCmd("continue")

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

        # The breakpoint should have a hit count of 2.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, substrs=[" resolved, hit count = 2"])
示例#8
0
    def test(self):
        """Break inside a() and b() defined within libfoo.a."""
        self.build()

        exe = os.path.join(os.getcwd(), "a.out")
        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)

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

        # Break at a(int) first.
        self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, substrs=["(int) arg = 1"])
        self.expect("frame variable __a_global", VARIABLES_DISPLAYED_CORRECTLY, 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)

        # 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"])
        self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, substrs=["(int) arg = 2"])
        self.expect("frame variable __b_global", VARIABLES_DISPLAYED_CORRECTLY, substrs=["(int) __b_global = 2"])
示例#9
0
    def test_break(self):
        """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")
        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)

        # Stop at -[MyString initWithNSString:].
        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')

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

        self.runCmd("run", RUN_SUCCEEDED)

        # First stop is +[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.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.runCmd("process continue")

        # Followed by -[MyString description].
        self.expect("thread backtrace", "Stop at -[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]"])

        self.runCmd("process continue")

        # Followed by -[NSAutoreleasePool release].
        self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]",
            substrs = ["Foundation`-[NSAutoreleasePool release]"])
示例#10
0
    def test_false(self):
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

        self.runCmd("target create %s" % exe)
        lldbutil.run_break_set_by_symbol(self, "bkpt_false",
                extra_options="--skip-prologue 0")

        self.runCmd("run")
        self.assertEqual(self.process().GetState(), lldb.eStateExited,
                "Breakpoint does not get hit")
示例#11
0
    def common_setup(self):
        exe = os.path.join(os.getcwd(), "a.out")

        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        # Break in main().
        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"])
示例#12
0
    def start_test(self, symbol):
        exe = self.getBuildArtifact("a.out")

        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        # Break in main().
        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'])
示例#13
0
    def test_watched_var_should_only_hit_when_in_scope(self):
        """Test that a variable watchpoint should only hit when in scope."""
        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 in main.
        lldbutil.run_break_set_by_symbol(
            self, "main", num_expected_locations=-1)

        # Run the program.
        self.runCmd("run", RUN_SUCCEEDED)

        # 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'])

        # 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'])

        # 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.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.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'])

        # 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'])
示例#14
0
    def test_expression_lookups_objc(self):
        """Test running an expression detect spurious debug info lookups (DWARF)."""
        self.build()
        exe = self.getBuildArtifact("a.out")
        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)

        self.runCmd("run", RUN_SUCCEEDED)

        global file_index
        # Log any DWARF lookups
        ++file_index
        logfile = os.path.join(
            self.getBuildDir(),
            "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)

        self.addTearDownHook(cleanup)

        if os.path.exists(logfile):
            f = open(logfile)
            lines = f.readlines()
            num_errors = 0
            for line in lines:
                if "$__lldb" in line:
                    if num_errors == 0:
                        print(
                            "error: found spurious name lookups when evaluating an expression:")
                    num_errors += 1
                    print(line, end='')
            self.assertTrue(num_errors == 0, "Spurious lookups detected")
            f.close()
示例#15
0
    def test_delete_all_breakpoints(self):
        """Test that deleting all breakpoints works."""
        self.build()
        exe = self.getBuildArtifact("a.out")
        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_symbol(self, "main")
        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)

        self.runCmd("breakpoint delete")
        self.runCmd("process continue")
        self.expect("process status", PROCESS_STOPPED,
                    patterns=['Process .* exited with status = 0'])
示例#16
0
    def test(self):
        """Test 'callback' has function ptr type, then break on the function."""
        self.build()
        self.runToBreakpoint()

        # Check that the 'callback' variable display properly.
        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)
        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'])
示例#17
0
    def test(self):
        """Test target.move-to-nearest logic"""

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

        lldbutil.run_break_set_by_symbol(self, 'main', sym_exact=True)
        environment = self.registerSharedLibrariesWithTarget(target, ["foo"])
        process = target.LaunchSimple(None, environment, self.get_process_working_directory())
        self.assertEquals(process.GetState(), lldb.eStateStopped)

        # Regardless of the -m value the breakpoint should have exactly one
        # location on the foo functions
        self.runCmd("settings set target.move-to-nearest-code true")
        lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line1,
                loc_exact=True, extra_options="-m 1")
        lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line2,
                loc_exact=True, extra_options="-m 1")

        self.runCmd("settings set target.move-to-nearest-code false")
        lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line1,
                loc_exact=True, extra_options="-m 0")
        lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line2,
                loc_exact=True, extra_options="-m 0")


        # Make sure we set a breakpoint in main with -m 1 for various lines in
        # the function declaration
        # "int"
        lldbutil.run_break_set_by_file_and_line(self, 'main.cpp',
                self.line_main-1, extra_options="-m 1")
        # "main()"
        lldbutil.run_break_set_by_file_and_line(self, 'main.cpp',
                self.line_main, extra_options="-m 1")
        # "{"
        lldbutil.run_break_set_by_file_and_line(self, 'main.cpp',
                self.line_main+1, extra_options="-m 1")
        # "return .."
        lldbutil.run_break_set_by_file_and_line(self, 'main.cpp',
                self.line_main+2, extra_options="-m 1")

        # Make sure we don't put move the breakpoint if it is set between two functions:
        lldbutil.run_break_set_by_file_and_line(self, 'main.cpp',
                self.line_between, extra_options="-m 1", num_expected_locations=0)
示例#18
0
    def test_static_init_during_load(self):
        """Test that we can set breakpoints correctly in static initializers"""

        self.build()
        self.copy_shlibs_to_remote()

        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)

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

        self.runCmd("continue")
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
                    substrs=['stopped',
                             'a_init',
                             'stop reason = breakpoint %d' % a_init_bp_num])
        self.expect("thread backtrace",
                    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])
        self.expect("thread backtrace",
                    substrs=['b_init',
                             'dlopen',
                             'main'])
示例#19
0
    def test_true(self):
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

        self.runCmd("target create %s" % exe)
        bpid = lldbutil.run_break_set_by_symbol(self, "bkpt_true",
                extra_options="--skip-prologue 0")

        self.runCmd("run")
        self.assertIsNotNone(lldbutil.get_one_thread_stopped_at_breakpoint_id(
            self.process(), bpid))
    def test_memory_read(self):
        self.build()
        exe = os.path.join (os.getcwd(), "a.out")

        target = self.dbg.CreateTarget(exe)
        lldbutil.run_break_set_by_symbol(self, "main")

        process = target.LaunchSimple (None, None, self.get_process_working_directory())
        self.assertTrue(process, PROCESS_IS_VALID)
        self.assertEqual(process.GetState(), lldb.eStateStopped, "Process is stopped")

        pc = process.GetSelectedThread().GetSelectedFrame().GetPC()
        for size in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
            error = lldb.SBError()
            memory = process.ReadMemory(pc, size, error)
            self.assertTrue(error.Success())
            self.match("process plugin packet send x%x,%x" % (pc, size), ["response:", memory])
            self.match("process plugin packet send m%x,%x" % (pc, size), ["response:", binascii.hexlify(memory)])

        process.Continue()
        self.assertEqual(process.GetState(), lldb.eStateExited, "Process exited")
示例#21
0
    def test_static_init_during_load(self):
        """Test that we can set breakpoints correctly in static initializers"""
        self.copy_shlibs_to_remote()

        exe = self.getBuildArtifact("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)

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

        self.runCmd("continue")
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
                    substrs=['stopped',
                             'b_init',
                             'stop reason = breakpoint %d' % b_init_bp_num])
        self.expect("thread backtrace",
                    substrs=['b_init',
                             'dlopen',
                             'main'])

        self.runCmd("continue")
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
                    substrs=['stopped',
                             'a_init',
                             'stop reason = breakpoint %d' % a_init_bp_num])
        self.expect("thread backtrace",
                    substrs=['a_init',
                             'dlopen',
                             'main'])
示例#22
0
    def test_and_run_command(self):
        """Test interpreted and JITted expressions on constant values."""
        self.build()
        exe = self.getBuildArtifact("a.out")
        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        # Break inside the main.
        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'])

        # The breakpoint should have a hit count of 1.
        lldbutil.check_breakpoint(self, bpno=1, expected_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'])

        # Try an interpreted expression.
        self.expect("expr (index + 512)",
                    VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['1024'])

        # Try a JITted expression.
        self.expect("expr (int)getpid(); (index - 256)",
                    VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['256'])

        self.runCmd("kill")
示例#23
0
    def test_load_unload(self):
        """Test breakpoint by name works correctly with dlopen'ing."""
        self.copy_shlibs_to_remote()

        exe = self.getBuildArtifact("a.out")
        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)

        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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f",
                    BREAKPOINT_HIT_ONCE,
                    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.
        self.runCmd("continue")

        # 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'])

        # The breakpoint should have a hit count of 2.
        self.expect("breakpoint list -f",
                    BREAKPOINT_HIT_ONCE,
                    substrs=[' resolved, hit count = 2'])
示例#24
0
    def breakpoint_options_language_test(self):
        """Test breakpoint command for language option."""
        exe = os.path.join(os.getcwd(), "a.out")
        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)

        # 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)
        self.runCmd("settings set target.language c")
        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."])

        # 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"])
示例#25
0
    def test_break(self):
        """Test 'expr member' continues to work for optimized build."""
        self.build()
        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)

        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('expression member', startstr="(int) $0 = 5")

        # <rdar://problem/12693963>
        interp = self.dbg.GetCommandInterpreter()
        result = lldb.SBCommandReturnObject()
        interp.HandleCommand('frame variable self', result)
        output = result.GetOutput()

        desired_pointer = "0x0"

        mo = re.search("0x[0-9a-f]+", output)

        if mo:
            desired_pointer = mo.group(0)

        self.expect('expression (self)',
                    substrs=[("(%s *) $1 = " % self.myclass), desired_pointer])

        self.expect('expression self->non_member',
                    error=True,
                    substrs=["does not have a member named 'non_member'"])
    def break_commands(self):
        """Tests that we can break on a partial name of a Swift function"""
        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
        lldbutil.run_break_set_by_symbol(self,"incr")
        lldbutil.run_break_set_by_symbol(self,"Accumulator.decr")

        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 select 0", substrs = ['Accumulator','incr'])

        self.runCmd("continue", RUN_SUCCEEDED)

        self.expect("frame select 0", substrs = ['Accumulator','decr'])

        self.runCmd("continue", RUN_SUCCEEDED)

        self.expect("frame select 0", substrs = ['Accumulator','incr'])
    def break_commands(self):
        """Tests that we can break on a partial name of a Swift function"""
        self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET)
        lldbutil.run_break_set_by_symbol(self, "incr")
        lldbutil.run_break_set_by_symbol(self, "Accumulator.decr")

        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 select 0", substrs=['Accumulator', 'incr'])

        self.runCmd("continue", RUN_SUCCEEDED)

        self.expect("frame select 0", substrs=['Accumulator', 'decr'])

        self.runCmd("continue", RUN_SUCCEEDED)

        self.expect("frame select 0", substrs=['Accumulator', 'incr'])
    def do_test(self, dictionary=None):
        """Display *bar_ptr when stopped on a function with forward declaration of struct bar."""
        self.build(dictionary=dictionary)
        exe = self.getBuildArtifact("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_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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
                    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'])

        # And so should this.
        self.expect(
            "expression --show-types -- *bar_ptr",
            VARIABLES_DISPLAYED_CORRECTLY,
            substrs=[
                '(bar)',
                '(int) a = 1',
                '(int) b = 2'])
示例#29
0
    def test_and_run_command(self):
        """Test interpreted and JITted expressions on constant values."""
        self.build()
        exe = self.getBuildArtifact("a.out")
        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        # Break inside the main.
        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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
                    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'])

        # Try an interpreted expression.
        self.expect("expr (index + 512)", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['1024'])

        # Try a JITted expression.
        self.expect(
            "expr (int)getpid(); (index - 256)",
            VARIABLES_DISPLAYED_CORRECTLY,
            substrs=['256'])

        self.runCmd("kill")
示例#30
0
    def test(self):
        """Test 'callback' has function ptr type, then break on the function."""
        self.build()
        self.runToBreakpoint()

        # Check that the 'callback' variable display properly.
        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)
        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'])
示例#31
0
    def test_break(self):
        """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'."""
        if self.getArchitecture() != 'x86_64':
            self.skipTest("This only applies to the v2 runtime")

        self.build()
        exe = self.getBuildArtifact("a.out")
        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)

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

        # 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\)"])

        # Static methods on NSString should work.
        self.expect(
            "expr [NSString stringWithCString:\"foo\" encoding:1]",
            VALID_TYPE,
            substrs=[
                "(id)",
                "$1"])

        self.expect("po $1", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=["foo"])
示例#32
0
    def test(self):
        """Test that C++ supports char8_t correctly."""
        self.build()
        exe = self.getBuildArtifact("a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        # FIXME: We should be able to test this with target variable, but the
        # data formatter output is broken.
        lldbutil.run_break_set_by_symbol(self, 'main')
        self.runCmd("run", RUN_SUCCEEDED)

        self.expect_expr("a",
                         result_type="char8_t",
                         result_summary="0x61 u8'a'")
        self.expect_expr("ab",
                         result_type="const char8_t *",
                         result_summary='u8"你好"')
        self.expect_expr("abc",
                         result_type="char8_t [9]",
                         result_summary='u8"你好"')
示例#33
0
    def test_expr_commands(self):
        """The evaluating printf(...) after break stop and then up a stack frame."""
        self.build()

        self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)

        lldbutil.run_break_set_by_symbol (self, 'foo', sym_exact=True, num_expected_locations=1)

        self.runCmd("run", RUN_SUCCEEDED)

        self.runCmd("frame variable")

        # This works fine.
        self.runCmd('expression (int)printf("value is: %d.\\n", value);')

        # rdar://problem/9531204
        # "Error dematerializing struct" error when evaluating expressions "up" on the stack
        self.runCmd('up') # frame select -r 1

        self.runCmd("frame variable")

        # This does not currently.
        self.runCmd('expression (int)printf("argc is: %d.\\n", argc)')
示例#34
0
    def test_expression_lookups_objc(self):
        """Test running an expression detect spurious debug info lookups (DWARF)."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")
        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)

        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")
        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)
        
        self.addTearDownHook(cleanup)
        
        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:")
                    num_errors += 1
                    print(line, end='')
            self.assertTrue(num_errors == 0, "Spurious lookups detected")
            f.close()
示例#35
0
    def test_symbolic_breakpoint(self):
        self.build()
        self.common_setup()

        lldbutil.run_break_set_by_symbol(self,
                                         "foo",
                                         sym_exact=True,
                                         num_expected_locations=1)

        # Now launch the process, and do not stop at entry point.
        process = self.target.LaunchSimple(
            None, self.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"],
        )
        # The breakpoint should have a hit count of 1.
        lldbutil.check_breakpoint(self, bpno=1, expected_hit_count=1)

        thread = process.GetSelectedThread()
        stack_frames = lldbutil.get_stack_frames(thread)
        self.assertGreater(len(stack_frames), 2)

        leaf_frame = stack_frames[0]
        self.assertEqual("foo.c",
                         leaf_frame.GetLineEntry().GetFileSpec().GetFilename())
        self.assertEqual(4, leaf_frame.GetLineEntry().GetLine())

        parent_frame = stack_frames[1]
        self.assertEqual(
            "shared.c",
            parent_frame.GetLineEntry().GetFileSpec().GetFilename())
        self.assertEqual(7, parent_frame.GetLineEntry().GetLine())
示例#36
0
    def test(self):
        """Break inside a() and b() defined within libfoo.a."""
        self.build()

        exe = self.getBuildArtifact("a.out")
        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)

        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'])

        # Break at a(int) first.
        self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['(int) arg = 1'])
        self.expect("frame variable __a_global", VARIABLES_DISPLAYED_CORRECTLY,
                    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)

        # 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'])
        self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['(int) arg = 2'])
        self.expect("frame variable __b_global", VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=['(int) __b_global = 2'])
示例#37
0
    def test(self):
        """Test breakpoint works correctly with dead-code stripping."""
        self.build()
        exe = self.getBuildArtifact("a.out")
        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")

        # Break by function name f2 (dead code).
        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")

        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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f 1",
                    BREAKPOINT_HIT_ONCE,
                    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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f 3",
                    BREAKPOINT_HIT_ONCE,
                    substrs=[' resolved, hit count = 1'])
示例#38
0
    def test(self):
        """Test breakpoint works correctly with dead-code stripping."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")
        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")

        # Break by function name f2 (dead code).
        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")

        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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f 1", BREAKPOINT_HIT_ONCE,
                    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'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f 3", BREAKPOINT_HIT_ONCE,
                    substrs=[' resolved, hit count = 1'])
    def breakpoint_options_language_test(self):
        """Test breakpoint command for language option."""
        exe = self.getBuildArtifact("a.out")
        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)

        # 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)
        self.runCmd("settings set target.language c")
        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."])

        # 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"])
示例#40
0
    def test_break(self):
        """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'."""
        self.build()
        exe = self.getBuildArtifact("a.out")
        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)

        # Stop at -[MyString initWithNSString:].
        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')

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

        self.runCmd("run", RUN_SUCCEEDED)

        # First stop is +[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.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.runCmd("process continue")

        # Followed by -[MyString description].
        self.expect("thread backtrace",
                    "Stop at -[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]"])

        self.runCmd("process continue")

        # Followed by -[NSAutoreleasePool release].
        self.expect("thread backtrace",
                    "Stop at -[NSAutoreleasePool release]",
                    substrs=["Foundation`-[NSAutoreleasePool release]"])
示例#41
0
    def test_data_type_and_expr(self):
        """Lookup objective-c data types and evaluate expressions."""
        self.build()
        exe = self.getBuildArtifact("a.out")
        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)
        #        self.expect("breakpoint set -n '-[MyString description]", BREAKPOINT_CREATED,
        # 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]"])

        # 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'
                    ])

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

        # rdar://problem/8651752
        # don't crash trying to ask clang how many children an empty record has
        self.runCmd("frame variable *_cmd")

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

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

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

        # isa should be accessible.
        self.expect("expression self->isa",
                    VARIABLES_DISPLAYED_CORRECTLY,
                    substrs=["Class)"])

        # This should fail expectedly.
        self.expect(
            "expression self->non_existent_member",
            COMMAND_FAILED_AS_EXPECTED,
            error=True,
            substrs=[
                "error:",
                "'MyString' does not have a member named 'non_existent_member'"
            ])

        # Use expression parser.
        self.runCmd("expression self->str")
        self.runCmd("expression self->date")

        # (lldb) expression self->str
        # error: instance variable 'str' is protected
        # error: 1 errors parsing expression
        #
        # (lldb) expression self->date
        # error: instance variable 'date' is protected
        # error: 1 errors parsing expression
        #

        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)

        self.runCmd("process continue")

        # rdar://problem/8542091
        # 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: "])
示例#42
0
    def fp_register_write(self):
        exe = os.path.join(os.getcwd(), "a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        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.GetProcess()
        self.assertTrue(process.GetState() == lldb.eStateStopped,
                        PROCESS_STOPPED)

        thread = process.GetThreadAtIndex(0)
        self.assertTrue(thread.IsValid(), "current thread is valid")

        currentFrame = thread.GetFrameAtIndex(0)
        self.assertTrue(currentFrame.IsValid(), "current frame is valid")

        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),
                ("mxcsrmask", "0x0000ff0e", False),
            ]

            st0regname = None
            if currentFrame.FindRegister("st0").IsValid():
                st0regname = "st0"
            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))
        elif self.getArchitecture() in ['arm64', 'aarch64']:
            reg_list = [
                # reg      value
                # must-have
                ("fpsr", "0xfbf79f9f", True),
                ("s0", "1.25", True),
                ("s31", "0.75", True),
                ("d1", "123", True),
                ("d17", "987", False),
                ("v1",
                 "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}",
                 True),
                ("v14",
                 "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}",
                 False),
            ]
        elif self.getArchitecture() in ['armv7'] and self.platformIsDarwin():
            reg_list = [
                # reg      value
                # must-have
                ("fpsr", "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),
            ]
        elif self.getArchitecture() in ['arm', 'armv7k']:
            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),
            ]

        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
            has_mpx = False
            # Returns an SBValueList.
            registerSets = currentFrame.GetRegisters()
            for registerSet in registerSets:
                if 'advanced vector extensions' in registerSet.GetName().lower(
                ):
                    has_avx = True
                if 'memory protection extension' in registerSet.GetName(
                ).lower():
                    has_mpx = True

            if has_avx:
                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'])
            else:
                self.runCmd("register read ymm0")

            if has_mpx:
                # Test write and read for bnd0.
                new_value_w = "{0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f 0x10}"
                self.runCmd("register write bnd0 \'" + new_value_w + "\'")
                new_value_r = "{0x0807060504030201 0x100f0e0d0c0b0a09}"
                self.expect("register read bnd0",
                            substrs=['bnd0 = ', new_value_r])
                self.expect("expr $bnd0", substrs=['vector_type'])

                # Test write and for bndstatus.
                new_value = "{0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08}"
                self.write_and_read(currentFrame, "bndstatus", new_value)
                self.expect("expr $bndstatus", substrs=['vector_type'])
            else:
                self.runCmd("register read bnd0")
    def test_simple_disasm(self):
        """Test the lldb 'disassemble' command"""
        self.build()

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
        self.assertTrue(target, VALID_TARGET)

        print(target)
        for module in target.modules:
            print(module)

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

        # Stop at -[MyString initWithNSString:].
        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')

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

        self.runCmd("run", RUN_SUCCEEDED)

        # First stop is +[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")

        self.runCmd("process continue")
        # Skip another breakpoint for +[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:]"])

        # Do the disassemble for the currently stopped function.
        self.runCmd("disassemble -f")

        self.runCmd("process continue")

        # Followed by -[MyString description].
        self.expect("thread backtrace",
                    "Stop at -[MyString description]",
                    substrs=["a.out`-[MyString description]"])

        # Do the disassemble for the currently stopped function.
        self.runCmd("disassemble -f")

        self.runCmd("process continue")
        # Skip another breakpoint for -[MyString description].
        self.runCmd("process continue")

        # Followed by -[NSAutoreleasePool release].
        self.expect("thread backtrace",
                    "Stop at -[NSAutoreleasePool release]",
                    substrs=["Foundation`-[NSAutoreleasePool release]"])

        # Do the disassemble for the currently stopped function.
        self.runCmd("disassemble -f")
示例#44
0
    def fp_register_write(self):
        exe = os.path.join(os.getcwd(), "a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        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.GetProcess()
        self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)

        thread = process.GetThreadAtIndex(0)
        self.assertTrue(thread.IsValid(), "current thread is valid")

        currentFrame = thread.GetFrameAtIndex(0)
        self.assertTrue(currentFrame.IsValid(), "current frame is valid")

        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),
                ("mxcsrmask", "0x0000ff0e", False),
            ]

            st0regname = None
            if currentFrame.FindRegister("st0").IsValid():
                st0regname = "st0"
            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))
        elif self.getArchitecture() in ['arm']:
            reg_list = [
                # reg      value                                                                               must-have
                ("fpscr", "0x0000ff0e",                                                                        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.
            for registerSet in registerSets:
                if 'advanced vector extensions' in registerSet.GetName().lower():
                    has_avx = True
                    break

            if has_avx:
                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'])
            else:
                self.runCmd("register read ymm0")
示例#45
0
    def test_data_type_and_expr(self):
        """Lookup objective-c data types and evaluate expressions."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")
        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)
#        self.expect("breakpoint set -n '-[MyString description]", BREAKPOINT_CREATED,
#            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]"])

        # 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'])

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

        # rdar://problem/8651752
        # don't crash trying to ask clang how many children an empty record has
        self.runCmd("frame variable *_cmd")

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

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

        # 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"])
        
        # isa should be accessible.
        self.expect("expression self->isa", VARIABLES_DISPLAYED_CORRECTLY,
            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'")

        # Use expression parser.
        self.runCmd("expression self->str")
        self.runCmd("expression self->date")

        # (lldb) expression self->str
        # error: instance variable 'str' is protected
        # error: 1 errors parsing expression
        #
        # (lldb) expression self->date
        # error: instance variable 'date' is protected
        # error: 1 errors parsing expression
        #

        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)

        self.runCmd("process continue")

        # rdar://problem/8542091
        # 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: "])
示例#46
0
    def test(self):
        """Test stepping over watchpoints."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

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

        lldbutil.run_break_set_by_symbol(self, "main")

        process = target.LaunchSimple(None, None, self.get_process_working_directory())
        self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
        self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)

        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "Failed to get thread.")

        frame = thread.GetFrameAtIndex(0)
        self.assertTrue(frame.IsValid(), "Failed to get frame.")

        read_value = frame.FindValue("g_watch_me_read", lldb.eValueTypeVariableGlobal)
        self.assertTrue(read_value.IsValid(), "Failed to find read value.")

        error = lldb.SBError()

        # resolve_location=True, read=True, write=False
        read_watchpoint = read_value.Watch(True, True, False, error)
        self.assertTrue(error.Success(), "Error while setting watchpoint: %s" % error.GetCString())
        self.assertTrue(read_watchpoint, "Failed to set read watchpoint.")

        thread.StepOver()
        self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint, STOPPED_DUE_TO_WATCHPOINT)
        self.assertTrue(thread.GetStopDescription(20) == "watchpoint 1")

        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
        self.assertTrue(thread.GetStopDescription(20) == "step over")

        self.step_inst_for_watchpoint(1)

        write_value = frame.FindValue("g_watch_me_write", 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
        arch = self.getArchitecture()
        if re.match("^mips", arch):
            self.runCmd("watchpoint delete 1")

        # resolve_location=True, read=False, write=True
        write_watchpoint = write_value.Watch(True, False, True, error)
        self.assertTrue(read_watchpoint, "Failed to set write watchpoint.")
        self.assertTrue(error.Success(), "Error while setting watchpoint: %s" % error.GetCString())

        thread.StepOver()
        self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint, STOPPED_DUE_TO_WATCHPOINT)
        self.assertTrue(thread.GetStopDescription(20) == "watchpoint 2")

        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
        self.assertTrue(thread.GetStopDescription(20) == "step over")

        self.step_inst_for_watchpoint(2)
示例#47
0
    def breakpoint_conditions(self, inline=False):
        """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'."""
        exe = os.path.join(os.getcwd(), "a.out")
        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        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)
        else:
            # Create a breakpoint by function name 'c'.
            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")

        # 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'])

        # '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')

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

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

        # 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:"])

        # 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'])

        # '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.runCmd("process kill")
        self.runCmd("breakpoint disable")

        self.runCmd("breakpoint set -p Loop")
        arch = self.getArchitecture()
        if arch in ['x86_64', 'i386']:
            self.runCmd("breakpoint modify -c ($eax&&i)")
        elif arch in ['aarch64']:
            self.runCmd("breakpoint modify -c ($x1&&i)")
        elif arch in ['arm']:
            self.runCmd("breakpoint modify -c ($r0&&i)")
        elif re.match("mips",arch):
            self.runCmd("breakpoint modify -c ($r2&&i)")
        elif arch in ['s390x']:
            self.runCmd("breakpoint modify -c ($r2&&i)")
        self.runCmd("run")

        self.expect("process status", PROCESS_STOPPED,
            patterns = ['Process .* stopped'])

        self.runCmd("continue")

        self.expect("process status", PROCESS_EXITED,
            patterns = ['Process .* exited'])
    def test_frame_recognizer_1(self):
        self.build()

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

        self.runCmd("command script import " +
                    os.path.join(self.getSourceDir(), "recognizer.py"))

        self.expect("frame recognizer list",
                    substrs=['no matching results found.'])

        self.runCmd(
            "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo"
        )

        self.expect(
            "frame recognizer list",
            substrs=[
                '0: recognizer.MyFrameRecognizer, module a.out, function foo'
            ])

        self.runCmd(
            "frame recognizer add -l recognizer.MyOtherFrameRecognizer -s a.out -n bar -x"
        )

        self.expect(
            "frame recognizer list",
            substrs=[
                '1: recognizer.MyOtherFrameRecognizer, module a.out, function bar (regexp)',
                '0: recognizer.MyFrameRecognizer, module a.out, function foo'
            ])

        self.runCmd("frame recognizer delete 0")

        self.expect(
            "frame recognizer list",
            substrs=[
                '1: recognizer.MyOtherFrameRecognizer, module a.out, function bar (regexp)'
            ])

        self.runCmd("frame recognizer clear")

        self.expect("frame recognizer list",
                    substrs=['no matching results found.'])

        self.runCmd(
            "frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo"
        )

        lldbutil.run_break_set_by_symbol(self, "foo")
        self.runCmd("r")

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

        process = target.GetProcess()
        thread = process.GetSelectedThread()
        frame = thread.GetSelectedFrame()

        self.assertEqual(frame.GetSymbol().GetName(), "foo")
        self.assertFalse(frame.GetLineEntry().IsValid())

        self.expect("frame variable", substrs=['(int) a = 42', '(int) b = 56'])

        # Recognized arguments don't show up by default...
        variables = frame.GetVariables(lldb.SBVariablesOptions())
        self.assertEqual(variables.GetSize(), 0)

        # ...unless you set target.display-recognized-arguments to 1...
        self.runCmd("settings set target.display-recognized-arguments 1")
        variables = frame.GetVariables(lldb.SBVariablesOptions())
        self.assertEqual(variables.GetSize(), 2)

        # ...and you can reset it back to 0 to hide them again...
        self.runCmd("settings set target.display-recognized-arguments 0")
        variables = frame.GetVariables(lldb.SBVariablesOptions())
        self.assertEqual(variables.GetSize(), 0)

        # ... or explicitly ask for them with SetIncludeRecognizedArguments(True).
        opts = lldb.SBVariablesOptions()
        opts.SetIncludeRecognizedArguments(True)
        variables = frame.GetVariables(opts)

        self.assertEqual(variables.GetSize(), 2)
        self.assertEqual(variables.GetValueAtIndex(0).name, "a")
        self.assertEqual(variables.GetValueAtIndex(0).signed, 42)
        self.assertEqual(
            variables.GetValueAtIndex(0).GetValueType(),
            lldb.eValueTypeVariableArgument)
        self.assertEqual(variables.GetValueAtIndex(1).name, "b")
        self.assertEqual(variables.GetValueAtIndex(1).signed, 56)
        self.assertEqual(
            variables.GetValueAtIndex(1).GetValueType(),
            lldb.eValueTypeVariableArgument)

        self.expect(
            "frame recognizer info 0",
            substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer'])

        self.expect("frame recognizer info 999",
                    error=True,
                    substrs=['no frame with index 999'])

        self.expect("frame recognizer info 1",
                    substrs=['frame 1 not recognized by any recognizer'])

        # FIXME: The following doesn't work yet, but should be fixed.
        """
    def test(self):
        """Test that we can backtrace correctly with _sigtramp on the stack"""
        self.build()
        self.setTearDownCleanup()

        exe = os.path.join(os.getcwd(), "a.out")
        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)

        process = target.LaunchSimple(
            None, None, self.get_process_working_directory())

        if not process:
            self.fail("SBTarget.Launch() 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()))

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

        thread = process.GetThreadAtIndex(0)

        found_handler = False
        found_sigtramp = False
        found_kill = False
        found_main = False

        for f in thread.frames:
            if f.GetFunctionName() == "handler":
                found_handler = True
            if f.GetFunctionName() == "_sigtramp":
                found_sigtramp = True
            if f.GetFunctionName() == "__kill":
                found_kill = True
            if f.GetFunctionName() == "main":
                found_main = True

        if self.TraceOn():
            print("Backtrace once we're stopped:")
            for f in thread.frames:
                print("  %d %s" % (f.GetFrameID(), f.GetFunctionName()))

        if not found_handler:
            self.fail("Unable to find handler() in backtrace.")

        if not found_sigtramp:
            self.fail("Unable to find _sigtramp() in backtrace.")

        if not found_kill:
            self.fail("Unable to find kill() in backtrace.")

        if not found_main:
            self.fail("Unable to find main() in backtrace.")
示例#50
0
    def test(self):
        """Test stepping over watchpoints."""
        self.build()
        exe = os.path.join(os.getcwd(), 'a.out')

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

        lldbutil.run_break_set_by_symbol(self, 'main')

        process = target.LaunchSimple(None, None,
                                      self.get_process_working_directory())
        self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
        self.assertTrue(process.GetState() == lldb.eStateStopped,
                        PROCESS_STOPPED)

        thread = lldbutil.get_stopped_thread(process,
                                             lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "Failed to get thread.")

        frame = thread.GetFrameAtIndex(0)
        self.assertTrue(frame.IsValid(), "Failed to get frame.")

        read_value = frame.FindValue('g_watch_me_read',
                                     lldb.eValueTypeVariableGlobal)
        self.assertTrue(read_value.IsValid(), "Failed to find read value.")

        error = lldb.SBError()

        # resolve_location=True, read=True, write=False
        read_watchpoint = read_value.Watch(True, True, False, error)
        self.assertTrue(error.Success(),
                        "Error while setting watchpoint: %s" %
                        error.GetCString())
        self.assertTrue(read_watchpoint, "Failed to set read watchpoint.")

        thread.StepOver()
        self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint,
                        STOPPED_DUE_TO_WATCHPOINT)
        self.assertTrue(thread.GetStopDescription(20) == 'watchpoint 1')

        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped,
                        PROCESS_STOPPED)
        self.assertTrue(thread.GetStopDescription(20) == 'step over')

        self.step_inst_for_watchpoint(1)

        write_value = frame.FindValue('g_watch_me_write',
                                      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
        arch = self.getArchitecture()
        if arch in ['mips', 'mipsel', 'mips64', 'mips64el']:
            self.runCmd("watchpoint delete 1")

        # resolve_location=True, read=False, write=True
        write_watchpoint = write_value.Watch(True, False, True, error)
        self.assertTrue(read_watchpoint, "Failed to set write watchpoint.")
        self.assertTrue(error.Success(),
                        "Error while setting watchpoint: %s" %
                        error.GetCString())

        thread.StepOver()
        self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint,
                        STOPPED_DUE_TO_WATCHPOINT)
        self.assertTrue(thread.GetStopDescription(20) == 'watchpoint 2')

        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped,
                        PROCESS_STOPPED)
        self.assertTrue(thread.GetStopDescription(20) == 'step over')

        self.step_inst_for_watchpoint(2)
示例#51
0
    def signal_test(self, signal, test_passing):
        """Test that we handle inferior raising signals"""
        exe = self.getBuildArtifact("a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)
        lldbutil.run_break_set_by_symbol(self, "main")
        self.default_pass = ""
        self.default_stop = ""
        self.default_notify = ""

        # launch
        process = self.launch(target, signal)
        signo = process.GetUnixSignals().GetSignalNumberFromName(signal)

        # retrieve default signal disposition
        (self.default_pass, self.default_stop,
         self.default_notify) = lldbutil.get_actions_for_signal(self, signal)

        # Make sure we stop at the signal
        lldbutil.set_actions_for_signal(self, signal, "false", "true", "true")
        process.Continue()
        self.assertState(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), signo,
                         "The stop signal was %s" % signal)

        # Continue until we exit.
        process.Continue()
        self.assertState(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), 0)

        process = self.launch(target, signal)

        # Make sure we do not stop at the signal. We should still get the
        # notification.
        lldbutil.set_actions_for_signal(self, signal, "false", "false", "true")
        self.expect("process continue",
                    substrs=["stopped and restarted", signal])
        self.assertState(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.
        lldbutil.set_actions_for_signal(self, signal, "false", "false",
                                        "false")
        self.expect("process continue",
                    substrs=["stopped and restarted"],
                    matching=False)
        self.assertState(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), 0)

        if not test_passing:
            # reset signal handling to default
            lldbutil.set_actions_for_signal(self, signal, self.default_pass,
                                            self.default_stop,
                                            self.default_notify)
            return

        # launch again
        process = self.launch(target, signal)

        # Make sure we stop at the signal
        lldbutil.set_actions_for_signal(self, signal, "true", "true", "true")
        process.Continue()
        self.assertState(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)

        # Continue until we exit. The process should receive the signal.
        process.Continue()
        self.assertState(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), signo)

        # launch again
        process = self.launch(target, signal)

        # Make sure we do not stop at the signal. We should still get the notification. Process
        # should receive the signal.
        lldbutil.set_actions_for_signal(self, signal, "true", "false", "true")
        self.expect("process continue",
                    substrs=["stopped and restarted", signal])
        self.assertState(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), signo)

        # launch again
        process = self.launch(target, signal)

        # Make sure we do not stop at the signal, and we do not get the notification. Process
        # should receive the signal.
        lldbutil.set_actions_for_signal(self, signal, "true", "false", "false")
        self.expect("process continue",
                    substrs=["stopped and restarted"],
                    matching=False)
        self.assertState(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), signo)

        # reset signal handling to default
        lldbutil.set_actions_for_signal(self, signal, self.default_pass,
                                        self.default_stop, self.default_notify)
示例#52
0
    def fp_register_write(self):
        exe = os.path.join(os.getcwd(), "a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        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.GetProcess()
        self.assertTrue(process.GetState() == lldb.eStateStopped,
                        PROCESS_STOPPED)

        thread = process.GetThreadAtIndex(0)
        self.assertTrue(thread.IsValid(), "current thread is valid")

        currentFrame = thread.GetFrameAtIndex(0)
        self.assertTrue(currentFrame.IsValid(), "current frame is valid")

        self.write_and_restore(currentFrame, "fcw", False)
        self.write_and_restore(currentFrame, "fsw", False)
        self.write_and_restore(currentFrame, "ftw", False)
        self.write_and_restore(currentFrame, "ip", False)
        self.write_and_restore(currentFrame, "dp", False)
        self.write_and_restore(currentFrame, "mxcsr", False)
        self.write_and_restore(currentFrame, "mxcsrmask", False)

        st0regname = "st0"
        if currentFrame.FindRegister(st0regname).IsValid() == False:
            st0regname = "stmm0"
        if currentFrame.FindRegister(st0regname).IsValid() == False:
            return  # TODO: anything smarter here

        new_value = "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00}"
        self.vector_write_and_read(currentFrame, st0regname, new_value)

        new_value = "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}"
        self.vector_write_and_read(currentFrame, "xmm0", new_value)
        new_value = "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}"
        self.vector_write_and_read(currentFrame, "xmm15", new_value, False)

        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.
        for registerSet in registerSets:
            if 'advanced vector extensions' in registerSet.GetName().lower():
                has_avx = True
                break

        if has_avx:
            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.vector_write_and_read(currentFrame, "ymm0", new_value)
            self.vector_write_and_read(currentFrame, "ymm7", new_value)
            self.expect("expr $ymm0", substrs=['vector_type'])
        else:
            self.runCmd("register read ymm0")
示例#53
0
    def test(self):
        """Test stepping over watchpoints."""
        self.build()
        target = self.createTestTarget()

        lldbutil.run_break_set_by_symbol(self, 'main')

        process = target.LaunchSimple(None, None,
                                      self.get_process_working_directory())
        self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
        self.assertState(process.GetState(), lldb.eStateStopped,
                         PROCESS_STOPPED)

        thread = lldbutil.get_stopped_thread(process,
                                             lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "Failed to get thread.")

        frame = thread.GetFrameAtIndex(0)
        self.assertTrue(frame.IsValid(), "Failed to get frame.")

        read_value = frame.FindValue('g_watch_me_read',
                                     lldb.eValueTypeVariableGlobal)
        self.assertTrue(read_value.IsValid(), "Failed to find read value.")

        error = lldb.SBError()

        # resolve_location=True, read=True, write=False
        read_watchpoint = read_value.Watch(True, True, False, error)
        self.assertSuccess(error, "Error while setting watchpoint")
        self.assertTrue(read_watchpoint, "Failed to set read watchpoint.")

        thread.StepOver()
        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonWatchpoint,
                        STOPPED_DUE_TO_WATCHPOINT)
        self.assertEquals(thread.GetStopDescription(20), 'watchpoint 1')

        process.Continue()
        self.assertState(process.GetState(), lldb.eStateStopped,
                         PROCESS_STOPPED)
        self.assertEquals(thread.GetStopDescription(20), 'step over')

        self.step_inst_for_watchpoint(1)

        write_value = frame.FindValue('g_watch_me_write',
                                      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
        arch = self.getArchitecture()
        if re.match("^mips", arch) or re.match("powerpc64le", arch):
            self.runCmd("watchpoint delete 1")

        # resolve_location=True, read=False, write=True
        write_watchpoint = write_value.Watch(True, False, True, error)
        self.assertTrue(write_watchpoint, "Failed to set write watchpoint.")
        self.assertSuccess(error, "Error while setting watchpoint")

        thread.StepOver()
        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonWatchpoint,
                        STOPPED_DUE_TO_WATCHPOINT)
        self.assertEquals(thread.GetStopDescription(20), 'watchpoint 2')

        process.Continue()
        self.assertState(process.GetState(), lldb.eStateStopped,
                         PROCESS_STOPPED)
        self.assertEquals(thread.GetStopDescription(20), 'step over')

        self.step_inst_for_watchpoint(2)
示例#54
0
    def breakpoint_conditions(self, inline=False):
        """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'."""
        exe = self.getBuildArtifact("a.out")
        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        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)
        else:
            # Create a breakpoint by function name 'c'.
            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")

        # 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'])

        # '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')

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

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

        # 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:"])

        # 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'])

        # '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.runCmd("process kill")
示例#55
0
    def signal_test(self, signal, test_passing):
        """Test that we handle inferior raising signals"""
        exe = os.path.join(os.getcwd(), "a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)
        lldbutil.run_break_set_by_symbol(self, "main")

        # launch
        process = self.launch(target, signal)
        signo = process.GetUnixSignals().GetSignalNumberFromName(signal)

        # 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)
        if not match:
            self.fail('Unable to retrieve default signal disposition.')
        default_pass = match.group(1)
        default_stop = match.group(2)
        default_notify = match.group(3)

        # Make sure we stop at the signal
        self.set_handle(signal, "false", "true", "true")
        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), signo,
                         "The stop signal was %s" % signal)

        # Continue until we exit.
        process.Continue()
        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. We should still get the
        # notification.
        self.set_handle(signal, "false", "false", "true")
        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.
        self.set_handle(signal, "false", "false", "false")
        self.expect("process continue",
                    substrs=["stopped and restarted"],
                    matching=False)
        self.assertEqual(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), 0)

        if not test_passing:
            # reset signal handling to default
            self.set_handle(signal, default_pass, default_stop, default_notify)
            return

        # launch again
        process = self.launch(target, signal)

        # Make sure we stop at the signal
        self.set_handle(signal, "true", "true", "true")
        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)

        # Continue until we exit. The process should receive the signal.
        process.Continue()
        self.assertEqual(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), signo)

        # launch again
        process = self.launch(target, signal)

        # 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.assertEqual(process.GetState(), lldb.eStateExited)
        self.assertEqual(process.GetExitStatus(), signo)

        # launch again
        process = self.launch(target, signal)

        # 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.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)
示例#56
0
    def test(self):
        """Test that we can backtrace correctly with _sigtramp on the stack"""
        self.build()
        self.setTearDownCleanup()

        exe = os.path.join(os.getcwd(), "a.out")
        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)

        process = target.LaunchSimple(
            None, None, self.get_process_working_directory())

        if not process:
            self.fail("SBTarget.Launch() 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()))

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

        thread = process.GetThreadAtIndex(0)

        found_handler = False
        found_sigtramp = False
        found_kill = False
        found_main = False

        for f in thread.frames:
            if f.GetFunctionName() == "handler":
                found_handler = True
            if f.GetFunctionName() == "_sigtramp":
                found_sigtramp = True
            if f.GetFunctionName() == "__kill":
                found_kill = True
            if f.GetFunctionName() == "main":
                found_main = True

        if self.TraceOn():
            print("Backtrace once we're stopped:")
            for f in thread.frames:
                print("  %d %s" % (f.GetFrameID(), f.GetFunctionName()))

        if not found_handler:
            self.fail("Unable to find handler() in backtrace.")

        if not found_sigtramp:
            self.fail("Unable to find _sigtramp() in backtrace.")

        if not found_kill:
            self.fail("Unable to find kill() in backtrace.")

        if not found_main:
            self.fail("Unable to find main() in backtrace.")