from Elf import *
from sys import *


def chopaddress(address):
	addy = address.strip(' \*$')
	try:
		if (addy[1] == 'x'):
			addy = addy[2:]
	except:
		pass
	return addy
			


class DisassDATA:
	
	def __init__(self,filename,parent = None):
		self.bytes = ""
		self.myElf = None
		self.baseaddress = 0
		self.endaddress = 0
		self.parent = parent
		self.init(filename)
		
	
	def __str__(self):
		s = "DATA:\n base address = 0x%x\tsize = 0x%x\n"%(self.baseaddress, len(self.bytes))
		s +=self.bytes
		return s
		
	def init(self,filename):
		try:
			self.myElf = Elf(filename)
			self.rodata = self.myElf.getSection('.rodata')
			self.bytes = self.rodata.getBytes()
			self.baseaddress = self.rodata.sh_addr
			self.endaddress = (self.rodata.sh_addr + len(self.bytes))
		except:
			self.rodata = ""
			self.bytes = ""
			self.baseaddress = 0
			self.endaddress = 0
			self.myElf = Elf(None)

	
	def getRepr(self,address):
		#print >>sys.stderr,("DATA.getRepr('%s')"%address)
		try:	
			lookup = int(chopaddress(address),16)
			if (lookup >= self.baseaddress and lookup <= self.endaddress):
				offset = lookup - self.baseaddress
				end = self.bytes.find('\x00', offset)
				if (end > -1): 
					return "\t'%s'"%self.bytes[offset:end]
				else: 
					return "\t'%s'"%self.bytes[offset:]
		except:
			pass
		return ""
		

me = DisassDATA(argv[1])
