def stop(self): bp_in_urts = is_bp_in_urts() if bp_in_urts == True: if SIZE == 4: tcs_addr_1 = gdb.parse_and_eval("$eax") tcs_addr = ctypes.c_uint32(tcs_addr_1).value elif SIZE == 8: tcs_addr_1 = gdb.parse_and_eval("$rdi") tcs_addr = ctypes.c_uint64(tcs_addr_1).value enclave_info_addr = gdb.parse_and_eval("*(void **)&g_debug_enclave_info_list") if enclave_info_addr != 0: node = retrieve_enclave_info(enclave_info_addr) else: return False if node != None: node.append_tcs_list(tcs_addr) string = read_from_memory(tcs_addr + 8, 4) if string == None: return False flag = struct.unpack('I', string)[0] flag |= 1 gdb_cmd = "set *(unsigned int *)%#x = %#x" %(tcs_addr + 8, flag) gdb.execute(gdb_cmd, False, True) return False
def print_disassembly(self): ''' Attempts to print some disassembled instructions from the function containing $pc to GDB's STDOUT. If GDB is unable to print the disassembled instructions, an error message will be printed. If GDB's version is less than 7.3, the entire disassembled function will be printed (if possible). Otherwise only a subset of the function will be printed. This behavior is due to a bug in the Python API of earlier versions of GDB. In these versions, the results of the 'disassemble' command are always printed directly to GDB's STDOUT rather than optionally being suppressed and passed as a return value via the Python API. ''' if gdb_ver() < "7.3": try: gdb.execute("disas $pc", False, True) except RuntimeError as e: warnings.warn(e) return try: disas = gdb.execute("disas $pc", False, True).splitlines() pos = 0 for line in disas: if re.match(self._pc_regex, line): break pos += 1 print "\n".join(disas[max(pos-5,0):pos+5]) except RuntimeError as e: warnings.warn(e)
def invoke (self, arg, from_tty): self.dont_repeat() num = arg and int(arg) or 100 self.setup() try: while num > 0: num -= 1 gdb.execute('continue') frame = gdb.selected_frame() if frame.pc() != self.func: raise KeyboardInterrupt node = gdb.parse_and_eval('(NODE*) $rsi') file = node['nd_file'].string() line = gdb.parse_and_eval('nd_line(%s)' % node) method = gdb.parse_and_eval('rb_id2name($rcx)') method = method > 0 and method.string() or '(unknown)' print "%s in %s:%d" % (method,file,line) self.teardown() except KeyboardInterrupt: self.teardown() except RuntimeError, text: self.teardown() if not re.search('signaled while in a function called from GDB', text): raise
def cmd_dump(filename, args, format="binary", type="value"): cmd = "dump %s %s %s %s" % (format, type, filename, args) debug("cmd_dump: executing '%s'..." % cmd ) try: gdb.execute(cmd) except RuntimeError as e: error("%s" % e)
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'))
def get_arg(self, num): if num > 1: raise Exception("get_arg %d is not supported." %num) gdb.execute("up", False, True) ret = long(gdb.parse_and_eval("*(unsigned int *)($esp + " + str(num * 4) + ")")) gdb.execute("down", False, True) return ret
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 not_released_add(addr, size, memtype, line=None, bt=None): global not_released if addr == 0: return if addr in not_released: if line == None: line = get_info_line(True) if bt == None: bt = str(gdb.execute("backtrace", True, True)).strip() print(lang.string("Error in not_released_add addr 0x%x old: %s new: %d, %s, %s, %s. Please report this message to https://github.com/teawater/cma/issues/.") %(addr, not_released[addr], size, memtype, line, bt)) not_released[addr] = [] not_released[addr].append(size) if line == None: not_released[addr].append(get_info_line(True)) else: not_released[addr].append(line) if record_bt and bt == None: bt = str(gdb.execute("backtrace", True, True)).strip() not_released[addr].append(time.time()) not_released[addr].append(memtype) if record_bt: not_released[addr].append(bt)
def released_add(addr, memtype, line=None, bt=None): global not_released, released if addr == 0: return if addr in not_released: if record_released: cur_time = time.time() if line == None: line = get_info_line(False) if not_released[addr][3] != memtype: if bt == None: bt = str(gdb.execute("backtrace", True, True)).strip() print(lang.string("Error in released_add addr 0x%x old: %s new: %s, %s, %s. Please report this message to https://github.com/teawater/cma/issues/.") %(addr, not_released[addr], memtype, line, bt)) return add = [addr, not_released[addr][0], not_released[addr][1], line, cur_time - not_released[addr][2], not_released[addr][3]] if record_bt: add.append(not_released[addr][4]) if bt == None: add.append(str(gdb.execute("backtrace", True, True)).strip()) else: add.append(bt) released.append(add) del not_released[addr]
def search_region(region, data): command = "find /w {:s}, +{:s}, {:s}".format(region[0], region[2], data) output = gdb.execute(command, False, True) numfound = int(gdb.execute("print $numfound", False, True).split()[2]) if numfound > 0: return output.splitlines()[:-1] return []
def invoke(self, arg, from_tty): pid = str(gdb.inferiors()[0].pid) cmd = "cat /proc/" + pid + "/maps | grep " res = subprocess.Popen(cmd + arg, shell=True, stdout=subprocess.PIPE).communicate()[0] if (len(res) == 0): print '**** Library %s not found. ' % arg print ' Do: cat /proc/%d/maps to see all libs.' % pid return lib=subprocess.Popen(cmd + arg + " | head -1 | sed -e 's%[^/]*\\(/.*\\)%\\1%'", shell=True, stdout=subprocess.PIPE).communicate()[0].rstrip() segAddr=subprocess.Popen(cmd + lib + "| grep r-xp |"\ "sed -e 's%^\\([0-9a-f]*\\).*%0x\\1%'", shell=True, stdout=subprocess.PIPE).communicate()[0] segDataAddr=subprocess.Popen(cmd + lib + " | grep rw-p | sed -e 's%^\\([0-9a-f]*\\).*%0x\\1%'", shell=True, stdout=subprocess.PIPE).communicate()[0] textOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.text ' | " \ "sed -e 's%^.*text[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'", shell=True, stdout=subprocess.PIPE).communicate()[0] dataOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.data ' | "\ "sed -e 's%^.*data[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'", shell=True, stdout=subprocess.PIPE).communicate()[0] bssOffset=subprocess.Popen("readelf -S " + lib +" | grep '\.bss ' | "\ "sed -e 's%^.*bss[^0-9a-f]*[0-9a-f]*\\s*\\([0-9a-f]*\\).*%0x\\1%'", shell=True, stdout=subprocess.PIPE).communicate()[0] gdb.execute("add-symbol-file " + lib + " " + str(long(segAddr, 16) + long(textOffset, 16)) + " -s .data " + str(long(segDataAddr, 16) + long(dataOffset, 16)) + " -s .bss " + str(long(segDataAddr, 16) + long(bssOffset, 16)), True, True)
def pyobject_fromcode(self, code, gdbvar=None): if gdbvar is not None: d = {'varname':gdbvar, 'code':code} gdb.execute('set $%(varname)s = %(code)s' % d) code = '$' + gdbvar return libpython.PyObjectPtr.from_pyobject_ptr(self.get_pyobject(code))
def create_inferior(self, inferior_id): gdb_inferior = None try: gdb_inferior = (i for i in gdb.inferiors() if i.num == inferior_id).next() except StopIteration: return None cpu = None info_inferiors = gdb.execute('info inferiors', False, True) info_target = gdb.execute('info target', False, True) try: matches = self._inferior_expression.findall(info_inferiors) inferior = (i for i in matches if int(i[0]) == inferior_id).next() inferior_path = os.path.abspath(inferior[2]).strip() matches = self._file_expression.findall(info_target) try: target = (i[1] for i in matches if os.path.abspath(i[0]).strip() == inferior_path).next() architecture = self._target_to_architecture(target) cpu = self._cpu_factory.create_cpu(architecture) except StopIteration: registers = self._registers() cpu = GenericCpu(self._cpu_factory, registers) except TypeError: return None return GdbInferior(cpu, gdb_inferior)
def bp(where): """ Set a breakpoint at the specified address. """ result = pwndbg.commands.fix(where) if result is not None: gdb.execute('break *%#x' % int(result))
def invoke(self, arg, from_tty): gdb.execute('target remote :1234') global status_enum status_enum.running = gdb.parse_and_eval('sched::thread::running') status_enum.waiting = gdb.parse_and_eval('sched::thread::waiting') status_enum.queued = gdb.parse_and_eval('sched::thread::queued') status_enum.waking = gdb.parse_and_eval('sched::thread::waking')
def get_top_lastremainder(): global main_arena global fastbinsize global top global last_remainder chunk = {} if capsize == 0 : arch = getarch() #get top cmd = "x/" + word + hex(main_arena + fastbinsize*capsize + 8 ) chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) chunk["size"] = 0 if chunk["addr"] : cmd = "x/" + word + hex(chunk["addr"]+capsize*1) try : chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8 if chunk["size"] > 0x21000 : chunk["memerror"] = "top is broken ?" except : chunk["memerror"] = "invaild memory" top = copy.deepcopy(chunk) #get last_remainder chunk = {} cmd = "x/" + word + hex(main_arena + (fastbinsize+1)*capsize + 8 ) chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) chunk["size"] = 0 if chunk["addr"] : cmd = "x/" + word + hex(chunk["addr"]+capsize*1) try : chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8 except : chunk["memerror"] = "invaild memory" last_remainder = copy.deepcopy(chunk)
def get_fast_bin(): global main_arena global fastbin global fastbinsize global freememoryarea fastbin = [] #freememoryarea = [] if capsize == 0 : arch = getarch() for i in range(fastbinsize-3): fastbin.append([]) chunk = {} is_overlap = (None,None) cmd = "x/" + word + hex(main_arena + i*capsize + 8) chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) while chunk["addr"] and not is_overlap[0]: cmd = "x/" + word + hex(chunk["addr"]+capsize*1) try : chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8 except : chunk["memerror"] = "invaild memory" break is_overlap = check_overlap(chunk["addr"], (capsize*2)*(i+2)) chunk["overlap"] = is_overlap freememoryarea[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"],chunk["addr"] + (capsize*2)*(i+2) ,chunk)) fastbin[i].append(copy.deepcopy(chunk)) cmd = "x/" + word + hex(chunk["addr"]+capsize*2) chunk = {} chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) if not is_overlap[0]: chunk["size"] = 0 chunk["overlap"] = None fastbin[i].append(copy.deepcopy(chunk))
def do_unwinder_test(): # The unwinder is disabled by default for the moment. Turn it on to check # that the unwinder works as expected. import gdb gdb.execute("enable unwinder .* SpiderMonkey") run_fragment('unwind.simple', 'Something') first = True # The unwinder is a bit flaky still but should at least be able to # recognize one set of entry and exit frames. This also tests to # make sure we didn't end up solely in the interpreter. found_entry = False found_exit = False found_main = False frames = list(gdb.frames.execute_frame_filters(gdb.newest_frame(), 0, -1)) for frame in frames: print("examining " + frame.function()) if first: assert_eq(frame.function().startswith("Something"), True) first = False elif frame.function() == "<<JitFrame_Exit>>": found_exit = True elif frame.function() == "<<JitFrame_Entry>>": found_entry = True elif frame.function() == "main": found_main = True # Had to have found a frame. assert_eq(first, False) # Had to have found main. assert_eq(found_main, True) # Had to have found the entry and exit frames. assert_eq(found_exit, True) assert_eq(found_entry, True)
def getregs(self): # TODO, change to MI? info_register_text = gdb.execute("info registers", False, True) # first, uniform the output line_per_register = filter(None, info_register_text.replace('\t', ' ').split('\n')) # then, get with the first two fields, the name and its value names_and_values = dict(map(lambda line: line.split()[:2], line_per_register)) regs_struct = ptrace_registers_t() field_names = map(lambda definition: definition[0], regs_struct._fields_) if RUNNING_LINUX: for n in field_names: if n in ("fs_base", "gs_base"): continue # TODO see https://www.sourceware.org/ml/gdb-patches/2015-11/msg00078.html if n.startswith("__"): #__cs, __ds, __es, __fs, __gs, __ss v = names_and_values[n[2:]] # TODO use the value of xx for __xx? elif n == 'orig_eax': #beware! no all the registers are shown in "info registers" v = hex(int(gdb.execute("print $orig_eax", False, True).split("=")[1])) elif n == 'orig_rax': #beware! no all the registers are shown in "info registers" v = hex(int(gdb.execute("print $orig_rax", False, True).split("=")[1])) else: v = names_and_values[n] if v.endswith("L"): v = v[:-1] setattr(regs_struct, n, int(v, 16)) # gdb returns the values in hex else: raise NotImplementedError("Not implemented yet!: The get registers may be supported for other architectures in the future.") return regs_struct
def add_main_exe_to_symbols(): if not pwndbg.remote.is_remote(): return exe = pwndbg.elf.exe() if not exe: return addr = exe.address if not addr: return addr = int(addr) mmap = pwndbg.vmmap.find(addr) if not mmap: return path = mmap.objfile if path: try: gdb.execute('add-symbol-file %s %#x' % (path, addr), from_tty=False, to_string=True) except gdb.error: pass
def check_step(): "Step an instruction, check it moved." start_pc = gdb.parse_and_eval('$pc') gdb.execute("si") end_pc = gdb.parse_and_eval('$pc') return not (start_pc == end_pc)
def invoke(self, arg, from_tty): argv = gdb.string_to_argv(arg) state.restore() #gdb.execute("thread 15", False, True) #cur_os_thread = gdb.selected_thread().num frame = gdb.newest_frame() handle_attach = False count = 0 while True: function = frame.function() if function and function.name == "hpx::util::command_line_handling::handle_attach_debugger()": handle_attach = True break frame = frame.older() if not frame or count > 5: break count = count + 1 if handle_attach: frame.select() gdb.execute("set var i = 1", True) #gdb.execute("thread %d" % cur_os_thread, False, True) if len(argv) == 0: print "Continuing..." gdb.execute("continue") else: if argv[0] != "hook": print "wrong argument ..."
def invoke(self,arg,from_tty): from attach_c import get_processes, choose_pid procs = get_processes(self.user,arg) pid = choose_pid(procs) if pid: print 'attaching: ',pid gdb.execute('attach %s' % pid,True)
def invoke(self, arg, from_tty): breakpoints = arg current_pc_int = int(SysUtils.extract_address(str(gdb.parse_and_eval("$pc"))), 16) try: disas_output = gdb.execute("disas $pc-30,$pc", to_string=True) # Just before the line "End of assembler dump" last_instruction = disas_output.splitlines()[-2] previous_pc_address = SysUtils.extract_address(last_instruction) except: previous_pc_address = hex(current_pc_int) global track_watchpoint_dict try: count = track_watchpoint_dict[breakpoints][current_pc_int][0] + 1 except KeyError: if breakpoints not in track_watchpoint_dict: track_watchpoint_dict[breakpoints] = OrderedDict() count = 1 register_info = ScriptUtils.get_general_registers() register_info.update(ScriptUtils.get_flag_registers()) register_info.update(ScriptUtils.get_segment_registers()) float_info = ScriptUtils.get_float_registers() disas_info = gdb.execute("disas " + previous_pc_address + ",+40", to_string=True).replace("=>", " ") track_watchpoint_dict[breakpoints][current_pc_int] = [count, previous_pc_address, register_info, float_info, disas_info] track_watchpoint_file = SysUtils.get_track_watchpoint_file(pid, breakpoints) pickle.dump(track_watchpoint_dict[breakpoints], open(track_watchpoint_file, "wb"))
def usage(): print "Usage:" print "\t./in-memory-fuzz.py <function to fuzz> <program> <arguments...>" print "Examples:" print "\t./in-memory-fuzz.py parse getdomain [email protected]" print "\t./in-memory-fuzz.py *0x40064d getdomain [email protected]" gdb.execute('quit')
def onActualStop(self): if not self.beginOfCall: gdb.execute("finish") else: gdb.execute("continue") return False
def invoke(self, *args): try: gdb.execute(self._command, to_string=True) while not self.is_relevant_function(gdb.selected_frame()): gdb.execute(self._command, to_string=True) except RuntimeError, e: raise gdb.GdbError(*e.args)
def invoke(self, arg, from_tty): break_info=self._retrive_ptrs() gdb.execute("delete",False, True) gdb.execute("set pagination off") for addr,name in break_info.iteritems(): _CallTracerBreakpoint(r'*'+addr, name,self._stack)
def pyobject_fromcode(self, code, gdbvar=None): if gdbvar is not None: d = {"varname": gdbvar, "code": code} gdb.execute("set $%(varname)s = %(code)s" % d) code = "$" + gdbvar return libpython.PyObjectPtr.from_pyobject_ptr(self.get_pyobject(code))
def write(self, address, value, bits = 32): """ Set a value in memory """ t = "uint{:d}_t".format(bits) cmd = "set *({} *){} = {}".format(t, address, value) #gdb.write("RUN: {}\n".format(cmd)) gdb.execute(cmd, True, True)
if m is None: bp_count[bps[bp]] = 0 else: bp_count[bps[bp]] = int(m.group(1)) return bp_count qemu = backgroundProc( "qemu-system-arm -gdb tcp::{} -M stm32-p103 -nographic -kernel ".format( port) + gdb.objfiles()[0].filename) try: print "Initialising..." gdb.execute("set confirm off") gdb.execute("set height 0") gdb.execute("delete breakpoints", to_string=True) # gdb.execute("file "+fname, to_string=True) gdb.execute("tar ext :{}".format(port), to_string=True) gdb.execute("load", to_string=True) gdb.execute("break exit", to_string=True) fdir = getExecDir() output_iters = fdir + "/output_iters" files = findSources() print "Exec dir:", fdir print "Creating breakpoints..."
def restore_regs(self, values): gdb.newest_frame().select() for reg, value in values.items(): gdb.execute('set $%s = %s' % (reg, value))
def invoke(self, arg, from_tty): for r in reactors(): gdb.write("\nShard %d: \n\n" % (r['_id'])) gdb.execute(arg)
# from libstdcxx printers def get_basic_type(type): # If it points to a reference, get the reference. if type.code == gdb.TYPE_CODE_REF: type = type.target() # Get the unqualified type, stripped of typedefs. type = type.unqualified().strip_typedefs() return type from gdb import execute _have_execute_to_string = True try: s = execute('help', True, True) # detect how to invoke ptype ptype_cmd = 'ptype/mtr' try: gdb.execute(ptype_cmd + ' void', True, True) except RuntimeError: ptype_cmd = 'ptype' except TypeError: _have_execute_to_string = False try: from gdb import parse_and_eval except ImportError: # from http://stackoverflow.com/a/2290941/717706 def parse_and_eval(exp): if gdb.VERSION.startswith("6.8.50.2009"):
def load_all(): pref = "~/PycharmProjects/cp/" gdb.execute("source " + pref + "internal/log.py") gdb.execute("source " + pref + "internal/common.py") gdb.execute("source " + pref + "i386/i386.py") gdb.execute("source " + pref + "mips/mips_o32.py") gdb.execute("source " + pref + "internal/breakpoint_handler.py") gdb.execute("d") #gdb.execute("python BreakpointHandler(\"*" + get_arch().break_addr + "\")") gdb.execute("set pagination off")
def run_cmd(gdb_cmd): return gdb.execute(gdb_cmd, to_string=True)
def getValue(v): s = gdb.execute("p/x " + v, to_string=True) return int(s.split('=')[1].strip()[2:], 16)
def probe_qemu(): try: return gdb.execute("monitor info version", to_string=True) != "" except gdb.error: return False
if "70617373776f72643132333435" in str(binascii.hexlify(data)): self.trailing_calls = 1 print(register, binascii.hexlify(data), length) elif self.trailing_calls > 0: print(register, binascii.hexlify(data), length) self.trailing_calls = self.trailing_calls - 1 except gdb.MemoryError: traceback.print_exc() return True except: traceback.print_exc() return True # return False to continue the execution of the program return False # GDB setup gdb.execute("set print repeats unlimited") gdb.execute("set print elements unlimited") gdb.execute("set pagination off") # generate sniffer breakpoint SnifferBreakpoint() # run and sniff gdb.execute('continue') # gdb.execute('detach') # gdb.execute('quit')
def probe_kgdb(): try: thread_info = gdb.execute("info thread 2", to_string=True) return "shadowCPU0" in thread_info except gdb.error: return False
def get_pagination(): out = gdb.execute('show pagination', to_string=True) return out.split()[-1].rstrip('.')
def usage(): print("Usage:") print("\tsudo ./md5-sniffer-latest-v4.py -p <pid>") gdb.execute('quit')
def remote_connect(): gdb.execute('target remote :1234')
# -*- coding: utf-8 -*- ######################################################################### # File Name: gdb_script.py # Created on : 2019-10-09 17:46:11 # Author: raycp # Last Modified: 2019-10-09 18:06:47 # Description: script for debug lkm ######################################################################### import gdb ko_base = int(input("ko base: "), 16) gdb.execute("target remote 127.0.0.1:1234") gdb.execute("add-symbol-file ./core.ko 0x%x" % (ko_base)) #gdb.execute("b")
def clear_symbols(): gdb.execute('file') gdb.execute('symbol-file')
def add_symbol_file(file_name, i_text_addr, i_data_addr): gdb.execute('add-symbol-file ' + file_name + ' ' + hex(i_text_addr) + ' -s .data ' + hex(i_data_addr))
def step_into(self): gdb.execute("stepi", to_string=True)
def invoke(self, arg, from_tty): self.dont_repeat() clear_symbols() pagination = get_pagination() if pagination == 'on': print('Turning pagination off') gdb.execute('set pagination off') if arg: drivers = [d for d in arg.split() if not d.startswith('-')] if drivers: print('Using pre-defined driver list: ' + str(drivers)) if '-64' in arg.split(): self.arch = 'X64' gdb.execute('set architecture i386:x86-64:intel') else: drivers = None if not os.path.isdir('Build'): print('Directory "Build" is missing') print('With architecture ' + self.arch) files_in_log = OrderedDict() load_addresses = {} used_addresses = {} # if same file is loaded multiple times in log, use last occurence for base_addr, file_name in self.get_drivers(drivers): files_in_log[file_name] = base_addr for file_name in files_in_log: efi_file = self.find_file(file_name) if not efi_file: print('File ' + file_name + ' not found') continue debug_file = efi_file[:-3] + 'debug' if not os.path.isfile(debug_file): print('No debug file for ' + efi_file) continue print('EFI file ' + efi_file) if efi_file and debug_file: text_addr, data_addr = self.get_addresses(efi_file) if not text_addr or not data_addr: continue base_addr = files_in_log[file_name] prev_used = used_addresses.get(base_addr) if prev_used: print('WARNING: duplicate base address ' + base_addr) print('(was previously provided for ' + prev_used + ')') print('Only new file will be loaded') del load_addresses[prev_used] else: used_addresses[base_addr] = debug_file load_addresses[debug_file] = (update_addresses( base_addr, text_addr, data_addr)) if load_addresses: for debug_file in load_addresses: add_symbol_file(debug_file, *load_addresses[debug_file]) else: print('No symbols loaded') if pagination == 'on': print('Restoring pagination') gdb.execute('set pagination on') if arg and '-r' in arg.split(): remote_connect()
if args is None: return None return map(self.wrap_symbol, args) class ColorFilter(object): def __init__(self): self.name = "colorize" # Give this a low priority so it runs last. self.priority = 0 self.enabled = True gdb.frame_filters[self.name] = self def filter(self, frame_iter): return map(ColorDecorator, frame_iter) ColorFilter() # Defaults. gdb.execute("set backtrace argument foreground yellow", to_string = True) gdb.execute("set backtrace function foreground black", to_string = True) gdb.execute("set backtrace function background magenta", to_string = True) gdb.execute("set backtrace std_function foreground cyan", to_string = True) gdb.execute("set backtrace std_function intensity faint", to_string = True) gdb.execute("set backtrace filename foreground black", to_string = True) gdb.execute("set backtrace filename background green", to_string = True) gdb.execute("set backtrace std_filename foreground green", to_string = True)
def run(self): gdb.execute("continue")
def local_info(self): return gdb.execute('info locals', to_string=True)
def set_reg(self, name, value): if name == "efl": name = "eflags" gdb.execute("set $%s = %d" % (name, value))
def test_cyset(self): self.break_and_run('os.path.join("foo", "bar")') gdb.execute('cy set a = $cy_eval("{None: []}")') stringvalue = self.read_var("a", cast_to=str) self.assertEqual(stringvalue, "{None: []}")
def break_and_run(self, source_line): break_lineno = test_libcython.source_to_lineno[source_line] gdb.execute('cy break codefile:%d' % break_lineno, to_string=True) gdb.execute('run', to_string=True)
def eval_command(self, command): gdb.execute('cy exec open(%r, "w").write(str(%s))' % (self.tmpfilename, command)) return self.tmpfile.read().strip()
def break_and_run_func(self, funcname): gdb.execute('cy break ' + funcname) gdb.execute('cy run')
def test_c_step(self): self.break_and_run('some_c_function()') gdb.execute('cy step', to_string=True) self.assertEqual(gdb.selected_frame().name(), 'some_c_function')
def test_python_exec(self): self.break_and_run('os.path.join("foo", "bar")') gdb.execute('cy step') gdb.execute('cy exec some_random_var = 14') self.assertEqual('14', self.eval_command('some_random_var'))
def step(self, varnames_and_values, source_line=None, lineno=None): gdb.execute(self.command) for varname, value in varnames_and_values: self.assertEqual(self.read_var(varname), value, self.local_info()) self.lineno_equals(source_line, lineno)
def test_print(self): self.break_and_run('c = 2') result = gdb.execute('cy print b', to_string=True) self.assertEqual('b = (int) 1\n', result)