comparison examples/inject_redir.py @ 119:4f508f84c8a1

Add inject_redir.py example
author Thinker K.F. Li <thinker@codemud.net>
date Fri, 05 Aug 2011 14:39:32 +0800
parents
children ff6f869273b7
comparison
equal deleted inserted replaced
118:7b537e0d8e7a 119:4f508f84c8a1
1 ## \file
2 #
3 # This is an example of inject a class from source to destinate DEX, and
4 # rewrite all references of a specified class with the injected one and its
5 # methods. All calls of specified class will be redirected to the
6 # injected class.
7 #
8 from paraspace.dexfile import DEXFile, DEXFile_linked
9 from paraspace.dex_deptracker import prepare_dep_decls
10 from paraspace.dex_deptracker import restore_dependencies
11 from paraspace.injection import inject_classdefs, make_methodidxs_redir_map
12 from paraspace.injection import dexfile_redirect_types
13 import sys
14
15 if len(sys.argv) != 6:
16 print >> sys.stderr, \
17 'usage: %s <src dex> <inject class> ' \
18 '<dst dex> <redirect class> <output>' % \
19 (sys.argv[0])
20 sys.exit(1)
21 pass
22
23 src_dexname = sys.argv[1]
24 inj_classname = sys.argv[2]
25 dst_dexname = sys.argv[3]
26 redir_classname = sys.argv[4]
27 output_name = sys.argv[5]
28
29 decls = prepare_dep_decls()
30
31 src_dex = DEXFile.open(src_dexname)
32 src_linked = DEXFile_linked.build_dependencies(src_dex, decls)
33
34 dst_dex = DEXFile.open(dst_dexname)
35 dst_linked = DEXFile_linked.build_dependencies(dst_dex, decls)
36
37 inj_classdef = src_linked.find_class_name(inj_classname)
38 injected_classdefs = inject_classdefs(dst_linked, src_linked, [inj_classdef])
39
40 redir_typeid = dst_linked.find_typeid_name(redir_classname)
41 redir_typeidx = dst_linked.get_idx_typeid(redir_typeid)
42 inj_typeid = dst_linked.find_typeid_name(inj_classname)
43 inj_typeidx = dst_linked.get_idx_typeid(inj_typeid)
44 typeidxs_redir = {redir_typeidx: inj_typeidx}
45
46 methodidxs_redir = \
47 make_methodidxs_redir_map(dst_linked, dst_linked, typeidxs_redir)
48
49 injected_typeidxs = [dst_linked.get_idx_classdef(classdef)
50 for classdef in injected_classdefs]
51 dexfile_redirect_types(dst_linked, typeidxs_redir, methodidxs_redir,
52 excludes=injected_typeidxs)
53
54 restore_dependencies(dst_linked, decls)
55 dst_linked.make_checksum()
56
57 restore_raw = dst_linked.to_str()
58
59 ofile = open(output_name, 'w')
60 ofile.write(restore_raw)
61 ofile.close()