Пример #1
0
    def trace(self):
        self.type = 'list'
        self.curr = None
        self.main = gdb.parse_and_eval('rb_main_thread')

        self.unwind = gdb.parameter('unwindonsignal')
        gdb.execute('set unwindonsignal on')

        gdb.execute('watch rb_curr_thread')
        gdb.breakpoints()[-1].silent = True
        num = gdb.breakpoints()[-1].number

        try:
            prev = None
            while True:
                gdb.execute('continue')
                curr = gdb.parse_and_eval('rb_curr_thread')
                if curr == prev: break
                self.print_thread(curr)
                prev = curr
        except KeyboardInterrupt:
            None

        gdb.execute('delete %d' % num)
        gdb.execute('set unwindonsignal %s' % (self.unwind and 'on' or 'off'))
Пример #2
0
    def load_all_symbols(self):
        gdb.write("loading vmlinux\n")

        # Dropping symbols will disable all breakpoints. So save their states
        # and restore them afterward.
        saved_states = []
        if hasattr(gdb, 'breakpoints') and not gdb.breakpoints() is None:
            for bp in gdb.breakpoints():
                saved_states.append({'breakpoint': bp, 'enabled': bp.enabled})

        # drop all current symbols and reload vmlinux
        orig_vmlinux = 'vmlinux'
        for obj in gdb.objfiles():
            if obj.filename.endswith('vmlinux'):
                orig_vmlinux = obj.filename
        gdb.execute("symbol-file", to_string=True)
        gdb.execute("symbol-file {0}".format(orig_vmlinux))

        self.loaded_modules = []
        module_list = modules.module_list()
        if not module_list:
            gdb.write("no modules found\n")
        else:
            [self.load_module_symbols(module) for module in module_list]

        for saved_state in saved_states:
            saved_state['breakpoint'].enabled = saved_state['enabled']
Пример #3
0
  def trace (self):
    self.type = 'list'
    self.curr = None
    self.main = gdb.parse_and_eval('rb_main_thread')

    self.unwind = gdb.parameter('unwindonsignal')
    gdb.execute('set unwindonsignal on')

    gdb.execute('watch rb_curr_thread')
    gdb.breakpoints()[-1].silent = True
    num = gdb.breakpoints()[-1].number

    try:
      prev = None
      while True:
        gdb.execute('continue')
        curr = gdb.parse_and_eval('rb_curr_thread')
        if curr == prev: break
        self.print_thread(curr)
        prev = curr
    except KeyboardInterrupt:
      None

    gdb.execute('delete %d' % num)
    gdb.execute('set unwindonsignal %s' % (self.unwind and 'on' or 'off'))
Пример #4
0
    def load_all_symbols(self):
        gdb.write("loading vmlinux\n")

        # Dropping symbols will disable all breakpoints. So save their states
        # and restore them afterward.
        saved_states = []
        if hasattr(gdb, 'breakpoints') and not gdb.breakpoints() is None:
            for bp in gdb.breakpoints():
                saved_states.append({'breakpoint': bp, 'enabled': bp.enabled})

        # drop all current symbols and reload vmlinux
        orig_vmlinux = 'vmlinux'
        for obj in gdb.objfiles():
            if (obj.filename.endswith('vmlinux')
                    or obj.filename.endswith('vmlinux.debug')):
                orig_vmlinux = obj.filename
        gdb.execute("symbol-file", to_string=True)
        gdb.execute("symbol-file {0}".format(orig_vmlinux))

        self.loaded_modules = []
        module_list = modules.module_list()
        if not module_list:
            gdb.write("no modules found\n")
        else:
            [self.load_module_symbols(module) for module in module_list]

        for saved_state in saved_states:
            saved_state['breakpoint'].enabled = saved_state['enabled']
Пример #5
0
def init(output=True):
    global proc_name, is_pie_on
    if not set_current_pid():
        return
    proc_name = get_proc_name()
    is_pie_on = pie_on(proc_name)
    if is_pie_on:
        set_elf_base(proc_name, output)
    gdb.execute('getheap', to_string=(not output))
    gdb.execute('libc', to_string=(not output))
    if is_pie_on:
        # if existing some breakpoints, delete them and set new breakpoints
        if gdb.breakpoints():
            breakpoints = []
            for br in gdb.breakpoints():
                if not br.location:  # watchpoint will be None
                    br.delete()
                    continue
                # won't delete symbol breakpoint
                find = re.findall('^\*((?:0x)?[0-9a-fA-F]+)$', br.location)
                # TODO: convert number to symbol if possible
                if find:
                    location = int(find[0],
                                   0)  # let python figure out the base
                    breakpoints.append(location - elf_base_old)
                    br.delete()
            for i in breakpoints:
                gdb.execute('b *%d' % (i + elf_base))
