Move to tools
[obnox/wireshark/wip.git] / tools / ethereal_gen.py
1 # -*- python -*-
2 #
3 # $Id$
4 #
5 # ethereal_gen.py (part of idl2eth)
6 #
7 # Author : Frank Singleton (frank.singleton@ericsson.com)
8 #
9 #    Copyright (C) 2001 Frank Singleton, Ericsson Inc.
10 #
11 #  This file is a backend to "omniidl", used to generate "Ethereal"
12 #  dissectors from CORBA IDL descriptions. The output language generated
13 #  is "C". It will generate code to use the GIOP/IIOP get_CDR_XXX API.
14 #
15 #  Please see packet-giop.h in Wireshark distro for API description.
16 #  Wireshark is available at http://www.ethereal.com/
17 #
18 #  Omniidl is part of the OmniOrb distribution, and is available at
19 #  http://www.uk.research.att.com/omniORB/omniORB.html
20 #
21 #  This program is free software; you can redistribute it and/or modify it
22 #  under the terms of the GNU General Public License as published by
23 #  the Free Software Foundation; either version 2 of the License, or
24 #  (at your option) any later version.
25 #
26 #  This program is distributed in the hope that it will be useful,
27 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
28 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29 #  General Public License for more details.
30 #
31 #  You should have received a copy of the GNU General Public License
32 #  along with this program; if not, write to the Free Software
33 #  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
34 #  02111-1307, USA.
35 #
36 # Description:
37 #
38 #   Omniidl Back-end which parses an IDL list of "Operation" nodes
39 #   passed from ethereal_be2.py and generates "C" code for compiling
40 #   as a plugin for the  Ethereal IP Protocol Analyser.
41 #
42 #
43 # Strategy (sneaky but ...)
44 #
45 # problem: I dont know what variables to declare until AFTER the helper functions
46 # have been built, so ...
47 #
48 # There are 2 passes through genHelpers, the first one is there just to
49 # make sure the fn_hash data struct is populated properly.
50 # The second pass is the real thing, generating code and declaring
51 # variables (from the 1st pass) properly.
52 #
53
54
55 """Ethereal IDL compiler back-end."""
56
57 from omniidl import idlast, idltype, idlutil, output
58 import sys, string
59 import tempfile
60
61 #
62 # Output class, generates "C" src code for the sub-dissector
63 #
64 # in:
65 #
66 #
67 # self - me
68 # st   - output stream
69 # node - a reference to an Operations object.
70 # name - scoped name (Module::Module::Interface:: .. ::Operation
71 #
72
73
74
75 #
76 # TODO -- FS
77 #
78 # 1. generate hf[] data for searchable fields (but what is searchable?)
79 # 2. add item instead of add_text()
80 # 3. sequence handling [done]
81 # 4. User Exceptions [done]
82 # 5. Fix arrays, and structs containing arrays [done]
83 # 6. Handle pragmas.
84 # 7. Exception can be common to many operations, so handle them outside the
85 #    operation helper functions [done]
86 # 8. Automatic variable declaration [done, improve, still get some collisions.add variable delegator function ]
87 #    For example, mutlidimensional arrays.
88 # 9. wchar and wstring handling [giop API needs improving]
89 # 10. Support Fixed [done]
90 # 11. Support attributes (get/set) [started, needs language mapping option, perhaps ethereal GUI option
91 #     to set the attribute function prefix or suffix ? ] For now the prefix is "_get" and "_set"
92 #     eg: attribute string apple  =>   _get_apple and _set_apple
93 #
94 # 12. Implement IDL "union" code [done]
95 # 13. Implement support for plugins [done]
96 # 14. Dont generate code for empty operations (cf: exceptions without members)
97 # 15. Generate code to display Enums numerically and symbolically [done]
98 # 16. Place structs/unions in subtrees
99 # 17. Recursive struct and union handling [done ]
100 # 18. Improve variable naming for display (eg: structs, unions etc)
101 #
102 # Also test, Test, TEST
103 #
104
105
106
107 #
108 #   Strategy:
109 #    For every operation and attribute do
110 #       For return val and all parameters do
111 #       find basic IDL type for each parameter
112 #       output get_CDR_xxx
113 #       output exception handling code
114 #       output attribute handling code
115 #
116 #
117
118 class ethereal_gen_C:
119
120
121     #
122     # Turn DEBUG stuff on/off
123     #
124
125     DEBUG = 0
126
127     #
128     # Some string constants for our templates
129     #
130     c_u_octet8    = "guint64   u_octet8;"  
131     c_s_octet8    = "gint64    s_octet8;"  
132     c_u_octet4    = "guint32   u_octet4;"
133     c_s_octet4    = "gint32    s_octet4;"
134     c_u_octet2    = "guint16   u_octet2;"
135     c_s_octet2    = "gint16    s_octet2;"
136     c_u_octet1    = "guint8    u_octet1;"
137     c_s_octet1    = "gint8     s_octet1;"
138
139     c_float       = "gfloat    my_float;"
140     c_double      = "gdouble   my_double;"
141
142     c_seq         = "gchar   *seq = NULL;"          # pointer to buffer of gchars
143     c_i           = "guint32   i_";                 # loop index
144     c_i_lim       = "guint32   u_octet4_loop_";     # loop limit
145     c_u_disc      = "guint32   disc_u_";            # unsigned int union discriminant variable name (enum)
146     c_s_disc      = "gint32    disc_s_";            # signed int union discriminant variable name (other cases, except Enum)
147
148     #
149     # Constructor
150     #
151
152     def __init__(self, st, protocol_name, dissector_name ,description):
153         self.st = output.Stream(tempfile.TemporaryFile(),4) # for first pass only
154
155         self.st_save = st               # where 2nd pass should go
156         self.protoname = protocol_name  # Protocol Name (eg: ECHO)
157         self.dissname = dissector_name  # Dissector name (eg: echo)
158         self.description = description  # Detailed Protocol description (eg: Echo IDL Example)
159         self.exlist = []                # list of exceptions used in operations.
160         #self.curr_sname                # scoped name of current opnode or exnode I am visiting, used for generating "C" var declares
161         self.fn_hash = {}               # top level hash to contain key = function/exception and val = list of variable declarations
162                                         # ie a hash of lists
163         self.fn_hash_built = 0          # flag to indicate the 1st pass is complete, and the fn_hash is correctly
164                                         # populated with operations/vars and exceptions/vars
165
166
167     #
168     # genCode()
169     #
170     # Main entry point, controls sequence of
171     # generated code.
172     #
173     #
174
175     def genCode(self,oplist, atlist, enlist, stlist, unlist):   # operation,attribute,enums,struct and union lists
176
177
178         self.genHelpers(oplist,stlist,unlist)  # sneaky .. call it now, to populate the fn_hash
179                                         # so when I come to that operation later, I have the variables to
180                                         # declare already.
181
182         self.genExceptionHelpers(oplist) # sneaky .. call it now, to populate the fn_hash
183                                          # so when I come to that exception later, I have the variables to
184                                          # declare already.
185
186         self.genAttributeHelpers(atlist) # sneaky .. call it now, to populate the fn_hash
187                                          # so when I come to that exception later, I have the variables to
188                                          # declare already.
189
190
191         self.fn_hash_built = 1          # DONE, so now I know , see genOperation()
192
193         self.st = self.st_save
194         self.genHeader()                # initial dissector comments
195         self.genEthCopyright()          # Ethereal Copyright comments.
196         self.genGPL()                   # GPL license
197         self.genIncludes()
198         self.genDeclares(oplist,atlist,enlist,stlist,unlist)
199         self.genProtocol()
200         self.genRegisteredFields()
201         self.genOpList(oplist)          # string constant declares for operation names
202         self.genExList(oplist)          # string constant declares for user exceptions
203         self.genAtList(atlist)          # string constant declares for Attributes
204         self.genEnList(enlist)          # string constant declares for Enums
205
206
207         self.genExceptionHelpers(oplist)   # helper function to decode user exceptions that have members
208         self.genExceptionDelegator(oplist) # finds the helper function to decode a user exception
209         self.genAttributeHelpers(atlist)   # helper function to decode "attributes"
210
211         self.genHelpers(oplist,stlist,unlist)  # operation, struct and union decode helper functions
212
213         self.genMainEntryStart(oplist)
214         self.genOpDelegator(oplist)
215         self.genAtDelegator(atlist)
216         self.genMainEntryEnd()
217
218         self.gen_proto_register()
219         self.gen_proto_reg_handoff(oplist)
220         self.gen_plugin_register()
221
222         #self.dumpvars()                 # debug
223
224
225
226     #
227     # genHeader
228     #
229     # Generate Standard Ethereal Header Comments
230     #
231     #
232
233     def genHeader(self):
234         self.st.out(self.template_Header,dissector_name=self.dissname)
235         if self.DEBUG:
236             print "XXX genHeader"
237
238
239
240
241     #
242     # genEthCopyright
243     #
244     # Ethereal Copyright Info
245     #
246     #
247
248     def genEthCopyright(self):
249         if self.DEBUG:
250             print "XXX genEthCopyright"
251         self.st.out(self.template_ethereal_copyright)
252
253
254     #
255     # genGPL
256     #
257     # GPL licencse
258     #
259     #
260
261     def genGPL(self):
262         if self.DEBUG:
263             print "XXX genGPL"
264
265         self.st.out(self.template_GPL)
266
267     #
268     # genIncludes
269     #
270     # GPL licencse
271     #
272     #
273
274     def genIncludes(self):
275         if self.DEBUG:
276             print "XXX genIncludes"
277
278         self.st.out(self.template_Includes)
279
280
281     #
282     # denDeclares
283     #
284     # generate function prototypes if required
285     #
286     # Currently this is used for struct and union helper function declarations.
287     #
288
289
290     def genDeclares(self,oplist,atlist,enlist,stlist,unlist):
291         if self.DEBUG:
292             print "XXX genDeclares"
293
294         # prototype for start_dissecting()
295
296         self.st.out(self.template_prototype_start_dissecting)
297
298         # struct prototypes
299
300         self.st.out(self.template_prototype_struct_start)
301         for st in stlist:
302             #print st.repoId()
303             sname = self.namespace(st, "_")
304
305             self.st.out(self.template_prototype_struct_body, stname=st.repoId(),name=sname)
306         self.st.out(self.template_prototype_struct_end)
307
308         # union prototypes
309
310         self.st.out(self.template_prototype_union_start)
311         for un in unlist:
312             sname = self.namespace(un, "_")
313             self.st.out(self.template_prototype_union_body, unname=un.repoId(),name=sname)
314         self.st.out(self.template_prototype_union_end)
315
316
317
318
319     #
320     # genProtocol
321     #
322     #
323
324     def genProtocol(self):
325         self.st.out(self.template_protocol, dissector_name=self.dissname)
326         self.st.out(self.template_init_boundary)
327
328
329     #
330     # genProtoAndRegisteredFields
331     #
332     #
333
334     def genRegisteredFields(self):
335         self.st.out(self.template_registered_fields )
336
337
338
339     #
340     # genMainEntryStart
341     #
342
343     def genMainEntryStart(self,oplist):
344         self.st.out(self.template_main_dissector_start, dissname=self.dissname, disprot=self.protoname)
345         self.st.inc_indent()
346         self.st.out(self.template_main_dissector_switch_msgtype_start)
347         self.st.out(self.template_main_dissector_switch_msgtype_start_request_reply)
348         self.st.inc_indent()
349
350
351     #
352     # genMainEntryEnd
353     #
354
355     def genMainEntryEnd(self):
356
357         self.st.out(self.template_main_dissector_switch_msgtype_end_request_reply)
358         self.st.dec_indent()
359         self.st.out(self.template_main_dissector_switch_msgtype_all_other_msgtype)
360         self.st.dec_indent()
361         self.st.out(self.template_main_dissector_end)
362
363
364     #
365     # genOpList
366     #
367     # in: oplist
368     #
369     # out: C code for IDL operations
370     #
371     # eg:
372     #
373     # static const char Penguin_Echo_echoShort_op[] = "echoShort" ;
374     #
375
376     def genOpList(self,oplist):
377         self.st.out(self.template_comment_operations_start)
378
379         for n in oplist:
380             sname = self.namespace(n, "_")
381             opname = n.identifier()
382             self.st.out(self.template_operations_declare, sname=sname, opname=opname)
383
384         self.st.out(self.template_comment_operations_end)
385
386     #
387     # genExList
388     #
389     # in: oplist
390     #
391     # out: C code for IDL User Exceptions that contain members
392     #
393     # eg:
394     #
395     # static const char user_exception_tux_bad_value[] = "IDL:tux/bad_value:1.0" ;
396     #
397
398     def genExList(self,oplist):
399
400         self.st.out(self.template_comment_user_exceptions_string_declare_start)
401
402         exlist = self.get_exceptionList(oplist) # grab list of ALL UNIQUE exception nodes
403
404         for ex in exlist:
405             if self.DEBUG:
406                 print "XXX Exception " , ex.repoId()
407                 print "XXX Exception Identifier" , ex.identifier()
408                 print "XXX Exception Scoped Name" , ex.scopedName()
409
410             if (ex.members()):          # only if has members
411                 sname = self.namespace(ex, "_")
412                 exname = ex.repoId()
413                 self.st.out(self.template_user_exceptions_declare,  sname=sname, exname=ex.repoId())
414
415         self.st.out(self.template_comment_user_exceptions_string_declare_end)
416
417     #
418     # genAtList
419     #
420     # in: atlist
421     #
422     # out: C code for IDL attribute decalarations.
423     #
424     # NOTE: Mapping of attributes to  operation(function) names is tricky.
425     #
426     # The actual accessor function names are language-mapping specific. The attribute name
427     # is subject to OMG IDL's name scoping rules; the accessor function names are
428     # guaranteed not to collide with any legal operation names specifiable in OMG IDL.
429     #
430     # eg:
431     #
432     # static const char get_Penguin_Echo_get_width_at[] = "get_width" ;
433     # static const char set_Penguin_Echo_set_width_at[] = "set_width" ;
434     #
435     # or:
436     #
437     # static const char get_Penguin_Echo_get_width_at[] = "_get_width" ;
438     # static const char set_Penguin_Echo_set_width_at[] = "_set_width" ;
439     #
440     # TODO: Implement some language dependant templates to handle naming conventions
441     #       language <=> attribute. for C, C++. Java etc
442     #
443     # OR, just add a runtime GUI option to select language binding for attributes -- FS
444     #
445     #
446     #
447     # ie: def genAtlist(self,atlist,language)
448     #
449
450
451
452     def genAtList(self,atlist):
453         self.st.out(self.template_comment_attributes_start)
454
455         for n in atlist:
456             for i in n.declarators():   #
457                 sname = self.namespace(i, "_")
458                 atname = i.identifier()
459                 self.st.out(self.template_attributes_declare_Java_get, sname=sname, atname=atname)
460                 if not n.readonly():
461                     self.st.out(self.template_attributes_declare_Java_set, sname=sname, atname=atname)
462
463         self.st.out(self.template_comment_attributes_end)
464
465
466     #
467     # genEnList
468     #
469     # in: enlist
470     #
471     # out: C code for IDL Enum decalarations using "static const value_string" template
472     #
473
474
475
476     def genEnList(self,enlist):
477
478         self.st.out(self.template_comment_enums_start)
479
480         for enum in enlist:
481             sname = self.namespace(enum, "_")
482
483             self.st.out(self.template_comment_enum_comment, ename=enum.repoId())
484             self.st.out(self.template_value_string_start, valstringname=sname)
485             for enumerator in enum.enumerators():
486                 self.st.out(self.template_value_string_entry, intval=str(self.valFromEnum(enum,enumerator)), description=enumerator.identifier())
487
488
489             #atname = n.identifier()
490             self.st.out(self.template_value_string_end, valstringname=sname)
491
492         self.st.out(self.template_comment_enums_end)
493
494
495
496
497
498
499
500
501
502
503     #
504     # genExceptionDelegator
505     #
506     # in: oplist
507     #
508     # out: C code for User exception delegator
509     #
510     # eg:
511     #
512     #
513
514     def genExceptionDelegator(self,oplist):
515
516         self.st.out(self.template_main_exception_delegator_start)
517         self.st.inc_indent()
518
519         exlist = self.get_exceptionList(oplist) # grab list of ALL UNIQUE exception nodes
520
521         for ex in exlist:
522             if self.DEBUG:
523                 print "XXX Exception " , ex.repoId()
524                 print "XXX Exception Identifier" , ex.identifier()
525                 print "XXX Exception Scoped Name" , ex.scopedName()
526
527             if (ex.members()):          # only if has members
528                 sname = self.namespace(ex, "_")
529                 exname = ex.repoId()
530                 self.st.out(self.template_ex_delegate_code,  sname=sname, exname=ex.repoId())
531
532         self.st.dec_indent()
533         self.st.out(self.template_main_exception_delegator_end)
534
535
536     #
537     # genAttribueHelpers()
538     #
539     # Generate private helper functions to decode Attributes.
540     #
541     # in: atlist
542     #
543     # For readonly attribute - generate get_xxx()
544     # If NOT readonly attribute - also generate set_xxx()
545     #
546
547     def genAttributeHelpers(self,atlist):
548         if self.DEBUG:
549             print "XXX genAttributeHelpers: atlist = ", atlist
550
551         self.st.out(self.template_attribute_helpers_start)
552
553         for attrib in atlist:
554             for decl in attrib.declarators():
555                 self.genAtHelper(attrib,decl,"get") # get accessor
556                 if not attrib.readonly():
557                     self.genAtHelper(attrib,decl,"set") # set accessor
558
559         self.st.out(self.template_attribute_helpers_end)
560
561     #
562     # genAtHelper()
563     #
564     # Generate private helper functions to decode an attribute
565     #
566     # in: at - attribute node
567     # in: decl - declarator belonging to this attribute
568     # in: order - to generate a "get" or "set" helper
569
570     def genAtHelper(self,attrib,decl,order):
571         if self.DEBUG:
572             print "XXX genAtHelper"
573
574         sname = order + "_" + self.namespace(decl, "_")  # must use set or get prefix to avoid collision
575         self.curr_sname = sname                    # update current opnode/exnode scoped name
576
577         if not self.fn_hash_built:
578             self.fn_hash[sname] = []        # init empty list as val for this sname key
579                                             # but only if the fn_hash is not already built
580
581         self.st.out(self.template_attribute_helper_function_start, sname=sname, atname=decl.repoId())
582         self.st.inc_indent()
583
584         self.st.out(self.template_helper_function_vars_start)
585         self.dumpCvars(sname)
586         self.st.out(self.template_helper_function_vars_end )
587
588         self.st.out(self.template_exception_helper_function_get_endianess)
589
590         #
591         # TODO - attributes are simple types, so remove array handling
592         #
593
594         if decl.sizes():        # an array
595             indices = self.get_indices_from_sizes(decl.sizes())
596             string_indices = '%i ' % indices # convert int to string
597             self.st.out(self.template_get_CDR_array_comment, aname=decl.identifier(), asize=string_indices)
598             self.st.out(self.template_get_CDR_array_start, aname=decl.identifier(), aval=string_indices)
599             self.addvar(self.c_i + decl.identifier() + ";")
600
601             self.st.inc_indent()
602
603             self.getCDR3(attrib.attrType(), decl.identifier() )
604
605             self.st.dec_indent()
606             self.st.out(self.template_get_CDR_array_end)
607
608
609         else:
610
611             self.getCDR3(attrib.attrType(), decl.identifier() )
612
613         self.st.dec_indent()
614         self.st.out(self.template_attribute_helper_function_end)
615
616
617
618     #
619     # genExceptionHelpers()
620     #
621     # Generate private helper functions to decode Exceptions used
622     # within operations
623     #
624     # in: oplist
625     #
626
627
628     def genExceptionHelpers(self,oplist):
629         exlist = self.get_exceptionList(oplist) # grab list of exception nodes
630         if self.DEBUG:
631             print "XXX genExceptionHelpers: exlist = ", exlist
632
633         self.st.out(self.template_exception_helpers_start)
634         for ex in exlist:
635             if (ex.members()):          # only if has members
636                 #print "XXX Exception = " + ex.identifier()
637                 self.genExHelper(ex)
638
639         self.st.out(self.template_exception_helpers_end)
640
641
642     #
643     # genExhelper()
644     #
645     # Generate private helper functions to decode User Exceptions
646     #
647     # in: exnode ( an exception node)
648     #
649
650     def genExHelper(self,ex):
651         if self.DEBUG:
652             print "XXX genExHelper"
653
654         sname = self.namespace(ex, "_")
655         self.curr_sname = sname         # update current opnode/exnode scoped name
656         if not self.fn_hash_built:
657             self.fn_hash[sname] = []        # init empty list as val for this sname key
658                                             # but only if the fn_hash is not already built
659
660         self.st.out(self.template_exception_helper_function_start, sname=sname, exname=ex.repoId())
661         self.st.inc_indent()
662
663         self.st.out(self.template_helper_function_vars_start)
664         self.dumpCvars(sname)
665         self.st.out(self.template_helper_function_vars_end )
666
667         self.st.out(self.template_exception_helper_function_get_endianess)
668
669
670         for m in ex.members():
671             #print "XXX genExhelper, member = ", m, "member type = ", m.memberType()
672
673
674             for decl in m.declarators():
675                 #print "XXX genExhelper, d = ", decl
676                 if decl.sizes():        # an array
677                     indices = self.get_indices_from_sizes(decl.sizes())
678                     string_indices = '%i ' % indices # convert int to string
679                     self.st.out(self.template_get_CDR_array_comment, aname=decl.identifier(), asize=string_indices)
680                     self.st.out(self.template_get_CDR_array_start, aname=decl.identifier(), aval=string_indices)
681                     self.addvar(self.c_i + decl.identifier() + ";")
682
683                     self.st.inc_indent()
684                     self.getCDR3(m.memberType(), ex.identifier() + "_" + decl.identifier() )
685
686                     self.st.dec_indent()
687                     self.st.out(self.template_get_CDR_array_end)
688
689
690                 else:
691                     self.getCDR3(m.memberType(), ex.identifier() + "_" + decl.identifier() )
692
693         self.st.dec_indent()
694         self.st.out(self.template_exception_helper_function_end)
695
696
697     #
698     # genHelpers()
699     #
700     # Generate private helper functions for each IDL operation.
701     # Generate private helper functions for each IDL struct.
702     # Generate private helper functions for each IDL union.
703     #
704     #
705     # in: oplist, stlist, unlist
706     #
707
708
709     def genHelpers(self,oplist,stlist,unlist):
710         for op in oplist:
711             self.genOperation(op)
712         for st in stlist:
713             self.genStructHelper(st)
714         for un in unlist:
715             self.genUnionHelper(un)
716
717     #
718     # genOperation()
719     #
720     # Generate private helper functions for a specificIDL operation.
721     #
722     # in: opnode
723     #
724
725     def genOperation(self,opnode):
726         if self.DEBUG:
727             print "XXX genOperation called"
728
729         sname = self.namespace(opnode, "_")
730         if not self.fn_hash_built:
731             self.fn_hash[sname] = []        # init empty list as val for this sname key
732                                             # but only if the fn_hash is not already built
733
734         self.curr_sname = sname         # update current opnode's scoped name
735         opname = opnode.identifier()
736
737         self.st.out(self.template_helper_function_comment, repoid=opnode.repoId() )
738
739         self.st.out(self.template_helper_function_start, sname=sname)
740         self.st.inc_indent()
741
742         self.st.out(self.template_helper_function_vars_start)
743         self.dumpCvars(sname)
744         self.st.out(self.template_helper_function_vars_end )
745
746
747         self.st.out(self.template_helper_switch_msgtype_start)
748
749         self.st.out(self.template_helper_switch_msgtype_request_start)
750         self.st.inc_indent()
751         self.genOperationRequest(opnode)
752         self.st.out(self.template_helper_switch_msgtype_request_end)
753         self.st.dec_indent()
754
755         self.st.out(self.template_helper_switch_msgtype_reply_start)
756         self.st.inc_indent()
757
758         self.st.out(self.template_helper_switch_rep_status_start)
759
760
761         self.st.out(self.template_helper_switch_msgtype_reply_no_exception_start)
762         self.st.inc_indent()
763         self.genOperationReply(opnode)
764         self.st.out(self.template_helper_switch_msgtype_reply_no_exception_end)
765         self.st.dec_indent()
766
767         self.st.out(self.template_helper_switch_msgtype_reply_user_exception_start)
768         self.st.inc_indent()
769         self.genOpExceptions(opnode)
770         self.st.out(self.template_helper_switch_msgtype_reply_user_exception_end)
771         self.st.dec_indent()
772
773         self.st.out(self.template_helper_switch_msgtype_reply_default_start)
774         self.st.out(self.template_helper_switch_msgtype_reply_default_end)
775
776         self.st.out(self.template_helper_switch_rep_status_end)
777
778         self.st.dec_indent()
779
780         self.st.out(self.template_helper_switch_msgtype_default_start)
781         self.st.out(self.template_helper_switch_msgtype_default_end)
782
783         self.st.out(self.template_helper_switch_msgtype_end)
784         self.st.dec_indent()
785
786
787         self.st.out(self.template_helper_function_end, sname=sname)
788
789
790
791
792     #
793     # Decode function parameters for a GIOP request message
794     #
795     #
796
797     def genOperationRequest(self,opnode):
798         for p in opnode.parameters():
799             if p.is_in():
800                 if self.DEBUG:
801                     print "XXX parameter = " ,p
802                     print "XXX parameter type = " ,p.paramType()
803                     print "XXX parameter type kind = " ,p.paramType().kind()
804
805                 self.getCDR3(p.paramType(),p.identifier())
806
807
808     #
809     # Decode function parameters for a GIOP reply message
810     #
811
812
813     def genOperationReply(self,opnode):
814
815         rt = opnode.returnType()        # get return type
816         if self.DEBUG:
817             print "XXX opnode  = " , opnode
818             print "XXX return type  = " , rt
819             print "XXX return type.unalias  = " , rt.unalias()
820             print "XXX return type.kind()  = " , rt.kind();
821
822
823         if (rt.kind() == idltype.tk_alias): # a typdef return val possibly ?
824             #self.getCDR3(rt.decl().alias().aliasType(),"dummy")    # return value maybe a typedef
825             #self.get_CDR_alias(rt, "Operation_Return_Value" )
826             self.get_CDR_alias(rt, rt.name() )
827
828         else:
829             self.getCDR3(rt, "Operation_Return_Value")    # return value is NOT an alias
830
831         for p in opnode.parameters():
832             if p.is_out():              # out or inout
833                 self.getCDR3(p.paramType(),p.identifier())
834
835         #self.st.dec_indent()
836
837     def genOpExceptions(self,opnode):
838         for ex in opnode.raises():
839             if ex.members():
840                 #print ex.members()
841                 for m in ex.members():
842                     t=0
843                     #print m.memberType(), m.memberType().kind()
844     #
845     # Delegator for Operations
846     #
847
848     def genOpDelegator(self,oplist):
849         for op in oplist:
850             iname = "/".join(op.scopedName()[:-1])
851             opname = op.identifier()
852             sname = self.namespace(op, "_")
853             self.st.out(self.template_op_delegate_code, interface=iname, sname=sname)
854
855     #
856     # Delegator for Attributes
857     #
858
859     def genAtDelegator(self,atlist):
860         for a in atlist:
861             for i in a.declarators():
862                 atname = i.identifier()
863                 sname = self.namespace(i, "_")
864                 self.st.out(self.template_at_delegate_code_get, sname=sname)
865                 if not a.readonly():
866                     self.st.out(self.template_at_delegate_code_set, sname=sname)
867
868
869     #
870     # Add a variable declaration to the hash of list
871     #
872
873     def addvar(self, var):
874         if not ( var in self.fn_hash[self.curr_sname] ):
875             self.fn_hash[self.curr_sname].append(var)
876
877     #
878     # Print the variable declaration from  the hash of list
879     #
880
881
882     def dumpvars(self):
883         for fn in self.fn_hash.keys():
884             print "FN = " + fn
885             for v in self.fn_hash[fn]:
886                 print "-> " + v
887     #
888     # Print the "C" variable declaration from  the hash of list
889     # for a given scoped operation name (eg: tux_penguin_eat)
890     #
891
892
893     def dumpCvars(self, sname):
894             for v in self.fn_hash[sname]:
895                 self.st.out(v)
896
897
898     #
899     # Given an enum node, and a enumerator node, return
900     # the enumerator's numerical value.
901     #
902     # eg: enum Color {red,green,blue} should return
903     # val = 1 for green
904     #
905
906     def valFromEnum(self,enumNode, enumeratorNode):
907         if self.DEBUG:
908             print "XXX valFromEnum, enumNode = ", enumNode, " from ", enumNode.repoId()
909             print "XXX valFromEnum, enumeratorNode = ", enumeratorNode, " from ", enumeratorNode.repoId()
910
911         if isinstance(enumeratorNode,idlast.Enumerator):
912             value = enumNode.enumerators().index(enumeratorNode)
913             return value
914
915
916 ## tk_null               = 0
917 ## tk_void               = 1
918 ## tk_short              = 2
919 ## tk_long               = 3
920 ## tk_ushort             = 4
921 ## tk_ulong              = 5
922 ## tk_float              = 6
923 ## tk_double             = 7
924 ## tk_boolean            = 8
925 ## tk_char               = 9
926 ## tk_octet              = 10
927 ## tk_any                = 11
928 ## tk_TypeCode           = 12
929 ## tk_Principal          = 13
930 ## tk_objref             = 14
931 ## tk_struct             = 15
932 ## tk_union              = 16
933 ## tk_enum               = 17
934 ## tk_string             = 18
935 ## tk_sequence           = 19
936 ## tk_array              = 20
937 ## tk_alias              = 21
938 ## tk_except             = 22
939 ## tk_longlong           = 23
940 ## tk_ulonglong          = 24
941 ## tk_longdouble         = 25
942 ## tk_wchar              = 26
943 ## tk_wstring            = 27
944 ## tk_fixed              = 28
945 ## tk_value              = 29
946 ## tk_value_box          = 30
947 ## tk_native             = 31
948 ## tk_abstract_interface = 32
949
950
951     #
952     # getCDR()
953     #
954     # This is the main "iterator" function. It takes a node, and tries to output
955     # a get_CDR_XXX accessor method(s). It can call itself multiple times
956     # if I find nested structures etc.
957     #
958
959     def getCDR3(self,type,name="fred"):
960
961         pt = type.unalias().kind()      # param CDR type
962         pn = name                       # param name
963
964         if self.DEBUG:
965             print "XXX getCDR3: kind = " , pt
966
967         if pt == idltype.tk_ulong:
968             self.get_CDR_ulong(pn)
969         elif pt == idltype.tk_longlong:
970             self.get_CDR_longlong(pn)
971         elif pt == idltype.tk_ulonglong:
972             self.get_CDR_ulonglong(pn)
973         elif pt ==  idltype.tk_void:
974             self.get_CDR_void(pn)
975         elif pt ==  idltype.tk_short:
976             self.get_CDR_short(pn)
977         elif pt ==  idltype.tk_long:
978             self.get_CDR_long(pn)
979         elif pt ==  idltype.tk_ushort:
980             self.get_CDR_ushort(pn)
981         elif pt ==  idltype.tk_float:
982             self.get_CDR_float(pn)
983         elif pt ==  idltype.tk_double:
984             self.get_CDR_double(pn)
985         elif pt == idltype.tk_fixed:
986             self.get_CDR_fixed(type.unalias(),pn)
987         elif pt ==  idltype.tk_boolean:
988             self.get_CDR_boolean(pn)
989         elif pt ==  idltype.tk_char:
990             self.get_CDR_char(pn)
991         elif pt ==  idltype.tk_octet:
992             self.get_CDR_octet(pn)
993         elif pt ==  idltype.tk_any:
994             self.get_CDR_any(pn)
995         elif pt ==  idltype.tk_string:
996             self.get_CDR_string(pn)
997         elif pt ==  idltype.tk_wstring:
998             self.get_CDR_wstring(pn)
999         elif pt ==  idltype.tk_wchar:
1000             self.get_CDR_wchar(pn)
1001         elif pt ==  idltype.tk_enum:
1002             #print type.decl()
1003             self.get_CDR_enum(pn,type)
1004             #self.get_CDR_enum(pn)
1005
1006         elif pt ==  idltype.tk_struct:
1007             self.get_CDR_struct(type,pn)
1008         elif pt ==  idltype.tk_TypeCode: # will I ever get here ?
1009             self.get_CDR_TypeCode(pn)
1010         elif pt == idltype.tk_sequence and \
1011                  type.unalias().seqType().kind() == idltype.tk_octet:
1012             self.get_CDR_sequence_octet(type,pn)
1013         elif pt == idltype.tk_sequence:
1014             self.get_CDR_sequence(type,pn)
1015         elif pt == idltype.tk_objref:
1016             self.get_CDR_objref(type,pn)
1017         elif pt == idltype.tk_array:
1018             self.get_CDR_array(type,pn)
1019         elif pt == idltype.tk_union:
1020             self.get_CDR_union(type,pn)
1021         elif pt == idltype.tk_alias:
1022             if self.DEBUG:
1023                 print "XXXXX Alias type XXXXX " , type
1024             self.get_CDR_alias(type,pn)
1025         else:
1026             self.genWARNING("Unknown typecode = " + '%i ' % pt) # put comment in source code
1027
1028
1029     #
1030     # get_CDR_XXX methods are here ..
1031     #
1032     #
1033
1034
1035     def get_CDR_ulong(self,pn):
1036         self.st.out(self.template_get_CDR_ulong, varname=pn)
1037         self.addvar(self.c_u_octet4)
1038
1039     def get_CDR_short(self,pn):
1040         self.st.out(self.template_get_CDR_short, varname=pn)
1041         self.addvar(self.c_s_octet2)
1042
1043     def get_CDR_void(self,pn):
1044         self.st.out(self.template_get_CDR_void, varname=pn)
1045
1046     def get_CDR_long(self,pn):
1047         self.st.out(self.template_get_CDR_long, varname=pn)
1048         self.addvar(self.c_s_octet4)
1049
1050     def get_CDR_ushort(self,pn):
1051         self.st.out(self.template_get_CDR_ushort, varname=pn)
1052         self.addvar(self.c_u_octet2)
1053
1054     def get_CDR_float(self,pn):
1055         self.st.out(self.template_get_CDR_float, varname=pn)
1056         self.addvar(self.c_float)
1057
1058     def get_CDR_double(self,pn):
1059         self.st.out(self.template_get_CDR_double, varname=pn)
1060         self.addvar(self.c_double)
1061
1062     def get_CDR_longlong(self,pn):
1063         self.st.out(self.template_get_CDR_longlong, varname=pn)
1064         self.addvar(self.c_s_octet8)
1065
1066     def get_CDR_ulonglong(self,pn):
1067         self.st.out(self.template_get_CDR_ulonglong, varname=pn)
1068         self.addvar(self.c_u_octet8)
1069
1070     def get_CDR_boolean(self,pn):
1071         self.st.out(self.template_get_CDR_boolean, varname=pn)
1072         self.addvar(self.c_u_octet1)
1073
1074     def get_CDR_fixed(self,type,pn):
1075         if self.DEBUG:
1076             print "XXXX calling get_CDR_fixed, type = ", type
1077             print "XXXX calling get_CDR_fixed, type.digits() = ", type.digits()
1078             print "XXXX calling get_CDR_fixed, type.scale() = ", type.scale()
1079
1080         string_digits = '%i ' % type.digits() # convert int to string
1081         string_scale  = '%i ' % type.scale()  # convert int to string
1082         string_length  = '%i ' % self.dig_to_len(type.digits())  # how many octets to hilight for a number of digits
1083
1084         self.st.out(self.template_get_CDR_fixed, varname=pn, digits=string_digits, scale=string_scale, length=string_length )
1085         self.addvar(self.c_seq)
1086
1087
1088     def get_CDR_char(self,pn):
1089         self.st.out(self.template_get_CDR_char, varname=pn)
1090         self.addvar(self.c_u_octet1)
1091
1092     def get_CDR_octet(self,pn):
1093         self.st.out(self.template_get_CDR_octet, varname=pn)
1094         self.addvar(self.c_u_octet1)
1095
1096     def get_CDR_any(self,pn):
1097         self.st.out(self.template_get_CDR_any, varname=pn)
1098
1099     def get_CDR_enum(self,pn,type):
1100         #self.st.out(self.template_get_CDR_enum, varname=pn)
1101         sname = self.namespace(type.unalias(), "_")
1102         self.st.out(self.template_get_CDR_enum_symbolic, valstringarray=sname)
1103
1104
1105         self.addvar(self.c_u_octet4)
1106
1107     def get_CDR_string(self,pn):
1108         self.st.out(self.template_get_CDR_string, varname=pn)
1109         self.addvar(self.c_u_octet4)
1110         self.addvar(self.c_seq)
1111
1112     def get_CDR_wstring(self,pn):
1113         self.st.out(self.template_get_CDR_wstring, varname=pn)
1114         self.addvar(self.c_u_octet4)
1115         self.addvar(self.c_seq)
1116
1117     def get_CDR_wchar(self,pn):
1118         self.st.out(self.template_get_CDR_wchar, varname=pn)
1119         self.addvar(self.c_s_octet1)
1120         self.addvar(self.c_seq)
1121
1122     def get_CDR_TypeCode(self,pn):
1123         self.st.out(self.template_get_CDR_TypeCode, varname=pn)
1124         self.addvar(self.c_u_octet4)
1125
1126     def get_CDR_objref(self,type,pn):
1127         self.st.out(self.template_get_CDR_object)
1128
1129     def get_CDR_sequence_len(self,pn):
1130         self.st.out(self.template_get_CDR_sequence_length, seqname=pn)
1131         self.addvar(self.c_u_octet4)
1132
1133
1134
1135     def get_CDR_union(self,type,pn):
1136         if self.DEBUG:
1137             print "XXX Union type =" , type, " pn = ",pn
1138             print "XXX Union type.decl()" , type.decl()
1139             print "XXX Union Scoped Name" , type.scopedName()
1140
1141        #  If I am a typedef union {..}; node then find the union node
1142
1143         if isinstance(type.decl(), idlast.Declarator):
1144             ntype = type.decl().alias().aliasType().decl()
1145         else:
1146             ntype = type.decl()         # I am a union node
1147
1148         if self.DEBUG:
1149             print "XXX Union ntype =" , ntype
1150
1151         sname = self.namespace(ntype, "_")
1152         self.st.out(self.template_union_start, name=sname )
1153
1154         # Output a call to the union helper function so I can handle recursive union also.
1155
1156         self.st.out(self.template_decode_union,name=sname)
1157
1158         self.st.out(self.template_union_end, name=sname )
1159
1160
1161     #
1162     # Code to generate Union Helper functions
1163     #
1164     # in: un - a union node
1165     #
1166     #
1167
1168
1169     def genUnionHelper(self,un):
1170         if self.DEBUG:
1171             print "XXX Union type =" , un
1172             print "XXX Union type.decl()" , un.decl()
1173             print "XXX Union Scoped Name" , un.scopedName()
1174
1175         sname = self.namespace(un, "_")
1176         self.curr_sname = sname         # update current opnode/exnode/stnode/unnode scoped name
1177         if not self.fn_hash_built:
1178             self.fn_hash[sname] = []        # init empty list as val for this sname key
1179                                             # but only if the fn_hash is not already built
1180
1181         self.st.out(self.template_union_helper_function_start, sname=sname, unname=un.repoId())
1182         self.st.inc_indent()
1183
1184         self.st.out(self.template_helper_function_vars_start)
1185         self.dumpCvars(sname)
1186         self.st.out(self.template_helper_function_vars_end )
1187
1188         self.st.out(self.template_union_helper_function_get_endianess)
1189
1190         st = un.switchType().unalias() # may be typedef switch type, so find real type
1191
1192         self.st.out(self.template_comment_union_code_start, uname=un.repoId() )
1193
1194         self.getCDR3(st,un.identifier());
1195
1196         # Depending on what kind of discriminant I come accross (enum,integer,char,
1197         # short, boolean), make sure I cast the return value of the get_XXX accessor
1198         # to an appropriate value. Omniidl idlast.CaseLabel.value() accessor will
1199         # return an integer, or an Enumerator object that is then converted to its
1200         # integer equivalent.
1201         #
1202         #
1203         # NOTE - May be able to skip some of this stuff, but leave it in for now -- FS
1204         #
1205
1206         if (st.kind() == idltype.tk_enum):
1207             std = st.decl()
1208             self.st.out(self.template_comment_union_code_discriminant, uname=std.repoId() )
1209             self.st.out(self.template_union_code_save_discriminant_enum, discname=un.identifier() )
1210             self.addvar(self.c_s_disc + un.identifier() + ";")
1211
1212         elif (st.kind() == idltype.tk_long):
1213             self.st.out(self.template_union_code_save_discriminant_long, discname=un.identifier() )
1214             self.addvar(self.c_s_disc + un.identifier() + ";")
1215
1216         elif (st.kind() == idltype.tk_ulong):
1217             self.st.out(self.template_union_code_save_discriminant_ulong, discname=un.identifier() )
1218             self.addvar(self.c_s_disc + un.identifier() + ";")
1219
1220         elif (st.kind() == idltype.tk_short):
1221             self.st.out(self.template_union_code_save_discriminant_short, discname=un.identifier() )
1222             self.addvar(self.c_s_disc + un.identifier() + ";")
1223
1224         elif (st.kind() == idltype.tk_ushort):
1225             self.st.out(self.template_union_code_save_discriminant_ushort, discname=un.identifier() )
1226             self.addvar(self.c_s_disc + un.identifier() + ";")
1227
1228         elif (st.kind() == idltype.tk_boolean):
1229             self.st.out(self.template_union_code_save_discriminant_boolean, discname=un.identifier()  )
1230             self.addvar(self.c_s_disc + un.identifier() + ";")
1231
1232         elif (st.kind() == idltype.tk_char):
1233             self.st.out(self.template_union_code_save_discriminant_char, discname=un.identifier() )
1234             self.addvar(self.c_s_disc + un.identifier() + ";")
1235
1236         else:
1237             print "XXX Unknown st.kind() = ", st.kind()
1238
1239         #
1240         # Loop over all cases in this union
1241         #
1242
1243         for uc in un.cases():           # for all UnionCase objects in this union
1244             for cl in uc.labels():      # for all Caselabel objects in this UnionCase
1245
1246                 # get integer value, even if discriminant is
1247                 # an Enumerator node
1248
1249                 if isinstance(cl.value(),idlast.Enumerator):
1250                     if self.DEBUG:
1251                         print "XXX clv.identifier()", cl.value().identifier()
1252                         print "XXX clv.repoId()", cl.value().repoId()
1253                         print "XXX clv.scopedName()", cl.value().scopedName()
1254
1255                     # find index of enumerator in enum declaration
1256                     # eg: RED is index 0 in enum Colors { RED, BLUE, GREEN }
1257
1258                     clv = self.valFromEnum(std,cl.value())
1259
1260                 else:
1261                     clv = cl.value()
1262
1263                 #print "XXX clv = ",clv
1264
1265                 #
1266                 # if char, dont convert to int, but put inside single quotes so that it is understood by C.
1267                 # eg: if (disc == 'b')..
1268                 #
1269                 # TODO : handle \xxx chars generically from a function or table lookup rather than
1270                 #        a whole bunch of "if" statements. -- FS
1271
1272
1273                 if (st.kind() == idltype.tk_char):
1274                     if (clv == '\n'):          # newline
1275                         string_clv = "'\\n'"
1276                     elif (clv == '\t'):        # tab
1277                         string_clv = "'\\t'"
1278                     else:
1279                         string_clv = "'" + clv + "'"
1280                 else:
1281                     string_clv = '%i ' % clv
1282
1283                 #
1284                 # If default case, then skp comparison with discriminator
1285                 #
1286
1287                 if not cl.default():
1288                     self.st.out(self.template_comment_union_code_label_compare_start, discname=un.identifier(),labelval=string_clv )
1289                     self.st.inc_indent()
1290                 else:
1291                     self.st.out(self.template_comment_union_code_label_default_start  )
1292
1293
1294                 self.getCDR3(uc.caseType(),uc.declarator().identifier())
1295
1296                 if not cl.default():
1297                     self.st.dec_indent()
1298                     self.st.out(self.template_comment_union_code_label_compare_end )
1299                 else:
1300                     self.st.out(self.template_comment_union_code_label_default_end  )
1301
1302         self.st.dec_indent()
1303         self.st.out(self.template_union_helper_function_end)
1304
1305
1306
1307     #
1308     # Currently, get_CDR_alias is geared to finding typdef
1309     #
1310
1311     def get_CDR_alias(self,type,pn):
1312         if self.DEBUG:
1313             print "XXX get_CDR_alias, type = " ,type , " pn = " , pn
1314             print "XXX get_CDR_alias, type.decl() = " ,type.decl()
1315             print "XXX get_CDR_alias, type.decl().alias() = " ,type.decl().alias()
1316
1317         decl = type.decl()              # get declarator object
1318
1319         if (decl.sizes()):        # a typedef array
1320             indices = self.get_indices_from_sizes(decl.sizes())
1321             string_indices = '%i ' % indices # convert int to string
1322             self.st.out(self.template_get_CDR_array_comment, aname=pn, asize=string_indices)
1323
1324             self.st.out(self.template_get_CDR_array_start, aname=pn, aval=string_indices)
1325             self.addvar(self.c_i + pn + ";")
1326             self.st.inc_indent()
1327             self.getCDR3(type.decl().alias().aliasType(),  pn )
1328
1329             self.st.dec_indent()
1330             self.st.out(self.template_get_CDR_array_end)
1331
1332
1333         else:                           # a simple typdef
1334             if self.DEBUG:
1335                 print "XXX get_CDR_alias, type = " ,type , " pn = " , pn
1336                 print "XXX get_CDR_alias, type.decl() = " ,type.decl()
1337
1338             self.getCDR3(type, decl.identifier() )
1339
1340
1341
1342
1343
1344
1345     #
1346     # Handle structs, including recursive
1347     #
1348
1349     def get_CDR_struct(self,type,pn):
1350
1351         #  If I am a typedef struct {..}; node then find the struct node
1352
1353         if isinstance(type.decl(), idlast.Declarator):
1354             ntype = type.decl().alias().aliasType().decl()
1355         else:
1356             ntype = type.decl()         # I am a struct node
1357
1358         sname = self.namespace(ntype, "_")
1359         self.st.out(self.template_structure_start, name=sname )
1360
1361         # Output a call to the struct helper function so I can handle recursive structs also.
1362
1363         self.st.out(self.template_decode_struct,name=sname)
1364
1365         self.st.out(self.template_structure_end, name=sname )
1366
1367     #
1368     # genStructhelper()
1369     #
1370     # Generate private helper functions to decode a struct
1371     #
1372     # in: stnode ( a struct node)
1373     #
1374
1375     def genStructHelper(self,st):
1376         if self.DEBUG:
1377             print "XXX genStructHelper"
1378
1379         sname = self.namespace(st, "_")
1380         self.curr_sname = sname         # update current opnode/exnode/stnode scoped name
1381         if not self.fn_hash_built:
1382             self.fn_hash[sname] = []        # init empty list as val for this sname key
1383                                             # but only if the fn_hash is not already built
1384
1385         self.st.out(self.template_struct_helper_function_start, sname=sname, stname=st.repoId())
1386         self.st.inc_indent()
1387
1388         self.st.out(self.template_helper_function_vars_start)
1389         self.dumpCvars(sname)
1390         self.st.out(self.template_helper_function_vars_end )
1391
1392         self.st.out(self.template_struct_helper_function_get_endianess)
1393
1394         for m in st.members():
1395             for decl in m.declarators():
1396                 if decl.sizes():        # an array
1397                     indices = self.get_indices_from_sizes(decl.sizes())
1398                     string_indices = '%i ' % indices # convert int to string
1399                     self.st.out(self.template_get_CDR_array_comment, aname=decl.identifier(), asize=string_indices)
1400                     self.st.out(self.template_get_CDR_array_start, aname=decl.identifier(), aval=string_indices)
1401                     self.addvar(self.c_i + decl.identifier() + ";")
1402
1403                     self.st.inc_indent()
1404                     self.getCDR3(m.memberType(), st.identifier() + "_" + decl.identifier() )
1405                     self.st.dec_indent()
1406                     self.st.out(self.template_get_CDR_array_end)
1407
1408
1409                 else:
1410                     self.getCDR3(m.memberType(), st.identifier() + "_" + decl.identifier() )
1411
1412         self.st.dec_indent()
1413         self.st.out(self.template_struct_helper_function_end)
1414
1415
1416
1417
1418
1419     #
1420     # Generate code to access a sequence of a type
1421     #
1422
1423
1424     def get_CDR_sequence(self,type, pn):
1425         self.st.out(self.template_get_CDR_sequence_length, seqname=pn )
1426         self.st.out(self.template_get_CDR_sequence_loop_start, seqname=pn )
1427         self.addvar(self.c_i_lim + pn + ";" )
1428         self.addvar(self.c_i + pn + ";")
1429
1430         self.st.inc_indent()
1431         self.getCDR3(type.unalias().seqType(), pn ) # and start all over with the type
1432         self.st.dec_indent()
1433
1434         self.st.out(self.template_get_CDR_sequence_loop_end)
1435
1436
1437     #
1438     # Generate code to access a sequence of octet
1439     #
1440
1441     def get_CDR_sequence_octet(self,type, pn):
1442         self.st.out(self.template_get_CDR_sequence_length, seqname=pn)
1443         self.st.out(self.template_get_CDR_sequence_octet, seqname=pn)
1444         self.addvar(self.c_i_lim + pn + ";")
1445         self.addvar("gchar * binary_seq_" + pn + ";")
1446         self.addvar("gchar * text_seq_" + pn + ";")
1447
1448
1449     #
1450     # Generate code to access arrays,
1451     #
1452     # This is handled elsewhere. Arrays are either typedefs or in
1453     # structs
1454     #
1455     # TODO - Remove this
1456     #
1457
1458     def get_CDR_array(self,type, decl):
1459         if self.DEBUG:
1460             print "XXX get_CDR_array called "
1461             print "XXX array size = " ,decl.sizes()
1462
1463
1464    #
1465    # namespace()
1466    #
1467    # in - op node
1468    #
1469    # out - scoped operation name, using sep character instead of "::"
1470    #
1471    # eg: Penguin::Echo::echoWString => Penguin_Echo_echoWString if sep = "_"
1472    #
1473    #
1474
1475     def namespace(self,node,sep):
1476         sname = string.replace(idlutil.ccolonName(node.scopedName()), '::', sep)
1477         #print "XXX namespace: sname = " + sname
1478         return sname
1479
1480
1481     #
1482     # generate code for plugin initialisation
1483     #
1484
1485     def gen_plugin_register(self):
1486         self.st.out(self.template_plugin_register, description=self.description, protocol_name=self.protoname, dissector_name=self.dissname)
1487
1488     #
1489     # generate  register_giop_user_module code, and register only
1490     # unique interfaces that contain operations. Also output
1491     # a heuristic register in case we want to use that.
1492     #
1493     # TODO - make this a command line option
1494     #
1495     # -e explicit
1496     # -h heuristic
1497     #
1498
1499
1500
1501     def gen_proto_reg_handoff(self, oplist):
1502
1503         self.st.out(self.template_proto_reg_handoff_start, dissector_name=self.dissname)
1504         self.st.inc_indent()
1505
1506         for iname in self.get_intlist(oplist):
1507             self.st.out(self.template_proto_reg_handoff_body, dissector_name=self.dissname, protocol_name=self.protoname, interface=iname )
1508
1509         self.st.out(self.template_proto_reg_handoff_heuristic, dissector_name=self.dissname,  protocol_name=self.protoname)
1510         self.st.dec_indent()
1511
1512         self.st.out(self.template_proto_reg_handoff_end)
1513
1514
1515
1516     #
1517     # generate  proto_register_<protoname> code,
1518     #
1519
1520
1521     def gen_proto_register(self):
1522         self.st.out(self.template_proto_register, description=self.description, protocol_name=self.protoname, dissector_name=self.dissname)
1523
1524
1525     #
1526     # in - oplist[]
1527     #
1528     # out - a list of unique interface names. This will be used in
1529     # register_giop_user_module(dissect_giop_auto, "TEST IDL", "Penguin/Echo" );   so the operation
1530     # name must be removed from the scope. And we also only want unique interfaces.
1531     #
1532
1533     def get_intlist(self,oplist):
1534         int_hash = {}                   # holds a hash of unique interfaces
1535         for op in oplist:
1536             sc = op.scopedName()        # eg: penguin,tux,bite
1537             sc1 = sc[:-1]               # drop last entry
1538             sn = idlutil.slashName(sc1)         # penguin/tux
1539             if not int_hash.has_key(sn):
1540                 int_hash[sn] = 0;       # dummy val, but at least key is unique
1541         ret = int_hash.keys()
1542         ret.sort()
1543         return ret
1544
1545
1546
1547     #
1548     # in - oplist[]
1549     #
1550     # out - a list of exception nodes (unique). This will be used in
1551     # to generate dissect_exception_XXX functions.
1552     #
1553
1554
1555
1556     def get_exceptionList(self,oplist):
1557         ex_hash = {}                   # holds a hash of unique exceptions.
1558         for op in oplist:
1559             for ex in op.raises():
1560                 if not ex_hash.has_key(ex):
1561                     ex_hash[ex] = 0; # dummy val, but at least key is unique
1562                     if self.DEBUG:
1563                         print "XXX Exception = " + ex.identifier()
1564         ret = ex_hash.keys()
1565         ret.sort()
1566         return ret
1567
1568
1569
1570     #
1571     # Simple function to take a list of array sizes and find the
1572     # total number of elements
1573     #
1574     #
1575     # eg: temp[4][3] = 12 elements
1576     #
1577
1578     def get_indices_from_sizes(self,sizelist):
1579         val = 1;
1580         for i in sizelist:
1581             val = val * i
1582
1583         return val
1584
1585     #
1586     # Determine how many octets contain requested number
1587     # of digits for an "fixed" IDL type  "on the wire"
1588     #
1589
1590     def dig_to_len(self,dignum):
1591         return (dignum/2) + 1
1592
1593
1594
1595     #
1596     # Output some TODO comment
1597     #
1598
1599
1600     def genTODO(self,message):
1601         self.st.out(self.template_debug_TODO, message=message)
1602
1603     #
1604     # Output some WARNING comment
1605     #
1606
1607
1608     def genWARNING(self,message):
1609         self.st.out(self.template_debug_WARNING, message=message)
1610
1611     #
1612     # Templates for C code
1613     #
1614
1615     template_comment_operations_start = """\
1616 /*
1617  * IDL Operations Start
1618  */
1619  """
1620     template_operations_declare = """static const char @sname@_op[] = \"@opname@\" ;"""
1621
1622     template_comment_operations_end = """
1623 /*
1624  * IDL Operations End
1625  */
1626 """
1627     template_helper_function_comment = """\
1628 /*
1629  * @repoid@
1630  */
1631 """
1632     template_helper_function_vars_start = """
1633 /* Operation specific Variable declarations Begin */
1634 """
1635     template_helper_function_vars_end = """
1636 /* Operation specific Variable declarations End */
1637 """
1638     template_helper_function_start = """\
1639 static void decode_@sname@(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, int *offset _U_, MessageHeader *header, gchar *operation _U_) {
1640
1641     gboolean stream_is_big_endian;          /* big endianess */
1642 """
1643     template_helper_function_end = """\
1644 }
1645 """
1646     #
1647     # proto_reg_handoff() templates
1648     #
1649
1650     template_proto_reg_handoff_start = """
1651 /* register me as handler for these interfaces */
1652
1653 void proto_register_handoff_giop_@dissector_name@(void) {
1654
1655 """
1656     template_proto_reg_handoff_body = """
1657 /* Register for Explicit Dissection */
1658
1659 register_giop_user_module(dissect_@dissector_name@, \"@protocol_name@\", \"@interface@\", proto_@dissector_name@ );     /* explicit dissector */
1660 """
1661     template_proto_reg_handoff_heuristic = """
1662 /* Register for Heuristic Dissection */
1663
1664 register_giop_user(dissect_@dissector_name@, \"@protocol_name@\" ,proto_@dissector_name@);     /* heuristic dissector */
1665 """
1666     template_proto_reg_handoff_end = """
1667 }
1668 """
1669
1670     #
1671     # Initialize the protocol
1672     #
1673
1674     template_protocol = """
1675 /* Initialise the protocol and subtree pointers */
1676
1677 static int proto_@dissector_name@ = -1;
1678
1679 static gint ett_@dissector_name@ = -1;
1680 """
1681     #
1682     # Initialize the boundary Alignment
1683     #
1684
1685     template_init_boundary = """
1686 /* Initialise the initial Alignment */
1687
1688 static guint32  boundary = GIOP_HEADER_SIZE;  /* initial value */
1689 """
1690     #
1691     # Initialize the Registered fields
1692     #
1693
1694     template_registered_fields = """
1695
1696 /* Initialise the Registered fields */
1697
1698 /* TODO - Use registered fields */
1699 """
1700     #
1701     # plugin_register and plugin_reg_handoff templates
1702     #
1703
1704     template_plugin_register = """
1705 #ifndef ENABLE_STATIC
1706
1707 G_MODULE_EXPORT void
1708 plugin_register(void)
1709 {
1710    if (proto_@dissector_name@ == -1) {
1711      proto_register_giop_@dissector_name@();
1712    }
1713 }
1714
1715 G_MODULE_EXPORT void
1716 plugin_reg_handoff(void){
1717    proto_register_handoff_giop_@dissector_name@();
1718 }
1719 #endif
1720 """
1721     #
1722     # proto_register_<dissector name>(void) templates
1723     #
1724
1725     template_proto_register = """
1726
1727 /* Register the protocol with Ethereal */
1728
1729 void proto_register_giop_@dissector_name@(void) {
1730
1731    /* setup list of header fields */
1732
1733 #if 0
1734    static hf_register_info hf[] = {
1735
1736       /* no fields yet */
1737
1738    };
1739 #endif
1740
1741    /* setup protocol subtree array */
1742
1743    static gint *ett[] = {
1744       &ett_@dissector_name@,
1745    };
1746
1747    /* Register the protocol name and description */
1748
1749    proto_@dissector_name@ = proto_register_protocol(\"@description@\" , \"@protocol_name@\", \"giop-@dissector_name@\" );
1750
1751 #if 0
1752    proto_register_field_array(proto_@dissector_name@, hf, array_length(hf));
1753 #endif
1754    proto_register_subtree_array(ett,array_length(ett));
1755
1756 }
1757 """
1758     #
1759     # template for delegation code
1760     #
1761     
1762     template_op_delegate_code = """\
1763 if (strcmp(operation, @sname@_op) == 0
1764     && (!idlname || strcmp(idlname, \"@interface@\") == 0)) {
1765    tree = start_dissecting(tvb, pinfo, ptree, offset);
1766    decode_@sname@(tvb, pinfo, tree, offset, header, operation);
1767    return TRUE;
1768 }
1769 """
1770     #
1771     # Templates for the helper functions
1772     #
1773     #
1774     #
1775
1776     template_helper_switch_msgtype_start = """\
1777 stream_is_big_endian = is_big_endian(header);
1778
1779 switch(header->message_type) {
1780 """
1781     template_helper_switch_msgtype_default_start = """\
1782 default:
1783
1784     /* Unknown GIOP Exception */
1785
1786     g_warning("Unknown GIOP Message");
1787 """
1788     template_helper_switch_msgtype_default_end = """\
1789 break;
1790 """
1791     template_helper_switch_msgtype_end = """\
1792 } /* switch(header->message_type) */
1793 """
1794     template_helper_switch_msgtype_request_start = """\
1795 case Request:
1796 """
1797     template_helper_switch_msgtype_request_end = """\
1798 break;
1799 """
1800     template_helper_switch_msgtype_reply_start = """\
1801 case Reply:
1802 """
1803     template_helper_switch_msgtype_reply_no_exception_start = """\
1804 case NO_EXCEPTION:
1805 """
1806     template_helper_switch_msgtype_reply_no_exception_end = """\
1807 break;
1808 """    
1809     template_helper_switch_msgtype_reply_user_exception_start = """\
1810 case USER_EXCEPTION:
1811 """
1812     template_helper_switch_msgtype_reply_user_exception_end = """\
1813 break;
1814 """
1815     template_helper_switch_msgtype_reply_default_start = """\
1816 default:
1817
1818     /* Unknown Exception */
1819
1820     g_warning("Unknown Exception ");
1821 """
1822     template_helper_switch_msgtype_reply_default_end = """\
1823     break;
1824 """
1825     template_helper_switch_msgtype_reply_end = """\
1826 break;
1827 """
1828     template_helper_switch_msgtype_default_start = """\
1829 default:
1830
1831     /* Unknown GIOP Message */
1832
1833     g_warning("Unknown GIOP Message");
1834 """
1835     template_helper_switch_msgtype_default_end = """\
1836     break;
1837 """
1838     template_helper_switch_rep_status_start = """\
1839 switch(header->rep_status) {
1840 """
1841     template_helper_switch_rep_status_default_start = """\
1842 default:
1843
1844     /* Unknown Reply Status */
1845
1846     g_warning("Unknown Reply Status");
1847 """
1848     template_helper_switch_rep_status_default_end = """\
1849     break;
1850 """
1851     template_helper_switch_rep_status_end = """\
1852
1853 }   /* switch(header->message_type) */
1854
1855 break;
1856 """
1857     
1858     #
1859     # Templates for get_CDR_xxx accessors
1860     #
1861
1862     template_get_CDR_ulong = """\
1863 u_octet4 = get_CDR_ulong(tvb,offset,stream_is_big_endian, boundary);
1864 if (tree) {
1865    proto_tree_add_text(tree,tvb,*offset-4,4,"@varname@ = %u",u_octet4);
1866 }
1867 """
1868     template_get_CDR_short = """\
1869 s_octet2 = get_CDR_short(tvb,offset,stream_is_big_endian, boundary);
1870 if (tree) {
1871    proto_tree_add_text(tree,tvb,*offset-2,2,"@varname@ = %i",s_octet2);
1872 }
1873 """
1874     template_get_CDR_void = """\
1875 /* Function returns void */
1876 """
1877     template_get_CDR_long = """\
1878 s_octet4 = get_CDR_long(tvb,offset,stream_is_big_endian, boundary);
1879 if (tree) {
1880    proto_tree_add_text(tree,tvb,*offset-4,4,"@varname@ = %i",s_octet4);
1881 }
1882 """
1883     template_get_CDR_ushort = """\
1884 u_octet2 = get_CDR_ushort(tvb,offset,stream_is_big_endian, boundary);
1885 if (tree) {
1886    proto_tree_add_text(tree,tvb,*offset-2,2,"@varname@ = %u",u_octet2);
1887 }
1888 """
1889     template_get_CDR_float = """\
1890 my_float = get_CDR_float(tvb,offset,stream_is_big_endian, boundary);
1891 if (tree) {
1892    proto_tree_add_text(tree,tvb,*offset-4,4,"@varname@ = %.6e",my_float);
1893 }
1894 """
1895     template_get_CDR_double = """\
1896 my_double = get_CDR_double(tvb,offset,stream_is_big_endian, boundary);
1897 if (tree) {
1898    proto_tree_add_text(tree,tvb,*offset-8,8,"@varname@ = %.15e",my_double);
1899 }
1900 """
1901     template_get_CDR_longlong = """\
1902 s_octet8 = get_CDR_long_long(tvb,offset,stream_is_big_endian, boundary);
1903 if (tree) {
1904    proto_tree_add_text(tree,tvb,*offset-8,8,"@varname@ = %" PRId64,s_octet8);
1905 }
1906 """
1907     template_get_CDR_ulonglong = """\
1908 u_octet8 = get_CDR_ulong_long(tvb,offset,stream_is_big_endian, boundary);
1909 if (tree) {
1910    proto_tree_add_text(tree,tvb,*offset-8,8,"@varname@ = %" PRIu64,u_octet8);
1911 }
1912 """
1913     template_get_CDR_boolean = """\
1914 u_octet1 = get_CDR_boolean(tvb,offset);
1915 if (tree) {
1916    proto_tree_add_text(tree,tvb,*offset-1,1,"@varname@ = %u",u_octet1);
1917 }
1918 """
1919     template_get_CDR_char = """\
1920 u_octet1 = get_CDR_char(tvb,offset);
1921 if (tree) {
1922    proto_tree_add_text(tree,tvb,*offset-1,1,"@varname@ = %u",u_octet1);
1923 }
1924 """
1925     template_get_CDR_octet = """\
1926 u_octet1 = get_CDR_octet(tvb,offset);
1927 if (tree) {
1928    proto_tree_add_text(tree,tvb,*offset-1,1,"@varname@ = %u",u_octet1);
1929 }
1930 """
1931     template_get_CDR_any = """\
1932 get_CDR_any(tvb,tree,offset,stream_is_big_endian, boundary, header);
1933 """
1934     template_get_CDR_fixed = """\
1935 get_CDR_fixed(tvb, &seq, offset, @digits@, @scale@);
1936 if (tree) {
1937    proto_tree_add_text(tree,tvb,*offset-@length@, @length@, "@varname@ < @digits@, @scale@> = %s",seq);
1938 }
1939
1940 g_free(seq);          /*  free buffer  */
1941 seq = NULL;
1942 """
1943     template_get_CDR_enum_symbolic = """\
1944
1945 u_octet4 = get_CDR_enum(tvb,offset,stream_is_big_endian, boundary);
1946 if (tree) {
1947    proto_tree_add_text(tree,tvb,*offset-4,4,"Enum value = %u (%s)",u_octet4,val_to_str(u_octet4,@valstringarray@,"Unknown Enum Value"));
1948 }
1949 """
1950     template_get_CDR_string = """\
1951 u_octet4 = get_CDR_string(tvb, &seq, offset, stream_is_big_endian, boundary);
1952 if (tree) {
1953    proto_tree_add_text(tree,tvb,*offset-u_octet4,u_octet4,"@varname@ (%u) = %s",
1954       u_octet4, (u_octet4 > 0) ? seq : \"\");
1955 }
1956
1957 g_free(seq);          /*  free buffer  */
1958 seq = NULL;
1959 """
1960     template_get_CDR_wstring = """\
1961 u_octet4 = get_CDR_wstring(tvb, &seq, offset, stream_is_big_endian, boundary, header);
1962 if (tree) {
1963    proto_tree_add_text(tree,tvb,*offset-u_octet4,u_octet4,"@varname@ (%u) = %s",
1964       u_octet4, (u_octet4 > 0) ? seq : \"\");
1965 }
1966
1967 g_free(seq);          /*  free buffer  */
1968 seq = NULL;
1969 """
1970     template_get_CDR_wchar = """\
1971 s_octet1 = get_CDR_wchar(tvb, &seq, offset, header);
1972 if (tree) {
1973     if (s_octet1 > 0)
1974         proto_tree_add_text(tree,tvb,*offset-1-s_octet1,1,"length = %u",s_octet1);
1975
1976     if (s_octet1 < 0)
1977         s_octet1 = -s_octet1;
1978
1979     if (s_octet1 > 0)
1980         proto_tree_add_text(tree,tvb,*offset-s_octet1,s_octet1,"@varname@ = %s",seq);
1981
1982 }
1983
1984 g_free(seq);          /*  free buffer  */
1985 seq = NULL;
1986 """
1987     template_get_CDR_TypeCode = """\
1988 u_octet4 = get_CDR_typeCode(tvb, tree, offset, stream_is_big_endian, boundary, header);
1989
1990 """
1991
1992     template_get_CDR_object = """\
1993 get_CDR_object(tvb, pinfo, tree, offset, stream_is_big_endian, boundary);
1994
1995 """
1996     template_get_CDR_sequence_length = """\
1997 u_octet4_loop_@seqname@ = get_CDR_ulong(tvb, offset, stream_is_big_endian, boundary);
1998 if (tree) {
1999    proto_tree_add_text(tree,tvb,*offset-4, 4 ,"Seq length of @seqname@ = %u",u_octet4_loop_@seqname@);
2000 }
2001 """
2002     template_get_CDR_sequence_loop_start = """\
2003 for (i_@seqname@=0; i_@seqname@ < u_octet4_loop_@seqname@; i_@seqname@++) {
2004 """
2005     template_get_CDR_sequence_loop_end = """\
2006 }
2007 """
2008
2009     template_get_CDR_sequence_octet = """\
2010 if (u_octet4_loop_@seqname@ > 0 && tree) {
2011     get_CDR_octet_seq(tvb, &binary_seq_@seqname@, offset,
2012         u_octet4_loop_@seqname@);
2013     text_seq_@seqname@ = make_printable_string(binary_seq_@seqname@,
2014         u_octet4_loop_@seqname@);
2015     proto_tree_add_text(tree, tvb, *offset - u_octet4_loop_@seqname@,
2016         u_octet4_loop_@seqname@, \"@seqname@: %s\", text_seq_@seqname@);
2017     g_free(binary_seq_@seqname@);
2018     g_free(text_seq_@seqname@);
2019 }
2020 """
2021     template_get_CDR_array_start = """\
2022 for (i_@aname@=0; i_@aname@ < @aval@; i_@aname@++) {
2023 """
2024     template_get_CDR_array_end = """\
2025 }
2026 """
2027     template_get_CDR_array_comment = """\
2028 /* Array: @aname@[ @asize@]  */
2029 """
2030     template_structure_start = """\
2031 /*  Begin struct \"@name@\"  */
2032 """
2033     template_structure_end = """\
2034 /*  End struct \"@name@\"  */
2035 """
2036
2037     template_union_start = """\
2038 /*  Begin union \"@name@\"  */
2039 """
2040     template_union_end = """\
2041 /*  End union \"@name@\"  */
2042 """
2043
2044 #
2045 # Program Header Template
2046 #
2047
2048     template_Header = """\
2049 /* packet-@dissector_name@.c
2050  * Routines for IDL dissection
2051  *
2052  * Autogenerated from idl2eth
2053  * Copyright 2001 Frank Singleton <frank.singleton@@ericsson.com>
2054  */
2055
2056 """
2057
2058     template_ethereal_copyright = """\
2059 /*
2060  * Wireshark - Network traffic analyzer
2061  * By Gerald Combs
2062  * Copyright 1999 Gerald Combs
2063  */
2064
2065 """
2066
2067
2068
2069 #
2070 # GPL Template
2071 #
2072
2073
2074     template_GPL = """\
2075 /*
2076  * This program is free software; you can redistribute it and/or
2077  * modify it under the terms of the GNU General Public License
2078  * as published by the Free Software Foundation; either version 2
2079  * of the License, or (at your option) any later version.
2080  *
2081  * This program is distributed in the hope that it will be useful,
2082  * but WITHOUT ANY WARRANTY; without even the implied warranty of
2083  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2084  * GNU General Public License for more details.
2085  *
2086  * You should have received a copy of the GNU General Public License
2087  * along with this program; if not, write to the Free Software
2088  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
2089  */
2090 """
2091
2092 #
2093 # Includes template
2094 #
2095
2096     template_Includes = """\
2097
2098 #ifdef HAVE_CONFIG_H
2099 # include "config.h"
2100 #endif
2101
2102 #include <stdio.h>
2103 #include <stdlib.h>
2104 #include <gmodule.h>
2105
2106 #include <string.h>
2107 #include <glib.h>
2108 #include <epan/packet.h>
2109 #include <epan/proto.h>
2110 #include <epan/dissectors/packet-giop.h>
2111
2112 #ifndef ENABLE_STATIC
2113 G_MODULE_EXPORT const gchar version[] = "0.0.1";
2114 #endif
2115
2116 """
2117
2118
2119 #
2120 # Main dissector entry templates
2121 #
2122
2123     template_main_dissector_start = """\
2124 /*
2125  * Called once we accept the packet as being for us; it sets the
2126  * Protocol and Info columns and creates the top-level protocol
2127  * tree item.
2128  */
2129 static proto_tree *start_dissecting(tvbuff_t *tvb, packet_info *pinfo, proto_tree *ptree, int *offset) {
2130
2131     proto_item *ti = NULL;
2132     proto_tree *tree = NULL;            /* init later, inside if(tree) */
2133
2134     if (check_col(pinfo->cinfo, COL_PROTOCOL))
2135         col_set_str(pinfo->cinfo, COL_PROTOCOL, \"@disprot@\");
2136
2137     /*
2138      * Do not clear COL_INFO, as nothing is being written there by
2139      * this dissector yet. So leave it as is from the GIOP dissector.
2140      * TODO: add something useful to COL_INFO
2141      *  if (check_col(pinfo->cinfo, COL_INFO))
2142      *     col_clear(pinfo->cinfo, COL_INFO);
2143      */
2144
2145     if (ptree) {
2146         ti = proto_tree_add_item(ptree, proto_@dissname@, tvb, *offset, -1, FALSE);
2147         tree = proto_item_add_subtree(ti, ett_@dissname@);
2148     }
2149     return tree;
2150 }
2151
2152 static gboolean dissect_@dissname@(tvbuff_t *tvb, packet_info *pinfo, proto_tree *ptree, int *offset, MessageHeader *header, gchar *operation, gchar *idlname) {
2153
2154     gboolean be;                        /* big endianess */
2155     proto_tree *tree _U_;
2156
2157     be = is_big_endian(header);         /* get endianess - TODO use passed in stream_is_big_endian instead ? */
2158
2159     /* If we have a USER Exception, then decode it and return */
2160
2161     if ((header->message_type == Reply) && (header->rep_status == USER_EXCEPTION)) {
2162
2163        return decode_user_exception(tvb, pinfo, ptree, offset, header, operation);
2164
2165     }
2166 """
2167     template_main_dissector_switch_msgtype_start = """\
2168 switch(header->message_type) {
2169 """
2170     template_main_dissector_switch_msgtype_start_request_reply = """\
2171 case Request:
2172 case Reply:
2173 """
2174     template_main_dissector_switch_msgtype_end_request_reply = """\
2175
2176 break;
2177 """
2178     template_main_dissector_switch_msgtype_all_other_msgtype = """\
2179 case CancelRequest:
2180 case LocateRequest:
2181 case LocateReply:
2182 case CloseConnection:
2183 case MessageError:
2184 case Fragment:
2185    return FALSE;      /* not handled yet */
2186
2187 default:
2188    return FALSE;      /* not handled yet */
2189
2190 }   /* switch */
2191 """
2192     template_main_dissector_end = """\
2193
2194     return FALSE;
2195
2196 }  /* End of main dissector  */
2197 """
2198
2199
2200
2201
2202
2203
2204
2205 #-------------------------------------------------------------#
2206 #             Exception handling templates                    #
2207 #-------------------------------------------------------------#
2208
2209
2210
2211
2212
2213
2214
2215     template_exception_helpers_start = """\
2216 /*  Begin Exception Helper Functions  */
2217
2218 """
2219     template_exception_helpers_end = """\
2220
2221 /*  End Exception Helper Functions  */
2222 """
2223
2224
2225
2226 #
2227 # Templates for declaration of string constants for user exceptions.
2228 #
2229
2230     template_comment_user_exceptions_string_declare_start = """\
2231 /*  Begin Exception (containing members) String  Declare  */
2232
2233 """
2234     template_user_exceptions_declare = """static const char user_exception_@sname@[] = \"@exname@\" ; """
2235
2236
2237     template_comment_user_exceptions_string_declare_end = """\
2238
2239 /*  End Exception (containing members) String Declare  */
2240 """
2241
2242
2243
2244
2245 #
2246 # template for Main delegator for exception handling
2247 #
2248
2249     template_main_exception_delegator_start = """\
2250 /*
2251  * Main delegator for exception handling
2252  *
2253  */
2254
2255 static gboolean decode_user_exception(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *ptree _U_, int *offset _U_, MessageHeader *header, gchar *operation _U_ ) {
2256
2257     gboolean be _U_;                        /* big endianess */
2258     proto_tree *tree _U_;
2259
2260     if (!header->exception_id)
2261         return FALSE;
2262 """
2263
2264
2265 #
2266 # template for exception delegation code body
2267 #
2268     template_ex_delegate_code = """\
2269 if (strcmp(header->exception_id, user_exception_@sname@) == 0) {
2270    tree = start_dissecting(tvb, pinfo, ptree, offset);
2271    decode_ex_@sname@(tvb, pinfo, tree, offset, header, operation);   /*  @exname@  */
2272    return TRUE;
2273 }
2274 """
2275
2276
2277 #
2278 # End of Main delegator for exception handling
2279 #
2280
2281     template_main_exception_delegator_end = """\
2282
2283
2284     return FALSE;    /* user exception not found */
2285
2286 }
2287 """
2288
2289 #
2290 # template for exception helper code
2291 #
2292
2293
2294     template_exception_helper_function_start = """\
2295 /* Exception = @exname@ */
2296
2297 static void decode_ex_@sname@(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, int *offset _U_, MessageHeader *header _U_, gchar *operation _U_) {
2298
2299     gboolean stream_is_big_endian;          /* big endianess */
2300 """
2301
2302
2303
2304     #
2305     # Template for the helper function
2306     # to get stream endianess from header
2307     #
2308
2309     template_exception_helper_function_get_endianess = """\
2310 stream_is_big_endian = is_big_endian(header);  /* get stream endianess */
2311 """
2312     template_exception_helper_function_end = """\
2313 }
2314 """
2315
2316
2317 #
2318 # template for struct helper code
2319 #
2320
2321
2322     template_struct_helper_function_start = """\
2323 /* Struct = @stname@ */
2324
2325 static void decode_@sname@_st(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, int *offset _U_, MessageHeader *header _U_, gchar *operation _U_) {
2326
2327     gboolean stream_is_big_endian;          /* big endianess */
2328 """
2329
2330
2331
2332
2333     #
2334     # Template for the helper function
2335     # to get stream endianess from header
2336     #
2337
2338     template_struct_helper_function_get_endianess = """\
2339 stream_is_big_endian = is_big_endian(header);  /* get stream endianess */
2340 """
2341     template_struct_helper_function_end = """\
2342 }
2343 """
2344
2345 #
2346 # template for union helper code
2347 #
2348
2349
2350     template_union_helper_function_start = """\
2351 /* Union = @unname@ */
2352
2353 static void decode_@sname@_un(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, int *offset _U_, MessageHeader *header _U_, gchar *operation _U_) {
2354
2355     gboolean stream_is_big_endian;          /* big endianess */
2356 """
2357
2358
2359
2360
2361     #
2362     # Template for the helper function
2363     # to get stream endianess from header
2364     #
2365
2366     template_union_helper_function_get_endianess = """\
2367 stream_is_big_endian = is_big_endian(header);  /* get stream endianess */
2368 """
2369     template_union_helper_function_end = """\
2370 }
2371 """
2372
2373
2374
2375 #-------------------------------------------------------------#
2376 #             Value string  templates                         #
2377 #-------------------------------------------------------------#
2378
2379     template_value_string_start = """\
2380 static const value_string @valstringname@[] = {
2381 """
2382     template_value_string_entry = """\
2383    { @intval@, \"@description@\" }, """
2384
2385     template_value_string_end = """\
2386    { 0,       NULL },
2387 };
2388 """
2389
2390
2391
2392 #-------------------------------------------------------------#
2393 #             Enum   handling templates                       #
2394 #-------------------------------------------------------------#
2395
2396     template_comment_enums_start = """\
2397 /*
2398  * IDL Enums Start
2399  */
2400  """
2401     template_comment_enums_end = """\
2402 /*
2403  * IDL Enums End
2404  */
2405  """
2406     template_comment_enum_comment = """\
2407 /*
2408  * Enum = @ename@
2409  */
2410  """
2411
2412
2413
2414 #-------------------------------------------------------------#
2415 #             Attribute handling templates                    #
2416 #-------------------------------------------------------------#
2417
2418
2419     template_comment_attributes_start = """\
2420 /*
2421  * IDL Attributes Start
2422  */
2423  """
2424
2425     #
2426     # get/set accessor method names are language mapping dependant.
2427     #
2428
2429     template_attributes_declare_Java_get = """static const char get_@sname@_at[] = \"_get_@atname@\" ;"""
2430     template_attributes_declare_Java_set = """static const char set_@sname@_at[] = \"_set_@atname@\" ;"""
2431
2432     template_comment_attributes_end = """
2433 /*
2434  * IDL Attributes End
2435  */
2436 """
2437
2438
2439     #
2440     # template for Attribute delegation code
2441     #
2442     # Note: _get_xxx() should only be called for Reply with NO_EXCEPTION
2443     # Note: _set_xxx() should only be called for Request
2444     #
2445     #
2446
2447     template_at_delegate_code_get = """\
2448 if (strcmp(operation, get_@sname@_at) == 0 && (header->message_type == Reply) && (header->rep_status == NO_EXCEPTION) ) {
2449    tree = start_dissecting(tvb, pinfo, ptree, offset);
2450    decode_get_@sname@_at(tvb, pinfo, tree, offset, header, operation);
2451    return TRUE;
2452 }
2453 """
2454     template_at_delegate_code_set = """\
2455 if (strcmp(operation, set_@sname@_at) == 0 && (header->message_type == Request) ) {
2456    tree = start_dissecting(tvb, pinfo, ptree, offset);
2457    decode_set_@sname@_at(tvb, pinfo, tree, offset, header, operation);
2458    return TRUE;
2459 }
2460 """
2461     template_attribute_helpers_start = """\
2462 /*  Begin Attribute Helper Functions  */
2463 """
2464     template_attribute_helpers_end = """\
2465
2466 /*  End Attribute Helper Functions  */
2467 """
2468
2469 #
2470 # template for attribute helper code
2471 #
2472
2473
2474     template_attribute_helper_function_start = """\
2475
2476 /* Attribute = @atname@ */
2477
2478 static void decode_@sname@_at(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, int *offset _U_, MessageHeader *header _U_, gchar *operation _U_) {
2479
2480     gboolean stream_is_big_endian;          /* big endianess */
2481 """
2482
2483
2484
2485     #
2486     # Template for the helper function
2487     # to get stream endianess from header
2488     #
2489
2490     template_attribute_helper_function_get_endianess = """\
2491 stream_is_big_endian = is_big_endian(header);  /* get stream endianess */
2492 """
2493     template_attribute_helper_function_end = """\
2494 }
2495 """
2496
2497
2498 #-------------------------------------------------------------#
2499 #                     Debugging  templates                    #
2500 #-------------------------------------------------------------#
2501
2502     #
2503     # Template for outputting TODO "C" comments
2504     # so user know I need ti improve something.
2505     #
2506
2507     template_debug_TODO = """\
2508
2509 /* TODO - @message@ */
2510 """
2511     #
2512     # Template for outputting WARNING "C" comments
2513     # so user know if I have found a problem.
2514     #
2515
2516     template_debug_WARNING = """\
2517 /* WARNING - @message@ */
2518 """
2519
2520
2521
2522 #-------------------------------------------------------------#
2523 #                     IDL Union  templates                    #
2524 #-------------------------------------------------------------#
2525
2526     template_comment_union_code_start = """\
2527 /*
2528  * IDL Union Start - @uname@
2529  */
2530  """
2531     template_comment_union_code_end = """
2532 /*
2533  * IDL union End - @uname@
2534  */
2535 """
2536     template_comment_union_code_discriminant = """\
2537 /*
2538  * IDL Union - Discriminant - @uname@
2539  */
2540  """
2541     #
2542     # Cast Unions types to something appropriate
2543     # Enum value cast to guint32, all others cast to gint32
2544     # as omniidl accessor returns integer or Enum.
2545     #
2546
2547     template_union_code_save_discriminant_enum = """\
2548 disc_s_@discname@ = (gint32) u_octet4;     /* save Enum Value  discriminant and cast to gint32 */
2549 """
2550     template_union_code_save_discriminant_long = """\
2551 disc_s_@discname@ = (gint32) s_octet4;     /* save gint32 discriminant and cast to gint32 */
2552 """
2553
2554     template_union_code_save_discriminant_ulong = """\
2555 disc_s_@discname@ = (gint32) u_octet4;     /* save guint32 discriminant and cast to gint32 */
2556 """
2557     template_union_code_save_discriminant_short = """\
2558 disc_s_@discname@ = (gint32) s_octet2;     /* save gint16 discriminant and cast to gint32 */
2559 """
2560
2561     template_union_code_save_discriminant_ushort = """\
2562 disc_s_@discname@ = (gint32) u_octet2;     /* save guint16 discriminant and cast to gint32 */
2563 """
2564     template_union_code_save_discriminant_char = """\
2565 disc_s_@discname@ = (gint32) u_octet1;     /* save guint1 discriminant and cast to gint32 */
2566 """
2567     template_union_code_save_discriminant_boolean = """\
2568 disc_s_@discname@ = (gint32) u_octet1;     /* save guint1 discriminant and cast to gint32 */
2569 """
2570     template_comment_union_code_label_compare_start = """\
2571 if (disc_s_@discname@ == @labelval@) {
2572  """
2573     template_comment_union_code_label_compare_end = """\
2574     return;     /* End Compare for this discriminant type */
2575 }
2576  """
2577
2578
2579     template_comment_union_code_label_default_start = """
2580 /* Default Union Case Start */
2581 """
2582     template_comment_union_code_label_default_end = """\
2583 /* Default Union Case End */
2584  """
2585
2586     #
2587     # Templates for function prototypes.
2588     # This is used in genDeclares() for declaring function prototypes
2589     # for structs and union helper functions.
2590     #
2591
2592     template_prototype_start_dissecting = """
2593 static proto_tree *start_dissecting(tvbuff_t *tvb, packet_info *pinfo, proto_tree *ptree, int *offset);
2594
2595 """
2596     template_prototype_struct_start = """
2597 /* Struct prototype declaration Start */
2598 """
2599     template_prototype_struct_end = """
2600 /* Struct prototype declaration End */
2601 """
2602     template_prototype_struct_body = """
2603 /* Struct = @stname@ */
2604
2605 static void decode_@name@_st(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, int *offset _U_, MessageHeader *header _U_, gchar *operation _U_);
2606 """
2607     template_decode_struct = """
2608
2609 decode_@name@_st(tvb, pinfo, tree, offset, header, operation);
2610 """
2611     template_prototype_union_start = """
2612 /* Union prototype declaration Start */
2613 """
2614     template_prototype_union_end = """
2615 /* Union prototype declaration End */
2616
2617 """
2618     template_prototype_union_body = """
2619
2620 /* Union = @unname@ */
2621
2622 static void decode_@name@_un(tvbuff_t *tvb _U_, packet_info *pinfo _U_, proto_tree *tree _U_, int *offset _U_, MessageHeader *header _U_, gchar *operation _U_);
2623
2624 """
2625     template_decode_union = """
2626 decode_@name@_un(tvb, pinfo, tree, offset, header, operation);
2627 """
2628