Miasm2
 All Classes Namespaces Files Functions Variables Typedefs Properties Macros
utils.py
Go to the documentation of this file.
1 import logging
2 
3 log = logging.getLogger('loader_common')
4 hnd = logging.StreamHandler()
5 hnd.setFormatter(logging.Formatter("[%(levelname)s]: %(message)s"))
6 log.addHandler(hnd)
7 log.setLevel(logging.CRITICAL)
8 
9 
10 def canon_libname_libfunc(libname, libfunc):
11  dn = libname.split('.')[0]
12  if type(libfunc) == str:
13  return "%s_%s" % (dn, libfunc)
14  else:
15  return str(dn), libfunc
16 
17 
18 class libimp:
19 
20  def __init__(self, lib_base_ad=0x71111000, **kargs):
21  self.name2off = {}
22  self.libbase2lastad = {}
23  self.libbase_ad = lib_base_ad
24  self.lib_imp2ad = {}
25  self.lib_imp2dstad = {}
26  self.fad2cname = {}
27  self.fad2info = {}
28  self.all_exported_lib = []
29 
30  def lib_get_add_base(self, name):
31  name = name.lower().strip(' ')
32  if not "." in name:
33  log.debug('warning adding .dll to modulename')
34  name += '.dll'
35  log.debug(name)
36 
37  if name in self.name2off:
38  ad = self.name2off[name]
39  else:
40  ad = self.libbase_ad
41  log.debug('new lib %s 0x%x', name, ad)
42  self.name2off[name] = ad
43  self.libbase2lastad[ad] = ad + 0x1
44  self.lib_imp2ad[ad] = {}
45  self.lib_imp2dstad[ad] = {}
46  self.libbase_ad += 0x1000
47  return ad
48 
49  def lib_get_add_func(self, libad, imp_ord_or_name, dst_ad=None):
50  if not libad in self.name2off.values():
51  raise ValueError('unknown lib base!', hex(libad))
52 
53  # test if not ordinatl
54  # if imp_ord_or_name >0x10000:
55  # imp_ord_or_name = vm_get_str(imp_ord_or_name, 0x100)
56  # imp_ord_or_name = imp_ord_or_name[:imp_ord_or_name.find('\x00')]
57 
58  #/!\ can have multiple dst ad
59  if not imp_ord_or_name in self.lib_imp2dstad[libad]:
60  self.lib_imp2dstad[libad][imp_ord_or_name] = set()
61  self.lib_imp2dstad[libad][imp_ord_or_name].add(dst_ad)
62 
63  if imp_ord_or_name in self.lib_imp2ad[libad]:
64  return self.lib_imp2ad[libad][imp_ord_or_name]
65  # log.debug('new imp %s %s' % (imp_ord_or_name, dst_ad))
66  ad = self.libbase2lastad[libad]
67  self.libbase2lastad[libad] += 0x11 # arbitrary
68  self.lib_imp2ad[libad][imp_ord_or_name] = ad
69 
70  name_inv = dict([(x[1], x[0]) for x in self.name2off.items()])
71  c_name = canon_libname_libfunc(name_inv[libad], imp_ord_or_name)
72  self.fad2cname[ad] = c_name
73  self.fad2info[ad] = libad, imp_ord_or_name
74  return ad
75 
76  def check_dst_ad(self):
77  for ad in self.lib_imp2dstad:
78  all_ads = self.lib_imp2dstad[ad].values()
79  all_ads.sort()
80  for i, x in enumerate(all_ads[:-1]):
81  if x is None or all_ads[i + 1] is None:
82  return False
83  if x + 4 != all_ads[i + 1]:
84  return False
85  return True
86 
87