7
7
from binary import Binary
8
8
9
9
class Patcher :
10
- def __init__ (self , binary , verbose = False , cflags = None ):
10
+ def __init__ (self , binary , verbose = False , cflags = None , silent = False ):
11
11
self .bin = Binary (binary )
12
12
self .bin .verbose = verbose
13
13
self .bin .linker .cflags = cflags
14
14
self .patches = []
15
15
self .patchfiles = []
16
16
self .verbose = verbose
17
17
self .cflags = cflags
18
+ self .silent = silent
18
19
19
20
def add (self , path ):
20
21
if path .endswith ('.py' ):
@@ -26,12 +27,16 @@ def add(self, path):
26
27
continue
27
28
self .patchfiles .append ((name , os .path .join (base , os .path .basename (name ))))
28
29
30
+ def debug (self , * args ):
31
+ if not self .silent :
32
+ print >> sys .stderr , ' ' .join (map (str , args ))
33
+
29
34
def patch (self ):
30
35
cwd = os .getcwd ()
31
36
try :
32
37
for path , pathname in self .patchfiles :
33
38
sys .path .insert (0 , os .path .dirname (path ))
34
- print '[*]' , pathname
39
+ self . debug ( '[*]' , pathname )
35
40
patchfile = os .path .basename (path ).rsplit ('.' , 1 )[0 ]
36
41
patch = __import__ (patchfile )
37
42
sys .path .pop (0 )
@@ -48,8 +53,8 @@ def patch(self):
48
53
except AttributeError :
49
54
pass
50
55
except Exception :
51
- print 'Warning: could not preserve patch function order'
52
- traceback .print_exc ( )
56
+ self . debug ( 'Warning: could not preserve patch function order' )
57
+ self . debug ( traceback .format_exc () )
53
58
order = vars (patch ).values ()
54
59
55
60
for func in order :
@@ -58,19 +63,19 @@ def patch(self):
58
63
continue
59
64
60
65
if hasattr (func , '__call__' ):
61
- print ' [+] %s()' % func .__name__
66
+ self . debug ( ' [+] %s()' % func .__name__ )
62
67
with self .bin .collect () as patchset :
63
68
try :
64
69
func (patchset )
65
70
except Exception as e :
66
- print 'Exception thrown by patch:' , path , func .__name__
71
+ self . debug ( 'Exception thrown by patch:' , path , func .__name__ )
67
72
traceback .print_exc ()
68
- print 'Memory maps:'
73
+ self . debug ( 'Memory maps:' )
69
74
for prog in self .bin .elf .progs :
70
75
if prog .isload :
71
- print '0x%x-0x%x' % (prog .vaddr , prog .vaddr + prog .vsize )
76
+ self . debug ( '0x%x-0x%x' % (prog .vaddr , prog .vaddr + prog .vsize ) )
72
77
sys .exit (1 )
73
- print
78
+ self . debug ()
74
79
finally :
75
80
os .chdir (cwd )
76
81
0 commit comments