Exemplo n.º 1
0
    def test_lldb_iter_breakpoint(self):
        """Test breakpoint_iter works correctly for SBTarget -> SBBreakpoint."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

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

        breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)
        breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line2)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)

        self.assertTrue(target.GetNumBreakpoints() == 2)

        from lldbutil import get_description
        yours = []
        for i in range(target.GetNumBreakpoints()):
            yours.append(target.GetBreakpointAtIndex(i))
        mine = []
        for b in target.breakpoint_iter():
            mine.append(b)

        self.assertTrue(len(yours) == len(mine))
        for i in range(len(yours)):
            if self.TraceOn():
                print("yours[%d]='%s'" % (i, get_description(yours[i])))
                print("mine[%d]='%s'" % (i, get_description(mine[i])))
            self.assertTrue(yours[i] == mine[i],
                            "ID of yours[{0}] and mine[{0}] matches".format(i))
Exemplo n.º 2
0
    def update(self):
        target = self.driver.getTarget()
        if not target.IsValid():
            self.win.erase()
            self.win.noutrefresh()
            return
        selected = self.getSelected()
        self.clearItems()
        for i in range(0, target.GetNumBreakpoints()):
            bp = target.GetBreakpointAtIndex(i)
            if bp.IsInternal():
                continue
            text = lldbutil.get_description(bp)
            # FIXME: Use an API for this, not parsing the description.
            match = re.search('SBBreakpoint: id = ([^,]+), (.*)', text)
            try:
                id = match.group(1)
                desc = match.group(2).strip()
                if bp.IsEnabled():
                    text = '%s: %s' % (id, desc)
                else:
                    text = '%s: (disabled) %s' % (id, desc)
            except ValueError as e:
                # bp unparsable
                pass

            if self.showDetails.setdefault(bp.id, False):
                for location in bp:
                    desc = lldbutil.get_description(location,
                                                    lldb.eDescriptionLevelFull)
                    text += '\n  ' + desc
            self.addItem(text)
        self.setSelected(selected)
Exemplo n.º 3
0
    def get_description(self):
        """Exercise SBTaget.GetDescription() API."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        from lldbutil import get_description

        # get_description() allows no option to mean lldb.eDescriptionLevelBrief.
        desc = get_description(target)
        #desc = get_description(target, option=lldb.eDescriptionLevelBrief)
        if not desc:
            self.fail("SBTarget.GetDescription() failed")
        self.expect(desc, exe=False, substrs=['a.out'])
        self.expect(desc,
                    exe=False,
                    matching=False,
                    substrs=['Target', 'Module', 'Breakpoint'])

        desc = get_description(target, option=lldb.eDescriptionLevelFull)
        if not desc:
            self.fail("SBTarget.GetDescription() failed")
        self.expect(desc,
                    exe=False,
                    substrs=['a.out', 'Target', 'Module', 'Breakpoint'])
Exemplo n.º 4
0
    def describe_threads(self):
        ret = []
        for x in self.inferior_process:
            id = x.GetIndexID()
            reason = x.GetStopReason()
            status = "stopped" if x.IsStopped() else "running"
            reason_str = lldbutil.stop_reason_to_str(reason)
            if reason == lldb.eStopReasonBreakpoint:
                bpid = x.GetStopReasonDataAtIndex(0)
                bp = self.inferior_target.FindBreakpointByID(bpid)
                reason_str = "%s hit %d times" % (lldbutil.get_description(bp),
                                                  bp.GetHitCount())
            elif reason == lldb.eStopReasonWatchpoint:
                watchid = x.GetStopReasonDataAtIndex(0)
                watch = self.inferior_target.FindWatchpointByID(watchid)
                reason_str = "%s hit %d times" % (
                    lldbutil.get_description(watch), watch.GetHitCount())
            elif reason == lldb.eStopReasonSignal:
                reason_str = "signal %s" % (
                    signal_names[x.GetStopReasonDataAtIndex(0)])

            location = "\t".join([
                lldbutil.get_description(x.GetFrameAtIndex(i))
                for i in range(x.GetNumFrames())
            ])
            ret.append("thread %d %s due to %s at\n\t%s" %
                       (id, status, reason_str, location))
        return ret
Exemplo n.º 5
0
    def test_lldb_iter_module(self):
        """Test module_iter works correctly for SBTarget -> SBModule."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

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

        breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple(None, None,
                                      self.get_process_working_directory())

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

        from lldbutil import get_description
        yours = []
        for i in range(target.GetNumModules()):
            yours.append(target.GetModuleAtIndex(i))
        mine = []
        for m in target.module_iter():
            mine.append(m)

        self.assertTrue(len(yours) == len(mine))
        for i in range(len(yours)):
            if self.TraceOn():
                print "yours[%d]='%s'" % (i, get_description(yours[i]))
                print "mine[%d]='%s'" % (i, get_description(mine[i]))
            self.assertTrue(
                yours[i] == mine[i],
                "UUID+FileSpec of yours[{0}] and mine[{0}] matches".format(i))
Exemplo n.º 6
0
    def get_description(self):
        """Exercise SBTaget.GetDescription() API."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        from lldbutil import get_description

        # get_description() allows no option to mean lldb.eDescriptionLevelBrief.
        desc = get_description(target)
        #desc = get_description(target, option=lldb.eDescriptionLevelBrief)
        if not desc:
            self.fail("SBTarget.GetDescription() failed")
        self.expect(desc, exe=False,
            substrs = ['a.out'])
        self.expect(desc, exe=False, matching=False,
            substrs = ['Target', 'Module', 'Breakpoint'])

        desc = get_description(target, option=lldb.eDescriptionLevelFull)
        if not desc:
            self.fail("SBTarget.GetDescription() failed")
        self.expect(desc, exe=False,
            substrs = ['a.out', 'Target', 'Module', 'Breakpoint'])
Exemplo n.º 7
0
    def run(self, target=None):
        self.setup()

        if target is None:
            target = driver_instance().current_target()

        result = ''

        if target:
            for i in xrange(0, target.GetNumModules()):
                debug(debugPlugin | debugVerbose, lldbutil.get_description(target.GetModuleAtIndex(i)))
                result += lldbutil.get_description(target.GetModuleAtIndex(i)) + '\n'

            # Re-use a view, if we already have one.
            v = None
            for _v in self.window.views():
                if _v.name() == self._shared_libraries_view_name:
                    v = _v
                    break

            if v is None:
                v = self.window.new_file()
                v.set_name(self._shared_libraries_view_name)

            LLDBLayoutManager.clear_view(v)
            v.set_scratch(True)
            v.set_read_only(False)

            edit = v.begin_edit('lldb-shared-libraries-list')
            v.insert(edit, 0, result)
            v.end_edit(edit)
            v.set_read_only(True)