Пример #6
0
    def mark_breakpoints(self):
        breakpoints = []
        if gdb.breakpoints() is not None:
            breakpoints = gdb.breakpoints()
        new_breakpoints = {}
        for breakpoint in breakpoints:
            for filename, line in self.get_locations(breakpoint):
                if filename is not None and breakpoint.enabled:
                    new_breakpoints[(filename, line)] = 'breakpoint'
        if self.filename is not None:
            name = 'pc_and_breakpoint' if (self.filename, self.line) in new_breakpoints.keys() else 'just_pc'
            new_breakpoints[(self.filename, self.line)] = name

        old_breakpoints = set(self.breakpoints.keys())
        remove = { key: self.breakpoints[key] for key in old_breakpoints - set(new_breakpoints.keys()) }
        for (filename, line), (num, _) in remove.items():
            self.vim(op='unplace', num=num)
            del self.breakpoints[(filename, line)]

        for (filename, line), name in new_breakpoints.items():
            if (filename, line) not in self.breakpoints:
                self.breakpoints[(filename, line)] = (self.next_breakpoint, name)
                self.vim(op='place', num=self.next_breakpoint, name=name, line=line, filename=filename)
                self.next_breakpoint += 1
            else:
                num, old_name = self.breakpoints[(filename, line)]
                if old_name != name:
                    self.breakpoints[(filename, line)] = (num, name)
                    self.vim(op='replace', num=num, name=name, filename=filename)
Пример #7
0
    def test_break(self):
        breakpoint_amount = len(gdb.breakpoints() or ())
        gdb.execute('cy break codefile.spam')

        self.assertEqual(len(gdb.breakpoints()), breakpoint_amount + 1)
        bp = gdb.breakpoints()[-1]
        self.assertEqual(bp.type, gdb.BP_BREAKPOINT)
        assert self.spam_func.cname in bp.location
        assert bp.enabled
Пример #8
0
    def test_break(self):
        breakpoint_amount = len(gdb.breakpoints() or ())
        gdb.execute('cy break codefile.spam')

        self.assertEqual(len(gdb.breakpoints()), breakpoint_amount + 1)
        bp = gdb.breakpoints()[-1]
        self.assertEqual(bp.type, gdb.BP_BREAKPOINT)
        assert self.spam_func.cname in bp.location
        assert bp.enabled
Пример #9
0
 def toggle_breakpoints(self, filename, line):
     found = False
     if gdb.breakpoints() is not None:
         for breakpoint in gdb.breakpoints():
             for old_filename, old_line in self.get_locations(breakpoint):
                 if (old_filename, old_line) == (filename, line) and breakpoint.is_valid():
                     breakpoint.delete()
                     found = True
     if not found:
         gdb.execute("break %s:%d" % (filename, line))
Пример #10
0
    def invoke(self, arg, from_tty):
        nums = arg.split()
        if 'all' in nums:
            nums = map (lambda val: val.number, gdb.breakpoints())
        else:
            nums = map (self._to_num, nums)
            nums = filter (None, nums)

        for bp in gdb.breakpoints():
            if bp.number in nums:
                bp.enabled = not bp.enabled
Пример #11
0
    def invoke(self, arg, from_tty):
        if not gdb_running_under_rr():
            raise gdb.error('reverse-callback requires debugging under rr: ' +
                            'https://rr-project.org/')

        # Find the stack frame which extracts the bind state from the task.
        bind_state_frame = find_nearest_frame_matching(
            gdb.selected_frame(), lambda frame: frame.function() and re.match(
                '^base::internal::Invoker<base::internal::BindState<.*>' +
                '::RunOnce\(base::internal::BindStateBase\*\)$',
                frame.function().name))
        if bind_state_frame is None:
            raise Exception(
                'base::internal::Invoker frame not found; are you in a callback?'
            )
        bind_state_frame.select()

        # Disable all existing breakpoints.
        was_enabled = []
        for breakpoint in gdb.breakpoints():
            was_enabled.append(breakpoint.enabled)
            breakpoint.enabled = False

        # Break on the initialization of the BindState.
        storage_address = gdb.parse_and_eval('storage')
        watchpoint = gdb.Breakpoint('*' + str(storage_address),
                                    gdb.BP_WATCHPOINT)

        # Find the construction.
        gdb.execute('reverse-continue')

        # Restore breakpoints
        watchpoint.delete()
        for breakpoint, enabled in zip(gdb.breakpoints(), was_enabled):
            breakpoint.enabled = enabled

        # Find the stack frame which created the BindState.
        def in_bindstate(frame):
            return frame.function() and frame.function().name.startswith(
                'base::internal::BindState<')

        creation_frame = find_nearest_frame_matching(
            find_nearest_frame_matching(gdb.selected_frame(), in_bindstate),
            lambda frame: not in_bindstate(frame))

        # The callback creates the bindstate, step up once more to get the creator
        # of the callback.
        creation_frame.older().select()
Пример #12
0
 def prepare(self):
     print("[*] resetting hit counts")
     for bp in gdb.breakpoints():
         bp.hit_count = 0
         bp.silent = True
         bp.enabled = bp.number in self.enabled
     print("[*] enabled breakpoints: ", self.enabled)
