Python gdb.execute() Examples

The following are 30 code examples of gdb.execute(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gdb , or try the search function .
Example #1
Source File: gdb.py    From 7billionhumans with MIT License 6 votes vote down vote up
def end_of_level():
    global source
    try:
        #avg_speed = gdb.execute("print (float)GetAvgRunSpeed()", to_string=True)
        avg_speed = gdb.execute("printf \"%f\", (float)GetAvgRunSpeed()", to_string=True)
        fail_cnt = gdb.execute("printf \"%d\", (int)CountRunsFailed()", to_string=True)
        #partial = (fail_cnt, 25)
        ele.enabled = True
        print(">> source = {}".format(source))
        print(">> avg_speed = {}".format(avg_speed))
        print(">> fail_cnt = {}".format(fail_cnt))

        gdb.execute("continue")
    except Exception as e:
        error = traceback.format_exc()
        print(error) 
Example #2
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def procmap():
    data = gdb.execute('info proc exe',to_string = True)
    pid = re.search('process.*',data)
    if pid :
        pid = pid.group()
        pid = pid.split()[1]
        fpath = "/proc/" + pid + "/maps"
        if os.path.isfile(fpath): # if file exist, read memory mapping directly from file
            maps = open(fpath)
            infomap = maps.read()
            maps.close()
            return infomap
        else: # if file doesn't exist, use 'info proc map' to get the memory mapping
            return infoprocmap()
    else :
        return "error" 
Example #3
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def findsyscall(*arg):
    """ ind the syscall gadget"""
    vmmap = arg[0] if len(arg) > 0 else pwndbg.proc.exe
    arch = pwndbg.arch.current
    start, end = codeaddr()

    if arch == "x86-64" :
        gdb.execute("search -e -x 0f05 {}".format(vmmap))
    elif arch == "i386":
        gdb.execute("search -e -x cd80 {}".format(vmmap))
    elif arch == "arm":
        gdb.execute("search -e -x 00df80bc {}".format(vmmap))
    elif arch == "aarch64":
        gdb.execute("search -e -x 010000d4 {}".format(vmmap))
    else :
        print("arch not support") 
Example #4
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def getoff(sym):
    libc = libcbase()
    if type(sym) is int :
        return sym-libc
    else :
        try :
            data = gdb.execute("x/x " + sym ,to_string=True)
            if "No symbol" in data:
                return 0
            else :
                data = re.search("0x.*[0-9a-f] ",data)
                data = data.group()
                symaddr = int(data[:-1] ,16)
                return symaddr-libc
        except :
            return 0 
Example #5
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def at(*arg):
    """Automatically attach process by filename."""
    processname = arg[0] if len(arg) > 0 else pwndbg.proc.exe

    try :
        pidlist = map(int, subprocess.check_output('pidof $(basename {})'.format(processname), shell=True).decode('utf8').split())

        for pid in pidlist:
            if pid == pwndbg.proc.pid:
                continue
            print('attaching to {} ...'.format(processname))
            gdb.execute("attach {}".format(pid))
            getheapbase()
            libcbase()
            codeaddr()
            ldbase()
            return

        print("already attached on {}".format(pwndbg.proc.pid))
    except:
        print("no such process") 
Example #6
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def testfsop(addr=None):
    getarch()
    if addr :
        cmd = "x/" + word + hex(addr)
    else :
        cmd = "x/" + word + "&_IO_list_all"
    head = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
    chain = head
    print("---------- fp : 0x%x ----------" % chain)
    testorange(chain)
    try :
        while chain != 0 :
            cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(chain) +").file._chain"
            chain = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
            if chain != 0 :
                print("---------- fp : 0x%x ----------" % chain)
                testorange(chain)
    except :
        print("Chain is corrupted") 
Example #7
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def showfpchain():
    getarch()
    cmd = "x/" + word + "&_IO_list_all"
    head = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
    print("\033[32mfpchain:\033[1;37m ",end = "")
    chain = head
    print("0x%x" % chain,end = "")
    try :
        while chain != 0 :
            print(" --> ",end = "")
            cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(chain) +").file._chain"
            chain = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
            print("0x%x" % chain,end = "")
        print("")
    except :
        print("Chain is corrupted") 
Example #8
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def magic(self):
        """ Print usefual variables or function in glibc """
        getarch()
        
        try :
            print("========== function ==========")
            for f in magic_function :
                print("\033[34m" + f  + ":" + "\033[33m" +hex(getoff(f))) 
            print("\033[00m========== variables ==========")
            for v in magic_variable :
                cmd = "x/" + word + "&" +v
                content = gdb.execute(cmd,to_string=True).split(":")[1].strip()
                offset = hex(getoff("&"+ v))
                pad = 36 - len(v) - len(offset) - 2
                print("\033[34m%s\033[33m(%s)\033[37m%s: \033[37m%s" % (v, offset, ' ' *pad, content))
        except :
            print("You need run the program first") 
Example #9
Source File: gdb_service.py    From pyringe with Apache License 2.0 6 votes vote down vote up
def Detach(self):
    """Detaches from the inferior. If not attached, this is a no-op."""
    # We have to work around the python APIs weirdness :\
    if not self.IsAttached():
      return None
    # Gdb doesn't drain any pending SIGINTs it may have sent to the inferior
    # when it simply detaches. We can do this by letting the inferior continue,
    # and gdb will intercept any SIGINT that's still to-be-delivered; as soon as
    # we do so however, we may lose control of gdb (if we're running in
    # synchronous mode). So we queue an interruption and continue gdb right
    # afterwards, it will waitpid() for its inferior and collect all signals
    # that may have been queued.
    pid = gdb.selected_inferior().pid
    self.Interrupt([pid, None, None])
    self.Continue([pid, None, None])
    result = gdb.execute('detach', to_string=True)
    if not result:
      return None
    return result 
Example #10
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def at(self,*arg):
        """ Attach by processname """
        (processname,) = normalize_argv(arg,1)
        if not processname :
            processname = getprocname(relative=True)
            if not processname :
                print("Attaching program: ")
                print("No executable file specified.")
                print("Use the \"file\" or \"exec-file\" command.")
                return
        try :
            print("Attaching to %s ..." % processname)
            pidlist = subprocess.check_output("pidof " + processname,shell=True).decode('utf8').split()
            gdb.execute("attach " + pidlist[0])
            getheapbase()
            libcbase()
            codeaddr()
            ldbase()
        except :
            print( "No such process" ) 
Example #11
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def bcall(self,*arg):
        """ Set the breakpoint at some function call """
        (sym,)= normalize_argv(arg,1)
        call = searchcall(sym)
        if "not found" in call :
            print("symbol not found")
        else :
            if ispie():
                codebaseaddr,codeend = codeaddr()
                for callbase in call.split('\n')[:-1]: 
                    addr = int(callbase.split(':')[0],16) + codebaseaddr
                    cmd = "b*" + hex(addr)
                    print(gdb.execute(cmd,to_string=True))
            else:
                for callbase in  call.split('\n')[:-1]:
                    addr = int(callbase.split(':')[0],16)
                    cmd = "b*" + hex(addr)
                    print(gdb.execute(cmd,to_string=True)) 
Example #12
Source File: gdb-checksec.py    From gdb_commands with GNU General Public License v2.0 6 votes vote down vote up
def get_modules():
  mods = [] 

  # Get the binary currently being debugged
  inferiors_output = gdb.execute("info inferiors", False, True)
  mobjs = re.findall('\*?\s*(\w+)\s+(\w+ \d+)\s+([^\s]+)', inferiors_output)
  for m in mobjs:
    mods.append(m[2])
  
  # Get the sharedlibrarys
  sharedlibrary_output = gdb.execute("info sharedlibrary", False, True)
  #mobjs = re.findall("(0x[a-zA-Z0-9]+)\s+(0x[a-zA-Z0-9]+)\s+(\w+)(\s+\(\*\))?\s+([^\s]+)", sharedlibrary_output)
  mobjs = re.findall("(\/.*)", sharedlibrary_output)
  for m in mobjs:
    mods.append(m)
  return mods 
Example #13
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def get_smallbin(arena=None):
    global smallbin
    if not arena :
        arena = main_arena
    smallbin = {}
    if capsize == 0 :
        arch = getarch()
    max_smallbin_size = 512*int(capsize/4)
    cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins"
    bins_addr = int(gdb.execute(cmd,to_string=True).split(":")[0].split()[0].strip(),16)
    for size in range(capsize*4,max_smallbin_size,capsize*2):
        chunkhead = {}
        idx = int((size/(capsize*2)))-1 
        cmd = "x/" + word + hex(bins_addr + idx*capsize*2)  # calc the smallbin index
        chunkhead["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
        try :
            bins = trace_normal_bin(chunkhead,arena)
        except:
            corruptbin = True
            bins = None
        if bins and len(bins) > 0 :
            smallbin[hex(size)] = copy.deepcopy(bins) 
Example #14
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def get_fake_fast(addr,size = None):
    if capsize == 0 :
        arch = getarch()
    fast_max = int(gdb.execute("x/" + word + "&global_max_fast",to_string=True).split(":")[1].strip(),16)
    if not fast_max :
        fast_max = capsize*0x10
    if size :
        chunk_list = fake_fast(addr,size)
        for fakechunk in chunk_list :
            if len(chunk_list) > 0 :
                print("\033[1;33mfake chunk : \033[1;0m0x{:<12x}\033[1;33m  padding :\033[1;0m {:<8d}".format(fakechunk[0],fakechunk[1]))
    else :
        for i in range(int(fast_max/(capsize*2)-1)):
            size = capsize*2*2 + i*capsize*2
            chunk_list = fake_fast(addr,size) 
            if len(chunk_list) > 0 :
                print("-- size : %s --" % hex(size))
                for fakechunk in chunk_list :
                    print("\033[1;33mfake chunk :\033[1;0m 0x{:<12x}\033[1;33m  padding :\033[1;0m {:<8d}".format(fakechunk[0],fakechunk[1])) 
Example #15
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def putarenainfo():
    set_main_arena()
    if capsize == 0 :
        arch = getarch()
    cur_arena = 0
    if main_arena :
        try : 
            if capsize == 4 :
                nextoff = 0x10d*capsize + 0xc
            else :
                nextoff = 0x10d*capsize
            count = 0
            print("  Main Arena  ".center(50,"="))
            putheapinfo(main_arena)
            cur_arena = int(gdb.execute("x/" + word + hex(main_arena+nextoff),to_string=True).split(":")[1].strip(),16)
            while cur_arena != main_arena  :
                count +=1
                print(("  Arena " + str(count) + "  ").center(50,"="))
                putheapinfo(cur_arena)
                cur_arena = int(gdb.execute("x/" + word  + hex(cur_arena+nextoff),to_string=True).split(":")[1].strip(),16)
        except :
            print("Memory Error (heap)")
    else :
        print("Can't find heap info ") 
Example #16
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def get_largebin(arena=None):
    global largebin
    global corruptbin
    if not arena :
        arena = main_arena
    largebin = {}
    if capsize == 0 :
        arch = getarch()
    min_largebin = 512*int(capsize/4)
    cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins"
    bins_addr = int(gdb.execute(cmd,to_string=True).split(":")[0].split()[0].strip(),16)
    for idx in range(64,128):
        chunkhead = {}
        cmd = "x/" + word + hex(bins_addr + idx*capsize*2 - 2*capsize)  # calc the largbin index
        chunkhead["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
        try :
            bins = trace_normal_bin(chunkhead,arena)
        except :
            corruptbin = True
            bins = None
        if bins and len(bins) > 0 :
            largebin[idx] = copy.deepcopy(bins) 
Example #17
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 6 votes vote down vote up
def getoff(sym):
    libc = libcbase()
    if type(sym) is int :
        return sym-libc
    else :
        try :
            data = gdb.execute("x/x " + sym ,to_string=True)
            if "No symbol" in data:
                return 0
            else :
                data = re.search("0x.*[0-9a-f] ",data)
                data = data.group()
                symaddr = int(data[:-1] ,16)
                return symaddr-libc
        except :
            return 0 
Example #18
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def getcanary():
    arch = getarch()
    tlsaddr = gettls()
    if arch == "i386" :
        offset = 0x14
        result = gdb.execute("x/xw " + hex(tlsaddr + offset),to_string=True).split(":")[1].strip()
        return int(result ,16)   
    elif arch == "x86-64" :
        offset = 0x28
        result = gdb.execute("x/xg " + hex(tlsaddr + offset),to_string=True).split(":")[1].strip()
        return int(result,16)
    else :
        return "error" 
Example #19
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def get_reg(reg):
    cmd = "info register " + reg
    result = int(gdb.execute(cmd,to_string=True).split()[1].strip(),16)
    return result 
Example #20
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def codeaddr(): # ret (start,end)
    infomap = procmap()
    procname = getprocname()
    pat = ".*" + procname
    data = re.findall(pat,infomap)
    if data :
        codebaseaddr = data[0].split("-")[0]
        codeend = data[0].split("-")[1].split()[0]
        gdb.execute("set $code=%s" % hex(int(codebaseaddr,16)))
        return (int(codebaseaddr,16),int(codeend,16))
    else :
        return (0,0) 
Example #21
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def showfp(addr):
    if addr : 
        cmd = "p *(struct _IO_FILE_plus *)" + hex(addr)
        try :
            result = gdb.execute(cmd)
        except :
            print("Can't not access 0x%x" % addr)
    else :
        print("You need to specify an address") 
Example #22
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def getheapbase():
    infomap = procmap()
    data = re.search(".*heap\]",infomap)
    if data :
        heapbase = data.group().split("-")[0]
        gdb.execute("set $heap=%s" % hex(int(heapbase,16)))
        return int(heapbase,16)
    else :
        return 0 
Example #23
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def ldbase():
    infomap = procmap()
    data = re.search(".*ld.*\.so",infomap)
    if data :
        ldaddr = data.group().split("-")[0]
        gdb.execute("set $ld=%s" % hex(int(ldaddr,16)))
        return int(ldaddr,16)
    else :
        return 0 
Example #24
Source File: vgleaks.py    From gdb_python_api with MIT License 5 votes vote down vote up
def invoke(self, arg, from_tty):
        result = gdb.execute('mo leak full', False, True)
        while result.find('are definitely lost in loss record') is -1:
            try:
                gdb.execute('step', to_string = True)  # QUIETLY step
            except gdb.error:
                print('error while stepping')  # BOZO handle
                break
            result = gdb.execute('mo leak full', False, True)
        print('loss report:\n%s'%result)
        print('leak first noticed at:\n')
        gdb.execute('bt') 
Example #25
Source File: pwngdb.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def libcbase():
    infomap = procmap()
    data = re.search(".*libc.*\.so",infomap)
    if data :
        libcaddr = data.group().split("-")[0]
        gdb.execute("set $libc=%s" % hex(int(libcaddr,16)))
        return int(libcaddr,16)
    else :
        return 0 
Example #26
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def stop(self):
        if len(arch) == 0 :
            getarch()
        if arch == "x86-64":
            reg = "$rsi"
            arg = int(gdb.execute("info register " + reg,to_string=True).split()[1].strip(),16)
        else :
            # for _int_malloc in x86's glibc (unbuntu 14.04 & 16.04), size is stored in edx
            reg = "$edx"
            arg = int(gdb.execute("info register " + reg,to_string=True).split()[1].strip(),16)
        Malloc_bp_ret(arg)
        return False 
Example #27
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def get_tcache_entry():
    global tcache_entry
    get_tcache()
    if not tcache_enable :
        return
    tcache_entry = []
    get_tcache_count()
    if capsize == 0 :
        arch = getarch()
    if tcache and tcache_max_bin :
        entry_start = tcache + tcache_max_bin * tcache_counts_size
        for i in range(tcache_max_bin):
            tcache_entry.append([])
            chunk = {}
            is_overlap = (None,None)
            cmd = "x/" + word + hex(entry_start + i*capsize)
            entry = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
            while entry and not is_overlap[0] :
                chunk["addr"] = entry - capsize*2
                cmd = "x/" + word + hex(chunk["addr"] + capsize)
                try :
                    chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
                except :
                    chunk["memerror"] = "invaild memory"
                    tcache_entry[i].append(copy.deepcopy(chunk))
                    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))
                tcache_entry[i].append(copy.deepcopy(chunk))
                all_tcache_entry.append(chunk["addr"])
                cmd = "x/" + word + hex(chunk["addr"]+capsize*2)
                chunk = {}
                entry = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) 
Example #28
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def get_system_mem(arena=None):
    global system_mem
    if not arena :
        arena = main_arena
    if capsize == 0 :
        arch = getarch()
    cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").system_mem" 
    system_mem = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) 
Example #29
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def get_reg(reg):
    cmd = "info register " + reg
    result = int(gdb.execute(cmd,to_string=True).split()[1].strip(),16)
    return result 
Example #30
Source File: angelheap.py    From Pwngdb with GNU General Public License v3.0 5 votes vote down vote up
def get_tcache_count() :
    global tcache_count
    tcache_count = []
    if not tcache_enable :
        return
    if capsize == 0 :
        arch = getarch()
    count_size = int(tcache_max_bin * tcache_counts_size / capsize)
    for i in range(count_size):
        cmd = "x/" + word + hex(tcache + i*capsize)
        c = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
        for j in range(int(capsize / tcache_counts_size)):
            tcache_count.append((c >> j * 8*tcache_counts_size) & 0xff)