Exemplo n.º 8
0
    def test_lldb_iter_breakpoint(self):
        """Test breakpoint_iter works correctly for SBTarget -> SBBreakpoint."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

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

        breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)
        breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line2)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)

        self.assertTrue(target.GetNumBreakpoints() == 2)

        from lldbutil import get_description
        yours = []
        for i in range(target.GetNumBreakpoints()):
            yours.append(target.GetBreakpointAtIndex(i))
        mine = []
        for b in target.breakpoint_iter():
            mine.append(b)

        self.assertTrue(len(yours) == len(mine))
        for i in range(len(yours)):
            if self.TraceOn():
                print "yours[%d]='%s'" % (i, get_description(yours[i]))
                print "mine[%d]='%s'" % (i, get_description(mine[i]))
            self.assertTrue(yours[i] == mine[i],
                            "ID of yours[{0}] and mine[{0}] matches".format(i))
Exemplo n.º 9
0
    def update(self):
        target = self.driver.getTarget()
        if not target.IsValid():
            self.win.erase()
            self.win.noutrefresh()
            return
        selected = self.getSelected()
        self.clearItems()
        for i in range(0, target.GetNumBreakpoints()):
            bp = target.GetBreakpointAtIndex(i)
            if bp.IsInternal():
                continue
            text = lldbutil.get_description(bp)
            # FIXME: Use an API for this, not parsing the description.
            match = re.search('SBBreakpoint: id = ([^,]+), (.*)', text)
            try:
                id = match.group(1)
                desc = match.group(2).strip()
                if bp.IsEnabled():
                    text = '%s: %s' % (id, desc)
                else:
                    text = '%s: (disabled) %s' % (id, desc)
            except ValueError as e:
                # bp unparsable
                pass

            if self.showDetails.setdefault(bp.id, False):
                for location in bp:
                    desc = lldbutil.get_description(
                        location, lldb.eDescriptionLevelFull)
                    text += '\n  ' + desc
            self.addItem(text)
        self.setSelected(selected)
Exemplo n.º 10
0
    def test_lldb_iter_module(self):
        """Test module_iter works correctly for SBTarget -> SBModule."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

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

        breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple (None, None, self.get_process_working_directory())

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

        from lldbutil import get_description
        yours = []
        for i in range(target.GetNumModules()):
            yours.append(target.GetModuleAtIndex(i))
        mine = []
        for m in target.module_iter():
            mine.append(m)

        self.assertTrue(len(yours) == len(mine))
        for i in range(len(yours)):
            if self.TraceOn():
                print("yours[%d]='%s'" % (i, get_description(yours[i])))
                print("mine[%d]='%s'" % (i, get_description(mine[i])))
            self.assertTrue(yours[i] == mine[i],
                            "UUID+FileSpec of yours[{0}] and mine[{0}] matches".format(i))
Exemplo n.º 11
0
    def run(self, target=None):
        self.setup()

        if target is None:
            target = driver_instance().current_target()

        result = ''

        if target:
            for i in xrange(0, target.GetNumModules()):
                debug(debugPlugin | debugVerbose,
                      lldbutil.get_description(target.GetModuleAtIndex(i)))
                result += lldbutil.get_description(
                    target.GetModuleAtIndex(i)) + '\n'

            # Re-use a view, if we already have one.
            v = None
            for _v in self.window.views():
                if _v.name() == self._shared_libraries_view_name:
                    v = _v
                    break

            if v is None:
                v = self.window.new_file()
                v.set_name(self._shared_libraries_view_name)

            LLDBLayoutManager.clear_view(v)
            v.set_scratch(True)
            v.set_read_only(False)

            edit = v.begin_edit('lldb-shared-libraries-list')
            v.insert(edit, 0, result)
            v.end_edit(edit)
            v.set_read_only(True)
Exemplo n.º 12
0
    def print_obj(self, exe_name):
        """
        Test "print object" where another thread blocks the print object from making progress.

        Set a breakpoint on the line in my_pthread_routine.  Then switch threads
        to the main thread, and do print the lock_me object.  Since that will
        try to get the lock already gotten by my_pthread_routime thread, it will
        have to switch to running all threads, and that should then succeed.
        """
        exe = os.path.join(os.getcwd(), exe_name)

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

        breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)
        self.runCmd("breakpoint list")

        # Launch the process, and do not stop at the entry point.
        process = target.LaunchSimple (None, None, self.get_process_working_directory())

        self.runCmd("thread backtrace all")

        # Let's get the current stopped thread.  We'd like to switch to the
        # other thread to issue our 'po lock_me' command.
        import lldbutil
        this_thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(this_thread)

        # Find the other thread.  The iteration protocol of SBProcess and the
        # rich comparison methods (__eq__/__ne__) of SBThread come in handy.
        other_thread = None
        for t in process:
            if t != this_thread:
                other_thread = t
                break

        # Set the other thread as the selected thread to issue our 'po' command.other
        self.assertTrue(other_thread)
        process.SetSelectedThread(other_thread)
        if self.TraceOn():
            print "selected thread:" + lldbutil.get_description(other_thread)
        self.runCmd("thread backtrace")

        # We want to traverse the frame to the one corresponding to blocked.m to
        # issue our 'po lock_me' command.

        depth = other_thread.GetNumFrames()
        for i in range(depth):
            frame = other_thread.GetFrameAtIndex(i)
            name = frame.GetFunctionName()
            if name == 'main':
                other_thread.SetSelectedFrame(i)
                if self.TraceOn():
                    print "selected frame:" + lldbutil.get_description(frame)
                break

        self.expect("po lock_me", OBJECT_PRINTED_CORRECTLY,
            substrs = ['I am pretty special.'])
