extract.py 1.57 KB
#!/usr/bin/python

import sys, os, string, struct

prefix = ""

def compute_sig(obj, symbol):
  num_bytes = symbol["len"]
  offset = symbol["offset"]
  f = open("routines/%s" % symbol["name"], "w+")
  f.write(obj[offset:offset+num_bytes])
  f.close()

def extract_doto(archive, doto):
  #sys.stderr.write("Extracting '%s'\n" % doto)
  res = os.system("ar x %s %s" % (archive, doto))
  #sys.stderr.write("  res = %d\n" % res)
  os.chmod(doto, 0400)

def extract_symbols(doto):
  symbol_table = os.popen("readelf -s %s" % doto).readlines()
  symbols = []
  for sym in symbol_table:
    l = string.split(sym)
    if len(l) == 8 and l[3] == 'FUNC' and l[6] != 'UND' and l[2] != '0':
      d = {}
      d["name"] = l[7]
      d["offset"] = string.atoi(l[1], 16)
      d["len"] = string.atoi(l[2])
      d["file"] = doto
      symbols.append(d)
  return symbols

def get_text_offset(doto):
  sections = os.popen("readelf -S %s | cut -c 8-" % doto).readlines()
  offset = 0
  for s in sections:
    l = string.split(s)
    if len(l) > 0 and l[0] == ".text":
      offset = string.atoi(l[3], 16)
      break
  return offset

def main(argv):
  archive = argv[1]
  global prefix
  prefix = string.split(string.split(archive, '.')[0], '/')[-1]
  ofiles = string.split(os.popen("ar t %s" % archive).read())
  for doto in ofiles:
    extract_doto(archive, doto)
    symbols = extract_symbols(doto)
    offset = get_text_offset(doto)
       
    if offset != 0:
      obj = open(doto).read()[offset:]
      for sym in symbols:
        compute_sig(obj, sym)
  
    os.unlink(doto)

if __name__ == '__main__':
  main(sys.argv)