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
60 method = self.dispatch.get(type(obj), self.visitObj)
63 def visitObj(self, obj):
64 raise NotImplementedError
66 def visitAtom(self, obj):
67 return self.visitObj(obj)
69 def visitNone(self, obj):
70 return self.visitAtom(obj)
72 def visitBool(self, obj):
73 return self.visitAtom(obj)
75 def visitInt(self, obj):
76 return self.visitAtom(obj)
78 def visitFloat(self, obj):
79 return self.visitAtom(obj)
81 def visitStr(self, obj):
82 return self.visitAtom(obj)
84 def visitIterable(self, obj):
85 return self.visitObj(obj)
87 def visitTuple(self, obj):
88 return self.visitIterable(obj)
90 def visitList(self, obj):
91 return self.visitIterable(obj)
93 def visitDict(self, obj):
94 raise NotImplementedError
96 def visitByteArray(self, obj):
97 raise NotImplementedError
100 class Dumper(Visitor):
102 id_re = re.compile('^[_A-Za-z][_A-Za-z0-9]*$')
104 def visitObj(self, obj):
107 def visitStr(self, obj):
108 if self.id_re.match(obj):
113 def visitTuple(self, obj):
114 return '[' + ', '.join(itertools.imap(self.visit, obj)) + ']'
116 def visitList(self, obj):
117 return '(' + ', '.join(itertools.imap(self.visit, obj)) + ')'
119 def visitByteArray(self, obj):
120 return 'blob(%u)' % len(obj)
123 class Hasher(Visitor):
124 '''Returns a hashable version of the objtree.'''
126 def visitObj(self, obj):
129 def visitAtom(self, obj):
132 def visitIterable(self, obj):
133 return tuple(itertools.imap(self.visit, obj))
135 def visitByteArray(self, obj):
139 class Rebuilder(Visitor):
140 '''Returns a hashable version of the objtree.'''
142 def visitAtom(self, obj):
145 def visitIterable(self, obj):
149 newItem = self.visit(oldItem)
150 if newItem is not oldItem:
152 newItems.append(newItem)
155 return klass(changed)
159 def visitByteArray(self, obj):
165 def __init__(self, callTuple):
166 self.no, self.functionName, self.args, self.ret = callTuple
170 s = self.functionName
171 if self.no is not None:
172 s = str(self.no) + ' ' + s
174 s += '(' + ', '.join(itertools.imap(dumper.visit, self.args)) + ')'
175 if self.ret is not None:
177 s += dumper.visit(self.ret)
180 def __eq__(self, other):
182 self.functionName == other.functionName and \
183 self.args == other.args and \
184 self.ret == other.ret
187 if self._hash is None:
189 hashable = hasher.visit(self.functionName), hasher.visit(self.args), hasher.visit(self.ret)
190 self._hash = hash(hashable)
198 def __init__(self, stream):
202 while self.parseCall():
207 callTuple = pickle.load(self.stream)
211 call = self.callFactory(callTuple)
212 self.handleCall(call)
215 def handleCall(self, call):
219 class Counter(Unpickler):
221 def __init__(self, stream, quiet):
222 Unpickler.__init__(self, stream)
226 def handleCall(self, call):
228 sys.stdout.write(str(call))
229 sys.stdout.write('\n')
234 optparser = optparse.OptionParser(
235 usage="\n\tapitrace pickle trace. %prog [options]")
236 optparser.add_option(
238 action="store_true", dest="quiet", default=False,
239 help="don't dump calls to stdout")
241 (options, args) = optparser.parse_args(sys.argv[1:])
244 optparser.error('unexpected arguments')
246 # Change stdin to binary mode
253 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
255 startTime = time.time()
256 parser = Counter(sys.stdin, options.quiet)
258 stopTime = time.time()
259 duration = stopTime - startTime
260 sys.stderr.write('%u calls, %.03f secs, %u calls/sec\n' % (parser.calls, duration, parser.calls/duration))
263 if __name__ == '__main__':