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