Пример #13
0
 def update(self):
     for bp in gdb.breakpoints():
         if bp.hit_count != self.bp_hits[bp.number]:
             self.bp_hits[bp.number] = bp.hit_count
             print(
                 f"[{len(self.events)}] hit bp {bp.number} ({bp.location})")
             self.events.append(bp.number)
Пример #14
0
 def remove_old_bps():
     bps = gdb.breakpoints()
     if not bps:
         return
     for bp in bps:
         if getattr(bp, 'DYNAMORIO_BP', False):
             bp.delete()
Пример #15
0
def get_breakpoint(location=None,
                   expression=None,
                   condition=None,
                   number=None):
    """Return last breakpoint if not arguments given,
    or the breakpoint with given number if `number` given,
    or the first breakpoint matched given
    `location`(for `breakpoint`)/`expression`(for watchpoint) and `condition`.

    If there is no any breakpoint,
    raise gdb.GdbError('No breakpoints or watchpoints.')
    If there is no matched breakpoint, return None.
    """
    if location is None and expression is None and number is None:
        return get_last_breakpoint()
    bps = gdb.breakpoints()
    if bps is None: raise gdb.GdbError('No breakpoints or watchpoints.')

    if number is not None:
        for bp in bps:
            if bp.number == number:
                return bp
    else:
        for bp in bps:
            if (bp.location == location and bp.expression == expression
                    and bp.condition == condition):
                return bp
    return None
Пример #16
0
def sgx_debugger_init():
    print ("detect urts is loaded, initializing")
    global SIZE
    SIZE = gdb.parse_and_eval("sizeof(long)")
    inited = 0
    bps = gdb.breakpoints()
    if None != bps:
        for bp in bps:
            if bp.location == "sgx_debug_load_state_add_element":
                inited = 1
                break
    if os.getenv("OCCLUM_GDB") == "1":
        global OCCLUM_GDB
        OCCLUM_GDB = 1
    if inited == 0:
        detach_enclaves()
        gdb.execute("source gdb_sgx_cmd", False, True)
        UpdateOcallFrame()
        LoadEventBreakpoint()
        UnloadEventBreakpoint()
        GetTCSBreakpoint()
        if OCCLUM_GDB != 1:
            GetRandomStackBreakpoint()
        gdb.events.exited.connect(exit_handler)
    init_enclaves_debug()
Пример #17
0
 def invoke(self, arg, from_tty):
     arg = int(arg)
     for bp in gdb.breakpoints():
         if bp.number == arg:
             self.edit_and_reapply(bp)
             return
     raise gdb.GdbError("breakpoint " + arg + " not found")
Пример #18
0
def del_bps(start=None, end=None):
    '''
        Delete all gdb breakpoints
    '''

    for bp in gdb.breakpoints():
        bp.delete()
Пример #19
0
 def remove_old_bps():
     bps = gdb.breakpoints()
     if not bps:
         return
     for bp in bps:
         if getattr(bp, 'DYNAMORIO_BP', False):
             bp.delete()
Пример #20
0
 def invoke(self, arg, from_tty):
     arg = int(arg)
     for bp in gdb.breakpoints():
         if bp.number == arg:
             self.edit_and_reapply(bp)
             return
     raise gdb.GdbError("breakpoint " + arg + " not found")
Пример #21
0
def enable_msi_bp_dync():
    blist = gdb.breakpoints()
    for b in blist:
        if '__inc_opcode_cnt_dyn' == b.location and b.is_valid():
            b.enabled = True
            break
    return
Пример #22
0
def main(session):
    gdb.execute('set python print-stack full')
    if not session.out.show_unprocessed:
        gdb.execute('set inferior-tty /dev/null')
    try:
        # GDB will automatically load the symbols when needed, but if we do it first we get to detect problems
        load_libwayland_symbols(session)
    except RuntimeError as e:
        session.out.warn('Loading libwayland symbols failed: ' + str(e))
    WlConnectionCreateBreakpoint(session)
    WlConnectionDestroyBreakpoint(session)
    WlClosureCallBreakpoint(session, 'invoke', False)
    WlClosureCallBreakpoint(session, 'dispatch', False)
    WlClosureCallBreakpoint(session, 'send', True)
    WlClosureCallBreakpoint(session, 'queue', True)
    WlCommand('w', session)
    WlCommand('wl', session)
    WlCommand('wayland', session)
    for c in session.commands:
        WlSubcommand(c.name, session)
    session.out.log('Breakpoints: ' + repr(gdb.breakpoints()))
    if not check_libwayland_symbols(session):
        session.out.warn(
            'libwayland debug symbols were not found, so Wayland messages may not be detected in GDB mode'
        )
        session.out.warn(
            'See https://github.com/wmww/wayland-debug/blob/master/libwayland_debug_symbols.md for more information'
        )
