]> git.cworth.org Git - apitrace/blob - trace.py
More D2D spec tweaks.
[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
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 is_public_function(self, function):
328         return True
329
330     def trace_function_impl(self, function):
331         if self.is_public_function(function):
332             print 'extern "C" PUBLIC'
333         else:
334             print 'extern "C" PRIVATE'
335         print function.prototype() + ' {'
336         if function.type is not stdapi.Void:
337             print '    %s __result;' % function.type
338         self.trace_function_impl_body(function)
339         if function.type is not stdapi.Void:
340             self.wrap_ret(function, "__result")
341             print '    return __result;'
342         print '}'
343         print
344
345     def trace_function_impl_body(self, function):
346         print '    unsigned __call = Trace::localWriter.beginEnter(&__%s_sig);' % (function.name,)
347         for arg in function.args:
348             if not arg.output:
349                 self.unwrap_arg(function, arg)
350                 self.dump_arg(function, arg)
351         print '    Trace::localWriter.endEnter();'
352         self.dispatch_function(function)
353         print '    Trace::localWriter.beginLeave(__call);'
354         for arg in function.args:
355             if arg.output:
356                 self.dump_arg(function, arg)
357                 self.wrap_arg(function, arg)
358         if function.type is not stdapi.Void:
359             self.dump_ret(function, "__result")
360         print '    Trace::localWriter.endLeave();'
361
362     def dispatch_function(self, function, prefix='__', suffix=''):
363         if function.type is stdapi.Void:
364             result = ''
365         else:
366             result = '__result = '
367         dispatch = prefix + function.name + suffix
368         print '    %s%s(%s);' % (result, dispatch, ', '.join([str(arg.name) for arg in function.args]))
369
370     def dump_arg(self, function, arg):
371         print '    Trace::localWriter.beginArg(%u);' % (arg.index,)
372         self.dump_arg_instance(function, arg)
373         print '    Trace::localWriter.endArg();'
374
375     def dump_arg_instance(self, function, arg):
376         dump_instance(arg.type, arg.name)
377
378     def wrap_arg(self, function, arg):
379         wrap_instance(arg.type, arg.name)
380
381     def unwrap_arg(self, function, arg):
382         unwrap_instance(arg.type, arg.name)
383
384     def dump_ret(self, function, instance):
385         print '    Trace::localWriter.beginReturn();'
386         dump_instance(function.type, instance)
387         print '    Trace::localWriter.endReturn();'
388
389     def wrap_ret(self, function, instance):
390         wrap_instance(function.type, instance)
391
392     def unwrap_ret(self, function, instance):
393         unwrap_instance(function.type, instance)
394
395     def interface_wrap_impl(self, interface):
396         print '%s::%s(%s * pInstance) {' % (interface_wrap_name(interface), interface_wrap_name(interface), interface.name)
397         print '    m_pInstance = pInstance;'
398         print '}'
399         print
400         print '%s::~%s() {' % (interface_wrap_name(interface), interface_wrap_name(interface))
401         print '}'
402         print
403         for base, method in interface.itermethods2():
404             self.trace_method(interface, base, method)
405         print
406
407     def trace_method(self, interface, base, method):
408         print method.prototype(interface_wrap_name(interface) + '::' + method.name) + ' {'
409         print '    static const char * __args[%u] = {%s};' % (len(method.args) + 1, ', '.join(['"this"'] + ['"%s"' % arg.name for arg in method.args]))
410         print '    static const Trace::FunctionSig __sig = {%u, "%s", %u, __args};' % (int(method.id), interface.name + '::' + method.name, len(method.args) + 1)
411         print '    unsigned __call = Trace::localWriter.beginEnter(&__sig);'
412         print '    Trace::localWriter.beginArg(0);'
413         print '    Trace::localWriter.writeOpaque((const void *)m_pInstance);'
414         print '    Trace::localWriter.endArg();'
415         for arg in method.args:
416             if not arg.output:
417                 self.unwrap_arg(method, arg)
418                 self.dump_arg(method, arg)
419         if method.type is stdapi.Void:
420             result = ''
421         else:
422             print '    %s __result;' % method.type
423             result = '__result = '
424         print '    Trace::localWriter.endEnter();'
425         print '    %sstatic_cast<%s *>(m_pInstance)->%s(%s);' % (result, base, method.name, ', '.join([str(arg.name) for arg in method.args]))
426         print '    Trace::localWriter.beginLeave(__call);'
427         for arg in method.args:
428             if arg.output:
429                 self.dump_arg(method, arg)
430                 self.wrap_arg(method, arg)
431         if method.type is not stdapi.Void:
432             print '    Trace::localWriter.beginReturn();'
433             dump_instance(method.type, "__result")
434             print '    Trace::localWriter.endReturn();'
435             wrap_instance(method.type, '__result')
436         print '    Trace::localWriter.endLeave();'
437         if method.name == 'QueryInterface':
438             print '    if (ppvObj && *ppvObj) {'
439             print '        if (*ppvObj == m_pInstance) {'
440             print '            *ppvObj = this;'
441             print '        }'
442             for iface in self.api.interfaces:
443                 print '        else if (riid == IID_%s) {' % iface.name
444                 print '            *ppvObj = new Wrap%s((%s *) *ppvObj);' % (iface.name, iface.name)
445                 print '        }'
446             print '    }'
447         if method.name == 'Release':
448             assert method.type is not stdapi.Void
449             print '    if (!__result)'
450             print '        delete this;'
451         if method.type is not stdapi.Void:
452             print '    return __result;'
453         print '}'
454         print
455
456
457 class DllTracer(Tracer):
458
459     def __init__(self, dllname):
460         self.dllname = dllname
461     
462     def header(self, api):
463         print '''
464 static HINSTANCE g_hDll = NULL;
465
466 static PROC
467 __getPublicProcAddress(LPCSTR lpProcName)
468 {
469     if (!g_hDll) {
470         char szDll[MAX_PATH] = {0};
471         
472         if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
473             return NULL;
474         }
475         
476         strcat(szDll, "\\\\%s");
477         
478         g_hDll = LoadLibraryA(szDll);
479         if (!g_hDll) {
480             return NULL;
481         }
482     }
483         
484     return GetProcAddress(g_hDll, lpProcName);
485 }
486
487 ''' % self.dllname
488
489         dispatcher = Dispatcher()
490         dispatcher.dispatch_api(api)
491
492         Tracer.header(self, api)
493