]> git.cworth.org Git - apitrace/blob - trace.py
cli: Add a new "apitrace diff" command.
[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 specs.stdapi as 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 _write__%s(const %s &value) {' % (struct.tag, 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' % (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 _write__%s(const %s value) {' % (enum.tag, 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.tag)
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.tag)
107         print '   %u, %u, __bitmask%s_flags' % (bitmask.id, len(bitmask.values), bitmask.tag)
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     def visit_polymorphic(self, polymorphic):
139         print 'static void _write__%s(int selector, const %s & value) {' % (polymorphic.tag, polymorphic.expr)
140         print '    switch (selector) {'
141         for cases, type in polymorphic.iterswitch():
142             for case in cases:
143                 print '    %s:' % case
144             dump_instance(type, 'static_cast<%s>(value)' % (type,))
145             print '        break;'
146         print '    }'
147         print '}'
148         print
149
150
151 class DumpImplementer(stdapi.Visitor):
152     '''Dump an instance.'''
153
154     def visit_literal(self, literal, instance):
155         print '    trace::localWriter.write%s(%s);' % (literal.kind, instance)
156
157     def visit_string(self, string, instance):
158         if string.length is not None:
159             print '    trace::localWriter.writeString((const char *)%s, %s);' % (instance, string.length)
160         else:
161             print '    trace::localWriter.writeString((const char *)%s);' % instance
162
163     def visit_const(self, const, instance):
164         self.visit(const.type, instance)
165
166     def visit_struct(self, struct, instance):
167         print '    _write__%s(%s);' % (struct.tag, instance)
168
169     def visit_array(self, array, instance):
170         length = '__c' + array.type.tag
171         index = '__i' + array.type.tag
172         print '    if (%s) {' % instance
173         print '        size_t %s = %s;' % (length, array.length)
174         print '        trace::localWriter.beginArray(%s);' % length
175         print '        for (size_t %s = 0; %s < %s; ++%s) {' % (index, index, length, index)
176         print '            trace::localWriter.beginElement();'
177         self.visit(array.type, '(%s)[%s]' % (instance, index))
178         print '            trace::localWriter.endElement();'
179         print '        }'
180         print '        trace::localWriter.endArray();'
181         print '    } else {'
182         print '        trace::localWriter.writeNull();'
183         print '    }'
184
185     def visit_blob(self, blob, instance):
186         print '    trace::localWriter.writeBlob(%s, %s);' % (instance, blob.size)
187
188     def visit_enum(self, enum, instance):
189         print '    _write__%s(%s);' % (enum.tag, instance)
190
191     def visit_bitmask(self, bitmask, instance):
192         print '    trace::localWriter.writeBitmask(&__bitmask%s_sig, %s);' % (bitmask.tag, instance)
193
194     def visit_pointer(self, pointer, instance):
195         print '    if (%s) {' % instance
196         print '        trace::localWriter.beginArray(1);'
197         print '        trace::localWriter.beginElement();'
198         dump_instance(pointer.type, "*" + instance)
199         print '        trace::localWriter.endElement();'
200         print '        trace::localWriter.endArray();'
201         print '    } else {'
202         print '        trace::localWriter.writeNull();'
203         print '    }'
204
205     def visit_handle(self, handle, instance):
206         self.visit(handle.type, instance)
207
208     def visit_alias(self, alias, instance):
209         self.visit(alias.type, instance)
210
211     def visit_opaque(self, opaque, instance):
212         print '    trace::localWriter.writeOpaque((const void *)%s);' % instance
213
214     def visit_interface(self, interface, instance):
215         print '    trace::localWriter.writeOpaque((const void *)&%s);' % instance
216
217     def visit_polymorphic(self, polymorphic, instance):
218         print '    _write__%s(%s, %s);' % (polymorphic.tag, polymorphic.switch_expr, instance)
219
220
221 dump_instance = DumpImplementer().visit
222
223
224
225 class Wrapper(stdapi.Visitor):
226     '''Wrap an instance.'''
227
228     def visit_void(self, type, instance):
229         raise NotImplementedError
230
231     def visit_literal(self, type, instance):
232         pass
233
234     def visit_string(self, type, instance):
235         pass
236
237     def visit_const(self, type, instance):
238         pass
239
240     def visit_struct(self, struct, instance):
241         for type, name in struct.members:
242             self.visit(type, "(%s).%s" % (instance, name))
243
244     def visit_array(self, array, instance):
245         # XXX: actually it is possible to return an array of pointers
246         pass
247
248     def visit_blob(self, blob, instance):
249         pass
250
251     def visit_enum(self, enum, instance):
252         pass
253
254     def visit_bitmask(self, bitmask, instance):
255         pass
256
257     def visit_pointer(self, pointer, instance):
258         print "    if (%s) {" % instance
259         self.visit(pointer.type, "*" + instance)
260         print "    }"
261
262     def visit_handle(self, handle, instance):
263         self.visit(handle.type, instance)
264
265     def visit_alias(self, alias, instance):
266         self.visit(alias.type, instance)
267
268     def visit_opaque(self, opaque, instance):
269         pass
270     
271     def visit_interface(self, interface, instance):
272         assert instance.startswith('*')
273         instance = instance[1:]
274         print "    if (%s) {" % instance
275         print "        %s = new %s(%s);" % (instance, interface_wrap_name(interface), instance)
276         print "    }"
277     
278     def visit_polymorphic(self, type, instance):
279         # XXX: There might be polymorphic values that need wrapping in the future
280         pass
281
282
283 class Unwrapper(Wrapper):
284
285     def visit_interface(self, interface, instance):
286         assert instance.startswith('*')
287         instance = instance[1:]
288         print "    if (%s) {" % instance
289         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, interface_wrap_name(interface), instance)
290         print "    }"
291
292
293 wrap_instance = Wrapper().visit
294 unwrap_instance = Unwrapper().visit
295
296
297 class Tracer:
298
299     def __init__(self):
300         self.api = None
301
302     def trace_api(self, api):
303         self.api = api
304
305         self.header(api)
306
307         # Includes
308         for header in api.headers:
309             print header
310         print
311
312         # Type dumpers
313         types = api.all_types()
314         visitor = DumpDeclarator()
315         map(visitor.visit, types)
316         print
317
318         # Interfaces wrapers
319         interfaces = [type for type in types if isinstance(type, stdapi.Interface)]
320         map(self.interface_wrap_impl, interfaces)
321         print
322
323         # Function wrappers
324         map(self.trace_function_decl, api.functions)
325         map(self.trace_function_impl, api.functions)
326         print
327
328         self.footer(api)
329
330     def header(self, api):
331         pass
332
333     def footer(self, api):
334         pass
335
336     def trace_function_decl(self, function):
337         # Per-function declarations
338
339         if function.args:
340             print 'static const char * __%s_args[%u] = {%s};' % (function.name, len(function.args), ', '.join(['"%s"' % arg.name for arg in function.args]))
341         else:
342             print 'static const char ** __%s_args = NULL;' % (function.name,)
343         print 'static const trace::FunctionSig __%s_sig = {%u, "%s", %u, __%s_args};' % (function.name, function.id, function.name, len(function.args), function.name)
344         print
345
346     def is_public_function(self, function):
347         return True
348
349     def trace_function_impl(self, function):
350         if self.is_public_function(function):
351             print 'extern "C" PUBLIC'
352         else:
353             print 'extern "C" PRIVATE'
354         print function.prototype() + ' {'
355         if function.type is not stdapi.Void:
356             print '    %s __result;' % function.type
357         self.trace_function_impl_body(function)
358         if function.type is not stdapi.Void:
359             self.wrap_ret(function, "__result")
360             print '    return __result;'
361         print '}'
362         print
363
364     def trace_function_impl_body(self, function):
365         print '    unsigned __call = trace::localWriter.beginEnter(&__%s_sig);' % (function.name,)
366         for arg in function.args:
367             if not arg.output:
368                 self.unwrap_arg(function, arg)
369                 self.dump_arg(function, arg)
370         print '    trace::localWriter.endEnter();'
371         self.dispatch_function(function)
372         print '    trace::localWriter.beginLeave(__call);'
373         for arg in function.args:
374             if arg.output:
375                 self.dump_arg(function, arg)
376                 self.wrap_arg(function, arg)
377         if function.type is not stdapi.Void:
378             self.dump_ret(function, "__result")
379         print '    trace::localWriter.endLeave();'
380
381     def dispatch_function(self, function, prefix='__', suffix=''):
382         if function.type is stdapi.Void:
383             result = ''
384         else:
385             result = '__result = '
386         dispatch = prefix + function.name + suffix
387         print '    %s%s(%s);' % (result, dispatch, ', '.join([str(arg.name) for arg in function.args]))
388
389     def dump_arg(self, function, arg):
390         print '    trace::localWriter.beginArg(%u);' % (arg.index,)
391         self.dump_arg_instance(function, arg)
392         print '    trace::localWriter.endArg();'
393
394     def dump_arg_instance(self, function, arg):
395         dump_instance(arg.type, arg.name)
396
397     def wrap_arg(self, function, arg):
398         wrap_instance(arg.type, arg.name)
399
400     def unwrap_arg(self, function, arg):
401         unwrap_instance(arg.type, arg.name)
402
403     def dump_ret(self, function, instance):
404         print '    trace::localWriter.beginReturn();'
405         dump_instance(function.type, instance)
406         print '    trace::localWriter.endReturn();'
407
408     def wrap_ret(self, function, instance):
409         wrap_instance(function.type, instance)
410
411     def unwrap_ret(self, function, instance):
412         unwrap_instance(function.type, instance)
413
414     def interface_wrap_impl(self, interface):
415         print '%s::%s(%s * pInstance) {' % (interface_wrap_name(interface), interface_wrap_name(interface), interface.name)
416         print '    m_pInstance = pInstance;'
417         print '}'
418         print
419         print '%s::~%s() {' % (interface_wrap_name(interface), interface_wrap_name(interface))
420         print '}'
421         print
422         for method in interface.itermethods():
423             self.trace_method(interface, method)
424         print
425
426     def trace_method(self, interface, method):
427         print method.prototype(interface_wrap_name(interface) + '::' + method.name) + ' {'
428         print '    static const char * __args[%u] = {%s};' % (len(method.args) + 1, ', '.join(['"this"'] + ['"%s"' % arg.name for arg in method.args]))
429         print '    static const trace::FunctionSig __sig = {%u, "%s", %u, __args};' % (method.id, interface.name + '::' + method.name, len(method.args) + 1)
430         print '    unsigned __call = trace::localWriter.beginEnter(&__sig);'
431         print '    trace::localWriter.beginArg(0);'
432         print '    trace::localWriter.writeOpaque((const void *)m_pInstance);'
433         print '    trace::localWriter.endArg();'
434         for arg in method.args:
435             if not arg.output:
436                 self.unwrap_arg(method, arg)
437                 self.dump_arg(method, arg)
438         if method.type is stdapi.Void:
439             result = ''
440         else:
441             print '    %s __result;' % method.type
442             result = '__result = '
443         print '    trace::localWriter.endEnter();'
444         print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(arg.name) for arg in method.args]))
445         print '    trace::localWriter.beginLeave(__call);'
446         for arg in method.args:
447             if arg.output:
448                 self.dump_arg(method, arg)
449                 self.wrap_arg(method, arg)
450         if method.type is not stdapi.Void:
451             print '    trace::localWriter.beginReturn();'
452             dump_instance(method.type, "__result")
453             print '    trace::localWriter.endReturn();'
454             wrap_instance(method.type, '__result')
455         print '    trace::localWriter.endLeave();'
456         if method.name == 'QueryInterface':
457             print '    if (ppvObj && *ppvObj) {'
458             print '        if (*ppvObj == m_pInstance) {'
459             print '            *ppvObj = this;'
460             print '        }'
461             for iface in self.api.interfaces:
462                 print '        else if (riid == IID_%s) {' % iface.name
463                 print '            *ppvObj = new Wrap%s((%s *) *ppvObj);' % (iface.name, iface.name)
464                 print '        }'
465             print '    }'
466         if method.name == 'Release':
467             assert method.type is not stdapi.Void
468             print '    if (!__result)'
469             print '        delete this;'
470         if method.type is not stdapi.Void:
471             print '    return __result;'
472         print '}'
473         print
474
475
476 class DllTracer(Tracer):
477
478     def __init__(self, dllname):
479         self.dllname = dllname
480     
481     def header(self, api):
482         print '''
483 static HINSTANCE g_hDll = NULL;
484
485 static PROC
486 __getPublicProcAddress(LPCSTR lpProcName)
487 {
488     if (!g_hDll) {
489         char szDll[MAX_PATH] = {0};
490         
491         if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
492             return NULL;
493         }
494         
495         strcat(szDll, "\\\\%s");
496         
497         g_hDll = LoadLibraryA(szDll);
498         if (!g_hDll) {
499             return NULL;
500         }
501     }
502         
503     return GetProcAddress(g_hDll, lpProcName);
504 }
505
506 ''' % self.dllname
507
508         dispatcher = Dispatcher()
509         dispatcher.dispatch_api(api)
510
511         Tracer.header(self, api)
512