Пример #23
0
 def pkg_delete_bps(self, bps):
     valid_numbers = set(
         [bp.number for bp in gdb.breakpoints() if bp.is_valid()])
     stored_numbers = set(self.bp_gdb_mc.keys())
     invalid_numbers = stored_numbers - valid_numbers
     ids = []
     for number in invalid_numbers:
         bp_data = {}
         bp_data['number'] = number
         external_id = self.bp_gdb_mc[number]
         if external_id is not None:
             bp_data['external_id'] = external_id
         ids.append(bp_data)
         del self.bp_gdb_mc[number]
     for bp in bps:
         if not bp.is_valid():
             continue
         number = bp.number
         if number in self.bp_gdb_mc:
             bp_data = {}
             bp_data['number'] = number
             external_id = self.bp_gdb_mc[number]
             if external_id is not None:
                 bp_data['external_id'] = external_id
             ids.append(bp_data)
     if len(ids) == 0:
         return
     return {
         'cmd': 'bpsdel',
         'ids': ids,
     }
Пример #24
0
 def get_breakpoints(self):
     bps = gdb.breakpoints()
     bps_list = []
     for b in bps:
         if b.enabled:
             bps_list.append(b.location)
     return bps_list
Пример #25
0
 def seek(self, index):
     # TODO: prefer path of least stops
     bpnum = self.events[index]
     was_enabled = set()
     for bp in gdb.breakpoints():
         if bp.enabled:
             was_enabled.add(bp.number)
         bp.enabled = bp.number == bpnum
     skipcount = self.events[:index].count(bpnum)
     print("[*] seeking...")
     gdb.execute("run")
     for i in range(skipcount):
         gdb.execute("continue")
         # print(f"\u001b[1000D[*] {i+1} / {skipcount}")
     for bp in gdb.breakpoints():
         bp.enabled = bp.number in was_enabled
Пример #26
0
 def __init__(self, enabled=None):
     self.events = []
     self.enabled = enabled
     if self.enabled is None:
         self.enabled = [b.number for b in gdb.breakpoints()]
     self.ranges = [(bid, 0, None) for bid in self.enabled]
     self.bp_hits = defaultdict(int)
Пример #27
0
def oe_debugger_init():
    #execute "set displaced-stepping off" to workaround the gdb 7.11 issue
    gdb.execute("set displaced-stepping off", False, True)

    # When the inferior quits, execute cleanup.
    gdb.events.exited.connect(exited_handler)

    # Add a handler for every time an object file is loaded.
    # This is used when the debugger is attached to a running process.
    gdb.events.new_objfile.connect(new_objfile_handler)

    bps = gdb.breakpoints()
    if bps != None:
        for bp in bps:
            if bp.location == "oe_debug_enclave_created_hook" and bp.is_valid(
            ):
                return

    # Cleanup and set breakpoints.
    oe_debugger_cleanup()
    EnclaveCreationBreakpoint()
    EnclaveTerminationBreakpoint()
    ModuleLoadedBreakpoint()
    ModuleUnloadedBreakpoint()
    return
Пример #28
0
def del_bps(start=None,end=None):
    '''
        Delete all gdb breakpoints
    '''

    for bp in gdb.breakpoints():
        bp.delete()
Пример #29
0
def get_breakpoint(location=None, expression=None, condition=None, number=None):
    """Return last breakpoint if not arguments given,
    or the breakpoint with given number if `number` given,
    or the first breakpoint matched given
    `location`(for `breakpoint`)/`expression`(for watchpoint) and `condition`.

    If there is no any breakpoint,
    raise gdb.GdbError('No breakpoints or watchpoints.')
    If there is no matched breakpoint, return None.
    """
    if location is None and expression is None and number is None:
        return get_last_breakpoint()
    bps = gdb.breakpoints()
    if bps is None: raise gdb.GdbError('No breakpoints or watchpoints.')

    if number is not None:
        for bp in bps:
            if bp.number == number:
                return bp
    else:
        for bp in bps:
            if (bp.location == location and bp.expression == expression and
                bp.condition == condition):
                return bp
    return None
Пример #30
0
def disable_msi_bp():
    blist = gdb.breakpoints()
    for b in blist:
        if '__inc_opcode_cnt' == b.location and b.is_valid():
            b.enabled = False
            break
    return
Пример #31
0
def clear_temp_breaks():
    if not pwndbg.proc.alive:
        breakpoints = gdb.breakpoints()
        if breakpoints:
            for bp in breakpoints:
                if bp.temporary and not bp.visible:  #visible is used instead of internal because older gdb's don't support internal
                    bp.delete()
