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