#!/usr/bin/env python
import sys
import os

#(gdb)source /gdb_python/jmpreg_find.py

def getAsm(asm):
	tmp = sys.stdout
	sys.stdout = open("/gdb_python/tmp/temp.s","w")
	print("BITS 32")
	print("\n")
	print("_start:")
	print("		{0}".format(asm))

	sys.stdout.close()
	sys.stdout = tmp
	os.system("nasm /gdb_python/tmp/temp.s");
	os.system("ndisasm -b32 /gdb_python/tmp/temp");
	
	buf = []
	f = open("/gdb_python/tmp/temp", 'rb')
	for b in f.read():
		buf.append(hex(b))
	
	return buf
	
def gdbexecute(cmd, tostring):
	try:
		return gdb.execute(cmd,to_string=tostring)
	except:
		print("gdb.execute failed command = {0}".format(cmd))

def find_rop_asm(searchAsm, dumpSize, filePath):
	sys.stdout = open(filePath,"w")

	#shell cat /proc/xxxx/maps
	proc = gdbexecute('i proc map', True)
	ary = proc.split('\n')
	pid = ary[0].split(' ')[1]
	cmd = "/proc/{0}/maps".format(pid)
	maps = open(cmd).read()
	print("----------------------------------------------------------------------------------------------------------")
	print(cmd)
	print(maps)
	print("----------------------------------------------------------------------------------------------------------")
	
	for sb in searchAsm:
		print(sb)
	
	#find addr
	smap = maps.split('\n')
	smap.pop()

	for sb in searchAsm:
		ary = getAsm(sb)
		searchByte = ",".join(ary)

		for line in smap:
			words = line.split(' ')
			
			if words[1][2:3] != "x":
				continue
				
			addr = words[0].split('-')
			
			#find 0xXXXXXXXX,0xXXXXXXXX,sesarchByte
			cmd = "find /b 0x{0}, 0x{1}, {2}".format(addr[0],addr[1], searchByte)
			find = gdbexecute(cmd, True)
			
			ary = find.split('\n')
			ary.pop()
			for line2 in ary:
				faddr = line2.split(' ')
				if faddr[0][0:2] == "0x":
					cmd = "x/{0}i {1}".format(dumpSize,faddr[0])
					str = gdbexecute(cmd,True)
					
					print("----------------------------------------------------------------------------------------------------------")
					print(sb)
					print(line)
					print(cmd)
					for s in str.split('\n'):
						print(s)
						
	sys.stdout.close()
	sys.stdout = sys.__stdout__

searchAsm = ["jmp esp", "jmp eax", "jmp ecx", "jmp edx", "jmp ebx", "jmp ebp", "jmp esi", "jmp edi"]
			 
dumpSize = "10"

filePath = "/gdb_python/jmpreg_find.txt"

find_rop_asm(searchAsm,dumpSize,filePath)

print("write jmpreg_find.txt")
