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