Exemplo n.º 13
0
    def print_obj(self, exe_name):
        """
        Test "print object" where another thread blocks the print object from making progress.

        Set a breakpoint on the line in my_pthread_routine.  Then switch threads
        to the main thread, and do print the lock_me object.  Since that will
        try to get the lock already gotten by my_pthread_routime thread, it will
        have to switch to running all threads, and that should then succeed.
        """
        exe = os.path.join(os.getcwd(), exe_name)

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

        breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
        self.assertTrue(breakpoint, VALID_BREAKPOINT)
        self.runCmd("breakpoint list")

        # Launch the process, and do not stop at the entry point.
        process = target.LaunchSimple (None, None, self.get_process_working_directory())

        self.runCmd("thread backtrace all")

        # Let's get the current stopped thread.  We'd like to switch to the
        # other thread to issue our 'po lock_me' command.
        import lldbutil
        this_thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(this_thread)

        # Find the other thread.  The iteration protocol of SBProcess and the
        # rich comparison methods (__eq__/__ne__) of SBThread come in handy.
        other_thread = None
        for t in process:
            if t != this_thread:
                other_thread = t
                break

        # Set the other thread as the selected thread to issue our 'po' command.other
        self.assertTrue(other_thread)
        process.SetSelectedThread(other_thread)
        if self.TraceOn():
            print "selected thread:" + lldbutil.get_description(other_thread)
        self.runCmd("thread backtrace")

        # We want to traverse the frame to the one corresponding to blocked.m to
        # issue our 'po lock_me' command.

        depth = other_thread.GetNumFrames()
        for i in range(depth):
            frame = other_thread.GetFrameAtIndex(i)
            name = frame.GetFunctionName()
            if name == 'main':
                other_thread.SetSelectedFrame(i)
                if self.TraceOn():
                    print "selected frame:" + lldbutil.get_description(frame)
                break

        self.expect("po lock_me", OBJECT_PRINTED_CORRECTLY,
            substrs = ['I am pretty special.'])
Exemplo n.º 14
0
    def __handle_process_event(self, ev):
        type = ev.GetType()

        if type & lldb.SBProcess.eBroadcastBitSTDOUT:
            self.get_process_stdout()
        elif type & lldb.SBProcess.eBroadcastBitSTDOUT:
            self.get_process_stderr()
        elif type & lldb.SBProcess.eBroadcastBitInterrupt:
            debug(debugDriver, 'Got a process interrupt event!')
            lldbutil.get_description(ev)
            if self.__process_stopped_callback:
                self.__process_stopped_callback(self, lldb.SBProcess.GetProcessFromEvent(ev))
        elif type & lldb.SBProcess.eBroadcastBitStateChanged:
            self.get_process_stdout()
            self.get_process_stderr()

            # only after printing the std* can we print our prompts
            state = lldb.SBProcess.GetStateFromEvent(ev)
            if state == lldb.eStateInvalid:
                return

            process = lldb.SBProcess.GetProcessFromEvent(ev)
            assert process.IsValid()

            if state == lldb.eStateInvalid       \
                or state == lldb.eStateUnloaded  \
                or state == lldb.eStateConnected \
                or state == lldb.eStateAttaching \
                or state == lldb.eStateLaunching \
                or state == lldb.eStateStepping  \
                or state == lldb.eStateDetached:
                lldb_view_send("Process %llu %s\n", process.GetProcessID(),
                    self.debugger.StateAsCString(state))

            elif state == lldb.eStateRunning:
                None  # Don't be too chatty
            elif state == lldb.eStateExited:
                debug(debugDriver, 'process state: ' + lldbutil.state_type_to_str(state))
                r = self.interpret_command('process status')
                lldb_view_send(stdout_msg(r[0].GetOutput()))
                lldb_view_send(stderr_msg(r[0].GetError()))
                # Remove program counter markers
                if self.__process_stopped_callback:
                    self.__process_stopped_callback(self, process, state)
            elif state == lldb.eStateStopped     \
                or state == lldb.eStateCrashed   \
                or state == lldb.eStateSuspended:
                debug(debugDriver, 'process state: ' + lldbutil.state_type_to_str(state)) if state != lldb.eStateStopped else None

                if lldb.SBProcess.GetRestartedFromEvent(ev):
                    lldb_view_send('Process %llu stopped and was programmatically restarted.' %
                        process.GetProcessID())
                else:
                    self.__update_selected_thread()
                    if self.__process_stopped_callback:
                        self.__process_stopped_callback(self, process, state)
Exemplo n.º 15
0
            def run(self):
                #print "Running MyListeningThread:", self

                # Regular expression pattern for the event description.
                pattern = re.compile("data = {.*, state = (.*)}$")

                # Let's only try at most 6 times to retrieve our events.
                count = 0
                while True:
                    if listener.WaitForEvent(5, event):
                        desc = lldbutil.get_description(event)
                        #print "Event description:", desc
                        match = pattern.search(desc)
                        if not match:
                            break
                        if self.context.state == 0 and match.group(
                                1) == 'running':
                            self.context.state = 1
                            continue
                        elif self.context.state == 1 and match.group(
                                1) == 'stopped':
                            # Whoopee, both events have been received!
                            self.context.state = 2
                            break
                        else:
                            break
                    print "Timeout: listener.WaitForEvent"
                    count = count + 1
                    if count > 6:
                        break

                return
Exemplo n.º 16
0
    def updated_content(self):
        thread = self.__thread
        if not thread.IsValid():
            return 'Invalid thread. Has it finished its work?'
        target = thread.GetProcess().GetTarget()

        frame = thread.GetSelectedFrame()
        registerList = frame.GetRegisters()
        result = 'Frame registers:'
        for value in registerList:
            #print value
            result = result + ('\n%s (number of registers = %d):\n' % (value.GetName(), value.GetNumChildren()))
            for child in value:
                if child.GetValue() is not None:
                    # Let's assume no register name is bigger than 10 chars, for now.
                    # 18 chars are needed for 64 bit values: 0x0000000000000000
                    addr = lldb.SBAddress(child.GetValueAsUnsigned(), target)
                    desc = lldbutil.get_description(addr)
                    if re.match('0x[0-9A-Fa-f]+|^$', desc):
                        desc = ''
                    else:
                        desc = '; ' + desc
                    result = result + ('%10.10s = %.18s%s\n' % (child.GetName(), child.GetValue(), desc))

        return result
Exemplo n.º 17
0
    def run(self, target=None):
        self.setup()

        if target is None:
            target = driver_instance().debugger.GetSelectedTarget()

        if not target:
            sublime.error_message('No selected target.')
            return

        bp_list = []
        for bp in target.breakpoint_iter():
            # We're going to have to parse the description to know which kind
            # of breakpoint we have, since lldb doesn't reify that information.
            bp_list.append(self.parse_description(lldbutil.get_description(bp)))

        string = ', '.join(bp_list)
        v = self.window.get_output_panel('breakpoint list')

        LLDBLayoutManager.clear_view(v)
        v.set_read_only(False)
        edit = v.begin_edit('bp-list-view-clear')
        v.replace(edit, sublime.Region(0, v.size()), string)
        v.end_edit(edit)
        v.set_read_only(True)

        self.window.run_command('show_panel', {"panel": 'output.breakpoint list'})