Пример #32
0
def main(session):
    gdb.execute('set python print-stack full')
    if not session.out.show_unprocessed:
        gdb.execute('set inferior-tty /dev/null')
    WlConnectionCreateBreakpoint(session)
    WlConnectionDestroyBreakpoint(session)
    WlClosureCallBreakpoint(session, 'invoke', False)
    WlClosureCallBreakpoint(session, 'dispatch', False)
    WlClosureCallBreakpoint(session, 'send', True)
    WlClosureCallBreakpoint(session, 'queue', True)
    WlCommand('w', session)
    WlCommand('wl', session)
    WlCommand('wayland', session)
    for c in session.commands:
        WlSubcommand(c.name, session)
    session.out.log('Breakpoints: ' + repr(gdb.breakpoints()))
    try:
        result = check_libwayland()
        if result == None:
            session.out.log('libwayland found with debug symbols')
        else:
            session.out.log(result)
            session.out.error('Installed libwayland lacks debug symbols, GDB mode will not function')
    except RuntimeError as e:
        session.out.warn('Checking libwayland failed: ' + str(e))
Пример #33
0
    def GetBreakpoints(self,
                       source,
                       delete_breakpoint=None,
                       update_breakpoint=None):
        """Return all lines that have breakpoints in provided source file.

        This function is equal to GetBreakpoints, but does not require 'info break'.
        NOTE: Occasionally provides function breakpoints with an offset of 1."""
        import gdb
        breaklines = set()
        enabled = dict()

        breakpointlines = self.GetBreakpointLines(source)
        if update_breakpoint != None and update_breakpoint in breakpointlines:
            update_breakline = breakpointlines[update_breakpoint]
        else:
            update_breakline = None

        for breakpoint in gdb.breakpoints():
            key = breakpoint.number
            if breakpoint.number is not delete_breakpoint and key in breakpointlines:
                breakline = breakpointlines[key]
                breaklines.add(breakline)
                if breakline in enabled:
                    enabled[
                        breakline] = enabled[breakline] or breakpoint.enabled
                else:
                    enabled[breakline] = breakpoint.enabled

        return breaklines, enabled, update_breakline
Пример #34
0
def get_breakpoints_n():
	'''get int value with the number of the current break points'''
	try:
		bs = gdb.breakpoints()
	except gdb.error as e:
		raise gdb.GdbError(e.message)
		return -1
	return len(bs)
Пример #35
0
def is_mbp_existed():
    """ determine where a Maple breakpoint exists """
    blist = gdb.breakpoints()
    for b in blist:
        if m_debug.Debug:            m_debug.dbg_print("b.type=", b.type, "b.location=", b.location, "b.thread=", b.thread, "b.enabled=", b.enabled,\
          "b.is_valid()=", b.is_valid())
        if 'maple::maple_invoke_method' in b.location and b.is_valid():
            return True, b
    return False, None
Пример #36
0
 def invoke(self, arg, from_tty):
     bps = gdb.breakpoints()
     for bp in bps:
         s = gdb.decode_line(bp.location)[1][0]
         l = gdb.find_pc_line(s.pc)
         print l
         loc = ''
         
         print ("Breakpoint #%d - Location: %s Enabled: %s" % (bp.number, loc, bp.enabled))
Пример #37
0
def get_mbp_id():
    """ get a Maple breakpoint gdb.Breakpoint object id """
    blist = gdb.breakpoints()
    for b in blist:
        if m_debug.Debug:            m_debug.dbg_print("b.type=", b.type, "b.location=", b.location, "b.thread=", b.thread, "b.enabled=", b.enabled,\
          "b.is_valid()=", b.is_valid())
        if 'maple::maple_invoke_method' in b.location and b.is_valid():
            return b
    return None
Пример #38
0
def set_basic_breakpoints():
    for i in ["fancy_abort", "internal_error"]:
        found = False
        if gdb.breakpoints():
            for j in gdb.breakpoints():
                if j.location.find(i) >= 0:
                    print ("Breakpoint %i already set in %s (hit %i times)"
                           % (j.number, i, j.hit_count))
                    found = True
                    break
                pass
            pass

        if not found:
            gdb.Breakpoint (i)
            pass
        pass
    return
Пример #39
0
        def breakpoints(self, target_id=0):
            """
            Return a list of breakpoints.

            Returns data in the following structure:
            [
                {
                    "id":           1,
                    "enabled":      True,
                    "one_shot":     False,
                    "hit_count":    5,
                    "locations": [
                        {
                            "address":  0x100000cf0,
                            "name":     'main'
                        }
                    ]
                }
            ]
            """
            breakpoints = []

            # hahahahaha GDB sucks so much
            for b in (gdb.breakpoints() or ()):
                try:
                    if b.location.startswith('*'):
                        addr = int(b.location[1:], 16)
                    else:
                        output = gdb.execute('info addr {}'.format(b.location),
                                             to_string=True)
                        m = re.match('.*is at ([^ ]*) .*', output)
                        if not m:
                            m = re.match('.*at address ([^ ]*)\..*', output)
                        if m:
                            addr = int(m.group(1), 16)
                        else:
                            addr = 0
                except:
                    addr = 0

                breakpoints.append({
                    'id':
                    b.number,
                    'enabled':
                    b.enabled,
                    'one_shot':
                    b.temporary,
                    'hit_count':
                    b.hit_count,
                    'locations': [{
                        "address": addr,
                        "name": b.location
                    }]
                })

            return breakpoints
