]> git.cworth.org Git - apitrace/blob - base.py
Basic Linux/GLX tracing support.
[apitrace] / base.py
1 ##########################################################################
2 #
3 # Copyright 2008-2009 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 """C basic types"""
27
28
29 import debug
30
31
32 all_types = {}
33
34 class Type:
35
36     __seq = 0
37
38     def __init__(self, expr, id = ''):
39         self.expr = expr
40         
41         for char in id:
42             assert char.isalnum() or char in '_ '
43
44         id = id.replace(' ', '_')
45         
46         if id in all_types:
47             Type.__seq += 1
48             id += str(Type.__seq)
49         
50         assert id not in all_types
51         all_types[id] = self
52
53         self.id = id
54
55     def __str__(self):
56         return self.expr
57
58     def isoutput(self):
59         return False
60
61     def decl(self):
62         pass
63
64     def impl(self):
65         pass
66
67     def dump(self, instance):
68         raise NotImplementedError
69     
70     def wrap_instance(self, instance):
71         pass 
72
73     def unwrap_instance(self, instance):
74         pass
75
76
77 class _Void(Type):
78
79     def __init__(self):
80         Type.__init__(self, "void")
81
82 Void = _Void()
83
84
85 class Concrete(Type):
86
87     def decl(self):
88         print 'static void Dump%s(const %s &value);' % (self.id, self.expr)
89     
90     def impl(self):
91         print 'static void Dump%s(const %s &value) {' % (self.id, self.expr)
92         self._dump("value");
93         print '}'
94         print
95     
96     def _dump(self, instance):
97         raise NotImplementedError
98     
99     def dump(self, instance):
100         print '    Dump%s(%s);' % (self.id, instance)
101     
102
103 class Intrinsic(Concrete):
104
105     def __init__(self, expr, format):
106         Concrete.__init__(self, expr)
107         self.format = format
108
109     def _dump(self, instance):
110         print '    Log::TextF("%s", %s);' % (self.format, instance)
111
112
113 class Const(Type):
114
115     def __init__(self, type):
116
117         if isinstance(type, Pointer):
118             expr = type.expr + " const"
119         else:
120             expr = "const " + type.expr
121
122         Type.__init__(self, expr, 'C' + type.id)
123
124         self.type = type
125
126     def dump(self, instance):
127         self.type.dump(instance)
128
129
130 class Pointer(Type):
131
132     def __init__(self, type):
133         Type.__init__(self, type.expr + " *", 'P' + type.id)
134         self.type = type
135
136     def dump(self, instance):
137         print '    if(%s) {' % instance
138         print '        Log::BeginReference("%s", %s);' % (self.type, instance)
139         try:
140             self.type.dump("*" + instance)
141         except NotImplementedError:
142             pass
143         print '        Log::EndReference();'
144         print '    }'
145         print '    else'
146         print '        Log::Text("NULL");'
147
148     def wrap_instance(self, instance):
149         self.type.wrap_instance("*" + instance)
150
151     def unwrap_instance(self, instance):
152         self.type.wrap_instance("*" + instance)
153
154
155 def ConstPointer(type):
156     return Pointer(Const(type))
157
158
159 class OutPointer(Pointer):
160
161     def isoutput(self):
162         return True
163
164
165 class Enum(Concrete):
166
167     def __init__(self, name, values):
168         Concrete.__init__(self, name)
169         self.values = values
170     
171     def _dump(self, instance):
172         print '    switch(%s) {' % instance
173         for value in self.values:
174             print '    case %s:' % value
175             print '        Log::Text("%s");' % value
176             print '        break;'
177         print '    default:'
178         print '        Log::TextF("%%i", %s);' % instance
179         print '        break;'
180         print '    }'
181
182
183 class FakeEnum(Enum):
184
185     def __init__(self, type, values):
186         Enum.__init__(self, type.expr, values)
187         self.type = type
188
189
190 class Flags(Concrete):
191
192     def __init__(self, type, values):
193         Concrete.__init__(self, type.expr)
194         self.type = type
195         self.values = values
196
197     def _dump(self, instance):
198         print '    bool l_First = true;'
199         print '    %s l_Value = %s;' % (self.type, instance)
200         for value in self.values:
201             print '    if((l_Value & %s) == %s) {' % (value, value)
202             print '        if(!l_First)'
203             print '            Log::Text(" | ");'
204             print '        Log::Text("%s");' % value
205             print '        l_Value &= ~%s;' % value
206             print '        l_First = false;'
207             print '    }'
208         print '    if(l_Value || l_First) {'
209         print '        if(!l_First)'
210         print '            Log::Text(" | ");'
211         self.type.dump("l_Value");
212         print '    }'
213
214
215 class Array(Type):
216
217     def __init__(self, type, length):
218         Type.__init__(self, type.expr + " *", 'P' + type.id)
219         self.type = type
220         self.length = length
221
222     def dump(self, instance):
223         index = '__i' + self.type.id
224         print '    for (int %s = 0; %s < %s; ++%s) {' % (index, index, self.length, index)
225         print '        Log::BeginElement("%s");' % (self.type,)
226         self.type.dump('(%s)[%s]' % (instance, index))
227         print '        Log::EndElement();'
228         print '    }'
229
230     def wrap_instance(self, instance):
231         self.type.wrap_instance("*" + instance)
232
233     def unwrap_instance(self, instance):
234         self.type.wrap_instance("*" + instance)
235
236
237 class OutArray(Array):
238
239     def isoutput(self):
240         return True
241
242
243 class Struct(Concrete):
244
245     def __init__(self, name, members):
246         Concrete.__init__(self, name)
247         self.members = members
248
249     def _dump(self, instance):
250         for type, name in self.members:
251             print '    Log::BeginElement("%s", "%s");' % (type, name)
252             type.dump('(%s).%s' % (instance, name))
253             print '    Log::EndElement();'
254
255
256 class Alias(Type):
257
258     def __init__(self, name, type):
259         Type.__init__(self, name)
260         self.type = type
261
262     def dump(self, instance):
263         self.type.dump(instance)
264
265
266 class Out(Type):
267
268     def __init__(self, type):
269         Type.__init__(self, type.expr)
270         self.type = type
271
272     def isoutput(self):
273         return True
274
275     def decl(self):
276         self.type.decl()
277
278     def impl(self):
279         self.type.impl()
280
281     def dump(self, instance):
282         self.type.dump(instance)
283     
284     def wrap_instance(self, instance):
285         self.type.wrap_instance(instance)
286
287     def unwrap_instance(self, instance):
288         self.type.unwrap_instance(instance)
289
290
291 class Function:
292
293     def __init__(self, type, name, args, call = '__stdcall', fail = None):
294         self.type = type
295         self.name = name
296         self.args = args
297         self.call = call
298         self.fail = fail
299
300     def prototype(self, name=None):
301         if name is not None:
302             name = name.strip()
303         else:
304             name = self.name
305         s = name
306         if self.call:
307             s = self.call + ' ' + s
308         if name.startswith('*'):
309             s = '(' + s + ')'
310         s = self.type.expr + ' ' + s
311         s += "("
312         if self.args:
313             s += ", ".join(["%s %s" % (type, name) for type, name in self.args])
314         else:
315             s += "void"
316         s += ")"
317         return s
318
319     def pointer_type(self):
320         return 'P' + self.name
321
322     def pointer_value(self):
323         return 'p' + self.name
324
325     def wrap_decl(self):
326         ptype = self.pointer_type()
327         pvalue = self.pointer_value()
328         print 'typedef ' + self.prototype('* %s' % ptype) + ';'
329         print 'static %s %s = NULL;' % (ptype, pvalue)
330         print
331
332     def get_true_pointer(self):
333         raise NotImplementedError
334
335     def exit_impl(self):
336         print '            ExitProcess(0);'
337
338     def fail_impl(self):
339         if self.fail is not None:
340             if self.type is Void:
341                 assert self.fail == ''
342                 print '            return;' 
343             else:
344                 assert self.fail != ''
345                 print '            return %s;' % self.fail
346         else:
347             self.exit_impl()
348
349     def wrap_impl(self):
350         pvalue = self.pointer_value()
351         print self.prototype() + ' {'
352         if self.type is Void:
353             result = ''
354         else:
355             print '    %s result;' % self.type
356             result = 'result = '
357         self.get_true_pointer()
358         print '    Log::BeginCall("%s");' % (self.name)
359         for type, name in self.args:
360             if not type.isoutput():
361                 type.unwrap_instance(name)
362                 print '    Log::BeginArg("%s", "%s");' % (type, name)
363                 type.dump(name)
364                 print '    Log::EndArg();'
365         print '    %s%s(%s);' % (result, pvalue, ', '.join([str(name) for type, name in self.args]))
366         for type, name in self.args:
367             if type.isoutput():
368                 print '    Log::BeginArg("%s", "%s");' % (type, name)
369                 type.dump(name)
370                 print '    Log::EndArg();'
371                 type.wrap_instance(name)
372         if self.type is not Void:
373             print '    Log::BeginReturn("%s");' % self.type
374             self.type.dump("result")
375             print '    Log::EndReturn();'
376             self.type.wrap_instance('result')
377         print '    Log::EndCall();'
378         self.post_call_impl()
379         if self.type is not Void:
380             print '    return result;'
381         print '}'
382         print
383
384     def post_call_impl(self):
385         pass
386
387
388 class Interface(Type):
389
390     def __init__(self, name, base=None):
391         Type.__init__(self, name)
392         self.name = name
393         self.base = base
394         self.methods = []
395
396     def itermethods(self):
397         if self.base is not None:
398             for method in self.base.itermethods():
399                 yield method
400         for method in self.methods:
401             yield method
402         raise StopIteration
403
404     def wrap_name(self):
405         return "Wrap" + self.expr
406
407     def wrap_pre_decl(self):
408         print "class %s;" % self.wrap_name()
409
410     def wrap_decl(self):
411         print "class %s : public %s " % (self.wrap_name(), self.name)
412         print "{"
413         print "public:"
414         print "    %s(%s * pInstance);" % (self.wrap_name(), self.name)
415         print "    virtual ~%s();" % self.wrap_name()
416         print
417         for method in self.itermethods():
418             print "    " + method.prototype() + ";"
419         print
420         #print "private:"
421         print "    %s * m_pInstance;" % (self.name,)
422         print "};"
423         print
424
425     def wrap_impl(self):
426         print '%s::%s(%s * pInstance) {' % (self.wrap_name(), self.wrap_name(), self.name)
427         print '    m_pInstance = pInstance;'
428         print '}'
429         print
430         print '%s::~%s() {' % (self.wrap_name(), self.wrap_name())
431         print '}'
432         print
433         for method in self.itermethods():
434             print method.prototype(self.wrap_name() + '::' + method.name) + ' {'
435             if method.type is Void:
436                 result = ''
437             else:
438                 print '    %s result;' % method.type
439                 result = 'result = '
440             print '    Log::BeginCall("%s");' % (self.name + '::' + method.name)
441             print '    Log::BeginArg("%s *", "this");' % self.name
442             print '    Log::BeginReference("%s", m_pInstance);' % self.name
443             print '    Log::EndReference();'
444             print '    Log::EndArg();'
445             for type, name in method.args:
446                 if not type.isoutput():
447                     type.unwrap_instance(name)
448                     print '    Log::BeginArg("%s", "%s");' % (type, name)
449                     type.dump(name)
450                     print '    Log::EndArg();'
451             print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(name) for type, name in method.args]))
452             for type, name in method.args:
453                 if type.isoutput():
454                     print '    Log::BeginArg("%s", "%s");' % (type, name)
455                     type.dump(name)
456                     print '    Log::EndArg();'
457                     type.wrap_instance(name)
458             if method.type is not Void:
459                 print '    Log::BeginReturn("%s");' % method.type
460                 method.type.dump("result")
461                 print '    Log::EndReturn();'
462                 method.type.wrap_instance('result')
463             print '    Log::EndCall();'
464             if method.name == 'QueryInterface':
465                 print '    if(*ppvObj == m_pInstance)'
466                 print '        *ppvObj = this;'
467             if method.name == 'Release':
468                 assert method.type is not Void
469                 print '    if(!result)'
470                 print '        delete this;'
471             if method.type is not Void:
472                 print '    return result;'
473             print '}'
474             print
475         print
476
477
478 class Method(Function):
479
480     def __init__(self, type, name, args):
481         Function.__init__(self, type, name, args)
482
483
484 towrap = []
485
486 class WrapPointer(Pointer):
487
488     def __init__(self, type):
489         Pointer.__init__(self, type)
490         if type not in towrap:
491             towrap.append(type)
492
493     def wrap_instance(self, instance):
494         print "    if(%s)" % instance
495         print "        %s = new %s(%s);" % (instance, self.type.wrap_name(), instance)
496
497     def unwrap_instance(self, instance):
498         print "    if(%s)" % instance
499         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, self.type.wrap_name(), instance)
500
501
502 class _String(Type):
503
504     def __init__(self):
505         Type.__init__(self, "char *")
506
507     def dump(self, instance):
508         print '    Log::DumpString((const char *)%s);' % instance
509
510 String = _String()
511
512 class _WString(Type):
513
514     def __init__(self):
515         Type.__init__(self, "wchar_t *")
516
517     def dump(self, instance):
518         print '    Log::DumpWString(%s);' % instance
519
520 WString = _WString()
521
522
523 SChar = Intrinsic("signed char", "%i")
524 UChar = Intrinsic("unsigned char", "%u")
525 Short = Intrinsic("short", "%i")
526 Int = Intrinsic("int", "%i")
527 Long = Intrinsic("long", "%li")
528 UShort = Intrinsic("unsigned short", "%u")
529 UInt = Intrinsic("unsigned int", "%u")
530 ULong = Intrinsic("unsigned long", "%lu")
531 Float = Intrinsic("float", "%f")
532 Double = Intrinsic("double", "%f")
533 SizeT = Intrinsic("size_t", "%lu")
534
535
536 def wrap():
537     for type in all_types.itervalues():
538         type.decl()
539     print
540     for type in all_types.itervalues():
541         type.impl()
542     print
543     for type in towrap:
544         type.wrap_pre_decl()
545     print
546     for type in towrap:
547         type.wrap_decl()
548     print
549     for type in towrap:
550         type.wrap_impl()
551     print