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