Exemplo n.º 18
0
 def notifyExited(self, process):
     self.win.erase()
     target = lldbutil.get_description(process.GetTarget())
     pid = process.GetProcessID()
     ec = process.GetExitStatus()
     self.win.addstr("\nProcess %s [%d] has exited with exit-code %d" %
                     (target, pid, ec))
Exemplo n.º 19
0
    def run(self, target=None):
        self.setup()

        if target is None:
            target = driver_instance().debugger.GetSelectedTarget()

        if not target:
            sublime.error_message('No selected target.')
            return

        bp_list = []
        for bp in target.breakpoint_iter():
            # We're going to have to parse the description to know which kind
            # of breakpoint we have, since lldb doesn't reify that information.
            bp_list.append(self.parse_description(
                lldbutil.get_description(bp)))

        string = ', '.join(bp_list)
        v = self.window.get_output_panel('breakpoint list')

        LLDBLayoutManager.clear_view(v)
        v.set_read_only(False)
        edit = v.begin_edit('bp-list-view-clear')
        v.replace(edit, sublime.Region(0, v.size()), string)
        v.end_edit(edit)
        v.set_read_only(True)

        self.window.run_command('show_panel',
                                {"panel": 'output.breakpoint list'})
Exemplo n.º 20
0
            def run(self):
                #print "Running MyListeningThread:", self

                # Regular expression pattern for the event description.
                pattern = re.compile("data = {.*, state = (.*)}$")

                # Let's only try at most 6 times to retrieve our events.
                count = 0
                while True:
                    if listener.WaitForEventForBroadcasterWithType(5,
                                                                   broadcaster,
                                                                   lldb.SBProcess.eBroadcastBitStateChanged,
                                                                   event):
                        desc = lldbutil.get_description(event)
                        #print "Event description:", desc
                        match = pattern.search(desc)
                        if not match:
                            break;
                        if self.context.state == 0 and match.group(1) == 'running':
                            self.context.state = 1
                            continue
                        elif self.context.state == 1 and match.group(1) == 'stopped':
                            # Whoopee, both events have been received!
                            self.context.state = 2
                            break
                        else:
                            break
                    print "Timeout: listener.WaitForEvent"
                    count = count + 1
                    if count > 6:
                        break

                return
Exemplo n.º 21
0
        def getLocations(event):
            locs = {}

            bp = lldb.SBBreakpoint.GetBreakpointFromEvent(event)

            if bp.IsInternal():
                # don't show anything for internal breakpoints
                return

            for location in bp:
                # hack! getting the LineEntry via SBBreakpointLocation.GetAddress.GetLineEntry does not work good for
                # inlined frames, so we get the description (which does take into account inlined functions) and parse it.
                desc = lldbutil.get_description(location,
                                                lldb.eDescriptionLevelFull)
                match = re.search('at\ ([^:]+):([\d]+)', desc)
                try:
                    path = match.group(1)
                    line = int(match.group(2).strip())
                except ValueError as e:
                    # bp loc unparsable
                    continue

                if path in locs:
                    locs[path].add(line)
                else:
                    locs[path] = set([line])
            return locs
Exemplo n.º 22
0
    def updated_content(self):
        thread = self.__thread
        if not thread.IsValid():
            return 'Invalid thread. Has it finished its work?'
        target = thread.GetProcess().GetTarget()

        frame = thread.GetSelectedFrame()
        registerList = frame.GetRegisters()
        result = 'Frame registers:'
        for value in registerList:
            #print value
            result = result + ('\n%s (number of registers = %d):\n' %
                               (value.GetName(), value.GetNumChildren()))
            for child in value:
                if child.GetValue() is not None:
                    # Let's assume no register name is bigger than 10 chars, for now.
                    # 18 chars are needed for 64 bit values: 0x0000000000000000
                    addr = lldb.SBAddress(child.GetValueAsUnsigned(), target)
                    desc = lldbutil.get_description(addr)
                    if re.match('0x[0-9A-Fa-f]+|^$', desc):
                        desc = ''
                    else:
                        desc = '; ' + desc
                    result = result + (
                        '%10.10s = %.18s%s\n' %
                        (child.GetName(), child.GetValue(), desc))

        return result
Exemplo n.º 23
0
    def getLocations(event):
      locs = {}

      bp = lldb.SBBreakpoint.GetBreakpointFromEvent(event)

      if bp.IsInternal():
        # don't show anything for internal breakpoints
        return

      for location in bp:
        # hack! getting the LineEntry via SBBreakpointLocation.GetAddress.GetLineEntry does not work good for
        # inlined frames, so we get the description (which does take into account inlined functions) and parse it.
        desc = lldbutil.get_description(location, lldb.eDescriptionLevelFull)
        match = re.search('at\ ([^:]+):([\d]+)', desc)
        try:
          path = match.group(1)
          line = int(match.group(2).strip())
        except ValueError as e:
          # bp loc unparsable
          continue

        if path in locs:
          locs[path].add(line)
        else:
          locs[path] = set([line])
      return locs
Exemplo n.º 24
0
 def notifyExited(self, process):
     self.win.erase()
     target = lldbutil.get_description(process.GetTarget())
     pid = process.GetProcessID()
     ec = process.GetExitStatus()
     self.win.addstr(
         "\nProcess %s [%d] has exited with exit-code %d" %
         (target, pid, ec))
Exemplo n.º 25
0
 def notifyExited(self, process):
     self.win.erase()
     target = lldbutil.get_description(process.GetTarget())
     pid = process.GetProcessID()
     ec = process.GetExitStatus()
     self.win.addstr(
         "\nProcess {0!s} [{1:d}] has exited with exit-code {2:d}".format(
             target, pid, ec))
Exemplo n.º 26
0
    def step_out_with_python(self):
        self.step_out_thread.StepOut()

        reason = self.step_out_thread.GetStopReason()
        self.assertEqual(lldb.eStopReasonPlanComplete, reason,
            "Expected thread stop reason 'plancomplete', but got '%s'" % lldbutil.stop_reason_to_str(reason))

        # Verify location after stepping out
        frame = self.step_out_thread.GetFrameAtIndex(0)
        desc = lldbutil.get_description(frame.GetLineEntry())
        expect = "main.cpp:%d" % self.step_out_destination
        self.assertTrue(expect in desc, "Expected %s but thread stopped at %s" % (expect, desc))
