def start(*a): """ Set a breakpoint at a convenient location in the binary, generally 'main', 'init', or the entry point. """ run = 'run ' + ' '.join(a) symbols = [ "main", "_main", "__libc_start_main", "start", "_start", "init", "_init" ] for symbol in symbols: address = pwndbg.symbol.address(symbol) # print(symbol, address) if not address: continue # print("no symbol found") b = gdb.Breakpoint(symbol, temporary=True) gdb.execute(run, from_tty=False, to_string=True) return else: b = gdb.Breakpoint("_start", temporary=True) gdb.execute(run, from_tty=False, to_string=True) return # print(run) # Try a breakpoint at the binary entry entry(*a)
def test_bp_test_func_ret_true(self): """ [BP::test ret=true] """ gdb.Breakpoint('BP::test') gdb.execute('n') gdb.execute('p n=4') gdb.Breakpoint('Calculate::add') gdb.execute('c') self.gdbStrAssertEqual('a', '4') self.gdbStrAssertEqual('b', '5')
def __init__(self): gdb.Command.__init__(self,"elfbf", gdb.COMMAND_DATA) self.source = None self.rela_loop_break = gdb.Breakpoint("do-rel.h:117") #at the loop that processes relocation entries self.rela_loop_break.condition = "map->l_addr==0" self.rela_proc_break = gdb.Breakpoint("do-rel.h:120") #inside the loop that processes relocation entries self.rela_proc_break.enabled = False self.rela_proc_break.condition = "map->l_addr==0" self.rela_loop_exit = RelaLoopDoneBreakpoint("rtld.c:2262") self.rela_loop_exit._dostop = False
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)
def runback(self, address): b = gdb.Breakpoint( "*" + address, type=gdb.BP_WATCHPOINT, wp_class=gdb.WP_WRITE, internal=True ) while b.hit_count == 0: gdb.execute("rc", to_string=True) b.delete()
def breakrva(offset=None, module=None): offset = int(offset) if not module: module = get_exe_name() addr = translate_addr(offset, module) spec = "*%#x" % (addr) gdb.Breakpoint(spec)
def handle_new_objfile_event(self, event): """Handler for a new object file load event. If auto-attach has not been disabled, set a breakpoint at location 'BP_FCT'.""" if event is None: return if not 'libigfxdbgxchg64.so' in event.new_objfile.filename: return if not self.is_auto_attach_disabled(): self.hook_bp = gdb.Breakpoint(BP_FCT, type=gdb.BP_BREAKPOINT, internal=1, temporary=0) self.hook_bp.silent = True commands = ("python gdb.function.intelgt_auto_attach" + ".INTELGT_AUTO_ATTACH.init_gt_inferiors()") # Find out if we are in nonstop mode. It is safe to do it # here and only once, because the setting cannot be # changed after the program starts executing. nonstop_info = gdb.execute("show non-stop", False, True) self.is_nonstop = nonstop_info.endswith("on.\n") if self.is_nonstop: self.hook_bp.commands = commands + "\ncontinue -a" else: self.hook_bp.commands = commands + "\ncontinue"
def break_next_interrupt(address=None): ins = next_int(address) if ins: gdb.Breakpoint("*%#x" % ins.address, internal=True, temporary=True) gdb.execute('continue', from_tty=False, to_string=True) return ins
def xuntil(target): try: addr = int(target, 0) if not pwndbg.memory.peek(addr): print(message.error('Invalid address %#x' % addr)) return spec = "*%#x" % (addr) except (TypeError, ValueError): #The following gdb command will throw an error if the symbol is not defined. try: result = gdb.execute('info address %s' % target, to_string=True, from_tty=False) except gdb.error: print(message.error("Unable to resolve %s" % target)) return spec = target b = gdb.Breakpoint(spec, temporary=True) if pwndbg.proc.alive: gdb.execute("continue", from_tty=False) else: gdb.execute("run", from_tty=False)
def __init__(self, inf, while1, period=None): self.inferior = inf self.period = period self.pinMapping = {} self.bp = gdb.Breakpoint(source='main.c', line=while1) #self.bp.commands = '\n'.join(['silent']) #TODO: Verbosity? self.bp.enabled = True self.watchList = []
def put_fcn_hook(symbol, new_addr, patches): lookup_addr = sym_addr(symbol) if not lookup_addr or lookup_addr == new_addr: return bp_spec = "*{0}".format(lookup_addr) bp = gdb.Breakpoint(bp_spec, gdb.BP_BREAKPOINT, True, True) patches[lookup_addr] = Patch(symbol, new_addr, bp)
def process(self): for bpid in self.need_delete: bp = self.bpid_to_bp.get(bpid) if bp is not None: bp.delete() if bpid in self.bpid_to_bp: del self.bpid_to_bp[bpid] self.need_delete = [] for key, values in self.need_update.items(): bp_was_touched = False win_id, enabled, silent, ignore_count, temporary, thread, condition, commands, create_loc, number, after_create = values bpid = number if number is not None else self.key_to_bpid.get(key) if bpid is not None and bpid in self.bpid_to_bp: #bp exists #bpid can't be None, but breakpoint may be deleted bp = self.bpid_to_bp[bpid] else: #not exists, create assert create_loc is not None kw = { 'spec': create_loc, 'type': gdb.BP_BREAKPOINT, } if temporary is not None: kw['temporary'] = temporary bp = gdb.Breakpoint(**kw) bp_was_touched = True self.key_to_bpid[key] = bp.number self.bpid_to_bp[bp.number] = bp if after_create is not None: after_create(bp) if enabled is not None and bp.enabled != enabled: bp.enabled = enabled bp_was_touched = True if silent is not None and bp.silent != silent: bp.silent = silent bp_was_touched = True if ignore_count is not None and bp.ignore_count != ignore_count: bp.ignore_count = ignore_count bp_was_touched = True if thread == -1: thread = None if bp.thread != thread: bp.thread = thread bp_was_touched = True if bp.condition != condition: try: bp.condition = condition except gdb.error as e: pending_errors[win_id].append(str(e)) if not bp_was_touched: touch_breakpoint(bp) if bp.commands != commands: gdb.write( 'WARNING: parameter commands is not supported by front-end.\nYou can set him manually:\ncommands {number}\n{commands}\n' .format(number=bp.number, commands=commands)) self.need_update = {}
def __init__(self): self.count = 0 self.beginOfCall = True self.currentSyscall = -1 self.cstr = gdb.lookup_type("char").pointer() self.voidptr = gdb.lookup_type("void").pointer() self.recordPid = None gdb.Breakpoint("__kernel_vsyscall")
def exposed_set_breakpoint(self, client, has_stop, *args, **kwargs): """Create a breakpoint and connect it with the client-side mirror.""" if has_stop: class Breakpoint(gdb.Breakpoint): def stop(self): return client.stop() return Breakpoint(*args, **kwargs) return gdb.Breakpoint(*args, **kwargs)
def run_fragment(fragment, function='breakpoint'): # Arrange to stop at a reasonable place in the test program. bp = gdb.Breakpoint(function) try: gdb.execute("run %s" % (fragment, )) # Check that we did indeed stop by hitting the breakpoint we set. assert bp.hit_count == 1 finally: bp.delete() gdb.execute('frame 1')
def do_one_watch(sym, wtype, text): wp = gdb.Breakpoint(sym, gdb.BP_WATCHPOINT, wtype) gdb.execute("c") report_str = "%s for %s" % (text, sym) if wp.hit_count > 0: report(True, report_str) wp.delete() else: report(False, report_str)
def check_break(self, sym_name): "Setup breakpoint, continue and check we stopped." sym, ok = gdb.lookup_symbol(sym_name) bp = gdb.Breakpoint(sym_name) # It will be blocked here until breakpoint hits resume() # hopefully we came back end_pc = gdb.parse_and_eval('$pc') prGreen("[+] %s == %s %d" % (end_pc, sym.value(), bp.hit_count)) bp.delete() # can we test we hit bp? return end_pc == sym.value()
def main(): try: #gdb.execute("start -w 20 -n 1") gdb.execute("start -v 3 -w 5 -n 1") #student submissions cannot be counted on to have a verbosity parameter called v that can take 3 as a valid argument gdb.events.stop.connect (stop_handler) rtf_break = gdb.Breakpoint("request_thread_function", gdb.BP_BREAKPOINT, 0, False, False) wtf_break = gdb.Breakpoint("worker_thread_function", gdb.BP_BREAKPOINT, 0, False, False) mht_break = gdb.Breakpoint("make_histogram_table", gdb.BP_BREAKPOINT, 0, False, False) pcreate_break = gdb.Breakpoint("pthread_create", gdb.BP_BREAKPOINT, 0, False, False) pjoin_break = gdb.Breakpoint("pthread_join", gdb.BP_BREAKPOINT, 0, False, False) gdb.execute("cont") """ Guessing that this is the place where all the points would be tallied up based on the variables evaluated at the different break points. """ gdb.execute("quit") except TypeError: traceback.print_exc() gdb.execute("quit")
def run_test(): """Run through the tests one by one""" illegal_op = gdb.Breakpoint("illegal_op") stg = gdb.Breakpoint("stg") mvc_8 = gdb.Breakpoint("mvc_8") # Expect the following events: # 1x illegal_op breakpoint # 2x stg breakpoint, segv, breakpoint # 2x mvc_8 breakpoint, segv, breakpoint for _ in range(14): gdb.execute("c") report(illegal_op.hit_count == 1, "illegal_op.hit_count == 1") report(stg.hit_count == 4, "stg.hit_count == 4") report(mvc_8.hit_count == 4, "mvc_8.hit_count == 4") # The test must succeed. gdb.Breakpoint("_exit") gdb.execute("c") status = int(gdb.parse_and_eval("$r2")) report(status == 0, "status == 0")
def putBreak(self): global vimView out, err = vimView.execCmd('expand("%:p") . ":" . line(".")') fileName = out.rstrip() if not err: try: gdb.Breakpoint(fileName, gdb.BP_BREAKPOINT) except RuntimeError as ex: gdb.write(str(ex) + '\n') else: gdb.write('error: ' + err)
def invoke(self, thread, argument, from_tty=False): sections = gdb.execute('info target', to_string=True) address = None for match in self._text_exp.finditer(sections): if match.group('section') == '.text': address = abs(long(match.group('start'), 16)) break if address is not None: gdb.Breakpoint('*0x%x' % address) else: raise gdb.error('Unable to locate .text section!')
def execute_cpp_function(function_name): """Run until the end of a specified C++ function (assuming the function has a label 'break_here' at the end) :param function_name: C++ function name (str) :return: None """ breakpoint_location = '{}:break_here'.format(function_name) bp = gdb.Breakpoint(breakpoint_location, internal=True) bp.silent = True gdb.execute('run') assert bp.hit_count == 1 bp.delete()
def check_break(sym_name): "Setup breakpoint, continue and check we stopped." sym, ok = gdb.lookup_symbol(sym_name) bp = gdb.Breakpoint(sym_name) gdb.execute("c") # hopefully we came back end_pc = gdb.parse_and_eval('$pc') report(bp.hit_count == 1, "break @ %s (%s %d hits)" % (end_pc, sym.value(), bp.hit_count)) bp.delete()
def xuntil(target): addr = int(target) if not pwndbg.memory.peek(addr): print(message.error('Invalid address %#x' % addr)) return spec = "*%#x" % (addr) b = gdb.Breakpoint(spec, temporary=True) if pwndbg.proc.alive: gdb.execute("continue", from_tty=False) else: gdb.execute("run", from_tty=False)
def check_break(sym_name): "Setup breakpoint, continue and check we stopped." sym, ok = gdb.lookup_symbol(sym_name) bp = gdb.Breakpoint(sym_name) gdb.execute("c") # hopefully we came back end_pc = gdb.parse_and_eval('$pc') print("%s == %s %d" % (end_pc, sym.value(), bp.hit_count)) bp.delete() # can we test we hit bp? return end_pc == sym.value()
def invoke(self, arg, from_tty): # FIXME: Broken. lookup_global_symbol always works, but doesn't return # results for static symbols. lookup_symbol does, but only # works if there is a current frame, i.e. the program is running. sym = gdb.lookup_symbol(arg) if sym[0] == None: # just remember the name, the BP will be created later function_names[arg] = 1 # dummy value print "Remembering symbol '%s' for later addition" % arg else: # FIXME: Minor code duplication bp = gdb.Breakpoint(arg) function_bps[bp] = arg
def invoke(self, args, from_tty): self.dont_repeat() # Because of ASLR, we need to first break into the dynamic loader by # loading an invalid breakpoint invalid_bp = gdb.Breakpoint('*-1', internal=True) try: gdb.execute('run', to_string=True) except gdb.error: pass else: raise gdb.GdbError("gdb managed to insert an invalid breakpoint!") invalid_bp.delete() # Create a temporary breakpoint at the address of the entry point addr = EntryPoint.get() # When there is no dynamic loader, we are already at the entry point if to_int(gdb.parse_and_eval('$pc')) == addr: return # Continue the program until the temporary breakpoint gdb.Breakpoint('*0x{:x}'.format(addr), temporary=True, internal=True) gdb.execute('continue')
def count_calls(func_name): """ Counts how many times func_name is hit during the replay of the currently loaded recording and returns the hit count. """ # Set a breakpoint for the specified function. bp = gdb.Breakpoint(func_name) # Do "continue" until we have gone through the whole recording, potentially # hitting the breakpoint several times. end_of_time = udb.get_event_log_extent().max_bbcount while udb.time.get().bbcount < end_of_time: gdb.execute("continue") return bp.hit_count
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()
def invoke(self, arg, _): argv = gdb.string_to_argv(arg) (exe, test_input, result_path) = argv gdb.execute("file {}".format(exe)) gdb.Breakpoint("exit") gdb.execute("r {} 2>&1 >/dev/null".format(test_input)) tables = get_tables() for (module, (addr, length)) in tables.items(): mem = gdb.selected_inferior().read_memory(addr, length) with open(os.path.join(result_path, module + ".cov"), "wb") as handle: handle.write(mem)