diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/inject_redir.py	Fri Aug 05 14:39:32 2011 +0800
@@ -0,0 +1,61 @@
+## \file
+#
+# This is an example of inject a class from source to destinate DEX, and
+# rewrite all references of a specified class with the injected one and its
+# methods.  All calls of specified class will be redirected to the
+# injected class.
+#
+from paraspace.dexfile import DEXFile, DEXFile_linked
+from paraspace.dex_deptracker import prepare_dep_decls
+from paraspace.dex_deptracker import restore_dependencies
+from paraspace.injection import inject_classdefs, make_methodidxs_redir_map
+from paraspace.injection import dexfile_redirect_types
+import sys
+
+if len(sys.argv) != 6:
+    print >> sys.stderr, \
+        'usage: %s <src dex> <inject class> ' \
+        '<dst dex> <redirect class> <output>' % \
+        (sys.argv[0])
+    sys.exit(1)
+    pass
+
+src_dexname = sys.argv[1]
+inj_classname = sys.argv[2]
+dst_dexname = sys.argv[3]
+redir_classname = sys.argv[4]
+output_name = sys.argv[5]
+
+decls = prepare_dep_decls()
+
+src_dex = DEXFile.open(src_dexname)
+src_linked = DEXFile_linked.build_dependencies(src_dex, decls)
+
+dst_dex = DEXFile.open(dst_dexname)
+dst_linked = DEXFile_linked.build_dependencies(dst_dex, decls)
+
+inj_classdef = src_linked.find_class_name(inj_classname)
+injected_classdefs = inject_classdefs(dst_linked, src_linked, [inj_classdef])
+
+redir_typeid = dst_linked.find_typeid_name(redir_classname)
+redir_typeidx = dst_linked.get_idx_typeid(redir_typeid)
+inj_typeid = dst_linked.find_typeid_name(inj_classname)
+inj_typeidx = dst_linked.get_idx_typeid(inj_typeid)
+typeidxs_redir = {redir_typeidx: inj_typeidx}
+
+methodidxs_redir = \
+    make_methodidxs_redir_map(dst_linked, dst_linked, typeidxs_redir)
+
+injected_typeidxs = [dst_linked.get_idx_classdef(classdef)
+                     for classdef in injected_classdefs]
+dexfile_redirect_types(dst_linked, typeidxs_redir, methodidxs_redir,
+                       excludes=injected_typeidxs)
+
+restore_dependencies(dst_linked, decls)
+dst_linked.make_checksum()
+
+restore_raw = dst_linked.to_str()
+
+ofile = open(output_name, 'w')
+ofile.write(restore_raw)
+ofile.close()