Пример #40
0
def is_msi_bp_dync_existed():
    """ determines if the msi breakpoints exist or not """
    blist = gdb.breakpoints()
    for b in blist:
        if m_debug.Debug:
            m_debug.dbg_print("b.type=", b.type, "b.location=", b.location, "b.thread=", \
                    b.thread, "b.enabled=", b.enabled, "b.is_valid()=", b.is_valid())
        if '__inc_opcode_cnt_dyn' == b.location and b.is_valid():
            return True, b
    return False, None
Пример #41
0
def get_msi_bp_dync_id():
    """ gets an msi breakpoint gdb.Breakpoint object id """
    blist = gdb.breakpoints()
    for b in blist:
        if m_debug.Debug:
            m_debug.dbg_print("b.type=", b.type, "b.location=", b.location, "b.thread=", \
                    b.thread, "b.enabled=", b.enabled, "b.is_valid()=", b.is_valid())
        if '__inc_opcode_cnt_dyn' == b.location and b.is_valid():
            return b
    return None
Пример #42
0
def printSummary():
    "print hit counts for each sync point"
    print('\nSynchronization point occurences:')
    for bp in gdb.breakpoints():
        # finish breakpoints are not printed
        if type(bp) == SPTraceFunctionFinish:
            continue
        count = bp.syncHits
        name = bp.location if bp.type == gdb.BP_BREAKPOINT else bp.expression
        if count > 0:
            print('{:<30}{:<10}'.format(name, count))
Пример #43
0
 def invoke(self, arg, from_tty):
     targets = set(gdb.string_to_argv(arg) if arg else ["printf"])
     covered = [
         x.location for x in gdb.breakpoints()
         if isinstance(x, PrintfBreakpoint)
     ]
     for target in targets:
         if target in covered:
             print(target, "already hooked")
         else:
             print("hooking", target)
             PrintfBreakpoint(target)
Пример #44
0
        def breakpoints(self, target_id=0):
            """
            Return a list of breakpoints.

            Returns data in the following structure:
            [
                {
                    "id":           1,
                    "enabled":      True,
                    "one_shot":     False,
                    "hit_count":    5,
                    "locations": [
                        {
                            "address":  0x100000cf0,
                            "name":     'main'
                        }
                    ]
                }
            ]
            """
            breakpoints = []

            # hahahahaha GDB sucks so much
            for b in gdb.breakpoints():
                try:
                    if b.location.startswith('*'):
                        addr = int(b.location[1:], 16)
                    else:
                        output = gdb.execute('info addr {}'.format(b.location), to_string=True)
                        m = re.match('.*is at ([^ ]*) .*', output)
                        if not m:
                            m = re.match('.*at address ([^ ]*)\..*', output)
                        if m:
                            addr = int(m.group(1), 16)
                        else:
                            addr = 0
                except:
                    addr = 0

                breakpoints.append({
                    'id':           b.number,
                    'enabled':      b.enabled,
                    'one_shot':     b.temporary,
                    'hit_count':    b.hit_count,
                    'locations':    [{
                        "address":  addr,
                        "name":     b.location
                    }]
                })

            return breakpoints
Пример #45
0
def setBreakAtEntry():
	"""Sets a breakpoint at the programs entry point if a breakpoint does not already exist at that location."""
	file_info=gdb.execute("info file", False, True)
	mslines=file_info.split('\n')
	for s in mslines:
		if s.find("Entry point") > -1:
			address = '*'+s.split(': ')[-1]
			try:
				if address not in [ bp.location for bp in gdb.breakpoints() ]: 
					print 'Setting entry point breakpoint at ' + str(address)
					gdb.Breakpoint(address, gdb.BP_BREAKPOINT)
			except TypeError: # no breakpoints set
				print 'Setting entry point breakpoint at ' + str(address)
				gdb.Breakpoint(address, gdb.BP_BREAKPOINT)
Пример #46
0
def del_breakpoints():
	'''delete all currently enabled break points'''
	try:
		bs = gdb.breakpoints()
	except gdb.error as e:
		raise gdb.GdbError(e.message)
		return -1
	try:
		for b in bs:
			b.delete()
	except gdb.error as e:
		raise gdb.GdbError(e.message)
		return -1
	return 0
Пример #47
0
	def invoke (self, arg, from_tty):
		ci=gdb.execute("x/2i $pc", False, True)
		count=0
		for a in ci.split('\n'):
			if (count==0):
				[_, command] = a.split('>:')
				command = command.replace('\t','')
			elif ('<' in a):
				bits = a.split('<')
				address = bits[0].replace(' ', '')
				
			count+=1
		
		command = re.sub('\s+',' ',command)
		if (command.startswith('call')):
			cbits=command.split(' ')
			gdb.Breakpoint('*'+address, gdb.BP_BREAKPOINT, 0, True) # silent breakpoint
			out = gdb.execute("c", False, True).replace('\n', '')
			[one, two] = out.split(', ')
			print two
			gdb.breakpoints()[-1].delete() # delete last added breakpoint
		else:
			out = gdb.execute("si", False, True).replace('\n', '')
			print out
