2 ##########################################################################
4 # Copyright 2012 Jose Fonseca
7 # Permission is hereby granted, free of charge, to any person obtaining a copy
8 # of this software and associated documentation files (the "Software"), to deal
9 # in the Software without restriction, including without limitation the rights
10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 # copies of the Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
14 # The above copyright notice and this permission notice shall be included in
15 # all copies or substantial portions of the Software.
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 ##########################################################################/
27 '''Sample program for apitrace pickle command.
31 apitrace pickle foo.trace | python unpickle.py
41 import cPickle as pickle
48 self.dispatch[type(None)] = self.visitNone
49 self.dispatch[bool] = self.visitBool
50 self.dispatch[int] = self.visitInt
51 self.dispatch[long] = self.visitInt
52 self.dispatch[float] = self.visitFloat
53 self.dispatch[str] = self.visitStr
54 self.dispatch[tuple] = self.visitTuple
55 self.dispatch[list] = self.visitList
56 self.dispatch[dict] = self.visitDict
57 self.dispatch[bytearray] = self.visitByteArray
59 def visit(self, obj, *args, **kwargs):
60 return self.dispatch[type(obj)](obj, *args, **kwargs)
62 def visitAtom(self, obj, *args, **kwargs):
63 raise NotImplementedError
65 def visitNone(self, obj, *args, **kwargs):
66 return self.visitAtom(obj, *args, **kwargs)
68 def visitBool(self, obj, *args, **kwargs):
69 return self.visitAtom(obj, *args, **kwargs)
71 def visitInt(self, obj, *args, **kwargs):
72 return self.visitAtom(obj, *args, **kwargs)
74 def visitFloat(self, obj, *args, **kwargs):
75 return self.visitAtom(obj, *args, **kwargs)
77 def visitStr(self, obj, *args, **kwargs):
78 return self.visitAtom(obj, *args, **kwargs)
80 def visitIterable(self, obj, *args, **kwargs):
81 raise NotImplementedError
83 def visitTuple(self, obj, *args, **kwargs):
84 return self.visitIterable(obj, *args, **kwargs)
86 def visitList(self, obj, *args, **kwargs):
87 return self.visitIterable(obj, *args, **kwargs)
89 def visitDict(self, obj, *args, **kwargs):
90 raise NotImplementedError
92 def visitByteArray(self, obj, *args, **kwargs):
93 raise NotImplementedError
96 class Dumper(Visitor):
98 id_re = re.compile('^[_A-Za-z][_A-Za-z0-9]*$')
100 def visitAtom(self, obj, *args, **kwargs):
103 def visitStr(self, obj, *args, **kwargs):
104 if self.id_re.match(obj):
109 def visitTuple(self, obj, *args, **kwargs):
110 return '[' + ', '.join(itertools.imap(self.visit, obj)) + ']'
112 def visitList(self, obj, *args, **kwargs):
113 return '(' + ', '.join(itertools.imap(self.visit, obj)) + ')'
115 def visitByteArray(self, obj, *args, **kwargs):
116 return 'blob(%u)' % len(obj)
119 class Hasher(Visitor):
120 '''Returns a hashable version of the objtree.'''
122 def visitAtom(self, obj, *args, **kwargs):
125 def visitIterable(self, obj, *args, **kwargs):
126 return tuple(itertools.imap(self.visit, obj))
128 def visitByteArray(self, obj, *args, **kwargs):
134 def __init__(self, callTuple):
135 self.no, self.functionName, self.args, self.ret = callTuple
139 s = self.functionName
140 if self.no is not None:
141 s = str(self.no) + ' ' + s
143 s += '(' + ', '.join(itertools.imap(dumper.visit, self.args)) + ')'
144 if self.ret is not None:
146 s += dumper.visit(self.ret)
149 def __eq__(self, other):
151 self.functionName == other.functionName and \
152 self.args == other.args and \
153 self.ret == other.ret
156 if self._hash is None:
158 hashable = hasher.visit(self.functionName), hasher.visit(self.args), hasher.visit(self.ret)
159 self._hash = hash(hashable)
167 def __init__(self, stream):
171 while self.parseCall():
176 callTuple = pickle.load(self.stream)
180 call = self.callFactory(callTuple)
181 self.handleCall(call)
184 def handleCall(self, call):
188 class Counter(Unpickler):
190 def __init__(self, stream, quiet):
191 Unpickler.__init__(self, stream)
195 def handleCall(self, call):
197 sys.stdout.write(str(call))
198 sys.stdout.write('\n')
203 optparser = optparse.OptionParser(
204 usage="\n\tapitrace pickle trace. %prog [options]")
205 optparser.add_option(
207 action="store_true", dest="quiet", default=False,
208 help="don't dump calls to stdout")
210 (options, args) = optparser.parse_args(sys.argv[1:])
213 optparser.error('unexpected arguments')
215 # Change stdin to binary mode
222 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
224 startTime = time.time()
225 parser = Counter(sys.stdin, options.quiet)
227 stopTime = time.time()
228 duration = stopTime - startTime
229 sys.stderr.write('%u calls, %.03f secs, %u calls/sec\n' % (parser.calls, duration, parser.calls/duration))
232 if __name__ == '__main__':