Exemplo n.º 27
0
    def step_out_with_python(self):
        self.step_out_thread.StepOut()

        reason = self.step_out_thread.GetStopReason()
        self.assertEqual(lldb.eStopReasonPlanComplete, reason,
            "Expected thread stop reason 'plancomplete', but got '%s'" % lldbutil.stop_reason_to_str(reason))

        # Verify location after stepping out
        frame = self.step_out_thread.GetFrameAtIndex(0)
        desc = lldbutil.get_description(frame.GetLineEntry())
        expect = "main.cpp:%d" % self.step_out_destination
        self.assertTrue(expect in desc, "Expected %s but thread stopped at %s" % (expect, desc))
Exemplo n.º 28
0
    def describe_threads(self):
        ret = []
        for x in self.inferior_process:
            id = x.GetIndexID()
            reason = x.GetStopReason()
            status = "stopped" if x.IsStopped() else "running"
            reason_str = lldbutil.stop_reason_to_str(reason)
            if reason == lldb.eStopReasonBreakpoint:
                bpid = x.GetStopReasonDataAtIndex(0)
                bp = self.inferior_target.FindBreakpointByID(bpid)
                reason_str = "%s hit %d times" % (lldbutil.get_description(bp), bp.GetHitCount())
            elif reason == lldb.eStopReasonWatchpoint:
                watchid = x.GetStopReasonDataAtIndex(0)
                watch = self.inferior_target.FindWatchpointByID(watchid)
                reason_str = "%s hit %d times" % (lldbutil.get_description(watch), watch.GetHitCount())
            elif reason == lldb.eStopReasonSignal:
                reason_str = "signal %s" % (signal_names[x.GetStopReasonDataAtIndex(0)])

            location = "\t".join([lldbutil.get_description(x.GetFrameAtIndex(i)) for i in range(x.GetNumFrames())])
            ret.append("thread %d %s due to %s at\n\t%s" % (id, status, reason_str, location))
        return ret
Exemplo n.º 29
0
 def run(self):
     count = 0
     # Let's only try at most 4 times to retrieve any kind of event.
     # After that, the thread exits.
     while not count > 3:
         if traceOn:
             print "Try wait for event..."
         if listener.WaitForEvent(5, event):
             if traceOn:
                 desc = lldbutil.get_description(event)
                 print "Event description:", desc
                 print "Event data flavor:", event.GetDataFlavor()
                 print "Process state:", lldbutil.state_type_to_str(process.GetState())
                 print
         else:
             if traceOn:
                 print "timeout occurred waiting for event..."
         count = count + 1
     return
Exemplo n.º 30
0
            def run(self):
                #print "Running MyListeningThread:", self

                # Regular expression pattern for the event description.
                pattern = re.compile("data = {.*, state = (.*)}$")

                # Let's only try at most 6 times to retrieve our events.
                count = 0
                while True:
                    if listener.WaitForEvent(5, event):
                        desc = lldbutil.get_description(event)
                        #print "Event description:", desc
                        match = pattern.search(desc)
                        if not match:
                            break
                        if match.group(1) == 'connected':
                            # When debugging remote targets with lldb-server, we
                            # first get the 'connected' event.
                            self.context.assertTrue(self.context.state == None)
                            self.context.state = 'connected'
                            continue
                        elif match.group(1) == 'running':
                            self.context.assertTrue(
                                self.context.state == None
                                or self.context.state == 'connected')
                            self.context.state = 'running'
                            continue
                        elif match.group(1) == 'stopped':
                            self.context.assertTrue(
                                self.context.state == 'running')
                            # Whoopee, both events have been received!
                            self.context.state = 'stopped'
                            break
                        else:
                            break
                    print "Timeout: listener.WaitForEvent"
                    count = count + 1
                    if count > 6:
                        break

                return
Exemplo n.º 31
0
            def run(self):
                #print "Running MyListeningThread:", self

                # Regular expression pattern for the event description.
                pattern = re.compile("data = {.*, state = (.*)}$")

                # Let's only try at most 6 times to retrieve our events.
                count = 0
                while True:
                    if listener.WaitForEvent(5, event):
                        desc = lldbutil.get_description(event)
                        #print "Event description:", desc
                        match = pattern.search(desc)
                        if not match:
                            break;
                        if match.group(1) == 'connected':
                            # When debugging remote targets with lldb-server, we
                            # first get the 'connected' event.
                            self.context.assertTrue(self.context.state == None)
                            self.context.state = 'connected'
                            continue
                        elif match.group(1) == 'running':
                            self.context.assertTrue(self.context.state == None or self.context.state == 'connected')
                            self.context.state = 'running'
                            continue
                        elif match.group(1) == 'stopped':
                            self.context.assertTrue(self.context.state == 'running')
                            # Whoopee, both events have been received!
                            self.context.state = 'stopped'
                            break
                        else:
                            break
                    print "Timeout: listener.WaitForEvent"
                    count = count + 1
                    if count > 6:
                        break

                return