Пример #48
0
def stb_restore_breakpoints_enabled ():
    global stb_saved_bp_enabled
    global stb_tmp_breakpoint
    if stb_saved_bp_enabled:
        print "Restoring breakpoints enabled..."
        while stb_saved_bp_enabled:
            e = stb_saved_bp_enabled[-1]
            del stb_saved_bp_enabled[-1]
            for bp in gdb.breakpoints():
                if bp.number == e[0]:
                    bp.enabled = e[1]
                    break
        stb_saved_bp_enabled = None
        gdb.execute("delete breakpoint %d" % stb_tmp_breakpoint.number)
        stb_tmp_breakpoint = None
Пример #49
0
  def setup (self):
    commands = """
      set $func = malloc(1)
      p ((char*)$func)[0] = '\xc3'
      p mprotect(($func&0xfffffffffffff000), 1, 0x7)
      p rb_add_event_hook($func, RUBY_EVENT_C_CALL|RUBY_EVENT_CALL)
      b *$func
    """.split("\n")

    for c in commands:
      gdb.execute(c)

    gdb.breakpoints()[-1].silent = True
    self.func = gdb.parse_and_eval('$func')

    self.unwind = gdb.parameter('unwindonsignal')
    gdb.execute('set unwindonsignal on')
Пример #50
0
	def showBreak(self, no):
		# TODO: handle non-file name locations
		global vimView
		try:
			br = next(x for x in gdb.breakpoints() if x.number==no)
			try:
				fileName, lineNo = br.location.rsplit(':', 1)
				lineNo = int(lineNo)
			except ValueError:
				fileName = br.location
				lineNo = None

			if not vimView.openFile(fileName, lineNo, reopen=True):
				gdb.write('cannot open file "' + fileName + '"\n')

		except StopIteration:
			gdb.write('no breakpoint number ' + str(no) + '\n')
Пример #51
0
 def stop(self):
     '''
         bp is hit: finalize execution trace and exit
     '''
     comm = get_current()['comm'].string()
     if not comm.startswith(SLAVE_PROCESS_NAME):
         return
     print('Finalizing trace')
     dump_graphs()
     for bp in gdb.breakpoints():
         if bp == self:
             # We can't delete ourselve, so disable
             bp.enabled = False
         else:
             bp.delete()
     print('Done -- detach & quit')
     gdb.execute('detach')
     gdb.execute('quit')
Пример #52
0
def stb_disable_all_breakpoints (bp_num_to_return):
    global stb_saved_bp_enabled
    global stb_tmp_breakpoint
    bp_to_ret = None
    stb_tmp_breakpoint = None
    if not stb_saved_bp_enabled:
        stb_saved_bp_enabled = []
        for bp in gdb.breakpoints():
            print "... looking at bp num %d" % bp.number
            if bp.number == int(bp_num_to_return):
                print "... found bp num"
                bp_to_ret = bp
                stb_tmp_breakpoint = gdb.Breakpoint(bp.location)
            stb_saved_bp_enabled.append([bp.number, bp.enabled])
            bp.enabled = False
    else:
        print "Non restored breakpoints exists"
    return bp_to_ret
 def invoke(self, arg, from_tty):
     with open(arg, 'w') as f:
         for bp in gdb.breakpoints():
             instruction = "break " + bp.location
             if bp.thread is not None:
                 instruction += " thread " + bp.thread
             if bp.condition is not None:
                 instruction += " if " + bp.condition
             f.write(instruction)
             if not bp.is_valid() or not bp.enabled:
                 f.write("disable " + bp.number)
             commands = bp.commands
             if commands is not None:
                 f.write("commands")
                 for c in commands:
                     f.write(c)
                 f.write("end")
             f.write("\n")
Пример #54
0
def sgx_debugger_init():
    print ("detect urts is loaded, initializing")
    global SIZE
    SIZE = gdb.parse_and_eval("sizeof(long)")
    inited = 0
    bps = gdb.breakpoints()
    if None != bps:
        for bp in bps:
            if bp.location == "sgx_debug_load_state_add_element":
                inited = 1
                break
    if inited == 0:
        detach_enclaves()
        gdb.execute("source gdb_sgx_cmd", False, True)
        UpdateOcallFrame()
        LoadEventBreakpoint()
        UnloadEventBreakpoint()
        gdb.events.exited.connect(exit_handler)
    init_enclaves_debug()
Пример #55
0
 def invoke(self, arg, from_tty):
     with open(arg, 'w') as myfile:
         for breakpoint in gdb.breakpoints():
             try:
                 print >> myfile, "break", breakpoint.location,
                 if breakpoint.thread is not None:
                     print >> myfile, " thread", breakpoint.thread,
                 if breakpoint.condition is not None:
                     print >> myfile, " if", breakpoint.condition,
                 print >> myfile
                 if not breakpoint.enabled:
                     print >> myfile, "disable break" , breakpoint.number
                 if breakpoint.commands is not None:
                     print >> myfile, "commands"
                     print >> myfile, breakpoint.commands,
                     print >> myfile, "end"
                 print >> myfile
             except RuntimeError as e:
                 print "a"
