Last active
March 2, 2016 13:11
-
-
Save nicoster/7195565 to your computer and use it in GitHub Desktop.
This script finds the registers saved on the stack in each frame.As ESI, EDI usually serves as the 'this' ptr to an object, that's why it's named findthis. It is written in python. An extension pykd(http://pykd.codeplex.com/) needs to be installed and loaded before running the script in Windbg.Check http://nicoster.github.io/find-this-ptr-within…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
desc = ''' | |
Author: Nick X(nicoster@gmail) | |
This scripts finds the registers saved on the stack in each frame. | |
As ESI, EDI usually serves as the 'this' ptr to an object, that's why it's named findthis | |
Usage: | |
!py findthis [debug|desc] | |
Due to a bug in pykd that it won't allow modifying a file once it's loaded by '!py' cmd. | |
when you're debugging a script, we suggest you run the script this way, always do a load/unload of the pykd extension. | |
.load pykd.pyd;!py findthis\findthis;.unload pykd.pyd | |
Currently support x86 only. | |
Oct 2013: Created. | |
Nov 2013: Refactor the output to align with that of 'kL' command | |
Mar 2015: | |
. handle 'and esp, 0xfffffff8' in parsing assembly code | |
. remove the duplication of registers | |
. attempt to take advantage of 'dv /v /t this' command but in vain | |
. better debug logging | |
''' | |
import sys | |
import re | |
import tempfile | |
from pykd import * | |
pid = None | |
try: | |
pid = dbgCommand('|').split()[3] | |
except: | |
pass | |
cache = tempfile.gettempdir() + '\\findthis.' + pid | |
debug = False | |
system_modules = ['ntdll', 'kernel32', 'user32', 'kernelbase'] | |
registers = ['ebx', 'ecx', 'edx', 'esi', 'edi', 'eax'] | |
this_registers = ['esi', 'edi', 'ebx', 'edx', 'ecx'] | |
prologs = { | |
'_EH_prolog3': {16:'ebx', 20: 'esi', 24: 'edi'}, | |
'_EH_prolog3_GS': {16: 'ebx', 20: 'esi', 24: 'edi'}, | |
'_SEH_prolog4': {16: 'ebx', 20: 'esi', 24: 'edi'} | |
} | |
def dbg(*args): | |
if debug: | |
for arg in args: | |
print arg, | |
print '' | |
def handle_prolog(prolog, offset, results): | |
if prolog not in prologs: return False | |
for k,v in prologs[prolog].iteritems(): | |
results[k + offset] = v | |
return True | |
def IsAmbiguousSymbol(func): | |
funcs = dbgCommand('x ' + func.strip()).splitlines() | |
return len(funcs) | |
def parseFrameSymbol(frames, i, func_offset): | |
try: | |
ip = None | |
if i == len(frames) - 1: # last frame | |
ip = hex(reg('eip')) | |
else: | |
ip = frames[i + 1].split()[2] | |
int(ip, 16) # make sure it's a number | |
cmd = 'u ' + ip + '-' + func_offset + ' L10' | |
dbg(cmd) | |
return dbgCommand(cmd) | |
except BaseException, e: | |
dbg(dbgCommand('ln ' + ip + '-' + func_offset), e) | |
return None | |
def formatRegister(this, val, register): | |
dummy, class_name = this if this else (None, None) | |
if class_name and val and register in this_registers: | |
return register + ':<link cmd="dt ' + class_name + ' %08x' % val + '; .echo;.echo View this in Watch: (' \ | |
+ class_name + '*)%#x' % val + '; !py ' + sys.argv[0] + ' showcachelink">%08x' % val + '</link> ' | |
else: | |
return register + ':%08x' % val + ' ' | |
# find this register from PDB. but this doesn't really help enough. | |
# from example, ecx is marked as the this ptr. but in the function prologue ecx is stored in esi immediately and has never been stored in the stack | |
def getPrevClass(frame_index, func): | |
dbgCommand('.frame ' + frame_index) | |
this = dbgCommand('dv /v /t this').split() | |
# it's something like: [u'@esi', u'class', u'Foo', u'*', u'this', u'=', u'0x00c58cf8'] | |
if this and this[0] and this[0].startswith('@') and len(this) >= 7: | |
return (this[0][1:], ' '.join(this[2:-4])) | |
return (None, func.rsplit('::', 1)[0] if '::' in func else None) | |
def find_this(): | |
dprintln('findthis v1.0. nicoster@gmail. 2013. All Rights Reserved.') | |
dprintln('<link cmd="!py findthis desc">Details</link>\n', True) | |
output = [] | |
prev_class = None | |
stack = dbgCommand('knL100') | |
frames = stack.splitlines()[:0:-1] | |
for i in range(len(frames)): | |
dbg('\n\n-------\nprev-class:', prev_class) | |
frame = frames[i] | |
output.append(frame) | |
frame_index = None | |
try: | |
frame_index, ebp, ret_addr, symbol = frame.split(None, 3) | |
dbg('symbol: ' + symbol) | |
ebp = int(ebp, 16) | |
except: | |
prev_class = None | |
continue | |
module = symbol.split('!')[0] | |
if module.lower() in system_modules and not prev_class: | |
prev_class = None | |
continue | |
func_offset = None | |
func = None | |
if '+' in symbol: | |
func, func_offset = symbol.split('+') | |
else: | |
func = symbol | |
escaped_func = '@@(' + func + ')' if ' ' in func else func | |
try: code = dbgCommand('u ' + escaped_func + ' L10') | |
except BaseException, e: | |
if IsAmbiguousSymbol(func): | |
code = parseFrameSymbol(frames, i, func_offset) | |
if not code: | |
# prev_class should be obtained, as the registers might be availabe in next frame, thus we allow users to decode register via DML | |
prev_class = getPrevClass(frame_index, func) | |
continue | |
else: | |
dbg(e) | |
# prev_class should be obtained, as the registers might be availabe in next frame, thus we allow users to decode register via DML | |
prev_class = getPrevClass(frame_index, func) | |
continue | |
offset = 0 | |
results = {} | |
for line in code.split('\n'): | |
dbg(line) | |
# if not address, this line is not code | |
try: | |
addr, bytes, opcode, operands = line.split(None, 3) | |
int(addr, 16) | |
except: | |
continue | |
if opcode == 'push': | |
offset += 4 | |
if operands not in results.values(): | |
results[offset] = operands | |
continue | |
if opcode == 'pop': | |
offset -= 4 | |
results = dict([(k, v) for k, v in results.items() if v != operands]) # remove a reg (operands) from results | |
continue | |
# to deal with instructions like 'and esp,0FFFFFFF8h' | |
if opcode == 'and' and operands.startswith('esp'): | |
instant_value = operands.split(',')[1] | |
if instant_value.endswith('h'): | |
instant_value = instant_value[:-1] | |
esp = (ebp - offset + 4) & int(instant_value, 16) | |
offset = ebp - esp + 4 | |
dbg('%08x' % ebp, '%08x' % esp, offset) | |
if opcode == 'sub' and operands.startswith('esp'): | |
size = operands.split(',')[1] | |
if size.endswith('h'): | |
size = size[:-1] | |
offset += int(size, 16) | |
continue | |
if opcode == 'call': | |
if 'EH_prolog' in operands: | |
prolog = operands.split()[0].split('!')[1] | |
# it should have something like 'push 8' | |
assert(len(results) < 3 and results[4]) | |
size = results[4] | |
if size.endswith('h'): | |
size = size[:-1] | |
ret = handle_prolog(prolog, int(size, 16) + offset, results) | |
if not ret: | |
dbg('unhandled prolog:', operands) | |
break | |
if opcode.startswith('j'): | |
break | |
output_regs = '' | |
sorted_results = sorted(results.iteritems(), key=lambda d:d[0]) | |
for offset, register in sorted_results: | |
dbg(offset, register) | |
if register in registers: | |
output_regs += formatRegister(prev_class, ptrDWord(ebp - offset + 4), register) | |
if output_regs and len(output) > 1: output[-2] += ' [' + output_regs + ']' | |
prev_class = getPrevClass(frame_index, func) | |
# associate the first frame with the registers | |
output_regs = '' | |
for register in this_registers: | |
output_regs += formatRegister(prev_class, reg(register), register) | |
output[-1] += ' [' + output_regs + ']' | |
print 'Possible this ptrs have been highlighted. Click to decode them respectively.\n' | |
output = '\n'.join(output[::-1]) | |
dprintln(output, True) | |
try: | |
fp = open(cache, 'w') | |
fp.write(output) | |
fp.close() | |
except: | |
pass | |
def main(argv): | |
if len(argv) == 2: | |
if argv[1] == "desc": | |
print desc | |
elif argv[1] == 'cache': | |
try: | |
fp = open(cache, 'r') | |
dprintln(fp.read(), True) | |
fp.close() | |
except: | |
pass | |
elif argv[1] == 'showcachelink': | |
dprintln('\n<link cmd="!py ' + sys.argv[0] + ' cache">Show this ptrs</link>', True) | |
elif argv[1] == 'debug': | |
global debug | |
debug = True | |
main([]) | |
else: | |
find_this() | |
if __name__ == "__main__": | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment