]> git.cworth.org Git - apitrace/blob - trace.py
Fix writing/reading compressed length of the chunks.
[apitrace] / trace.py
1 ##########################################################################
2 #
3 # Copyright 2008-2010 VMware, Inc.
4 # All Rights Reserved.
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24 ##########################################################################/
25
26 """Common trace code generation."""
27
28
29 import stdapi
30 from dispatch import Dispatcher
31
32
33 def interface_wrap_name(interface):
34     return "Wrap" + interface.expr
35
36
37 class DumpDeclarator(stdapi.OnceVisitor):
38     '''Declare helper functions to dump complex types.'''
39
40     def visit_void(self, literal):
41         pass
42
43     def visit_literal(self, literal):
44         pass
45
46     def visit_string(self, string):
47         pass
48
49     def visit_const(self, const):
50         self.visit(const.type)
51
52     def visit_struct(self, struct):
53         for type, name in struct.members:
54             self.visit(type)
55         print 'static void __traceStruct%s(const %s &value) {' % (struct.id, struct.expr)
56         print '    static const char * members[%u] = {' % (len(struct.members),)
57         for type, name,  in struct.members:
58             print '        "%s",' % (name,)
59         print '    };'
60         print '    static const Trace::StructSig sig = {'
61         print '       %u, "%s", %u, members' % (int(struct.id), struct.name, len(struct.members))
62         print '    };'
63         print '    Trace::localWriter.beginStruct(&sig);'
64         for type, name in struct.members:
65             dump_instance(type, 'value.%s' % (name,))
66         print '    Trace::localWriter.endStruct();'
67         print '}'
68         print
69
70     def visit_array(self, array):
71         self.visit(array.type)
72
73     def visit_blob(self, array):
74         pass
75
76     __enum_id = 0
77
78     def visit_enum(self, enum):
79         print 'static void __traceEnum%s(const %s value) {' % (enum.id, enum.expr)
80         n = len(enum.values)
81         for i in range(n):
82             value = enum.values[i]
83             print '    static const Trace::EnumSig sig%u = {%u, "%s", %s};' % (i, DumpDeclarator.__enum_id, value, value)
84             DumpDeclarator.__enum_id += 1
85         print '    const Trace::EnumSig *sig;'
86         print '    switch(value) {'
87         for i in range(n):
88             value = enum.values[i]
89             print '    case %s:' % value
90             print '        sig = &sig%u;' % i
91             print '        break;'
92         print '    default:'
93         print '        Trace::localWriter.writeSInt(value);'
94         print '        return;'
95         print '    }'
96         print '    Trace::localWriter.writeEnum(sig);'
97         print '}'
98         print
99
100     def visit_bitmask(self, bitmask):
101         print 'static const Trace::BitmaskFlag __bitmask%s_flags[] = {' % (bitmask.id)
102         for value in bitmask.values:
103             print '   {"%s", %s},' % (value, value)
104         print '};'
105         print
106         print 'static const Trace::BitmaskSig __bitmask%s_sig = {' % (bitmask.id)
107         print '   %u, %u, __bitmask%s_flags' % (int(bitmask.id), len(bitmask.values), bitmask.id)
108         print '};'
109         print
110
111     def visit_pointer(self, pointer):
112         self.visit(pointer.type)
113
114     def visit_handle(self, handle):
115         self.visit(handle.type)
116
117     def visit_alias(self, alias):
118         self.visit(alias.type)
119
120     def visit_opaque(self, opaque):
121         pass
122
123     def visit_interface(self, interface):
124         print "class %s : public %s " % (interface_wrap_name(interface), interface.name)
125         print "{"
126         print "public:"
127         print "    %s(%s * pInstance);" % (interface_wrap_name(interface), interface.name)
128         print "    virtual ~%s();" % interface_wrap_name(interface)
129         print
130         for method in interface.itermethods():
131             print "    " + method.prototype() + ";"
132         print
133         #print "private:"
134         print "    %s * m_pInstance;" % (interface.name,)
135         print "};"
136         print
137
138
139 class DumpImplementer(stdapi.Visitor):
140     '''Dump an instance.'''
141
142     def visit_literal(self, literal, instance):
143         print '    Trace::localWriter.write%s(%s);' % (literal.format, instance)
144
145     def visit_string(self, string, instance):
146         if string.length is not None:
147             print '    Trace::localWriter.writeString((const char *)%s, %s);' % (instance, string.length)
148         else:
149             print '    Trace::localWriter.writeString((const char *)%s);' % instance
150
151     def visit_const(self, const, instance):
152         self.visit(const.type, instance)
153
154     def visit_struct(self, struct, instance):
155         print '    __traceStruct%s(%s);' % (struct.id, instance)
156
157     def visit_array(self, array, instance):
158         length = '__c' + array.type.id
159         index = '__i' + array.type.id
160         print '    if (%s) {' % instance
161         print '        size_t %s = %s;' % (length, array.length)
162         print '        Trace::localWriter.beginArray(%s);' % length
163         print '        for (size_t %s = 0; %s < %s; ++%s) {' % (index, index, length, index)
164         print '            Trace::localWriter.beginElement();'
165         self.visit(array.type, '(%s)[%s]' % (instance, index))
166         print '            Trace::localWriter.endElement();'
167         print '        }'
168         print '        Trace::localWriter.endArray();'
169         print '    } else {'
170         print '        Trace::localWriter.writeNull();'
171         print '    }'
172
173     def visit_blob(self, blob, instance):
174         print '    Trace::localWriter.writeBlob(%s, %s);' % (instance, blob.size)
175
176     def visit_enum(self, enum, instance):
177         print '    __traceEnum%s(%s);' % (enum.id, instance)
178
179     def visit_bitmask(self, bitmask, instance):
180         print '    Trace::localWriter.writeBitmask(&__bitmask%s_sig, %s);' % (bitmask.id, instance)
181
182     def visit_pointer(self, pointer, instance):
183         print '    if (%s) {' % instance
184         print '        Trace::localWriter.beginArray(1);'
185         print '        Trace::localWriter.beginElement();'
186         dump_instance(pointer.type, "*" + instance)
187         print '        Trace::localWriter.endElement();'
188         print '        Trace::localWriter.endArray();'
189         print '    } else {'
190         print '        Trace::localWriter.writeNull();'
191         print '    }'
192
193     def visit_handle(self, handle, instance):
194         self.visit(handle.type, instance)
195
196     def visit_alias(self, alias, instance):
197         self.visit(alias.type, instance)
198
199     def visit_opaque(self, opaque, instance):
200         print '    Trace::localWriter.writeOpaque((const void *)%s);' % instance
201
202     def visit_interface(self, interface, instance):
203         print '    Trace::localWriter.writeOpaque((const void *)&%s);' % instance
204
205
206 dump_instance = DumpImplementer().visit
207
208
209
210 class Wrapper(stdapi.Visitor):
211     '''Wrap an instance.'''
212
213     def visit_void(self, type, instance):
214         raise NotImplementedError
215
216     def visit_literal(self, type, instance):
217         pass
218
219     def visit_string(self, type, instance):
220         pass
221
222     def visit_const(self, type, instance):
223         pass
224
225     def visit_struct(self, struct, instance):
226         for type, name in struct.members:
227             self.visit(type, "(%s).%s" % (instance, name))
228
229     def visit_array(self, array, instance):
230         # XXX: actually it is possible to return an array of pointers
231         pass
232
233     def visit_blob(self, blob, instance):
234         pass
235
236     def visit_enum(self, enum, instance):
237         pass
238
239     def visit_bitmask(self, bitmask, instance):
240         pass
241
242     def visit_pointer(self, pointer, instance):
243         print "    if (%s) {" % instance
244         self.visit(pointer.type, "*" + instance)
245         print "    }"
246
247     def visit_handle(self, handle, instance):
248         self.visit(handle.type, instance)
249
250     def visit_alias(self, alias, instance):
251         self.visit(alias.type, instance)
252
253     def visit_opaque(self, opaque, instance):
254         pass
255     
256     def visit_interface(self, interface, instance):
257         assert instance.startswith('*')
258         instance = instance[1:]
259         print "    if (%s) {" % instance
260         print "        %s = new %s(%s);" % (instance, interface_wrap_name(interface), instance)
261         print "    }"
262
263
264 class Unwrapper(Wrapper):
265
266     def visit_interface(self, interface, instance):
267         assert instance.startswith('*')
268         instance = instance[1:]
269         print "    if (%s) {" % instance
270         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, interface_wrap_name(interface), instance)
271         print "    }"
272
273
274 wrap_instance = Wrapper().visit
275 unwrap_instance = Unwrapper().visit
276
277
278 class Tracer:
279
280     def __init__(self):
281         self.api = None
282
283     def trace_api(self, api):
284         self.api = api
285
286         self.header(api)
287
288         # Includes
289         for header in api.headers:
290             print header
291         print
292
293         # Type dumpers
294         types = api.all_types()
295         visitor = DumpDeclarator()
296         map(visitor.visit, types)
297         print
298
299         # Interfaces wrapers
300         interfaces = [type for type in types if isinstance(type, stdapi.Interface)]
301         map(self.interface_wrap_impl, interfaces)
302         print
303
304         # Function wrappers
305         map(self.trace_function_decl, api.functions)
306         map(self.trace_function_impl, api.functions)
307         print
308
309         self.footer(api)
310
311     def header(self, api):
312         pass
313
314     def footer(self, api):
315         pass
316
317     def trace_function_decl(self, function):
318         # Per-function declarations
319
320         if function.args:
321             print 'static const char * __%s_args[%u] = {%s};' % (function.name, len(function.args), ', '.join(['"%s"' % arg.name for arg in function.args]))
322         else:
323             print 'static const char ** __%s_args = NULL;' % (function.name,)
324         print 'static const Trace::FunctionSig __%s_sig = {%u, "%s", %u, __%s_args};' % (function.name, int(function.id), function.name, len(function.args), function.name)
325         print
326
327     def get_dispatch_function(self, function):
328         return '__' + function.name
329
330     def is_public_function(self, function):
331         return True
332
333     def trace_function_impl(self, function):
334         if self.is_public_function(function):
335             print 'extern "C" PUBLIC'
336         else:
337             print 'extern "C" PRIVATE'
338         print function.prototype() + ' {'
339         if function.type is not stdapi.Void:
340             print '    %s __result;' % function.type
341         self.trace_function_impl_body(function)
342         if function.type is not stdapi.Void:
343             self.wrap_ret(function, "__result")
344             print '    return __result;'
345         print '}'
346         print
347
348     def trace_function_impl_body(self, function):
349         print '    unsigned __call = Trace::localWriter.beginEnter(&__%s_sig);' % (function.name,)
350         for arg in function.args:
351             if not arg.output:
352                 self.unwrap_arg(function, arg)
353                 self.dump_arg(function, arg)
354         print '    Trace::localWriter.endEnter();'
355         self.dispatch_function(function)
356         print '    Trace::localWriter.beginLeave(__call);'
357         for arg in function.args:
358             if arg.output:
359                 self.dump_arg(function, arg)
360                 self.wrap_arg(function, arg)
361         if function.type is not stdapi.Void:
362             self.dump_ret(function, "__result")
363         print '    Trace::localWriter.endLeave();'
364
365     def dispatch_function(self, function):
366         if function.type is stdapi.Void:
367             result = ''
368         else:
369             result = '__result = '
370         dispatch = self.get_dispatch_function(function)
371         print '    %s%s(%s);' % (result, dispatch, ', '.join([str(arg.name) for arg in function.args]))
372
373     def dump_arg(self, function, arg):
374         print '    Trace::localWriter.beginArg(%u);' % (arg.index,)
375         self.dump_arg_instance(function, arg)
376         print '    Trace::localWriter.endArg();'
377
378     def dump_arg_instance(self, function, arg):
379         dump_instance(arg.type, arg.name)
380
381     def wrap_arg(self, function, arg):
382         wrap_instance(arg.type, arg.name)
383
384     def unwrap_arg(self, function, arg):
385         unwrap_instance(arg.type, arg.name)
386
387     def dump_ret(self, function, instance):
388         print '    Trace::localWriter.beginReturn();'
389         dump_instance(function.type, instance)
390         print '    Trace::localWriter.endReturn();'
391
392     def wrap_ret(self, function, instance):
393         wrap_instance(function.type, instance)
394
395     def unwrap_ret(self, function, instance):
396         unwrap_instance(function.type, instance)
397
398     def interface_wrap_impl(self, interface):
399         print '%s::%s(%s * pInstance) {' % (interface_wrap_name(interface), interface_wrap_name(interface), interface.name)
400         print '    m_pInstance = pInstance;'
401         print '}'
402         print
403         print '%s::~%s() {' % (interface_wrap_name(interface), interface_wrap_name(interface))
404         print '}'
405         print
406         for method in interface.itermethods():
407             self.trace_method(interface, method)
408         print
409
410     def trace_method(self, interface, method):
411         print method.prototype(interface_wrap_name(interface) + '::' + method.name) + ' {'
412         print '    static const char * __args[%u] = {%s};' % (len(method.args) + 1, ', '.join(['"this"'] + ['"%s"' % arg.name for arg in method.args]))
413         print '    static const Trace::FunctionSig __sig = {%u, "%s", %u, __args};' % (int(method.id), interface.name + '::' + method.name, len(method.args) + 1)
414         print '    unsigned __call = Trace::localWriter.beginEnter(&__sig);'
415         print '    Trace::localWriter.beginArg(0);'
416         print '    Trace::localWriter.writeOpaque((const void *)m_pInstance);'
417         print '    Trace::localWriter.endArg();'
418         for arg in method.args:
419             if not arg.output:
420                 self.unwrap_arg(method, arg)
421                 self.dump_arg(method, arg)
422         if method.type is stdapi.Void:
423             result = ''
424         else:
425             print '    %s __result;' % method.type
426             result = '__result = '
427         print '    Trace::localWriter.endEnter();'
428         print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(arg.name) for arg in method.args]))
429         print '    Trace::localWriter.beginLeave(__call);'
430         for arg in method.args:
431             if arg.output:
432                 self.dump_arg(method, arg)
433                 self.wrap_arg(method, arg)
434         if method.type is not stdapi.Void:
435             print '    Trace::localWriter.beginReturn();'
436             dump_instance(method.type, "__result")
437             print '    Trace::localWriter.endReturn();'
438             wrap_instance(method.type, '__result')
439         print '    Trace::localWriter.endLeave();'
440         if method.name == 'QueryInterface':
441             print '    if (ppvObj && *ppvObj) {'
442             print '        if (*ppvObj == m_pInstance) {'
443             print '            *ppvObj = this;'
444             print '        }'
445             for iface in self.api.interfaces:
446                 print '        else if (riid == IID_%s) {' % iface.name
447                 print '            *ppvObj = new Wrap%s((%s *) *ppvObj);' % (iface.name, iface.name)
448                 print '        }'
449             print '    }'
450         if method.name == 'Release':
451             assert method.type is not stdapi.Void
452             print '    if (!__result)'
453             print '        delete this;'
454         if method.type is not stdapi.Void:
455             print '    return __result;'
456         print '}'
457         print
458
459
460 class DllTracer(Tracer):
461
462     def __init__(self, dllname):
463         self.dllname = dllname
464     
465     def header(self, api):
466         print '''
467 static HINSTANCE g_hDll = NULL;
468
469 static PROC
470 __getPublicProcAddress(LPCSTR lpProcName)
471 {
472     if (!g_hDll) {
473         char szDll[MAX_PATH] = {0};
474         
475         if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
476             return NULL;
477         }
478         
479         strcat(szDll, "\\\\%s");
480         
481         g_hDll = LoadLibraryA(szDll);
482         if (!g_hDll) {
483             return NULL;
484         }
485     }
486         
487     return GetProcAddress(g_hDll, lpProcName);
488 }
489
490 ''' % self.dllname
491
492         dispatcher = Dispatcher()
493         dispatcher.dispatch_api(api)
494
495         Tracer.header(self, api)
496