]> git.cworth.org Git - apitrace/blob - base.py
Abstract process termination.
[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
35 class Visitor:
36
37     def visit(self, type, *args, **kwargs):
38         return type.visit(self, *args, **kwargs)
39
40     __call__ = visit
41
42     def visit_void(self, type, *args, **kwargs):
43         raise NotImplementedError
44
45     def visit_literal(self, type, *args, **kwargs):
46         raise NotImplementedError
47
48     def visit_const(self, type, *args, **kwargs):
49         raise NotImplementedError
50
51     def visit_struct(self, type, *args, **kwargs):
52         raise NotImplementedError
53
54     def visit_array(self, type, *args, **kwargs):
55         raise NotImplementedError
56
57     def visit_blob(self, type, *args, **kwargs):
58         raise NotImplementedError
59
60     def visit_enum(self, type, *args, **kwargs):
61         raise NotImplementedError
62
63     def visit_bitmask(self, type, *args, **kwargs):
64         raise NotImplementedError
65
66     def visit_pointer(self, type, *args, **kwargs):
67         raise NotImplementedError
68
69     def visit_alias(self, type, *args, **kwargs):
70         raise NotImplementedError
71
72     def visit_opaque(self, type, *args, **kwargs):
73         raise NotImplementedError
74
75
76 class Rebuilder(Visitor):
77
78     def visit_void(self, void):
79         return void
80
81     def visit_literal(self, literal):
82         return literal
83
84     def visit_const(self, const):
85         return Const(const.type)
86
87     def visit_struct(self, struct):
88         members = [self.visit(member) for member in struct.members]
89         return Struct(struct.name, members)
90
91     def visit_array(self, array):
92         type = self.visit(array.type)
93         return Array(type, array.length)
94
95     def visit_blob(self, blob):
96         type = self.visit(blob.type)
97         return Blob(type, blob.size)
98
99     def visit_enum(self, enum):
100         return enum
101
102     def visit_bitmask(self, bitmask):
103         type = self.visit(bitmask.type)
104         return Bitmask(type, bitmask.values)
105
106     def visit_pointer(self, pointer):
107         type = self.visit(pointer.type)
108         return Pointer(type)
109
110     def visit_alias(self, alias):
111         type = self.visit(alias.type)
112         return Alias(alias.expr, type)
113
114     def visit_opaque(self, opaque):
115         return opaque
116
117
118 class Type:
119
120     __seq = 0
121
122     def __init__(self, expr, id = ''):
123         self.expr = expr
124         
125         for char in id:
126             assert char.isalnum() or char in '_ '
127
128         id = id.replace(' ', '_')
129         
130         if id in all_types:
131             Type.__seq += 1
132             id += str(Type.__seq)
133         
134         assert id not in all_types
135         all_types[id] = self
136
137         self.id = id
138
139     def __str__(self):
140         return self.expr
141
142     def visit(self, visitor, *args, **kwargs):
143         raise NotImplementedError
144
145     def decl(self):
146         pass
147
148     def impl(self):
149         pass
150
151     def dump(self, instance):
152         raise NotImplementedError
153     
154     def wrap_instance(self, instance):
155         pass 
156
157     def unwrap_instance(self, instance):
158         pass
159
160
161 class _Void(Type):
162
163     def __init__(self):
164         Type.__init__(self, "void")
165
166     def visit(self, visitor, *args, **kwargs):
167         return visitor.visit_void(self, *args, **kwargs)
168
169 Void = _Void()
170
171
172 class Concrete(Type):
173
174     def decl(self):
175         print 'static void Dump%s(const %s &value);' % (self.id, self.expr)
176     
177     def impl(self):
178         print 'static void Dump%s(const %s &value) {' % (self.id, self.expr)
179         self._dump("value");
180         print '}'
181         print
182     
183     def _dump(self, instance):
184         raise NotImplementedError
185     
186     def dump(self, instance):
187         print '    Dump%s(%s);' % (self.id, instance)
188     
189
190 class Literal(Concrete):
191
192     def __init__(self, expr, format, base=10):
193         Concrete.__init__(self, expr)
194         self.format = format
195
196     def visit(self, visitor, *args, **kwargs):
197         return visitor.visit_literal(self, *args, **kwargs)
198
199     def _dump(self, instance):
200         print '    Log::Literal%s(%s);' % (self.format, instance)
201
202
203 class Const(Type):
204
205     def __init__(self, type):
206
207         if type.expr.startswith("const "):
208             expr = type.expr + " const"
209         else:
210             expr = "const " + type.expr
211
212         Type.__init__(self, expr, 'C' + type.id)
213
214         self.type = type
215
216     def visit(self, visitor, *args, **kwargs):
217         return visitor.visit_const(self, *args, **kwargs)
218
219     def dump(self, instance):
220         self.type.dump(instance)
221
222
223 class Pointer(Type):
224
225     def __init__(self, type):
226         Type.__init__(self, type.expr + " *", 'P' + type.id)
227         self.type = type
228
229     def visit(self, visitor, *args, **kwargs):
230         return visitor.visit_pointer(self, *args, **kwargs)
231
232     def dump(self, instance):
233         print '    if(%s) {' % instance
234         print '        Log::BeginPointer("%s", (const void *)%s);' % (self.type, instance)
235         try:
236             self.type.dump("*" + instance)
237         except NotImplementedError:
238             pass
239         print '        Log::EndPointer();'
240         print '    }'
241         print '    else'
242         print '        Log::LiteralNull();'
243
244     def wrap_instance(self, instance):
245         self.type.wrap_instance("*" + instance)
246
247     def unwrap_instance(self, instance):
248         self.type.wrap_instance("*" + instance)
249
250
251 def ConstPointer(type):
252     return Pointer(Const(type))
253
254
255 class Enum(Concrete):
256
257     def __init__(self, name, values):
258         Concrete.__init__(self, name)
259         self.values = values
260     
261     def visit(self, visitor, *args, **kwargs):
262         return visitor.visit_enum(self, *args, **kwargs)
263
264     def _dump(self, instance):
265         print '    switch(%s) {' % instance
266         for value in self.values:
267             print '    case %s:' % value
268             print '        Log::LiteralNamedConstant("%s", %s);' % (value, value)
269             print '        break;'
270         print '    default:'
271         print '        Log::LiteralSInt(%s);' % instance
272         print '        break;'
273         print '    }'
274
275
276 def FakeEnum(type, values):
277     return Enum(type.expr, values)
278
279
280 class Bitmask(Concrete):
281
282     def __init__(self, type, values):
283         Concrete.__init__(self, type.expr)
284         self.type = type
285         self.values = values
286
287     def visit(self, visitor, *args, **kwargs):
288         return visitor.visit_bitmask(self, *args, **kwargs)
289
290     def _dump(self, instance):
291         print '    %s l_Value = %s;' % (self.type, instance)
292         print '    Log::BeginBitmask("%s");' % (self.type,)
293         for value in self.values:
294             print '    if((l_Value & %s) == %s) {' % (value, value)
295             print '        Log::LiteralNamedConstant("%s", %s);' % (value, value)
296             print '        l_Value &= ~%s;' % value
297             print '    }'
298         print '    if(l_Value) {'
299         self.type.dump("l_Value");
300         print '    }'
301         print '    Log::EndBitmask();'
302
303 Flags = Bitmask
304
305
306 class Array(Type):
307
308     def __init__(self, type, length):
309         Type.__init__(self, type.expr + " *")
310         self.type = type
311         self.length = length
312
313     def visit(self, visitor, *args, **kwargs):
314         return visitor.visit_array(self, *args, **kwargs)
315
316     def dump(self, instance):
317         index = '__i' + self.type.id
318         print '    Log::BeginArray("%s", %s);' % (self.type, self.length)
319         print '    for (int %s = 0; %s < %s; ++%s) {' % (index, index, self.length, index)
320         print '        Log::BeginElement("%s");' % (self.type,)
321         self.type.dump('(%s)[%s]' % (instance, index))
322         print '        Log::EndElement();'
323         print '    }'
324         print '    Log::EndArray();'
325
326     def wrap_instance(self, instance):
327         self.type.wrap_instance("*" + instance)
328
329     def unwrap_instance(self, instance):
330         self.type.wrap_instance("*" + instance)
331
332
333 class Blob(Type):
334
335     def __init__(self, type, size):
336         Type.__init__(self, type.expr + ' *')
337         self.type = type
338         self.size = size
339
340     def visit(self, visitor, *args, **kwargs):
341         return visitor.visit_blob(self, *args, **kwargs)
342
343     def dump(self, instance):
344         print '    Log::LiteralBlob(%s, %s);' % (instance, self.size)
345
346
347 class Struct(Concrete):
348
349     def __init__(self, name, members):
350         Concrete.__init__(self, name)
351         self.name = name
352         self.members = members
353
354     def visit(self, visitor, *args, **kwargs):
355         return visitor.visit_struct(self, *args, **kwargs)
356
357     def _dump(self, instance):
358         print '    Log::BeginStruct("%s");' % (self.name,)
359         for type, name in self.members:
360             print '    Log::BeginMember("%s", "%s");' % (type, name)
361             type.dump('(%s).%s' % (instance, name))
362             print '    Log::EndMember();'
363         print '    Log::EndStruct();'
364
365
366 class Alias(Type):
367
368     def __init__(self, expr, type):
369         Type.__init__(self, expr)
370         self.type = type
371
372     def visit(self, visitor, *args, **kwargs):
373         return visitor.visit_alias(self, *args, **kwargs)
374
375     def dump(self, instance):
376         self.type.dump(instance)
377
378
379 def Out(type, name):
380     arg = Arg(type, name, output=True)
381     return arg
382
383
384 class Arg:
385
386     def __init__(self, type, name, output=False):
387         self.type = type
388         self.name = name
389         self.output = output
390
391     def __str__(self):
392         return '%s %s' % (self.type, self.name)
393
394
395 class Function:
396
397     def __init__(self, type, name, args, call = '__stdcall', fail = None):
398         self.type = type
399         self.name = name
400
401         self.args = []
402         for arg in args:
403             if isinstance(arg, tuple):
404                 arg_type, arg_name = arg
405                 arg = Arg(arg_type, arg_name)
406             self.args.append(arg)
407
408         self.call = call
409         self.fail = fail
410
411     def prototype(self, name=None):
412         if name is not None:
413             name = name.strip()
414         else:
415             name = self.name
416         s = name
417         if self.call:
418             s = self.call + ' ' + s
419         if name.startswith('*'):
420             s = '(' + s + ')'
421         s = self.type.expr + ' ' + s
422         s += "("
423         if self.args:
424             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
425         else:
426             s += "void"
427         s += ")"
428         return s
429
430     def pointer_type(self):
431         return 'P' + self.name
432
433     def pointer_value(self):
434         return 'p' + self.name
435
436     def wrap_decl(self):
437         ptype = self.pointer_type()
438         pvalue = self.pointer_value()
439         print 'typedef ' + self.prototype('* %s' % ptype) + ';'
440         print 'static %s %s = NULL;' % (ptype, pvalue)
441         print
442
443     def get_true_pointer(self):
444         raise NotImplementedError
445
446     def exit_impl(self):
447         print '            Log::Abort();'
448
449     def fail_impl(self):
450         if self.fail is not None:
451             if self.type is Void:
452                 assert self.fail == ''
453                 print '            return;' 
454             else:
455                 assert self.fail != ''
456                 print '            return %s;' % self.fail
457         else:
458             self.exit_impl()
459
460     def wrap_impl(self):
461         pvalue = self.pointer_value()
462         print self.prototype() + ' {'
463         if self.type is Void:
464             result = ''
465         else:
466             print '    %s result;' % self.type
467             result = 'result = '
468         self.get_true_pointer()
469         print '    Log::BeginCall("%s");' % (self.name)
470         for arg in self.args:
471             if not arg.output:
472                 arg.type.unwrap_instance(arg.name)
473                 print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
474                 arg.type.dump(arg.name)
475                 print '    Log::EndArg();'
476         print '    %s%s(%s);' % (result, pvalue, ', '.join([str(arg.name) for arg in self.args]))
477         for arg in self.args:
478             if arg.output:
479                 print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
480                 arg.type.dump(arg.name)
481                 print '    Log::EndArg();'
482                 arg.type.wrap_instance(arg.name)
483         if self.type is not Void:
484             print '    Log::BeginReturn("%s");' % self.type
485             self.type.dump("result")
486             print '    Log::EndReturn();'
487             self.type.wrap_instance('result')
488         print '    Log::EndCall();'
489         self.post_call_impl()
490         if self.type is not Void:
491             print '    return result;'
492         print '}'
493         print
494
495     def post_call_impl(self):
496         pass
497
498
499 class Interface(Type):
500
501     def __init__(self, name, base=None):
502         Type.__init__(self, name)
503         self.name = name
504         self.base = base
505         self.methods = []
506
507     def itermethods(self):
508         if self.base is not None:
509             for method in self.base.itermethods():
510                 yield method
511         for method in self.methods:
512             yield method
513         raise StopIteration
514
515     def wrap_name(self):
516         return "Wrap" + self.expr
517
518     def wrap_pre_decl(self):
519         print "class %s;" % self.wrap_name()
520
521     def wrap_decl(self):
522         print "class %s : public %s " % (self.wrap_name(), self.name)
523         print "{"
524         print "public:"
525         print "    %s(%s * pInstance);" % (self.wrap_name(), self.name)
526         print "    virtual ~%s();" % self.wrap_name()
527         print
528         for method in self.itermethods():
529             print "    " + method.prototype() + ";"
530         print
531         #print "private:"
532         print "    %s * m_pInstance;" % (self.name,)
533         print "};"
534         print
535
536     def wrap_impl(self):
537         print '%s::%s(%s * pInstance) {' % (self.wrap_name(), self.wrap_name(), self.name)
538         print '    m_pInstance = pInstance;'
539         print '}'
540         print
541         print '%s::~%s() {' % (self.wrap_name(), self.wrap_name())
542         print '}'
543         print
544         for method in self.itermethods():
545             print method.prototype(self.wrap_name() + '::' + method.name) + ' {'
546             if method.type is Void:
547                 result = ''
548             else:
549                 print '    %s result;' % method.type
550                 result = 'result = '
551             print '    Log::BeginCall("%s");' % (self.name + '::' + method.name)
552             print '    Log::BeginArg("%s *", "this");' % self.name
553             print '    Log::BeginPointer("%s", (const void *)m_pInstance);' % self.name
554             print '    Log::EndPointer();'
555             print '    Log::EndArg();'
556             for arg in method.args:
557                 if not arg.output:
558                     arg.type.unwrap_instance(arg.name)
559                     print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
560                     arg.type.dump(arg.name)
561                     print '    Log::EndArg();'
562             print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(arg.name) for arg in method.args]))
563             for arg in method.args:
564                 if arg.output:
565                     print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
566                     arg.type.dump(arg.name)
567                     print '    Log::EndArg();'
568                     arg.type.wrap_instance(arg.name)
569             if method.type is not Void:
570                 print '    Log::BeginReturn("%s");' % method.type
571                 method.type.dump("result")
572                 print '    Log::EndReturn();'
573                 method.type.wrap_instance('result')
574             print '    Log::EndCall();'
575             if method.name == 'QueryInterface':
576                 print '    if(*ppvObj == m_pInstance)'
577                 print '        *ppvObj = this;'
578             if method.name == 'Release':
579                 assert method.type is not Void
580                 print '    if(!result)'
581                 print '        delete this;'
582             if method.type is not Void:
583                 print '    return result;'
584             print '}'
585             print
586         print
587
588
589 class Method(Function):
590
591     def __init__(self, type, name, args):
592         Function.__init__(self, type, name, args, call = '__stdcall')
593
594
595 towrap = []
596
597 class WrapPointer(Pointer):
598
599     def __init__(self, type):
600         Pointer.__init__(self, type)
601         if type not in towrap:
602             towrap.append(type)
603
604     def wrap_instance(self, instance):
605         print "    if(%s)" % instance
606         print "        %s = new %s(%s);" % (instance, self.type.wrap_name(), instance)
607
608     def unwrap_instance(self, instance):
609         print "    if(%s)" % instance
610         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, self.type.wrap_name(), instance)
611
612
613 class _String(Type):
614
615     def __init__(self):
616         Type.__init__(self, "char *")
617
618     def visit(self, visitor, *args, **kwargs):
619         return visitor.visit_literal(self, *args, **kwargs)
620
621     def dump(self, instance):
622         print '    Log::LiteralString((const char *)%s);' % instance
623
624 String = _String()
625
626
627 class Opaque(Type):
628     '''Opaque pointer.'''
629
630     def __init__(self, expr):
631         Type.__init__(self, expr)
632
633     def visit(self, visitor, *args, **kwargs):
634         return visitor.visit_opaque(self, *args, **kwargs)
635
636     def dump(self, instance):
637         print '    Log::LiteralOpaque((const void *)%s);' % instance
638
639
640 def OpaquePointer(type):
641     return Opaque(type.expr + ' *')
642
643
644 Bool = Literal("bool", "Bool")
645 SChar = Literal("signed char", "SInt")
646 UChar = Literal("unsigned char", "UInt")
647 Short = Literal("short", "SInt")
648 Int = Literal("int", "SInt")
649 Long = Literal("long", "SInt")
650 LongLong = Literal("long long", "SInt")
651 UShort = Literal("unsigned short", "UInt")
652 UInt = Literal("unsigned int", "UInt")
653 ULong = Literal("unsigned long", "UInt")
654 Float = Literal("float", "Float")
655 Double = Literal("double", "Float")
656 SizeT = Literal("size_t", "UInt")
657 WString = Literal("wchar_t *", "WString")
658
659
660 def wrap():
661     for type in all_types.itervalues():
662         type.decl()
663     print
664     for type in all_types.itervalues():
665         type.impl()
666     print
667     for type in towrap:
668         type.wrap_pre_decl()
669     print
670     for type in towrap:
671         type.wrap_decl()
672     print
673     for type in towrap:
674         type.wrap_impl()
675     print