]> git.cworth.org Git - apitrace/blob - trace.py
Add support for GL_APPLE_flush_render
[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 '    __writer.beginStruct(&sig);'
64         for type, name in struct.members:
65             dump_instance(type, 'value.%s' % (name,))
66         print '    __writer.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 '        __writer.writeSInt(value);'
94         print '        return;'
95         print '    }'
96         print '    __writer.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 '    __writer.write%s(%s);' % (literal.format, instance)
144
145     def visit_string(self, string, instance):
146         if string.length is not None:
147             print '    __writer.writeString((const char *)%s, %s);' % (instance, string.length)
148         else:
149             print '    __writer.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 '        __writer.beginArray(%s);' % length
163         print '        for (size_t %s = 0; %s < %s; ++%s) {' % (index, index, length, index)
164         print '            __writer.beginElement();'
165         self.visit(array.type, '(%s)[%s]' % (instance, index))
166         print '            __writer.endElement();'
167         print '        }'
168         print '        __writer.endArray();'
169         print '    } else {'
170         print '        __writer.writeNull();'
171         print '    }'
172
173     def visit_blob(self, blob, instance):
174         print '    __writer.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 '    __writer.writeBitmask(&__bitmask%s_sig, %s);' % (bitmask.id, instance)
181
182     def visit_pointer(self, pointer, instance):
183         print '    if (%s) {' % instance
184         print '        __writer.beginArray(1);'
185         print '        __writer.beginElement();'
186         dump_instance(pointer.type, "*" + instance)
187         print '        __writer.endElement();'
188         print '        __writer.endArray();'
189         print '    } else {'
190         print '        __writer.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 '    __writer.writeOpaque((const void *)%s);' % instance
201
202     def visit_interface(self, interface, instance):
203         print '    __writer.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         print 'Trace::Writer __writer;'
313         print
314
315     def footer(self, api):
316         pass
317
318     def trace_function_decl(self, function):
319         # Per-function declarations
320
321         if function.args:
322             print 'static const char * __%s_args[%u] = {%s};' % (function.name, len(function.args), ', '.join(['"%s"' % arg.name for arg in function.args]))
323         else:
324             print 'static const char ** __%s_args = NULL;' % (function.name,)
325         print 'static const Trace::FunctionSig __%s_sig = {%u, "%s", %u, __%s_args};' % (function.name, int(function.id), function.name, len(function.args), function.name)
326         print
327
328     def get_dispatch_function(self, function):
329         return '__' + function.name
330
331     def is_public_function(self, function):
332         return True
333
334     def trace_function_impl(self, function):
335         if self.is_public_function(function):
336             print 'extern "C" PUBLIC'
337         else:
338             print 'extern "C" PRIVATE'
339         print function.prototype() + ' {'
340         if function.type is not stdapi.Void:
341             print '    %s __result;' % function.type
342         self.trace_function_impl_body(function)
343         if function.type is not stdapi.Void:
344             self.wrap_ret(function, "__result")
345             print '    return __result;'
346         print '}'
347         print
348
349     def trace_function_impl_body(self, function):
350         print '    unsigned __call = __writer.beginEnter(&__%s_sig);' % (function.name,)
351         for arg in function.args:
352             if not arg.output:
353                 self.unwrap_arg(function, arg)
354                 self.dump_arg(function, arg)
355         print '    __writer.endEnter();'
356         self.dispatch_function(function)
357         print '    __writer.beginLeave(__call);'
358         for arg in function.args:
359             if arg.output:
360                 self.dump_arg(function, arg)
361                 self.wrap_arg(function, arg)
362         if function.type is not stdapi.Void:
363             self.dump_ret(function, "__result")
364         print '    __writer.endLeave();'
365
366     def dispatch_function(self, function):
367         if function.type is stdapi.Void:
368             result = ''
369         else:
370             result = '__result = '
371         dispatch = self.get_dispatch_function(function)
372         print '    %s%s(%s);' % (result, dispatch, ', '.join([str(arg.name) for arg in function.args]))
373
374     def dump_arg(self, function, arg):
375         print '    __writer.beginArg(%u);' % (arg.index,)
376         self.dump_arg_instance(function, arg)
377         print '    __writer.endArg();'
378
379     def dump_arg_instance(self, function, arg):
380         dump_instance(arg.type, arg.name)
381
382     def wrap_arg(self, function, arg):
383         wrap_instance(arg.type, arg.name)
384
385     def unwrap_arg(self, function, arg):
386         unwrap_instance(arg.type, arg.name)
387
388     def dump_ret(self, function, instance):
389         print '    __writer.beginReturn();'
390         dump_instance(function.type, instance)
391         print '    __writer.endReturn();'
392
393     def wrap_ret(self, function, instance):
394         wrap_instance(function.type, instance)
395
396     def unwrap_ret(self, function, instance):
397         unwrap_instance(function.type, instance)
398
399     def interface_wrap_impl(self, interface):
400         print '%s::%s(%s * pInstance) {' % (interface_wrap_name(interface), interface_wrap_name(interface), interface.name)
401         print '    m_pInstance = pInstance;'
402         print '}'
403         print
404         print '%s::~%s() {' % (interface_wrap_name(interface), interface_wrap_name(interface))
405         print '}'
406         print
407         for method in interface.itermethods():
408             self.trace_method(interface, method)
409         print
410
411     def trace_method(self, interface, method):
412         print method.prototype(interface_wrap_name(interface) + '::' + method.name) + ' {'
413         print '    static const char * __args[%u] = {%s};' % (len(method.args) + 1, ', '.join(['"this"'] + ['"%s"' % arg.name for arg in method.args]))
414         print '    static const Trace::FunctionSig __sig = {%u, "%s", %u, __args};' % (int(method.id), interface.name + '::' + method.name, len(method.args) + 1)
415         print '    unsigned __call = __writer.beginEnter(&__sig);'
416         print '    __writer.beginArg(0);'
417         print '    __writer.writeOpaque((const void *)m_pInstance);'
418         print '    __writer.endArg();'
419         for arg in method.args:
420             if not arg.output:
421                 self.unwrap_arg(method, arg)
422                 self.dump_arg(method, arg)
423         if method.type is stdapi.Void:
424             result = ''
425         else:
426             print '    %s __result;' % method.type
427             result = '__result = '
428         print '    __writer.endEnter();'
429         print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(arg.name) for arg in method.args]))
430         print '    __writer.beginLeave(__call);'
431         for arg in method.args:
432             if arg.output:
433                 self.dump_arg(method, arg)
434                 self.wrap_arg(method, arg)
435         if method.type is not stdapi.Void:
436             print '    __writer.beginReturn();'
437             dump_instance(method.type, "__result")
438             print '    __writer.endReturn();'
439             wrap_instance(method.type, '__result')
440         print '    __writer.endLeave();'
441         if method.name == 'QueryInterface':
442             print '    if (ppvObj && *ppvObj) {'
443             print '        if (*ppvObj == m_pInstance) {'
444             print '            *ppvObj = this;'
445             print '        }'
446             for iface in self.api.interfaces:
447                 print '        else if (riid == IID_%s) {' % iface.name
448                 print '            *ppvObj = new Wrap%s((%s *) *ppvObj);' % (iface.name, iface.name)
449                 print '        }'
450             print '    }'
451         if method.name == 'Release':
452             assert method.type is not stdapi.Void
453             print '    if (!__result)'
454             print '        delete this;'
455         if method.type is not stdapi.Void:
456             print '    return __result;'
457         print '}'
458         print
459
460
461 class DllTracer(Tracer):
462
463     def __init__(self, dllname):
464         self.dllname = dllname
465     
466     def header(self, api):
467         print '''
468 static HINSTANCE g_hDll = NULL;
469
470 static PROC
471 __getPublicProcAddress(LPCSTR lpProcName)
472 {
473     if (!g_hDll) {
474         char szDll[MAX_PATH] = {0};
475         
476         if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
477             return NULL;
478         }
479         
480         strcat(szDll, "\\\\%s");
481         
482         g_hDll = LoadLibraryA(szDll);
483         if (!g_hDll) {
484             return NULL;
485         }
486     }
487         
488     return GetProcAddress(g_hDll, lpProcName);
489 }
490
491 ''' % self.dllname
492
493         dispatcher = Dispatcher()
494         dispatcher.dispatch_api(api)
495
496         Tracer.header(self, api)
497