]> git.cworth.org Git - apitrace/blob - trace.py
Use the process ID as process name when /proc/self/exe can't be read.
[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 '    Trace::BeginStruct(&sig);'
64         for type, name in struct.members:
65             dump_instance(type, 'value.%s' % (name,))
66         print '    Trace::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::LiteralSInt(value);'
94         print '        return;'
95         print '    }'
96         print '    Trace::LiteralEnum(sig);'
97         print '}'
98         print
99
100     def visit_bitmask(self, bitmask):
101         print 'static const Trace::BitmaskVal __bitmask%s_vals[] = {' % (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_vals' % (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::Literal%s(%s);' % (literal.format, instance)
144
145     def visit_string(self, string, instance):
146         if string.length is not None:
147             print '    Trace::LiteralString((const char *)%s, %s);' % (instance, string.length)
148         else:
149             print '    Trace::LiteralString((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 '        Trace::BeginArray(%s);' % (array.length,)
161         print '        for (int %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
162         print '            Trace::BeginElement();'
163         self.visit(array.type, '(%s)[%s]' % (instance, index))
164         print '            Trace::EndElement();'
165         print '        }'
166         print '        Trace::EndArray();'
167         print '    }'
168         print '    else'
169         print '        Trace::LiteralNull();'
170
171     def visit_blob(self, blob, instance):
172         print '    Trace::LiteralBlob(%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 '    Trace::LiteralBitmask(__bitmask%s_sig, %s);' % (bitmask.id, instance)
179
180     def visit_pointer(self, pointer, instance):
181         print '    if (%s) {' % instance
182         print '        Trace::BeginArray(1);'
183         print '        Trace::BeginElement();'
184         dump_instance(pointer.type, "*" + instance)
185         print '        Trace::EndElement();'
186         print '        Trace::EndArray();'
187         print '    }'
188         print '    else'
189         print '        Trace::LiteralNull();'
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 '    Trace::LiteralOpaque((const void *)%s);' % instance
199
200     def visit_interface(self, interface, instance):
201         print '    Trace::LiteralOpaque((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         self.visit(pointer.type, "*" + instance)
242
243     def visit_handle(self, handle, instance):
244         self.visit(handle.type, instance)
245
246     def visit_alias(self, alias, instance):
247         self.visit(alias.type, instance)
248
249     def visit_opaque(self, opaque, instance):
250         pass
251     
252     def visit_interface(self, interface, instance):
253         assert instance.startswith('*')
254         instance = instance[1:]
255         print "    if (%s)" % instance
256         print "        %s = new %s(%s);" % (instance, interface_wrap_name(interface), instance)
257
258
259 class Unwrapper(Wrapper):
260
261     def visit_interface(self, interface, instance):
262         assert instance.startswith('*')
263         instance = instance[1:]
264         print "    if (%s)" % instance
265         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, interface_wrap_name(interface), instance)
266
267
268 wrap_instance = Wrapper().visit
269 unwrap_instance = Unwrapper().visit
270
271
272 class Tracer:
273
274     def trace_api(self, api):
275         self.header(api)
276
277         # Includes
278         for header in api.headers:
279             print header
280         print
281
282         # Type dumpers
283         types = api.all_types()
284         visitor = DumpDeclarator()
285         map(visitor.visit, types)
286         print
287
288         # Interfaces wrapers
289         interfaces = [type for type in types if isinstance(type, stdapi.Interface)]
290         map(self.interface_wrap_impl, interfaces)
291         print
292
293         # Function wrappers
294         map(self.trace_function_decl, api.functions)
295         map(self.trace_function_impl, api.functions)
296         print
297
298         self.footer(api)
299
300     def header(self, api):
301         pass
302
303     def footer(self, api):
304         pass
305
306     def trace_function_decl(self, function):
307         # Per-function declarations
308
309         if function.args:
310             print 'static const char * __%s_args[%u] = {%s};' % (function.name, len(function.args), ', '.join(['"%s"' % arg.name for arg in function.args]))
311         else:
312             print 'static const char ** __%s_args = NULL;' % (function.name,)
313         print 'static const Trace::FunctionSig __%s_sig = {%u, "%s", %u, __%s_args};' % (function.name, int(function.id), function.name, len(function.args), function.name)
314         print
315
316     def get_dispatch_function(self, function):
317         return '__' + function.name
318
319     def is_public_function(self, function):
320         return True
321
322     def trace_function_impl(self, function):
323         if self.is_public_function(function):
324             print 'extern "C" PUBLIC'
325         else:
326             print 'extern "C" PRIVATE'
327         print function.prototype() + ' {'
328         if function.type is not stdapi.Void:
329             print '    %s __result;' % function.type
330         self.trace_function_impl_body(function)
331         if function.type is not stdapi.Void:
332             self.wrap_ret(function, "__result")
333             print '    return __result;'
334         print '}'
335         print
336
337     def trace_function_impl_body(self, function):
338         print '    unsigned __call = Trace::BeginEnter(__%s_sig);' % (function.name,)
339         for arg in function.args:
340             if not arg.output:
341                 self.unwrap_arg(function, arg)
342                 self.dump_arg(function, arg)
343         print '    Trace::EndEnter();'
344         self.dispatch_function(function)
345         print '    Trace::BeginLeave(__call);'
346         for arg in function.args:
347             if arg.output:
348                 self.dump_arg(function, arg)
349                 self.wrap_arg(function, arg)
350         if function.type is not stdapi.Void:
351             self.dump_ret(function, "__result")
352         print '    Trace::EndLeave();'
353
354     def dispatch_function(self, function):
355         if function.type is stdapi.Void:
356             result = ''
357         else:
358             result = '__result = '
359         dispatch = self.get_dispatch_function(function)
360         print '    %s%s(%s);' % (result, dispatch, ', '.join([str(arg.name) for arg in function.args]))
361
362     def dump_arg(self, function, arg):
363         print '    Trace::BeginArg(%u);' % (arg.index,)
364         self.dump_arg_instance(function, arg)
365         print '    Trace::EndArg();'
366
367     def dump_arg_instance(self, function, arg):
368         dump_instance(arg.type, arg.name)
369
370     def wrap_arg(self, function, arg):
371         wrap_instance(arg.type, arg.name)
372
373     def unwrap_arg(self, function, arg):
374         unwrap_instance(arg.type, arg.name)
375
376     def dump_ret(self, function, instance):
377         print '    Trace::BeginReturn();'
378         dump_instance(function.type, instance)
379         print '    Trace::EndReturn();'
380
381     def wrap_ret(self, function, instance):
382         wrap_instance(function.type, instance)
383
384     def unwrap_ret(self, function, instance):
385         unwrap_instance(function.type, instance)
386
387     def interface_wrap_impl(self, interface):
388         print '%s::%s(%s * pInstance) {' % (interface_wrap_name(interface), interface_wrap_name(interface), interface.name)
389         print '    m_pInstance = pInstance;'
390         print '}'
391         print
392         print '%s::~%s() {' % (interface_wrap_name(interface), interface_wrap_name(interface))
393         print '}'
394         print
395         for method in interface.itermethods():
396             self.trace_method(interface, method)
397         print
398
399     def trace_method(self, interface, method):
400         print method.prototype(interface_wrap_name(interface) + '::' + method.name) + ' {'
401         print '    static const char * __args[%u] = {%s};' % (len(method.args) + 1, ', '.join(['"this"'] + ['"%s"' % arg.name for arg in method.args]))
402         print '    static const Trace::FunctionSig __sig = {%u, "%s", %u, __args};' % (int(method.id), interface.name + '::' + method.name, len(method.args) + 1)
403         print '    unsigned __call = Trace::BeginEnter(__sig);'
404         print '    Trace::BeginArg(0);'
405         print '    Trace::LiteralOpaque((const void *)m_pInstance);'
406         print '    Trace::EndArg();'
407         for arg in method.args:
408             if not arg.output:
409                 self.unwrap_arg(method, arg)
410                 self.dump_arg(method, arg)
411         if method.type is stdapi.Void:
412             result = ''
413         else:
414             print '    %s __result;' % method.type
415             result = '__result = '
416         print '    Trace::EndEnter();'
417         print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(arg.name) for arg in method.args]))
418         print '    Trace::BeginLeave(__call);'
419         for arg in method.args:
420             if arg.output:
421                 self.dump_arg(method, arg)
422                 self.wrap_arg(method, arg)
423         if method.type is not stdapi.Void:
424             print '    Trace::BeginReturn();'
425             dump_instance(method.type, "__result")
426             print '    Trace::EndReturn();'
427             wrap_instance(method.type, '__result')
428         print '    Trace::EndLeave();'
429         if method.name == 'QueryInterface':
430             print '    if (*ppvObj == m_pInstance)'
431             print '        *ppvObj = this;'
432         if method.name == 'Release':
433             assert method.type is not stdapi.Void
434             print '    if (!__result)'
435             print '        delete this;'
436         if method.type is not stdapi.Void:
437             print '    return __result;'
438         print '}'
439         print
440
441
442 class DllTracer(Tracer):
443
444     def __init__(self, dllname):
445         self.dllname = dllname
446     
447     def header(self, api):
448         print '''
449 static HINSTANCE g_hDll = NULL;
450
451 static PROC
452 __getPublicProcAddress(LPCSTR lpProcName)
453 {
454     if (!g_hDll) {
455         char szDll[MAX_PATH] = {0};
456         
457         if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
458             return NULL;
459         }
460         
461         strcat(szDll, "\\\\%s");
462         
463         g_hDll = LoadLibraryA(szDll);
464         if (!g_hDll) {
465             return NULL;
466         }
467     }
468         
469     return GetProcAddress(g_hDll, lpProcName);
470 }
471
472 #define __abort() OS::Abort()
473 ''' % self.dllname
474
475         dispatcher = Dispatcher()
476         dispatcher.dispatch_api(api)
477
478         Tracer.header(self, api)
479