Exemplo n.º 32
0
    def resolve_symbol_context_with_address(self):
        """Exercise SBTaget.ResolveSymbolContextForAddress() API."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Now create the two breakpoints inside function 'a'.
        breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
        breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
        #print "breakpoint1:", breakpoint1
        #print "breakpoint2:", breakpoint2
        self.assertTrue(breakpoint1 and breakpoint1.GetNumLocations() == 1,
                        VALID_BREAKPOINT)
        self.assertTrue(breakpoint2 and breakpoint2.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple(None, None, os.getcwd())
        self.assertTrue(process, PROCESS_IS_VALID)

        # Frame #0 should be on self.line1.
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process,
                                             lldb.eStopReasonBreakpoint)
        self.assertTrue(
            thread.IsValid(),
            "There should be a thread stopped due to breakpoint condition")
        #self.runCmd("process status")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line1)

        address1 = lineEntry.GetStartAddress()

        # Continue the inferior, the breakpoint 2 should be hit.
        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process,
                                             lldb.eStopReasonBreakpoint)
        self.assertTrue(
            thread.IsValid(),
            "There should be a thread stopped due to breakpoint condition")
        #self.runCmd("process status")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line2)

        address2 = lineEntry.GetStartAddress()

        #print "address1:", address1
        #print "address2:", address2

        # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses from our line entry.
        context1 = target.ResolveSymbolContextForAddress(
            address1, lldb.eSymbolContextEverything)
        context2 = target.ResolveSymbolContextForAddress(
            address2, lldb.eSymbolContextEverything)

        self.assertTrue(context1 and context2)
        #print "context1:", context1
        #print "context2:", context2

        # Verify that the context point to the same function 'a'.
        symbol1 = context1.GetSymbol()
        symbol2 = context2.GetSymbol()
        self.assertTrue(symbol1 and symbol2)
        #print "symbol1:", symbol1
        #print "symbol2:", symbol2

        from lldbutil import get_description
        desc1 = get_description(symbol1)
        desc2 = get_description(symbol2)
        self.assertTrue(desc1 and desc2 and desc1 == desc2,
                        "The two addresses should resolve to the same symbol")
Exemplo n.º 33
0
    def symbol_context(self):
        """Get an SBSymbolContext object and call its many methods."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Now create a breakpoint on main.c by name 'c'.
        breakpoint = target.BreakpointCreateByName('c', 'a.out')
        #print "breakpoint:", breakpoint
        self.assertTrue(breakpoint and
                        breakpoint.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple (None, None, self.get_process_working_directory())
        self.assertTrue(process, PROCESS_IS_VALID)

        # Frame #0 should be on self.line.
        from lldbutil import get_stopped_thread
        thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
        frame0 = thread.GetFrameAtIndex(0)
        self.assertTrue(frame0.GetLineEntry().GetLine() == self.line)

        # Now get the SBSymbolContext from this frame.  We want everything. :-)
        context = frame0.GetSymbolContext(lldb.eSymbolContextEverything)
        self.assertTrue(context)

        # Get the description of this module.
        module = context.GetModule()
        desc = lldbutil.get_description(module)
        self.expect(desc, "The module should match", exe=False,
            substrs = [os.path.join(self.mydir, 'a.out')])

        compileUnit = context.GetCompileUnit()
        self.expect(str(compileUnit), "The compile unit should match", exe=False,
            substrs = [os.path.join(self.mydir, 'main.c')])

        function = context.GetFunction()
        self.assertTrue(function)
        #print "function:", function

        block = context.GetBlock()
        self.assertTrue(block)
        #print "block:", block

        lineEntry = context.GetLineEntry()
        #print "line entry:", lineEntry
        self.expect(lineEntry.GetFileSpec().GetDirectory(), "The line entry should have the correct directory",
                    exe=False,
            substrs = [self.mydir])
        self.expect(lineEntry.GetFileSpec().GetFilename(), "The line entry should have the correct filename",
                    exe=False,
            substrs = ['main.c'])
        self.assertTrue(lineEntry.GetLine() == self.line,
                        "The line entry's line number should match ")

        symbol = context.GetSymbol()
        self.assertTrue(function.GetName() == symbol.GetName() and symbol.GetName() == 'c',
                        "The symbol name should be 'c'")
Exemplo n.º 34
0
 def add(self, event):
   text = urwid.Text('* ' + lldbutil.get_description(event))
   self.events.append(text)
   self.set_focus(len(self.events)-1)
   return
Exemplo n.º 35
0
    def disasm_and_address_api(self):
        """Exercise getting SBAddress objects, disassembly, and SBAddress APIs."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Now create the two breakpoints inside function 'a'.
        breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
        breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
        #print "breakpoint1:", breakpoint1
        #print "breakpoint2:", breakpoint2
        self.assertTrue(breakpoint1 and breakpoint1.GetNumLocations() == 1,
                        VALID_BREAKPOINT)
        self.assertTrue(breakpoint2 and breakpoint2.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple(None, None, os.getcwd())
        self.assertTrue(process, PROCESS_IS_VALID)

        # Frame #0 should be on self.line1.
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process,
                                             lldb.eStopReasonBreakpoint)
        self.assertTrue(
            thread != None,
            "There should be a thread stopped due to breakpoint condition")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line1)

        address1 = lineEntry.GetStartAddress()
        #print "address1:", address1

        # Now call SBTarget.ResolveSymbolContextForAddress() with address1.
        context1 = target.ResolveSymbolContextForAddress(
            address1, lldb.eSymbolContextEverything)

        self.assertTrue(context1)
        if self.TraceOn():
            print "context1:", context1

        # Continue the inferior, the breakpoint 2 should be hit.
        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process,
                                             lldb.eStopReasonBreakpoint)
        self.assertTrue(
            thread != None,
            "There should be a thread stopped due to breakpoint condition")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line2)

        # Verify that the symbol and the function has the same address range per function 'a'.
        symbol = context1.GetSymbol()
        function = frame0.GetFunction()
        self.assertTrue(symbol and function)

        disasm_output = lldbutil.disassemble(target, symbol)
        if self.TraceOn():
            print "symbol:", symbol
            print "disassembly=>\n", disasm_output

        disasm_output = lldbutil.disassemble(target, function)
        if self.TraceOn():
            print "function:", function
            print "disassembly=>\n", disasm_output

        sa1 = symbol.GetStartAddress()
        #print "sa1:", sa1
        #print "sa1.GetFileAddress():", hex(sa1.GetFileAddress())
        #ea1 = symbol.GetEndAddress()
        #print "ea1:", ea1
        sa2 = function.GetStartAddress()
        #print "sa2:", sa2
        #print "sa2.GetFileAddress():", hex(sa2.GetFileAddress())
        #ea2 = function.GetEndAddress()
        #print "ea2:", ea2
        self.assertTrue(sa1 and sa2 and sa1 == sa2,
                        "The two starting addresses should be the same")

        from lldbutil import get_description
        desc1 = get_description(sa1)
        desc2 = get_description(sa2)
        self.assertTrue(
            desc1 and desc2 and desc1 == desc2,
            "SBAddress.GetDescription() API of sa1 and sa2 should return the same string"
        )
Exemplo n.º 36
0
    def symbol_context(self):
        """Get an SBSymbolContext object and call its many methods."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Now create a breakpoint on main.c by name 'c'.
        breakpoint = target.BreakpointCreateByName('c', 'a.out')
        #print "breakpoint:", breakpoint
        self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple(None, None, os.getcwd())
        self.assertTrue(process, PROCESS_IS_VALID)

        # Frame #0 should be on self.line.
        from lldbutil import get_stopped_thread
        thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(thread != None,
                        "There should be a thread stopped due to breakpoint")
        frame0 = thread.GetFrameAtIndex(0)
        self.assertTrue(frame0.GetLineEntry().GetLine() == self.line)

        # Now get the SBSymbolContext from this frame.  We want everything. :-)
        context = frame0.GetSymbolContext(lldb.eSymbolContextEverything)
        self.assertTrue(context)

        # Get the description of this module.
        module = context.GetModule()
        desc = lldbutil.get_description(module)
        self.expect(desc,
                    "The module should match",
                    exe=False,
                    substrs=[os.path.join(self.mydir, 'a.out')])

        compileUnit = context.GetCompileUnit()
        self.expect(str(compileUnit),
                    "The compile unit should match",
                    exe=False,
                    substrs=[os.path.join(self.mydir, 'main.c')])

        function = context.GetFunction()
        self.assertTrue(function)
        #print "function:", function

        block = context.GetBlock()
        self.assertTrue(block)
        #print "block:", block

        lineEntry = context.GetLineEntry()
        #print "line entry:", lineEntry
        self.expect(lineEntry.GetFileSpec().GetDirectory(),
                    "The line entry should have the correct directory",
                    exe=False,
                    substrs=[self.mydir])
        self.expect(lineEntry.GetFileSpec().GetFilename(),
                    "The line entry should have the correct filename",
                    exe=False,
                    substrs=['main.c'])
        self.assertTrue(lineEntry.GetLine() == self.line,
                        "The line entry's line number should match ")

        symbol = context.GetSymbol()
        self.assertTrue(
            function.GetName() == symbol.GetName() and symbol.GetName() == 'c',
            "The symbol name should be 'c'")
Exemplo n.º 37
0
 def notifyExited(self, process):
   self.win.erase()
   target = lldbutil.get_description(process.GetTarget())
   pid = process.GetProcessID()
   ec = process.GetExitStatus()
   self.win.addstr("\nProcess {0!s} [{1:d}] has exited with exit-code {2:d}".format(target, pid, ec))
Exemplo n.º 38
0
 def handleEvent(self, event):
     if isinstance(event, lldb.SBEvent):
         self.win.scroll()
         h = self.win.getmaxyx()[0]
         self.win.addstr(h - 1, 0, lldbutil.get_description(event))
     return
Exemplo n.º 39
0
    def do_watchpoint_iter(self):
        """Use SBTarget.watchpoint_iter() to do Pythonic iteration on the available watchpoints."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Create a breakpoint on main.c in order to set our watchpoint later.
        breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
        self.assertTrue(breakpoint and
                        breakpoint.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at the entry point.
        process = target.LaunchSimple(None, None, os.getcwd())

        # We should be stopped due to the breakpoint.  Get frame #0.
        process = target.GetProcess()
        self.assertTrue(process.GetState() == lldb.eStateStopped,
                        PROCESS_STOPPED)
        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        frame0 = thread.GetFrameAtIndex(0)

        # Watch 'global' for read and write.
        value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal)
        error = lldb.SBError();
        watchpoint = value.Watch(True, True, True, error)
        self.assertTrue(value and watchpoint,
                        "Successfully found the variable and set a watchpoint")
        self.DebugSBValue(value)

        # Hide stdout if not running with '-t' option.
        if not self.TraceOn():
            self.HideStdout()

        # There should be only 1 watchpoint location under the target.
        self.assertTrue(target.GetNumWatchpoints() == 1)
        self.assertTrue(watchpoint.IsEnabled())
        watch_id = watchpoint.GetID()
        self.assertTrue(watch_id != 0)

        # Continue.  Expect the program to stop due to the variable being written to.
        process.Continue()

        # Hide stdout if not running with '-t' option.
        if not self.TraceOn():
            self.HideStdout()

        # Print the stack traces.
        lldbutil.print_stacktraces(process)

        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
        self.assertTrue(thread, "The thread stopped due to watchpoint")
        self.DebugSBValue(value)

        # We currently only support hardware watchpoint.  Verify that we have a
        # meaningful hardware index at this point.  Exercise the printed repr of
        # SBWatchpointLocation.
        print watchpoint
        self.assertTrue(watchpoint.GetHardwareIndex() != -1)

        # SBWatchpoint.GetDescription() takes a description level arg.
        print lldbutil.get_description(watchpoint, lldb.eDescriptionLevelFull)

        # Now disable the 'rw' watchpoint.  The program won't stop when it reads
        # 'global' next.
        watchpoint.SetEnabled(False)
        self.assertTrue(watchpoint.GetHardwareIndex() == -1)
        self.assertFalse(watchpoint.IsEnabled())

        # Continue.  The program does not stop again when the variable is being
        # read from because the watchpoint location has been disabled.
        process.Continue()

        # At this point, the inferior process should have exited.
        self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)

        # Verify some vital statistics and exercise the iterator API.
        for watchpoint in target.watchpoint_iter():
            self.assertTrue(watchpoint)
            self.assertTrue(watchpoint.GetWatchSize() == 4)
            self.assertTrue(watchpoint.GetHitCount() == 1)
            print watchpoint
Exemplo n.º 40
0
    def resolve_symbol_context_with_address(self):
        """Exercise SBTaget.ResolveSymbolContextForAddress() API."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Now create the two breakpoints inside function 'a'.
        breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
        breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
        #print "breakpoint1:", breakpoint1
        #print "breakpoint2:", breakpoint2
        self.assertTrue(breakpoint1 and
                        breakpoint1.GetNumLocations() == 1,
                        VALID_BREAKPOINT)
        self.assertTrue(breakpoint2 and
                        breakpoint2.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple(None, None, os.getcwd())
        self.assertTrue(process, PROCESS_IS_VALID)

        # Frame #0 should be on self.line1.
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
        #self.runCmd("process status")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line1)

        address1 = lineEntry.GetStartAddress()

        # Continue the inferior, the breakpoint 2 should be hit.
        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
        #self.runCmd("process status")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line2)

        address2 = lineEntry.GetStartAddress()

        #print "address1:", address1
        #print "address2:", address2

        # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses from our line entry.
        context1 = target.ResolveSymbolContextForAddress(address1, lldb.eSymbolContextEverything)
        context2 = target.ResolveSymbolContextForAddress(address2, lldb.eSymbolContextEverything)

        self.assertTrue(context1 and context2)
        #print "context1:", context1
        #print "context2:", context2

        # Verify that the context point to the same function 'a'.
        symbol1 = context1.GetSymbol()
        symbol2 = context2.GetSymbol()
        self.assertTrue(symbol1 and symbol2)
        #print "symbol1:", symbol1
        #print "symbol2:", symbol2

        from lldbutil import get_description
        desc1 = get_description(symbol1)
        desc2 = get_description(symbol2)
        self.assertTrue(desc1 and desc2 and desc1 == desc2,
                        "The two addresses should resolve to the same symbol")
Exemplo n.º 41
0
 def handleEvent(self, event):
     if isinstance(event, lldb.SBEvent):
         self.win.scroll()
         h = self.win.getmaxyx()[0]
         self.win.addstr(h - 1, 0, lldbutil.get_description(event))
     return
Exemplo n.º 42
0
    def test(self):
        """Exercise getting SBAddress objects, disassembly, and SBAddress APIs."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Now create the two breakpoints inside function 'a'.
        breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
        breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
        #print("breakpoint1:", breakpoint1)
        #print("breakpoint2:", breakpoint2)
        self.assertTrue(breakpoint1 and
                        breakpoint1.GetNumLocations() == 1,
                        VALID_BREAKPOINT)
        self.assertTrue(breakpoint2 and
                        breakpoint2.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at entry point.
        process = target.LaunchSimple (None, None, self.get_process_working_directory())
        self.assertTrue(process, PROCESS_IS_VALID)

        # Frame #0 should be on self.line1.
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line1)

        address1 = lineEntry.GetStartAddress()
        #print("address1:", address1)

        # Now call SBTarget.ResolveSymbolContextForAddress() with address1.
        context1 = target.ResolveSymbolContextForAddress(address1, lldb.eSymbolContextEverything)

        self.assertTrue(context1)
        if self.TraceOn():
            print("context1:", context1)

        # Continue the inferior, the breakpoint 2 should be hit.
        process.Continue()
        self.assertTrue(process.GetState() == lldb.eStateStopped)
        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
        frame0 = thread.GetFrameAtIndex(0)
        lineEntry = frame0.GetLineEntry()
        self.assertTrue(lineEntry.GetLine() == self.line2)

        # Verify that the symbol and the function has the same address range per function 'a'.
        symbol = context1.GetSymbol()
        function = frame0.GetFunction()
        self.assertTrue(symbol and function)

        disasm_output = lldbutil.disassemble(target, symbol)
        if self.TraceOn():
            print("symbol:", symbol)
            print("disassembly=>\n", disasm_output)

        disasm_output = lldbutil.disassemble(target, function)
        if self.TraceOn():
            print("function:", function)
            print("disassembly=>\n", disasm_output)

        sa1 = symbol.GetStartAddress()
        #print("sa1:", sa1)
        #print("sa1.GetFileAddress():", hex(sa1.GetFileAddress()))
        #ea1 = symbol.GetEndAddress()
        #print("ea1:", ea1)
        sa2 = function.GetStartAddress()
        #print("sa2:", sa2)
        #print("sa2.GetFileAddress():", hex(sa2.GetFileAddress()))
        #ea2 = function.GetEndAddress()
        #print("ea2:", ea2)
        self.assertTrue(sa1 and sa2 and sa1 == sa2,
                        "The two starting addresses should be the same")

        from lldbutil import get_description
        desc1 = get_description(sa1)
        desc2 = get_description(sa2)
        self.assertTrue(desc1 and desc2 and desc1 == desc2,
                        "SBAddress.GetDescription() API of sa1 and sa2 should return the same string")
Exemplo n.º 43
0
    def do_watchpoint_iter(self):
        """Use SBTarget.watchpoint_iter() to do Pythonic iteration on the available watchpoints."""
        exe = os.path.join(os.getcwd(), "a.out")

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

        # Create a breakpoint on main.c in order to set our watchpoint later.
        breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
        self.assertTrue(breakpoint and
                        breakpoint.GetNumLocations() == 1,
                        VALID_BREAKPOINT)

        # Now launch the process, and do not stop at the entry point.
        process = target.LaunchSimple(None, None, os.getcwd())

        # We should be stopped due to the breakpoint.  Get frame #0.
        process = target.GetProcess()
        self.assertTrue(process.GetState() == lldb.eStateStopped,
                        PROCESS_STOPPED)
        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
        frame0 = thread.GetFrameAtIndex(0)

        # Watch 'global' for read and write.
        value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal)
        watchpoint = value.Watch(True, True, True)
        self.assertTrue(value and watchpoint,
                        "Successfully found the variable and set a watchpoint")
        self.DebugSBValue(value)

        # Hide stdout if not running with '-t' option.
        if not self.TraceOn():
            self.HideStdout()

        # There should be only 1 watchpoint location under the target.
        self.assertTrue(target.GetNumWatchpoints() == 1)
        self.assertTrue(watchpoint.IsEnabled())
        watch_id = watchpoint.GetID()
        self.assertTrue(watch_id != 0)

        # Continue.  Expect the program to stop due to the variable being written to.
        process.Continue()

        # Hide stdout if not running with '-t' option.
        if not self.TraceOn():
            self.HideStdout()

        # Print the stack traces.
        lldbutil.print_stacktraces(process)

        thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
        self.assertTrue(thread, "The thread stopped due to watchpoint")
        self.DebugSBValue(value)

        # We currently only support hardware watchpoint.  Verify that we have a
        # meaningful hardware index at this point.  Exercise the printed repr of
        # SBWatchpointLocation.
        print watchpoint
        self.assertTrue(watchpoint.GetHardwareIndex() != -1)

        # SBWatchpoint.GetDescription() takes a description level arg.
        print lldbutil.get_description(watchpoint, lldb.eDescriptionLevelFull)

        # Now disable the 'rw' watchpoint.  The program won't stop when it reads
        # 'global' next.
        watchpoint.SetEnabled(False)
        self.assertTrue(watchpoint.GetHardwareIndex() == -1)
        self.assertFalse(watchpoint.IsEnabled())

        # Continue.  The program does not stop again when the variable is being
        # read from because the watchpoint location has been disabled.
        process.Continue()

        # At this point, the inferior process should have exited.
        self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)

        # Verify some vital statistics and exercise the iterator API.
        for watchpoint in target.watchpoint_iter():
            self.assertTrue(watchpoint)
            self.assertTrue(watchpoint.GetWatchSize() == 4)
            self.assertTrue(watchpoint.GetHitCount() == 1)
            print watchpoint
Exemplo n.º 44
0
 def notify_exited(self, process):
   target = lldbutil.get_description(process.GetTarget())
   pid = process.GetProcessID()
   ec = process.GetExitStatus()
   self.walker.message("Process %s [%d] has exited with exit-code %d" % (target, pid, ec))