Пример #56
0
 def invoke(self, arg, from_tty):
     with open (arg, 'w') as f:
         for bp in gdb.breakpoints():
             print >> f, "break", bp.location,
             if bp.thread is not None:
                 print >> f, " thread", bp.thread,
             if bp.condition is not None:
                 print >> f, " if", bp.condition,
             print >> f
             if not bp.enabled:
                 print >> f, "disable $bpnum"
             # Note: we don't save the ignore count; there doesn't
             # seem to be much point.
             commands = bp.commands
             if commands is not None:
                 print >> f, "commands"
                 # Note that COMMANDS has a trailing newline.
                 print >> f, commands,
                 print >> f, "end"
             print >> f
Пример #57
0
	def invoke (self, arg, from_tty):
		if (not arg):
			print "Please provide a filename in which to save breakpoints"
		else:
			with open (arg, 'w') as f:
				bpcount=1
				for bp in gdb.breakpoints():
					print >> f, "break", bp.location,
					if bp.thread is not None:
						print >> f, " thread", bp.thread,
					if bp.condition is not None:
						print >> f, " if", bp.get_condition,
						print >> f
					if not bp.enabled:
						print >> f, "disable " + str(bpcount)
				
					bpcount+=1
					commands = bp.commands
					if commands is not None:
						print >> f, "commands"
						print >> f, commands,
						print >> f, "end"
						print >> f
Пример #58
0
 def invoke (self, arg, from_tty):
     self.dont_repeat ()
     bps = gdb.breakpoints ()
     if bps is None:
         raise RuntimeError, 'No breakpoints to save'
     with open (arg.strip (), 'w') as f:
         for bp in bps:
             print >> f, "break", bp.location,
             if bp.thread is not None:
                 print >> f, " thread", bp.thread,
             if bp.condition is not None:
                 print >> f, " if", bp.condition,
             print >> f
             if not bp.enabled:
                 print >> f, "disable $bpnum"
             # Note: we don't save the ignore count; there doesn't
             # seem to be much point.
             commands = bp.commands
             if commands is not None:
                 print >> f, "commands"
                 # Note that COMMANDS has a trailing newline.
                 print >> f, commands,
                 print >> f, "end"
             print >> f
Пример #59
0
def info(entry, *args):
    """In most cases, simply execute given arguments
    and return results as string.
    When `entry` is:
    * locals/args: Return dict{variable=value}
    * breakpoints: Return a list of gdb.Breakpoint
    * threads: Return a list of (is_current_thread, num, ptid, name, frame)
    """
    if entry.startswith(('ar', 'lo')):
        info = gdb.execute('info ' + entry, to_string=True).splitlines()
        # No arguments or No locals
        if len(info) == 1 and info[0].startswith('No '):
            return {}
        group = {}
        for line in info:
            variable, _, value = line.partition('=')
            group[variable.rstrip()] = value.lstrip()
        return group
    elif entry.startswith('b'):
        return gdb.breakpoints()
    elif entry.startswith('th'):
        return info_threads(*args)
    return gdb.execute(
        'info %s %s' % (entry, args_to_string(*args)), to_string=True)
Пример #60
0
        def breakpoints(self, target_id=0):
            """
            Return a list of breakpoints.

            Returns data in the following structure:
            [
                {
                    "id":           1,
                    "enabled":      True,
                    "one_shot":     False,
                    "hit_count":    5,
                    "locations": [
                        {
                            "address":  0x100000cf0,
                            "name":     'main'
                        }
                    ]
                }
            ]
            """
            breakpoints = []

            # hahahahaha GDB sucks so much
            for b in gdb.breakpoints():
                try:
                    if b.location.startswith('*'):
                        addr = int(b.location[1:], 16)
                    else:
                        output = gdb.execute('info addr {}'.format(b.location), to_string=True)
                        m = re.match('.*is at ([^ ]*) .*', output)
                        if not m:
                            m = re.match('.*at address ([^ ]*)\..*', output)
                        if m:
                            addr = int(m.group(1), 16)
                        else:
                            addr = 0
                except:
                    addr = 0

                breakpoints.append({
                    'id':           b.number,
                    'enabled':      b.enabled,
                    'one_shot':     b.temporary,
                    'hit_count':    b.hit_count,
                    'locations':    [{
                        "address":  addr,
                        "name":     b.location
                    }]
                })

            return breakpoints

            def capabilities(self):
                """
                Return a list of the debugger's capabilities.

                Thus far only the 'async' capability is supported. This indicates
                that the debugger host can be queried from a background thread,
                and that views can use non-blocking API requests without queueing
                requests to be dispatched next time the debugger stops.
                """
                return []