pidl:NDR/Parser: $size can be 'foo / 2' so we need to add '(' and ')'
[kai/samba.git] / pidl / lib / Parse / Pidl / Samba4 / NDR / Parser.pm
1 ###################################################
2 # Samba4 NDR parser generator for IDL structures
3 # Copyright tridge@samba.org 2000-2003
4 # Copyright tpot@samba.org 2001
5 # Copyright jelmer@samba.org 2004-2006
6 # released under the GNU GPL
7
8 package Parse::Pidl::Samba4::NDR::Parser;
9
10 require Exporter;
11 @ISA = qw(Exporter);
12 @EXPORT_OK = qw(check_null_pointer NeededFunction NeededElement NeededType $res NeededInterface TypeFunctionName ParseElementPrint);
13
14 use strict;
15 use Parse::Pidl::Typelist qw(hasType getType mapTypeName typeHasBody);
16 use Parse::Pidl::Util qw(has_property ParseExpr ParseExprExt print_uuid unmake_str);
17 use Parse::Pidl::CUtil qw(get_pointer_to get_value_of get_array_element);
18 use Parse::Pidl::NDR qw(GetPrevLevel GetNextLevel ContainsDeferred is_charset_array);
19 use Parse::Pidl::Samba4 qw(is_intree choose_header ArrayDynamicallyAllocated);
20 use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
21 use Parse::Pidl qw(warning);
22
23 use vars qw($VERSION);
24 $VERSION = '0.01';
25
26 # list of known types
27 my %typefamily;
28
29 sub new($$) {
30         my ($class) = @_;
31         my $self = { res => "", res_hdr => "", deferred => [], tabs => "", defer_tabs => "" };
32         bless($self, $class);
33 }
34
35 sub get_typefamily($)
36 {
37         my $n = shift;
38         return $typefamily{$n};
39 }
40
41 sub append_prefix($$)
42 {
43         my ($e, $var_name) = @_;
44         my $pointers = 0;
45         my $arrays = 0;
46
47         foreach my $l (@{$e->{LEVELS}}) {
48                 if ($l->{TYPE} eq "POINTER") {
49                         $pointers++;
50                 } elsif ($l->{TYPE} eq "ARRAY") {
51                         $arrays++;
52                         if (($pointers == 0) and 
53                             (not $l->{IS_FIXED}) and
54                             (not $l->{IS_INLINE})) {
55                                 return get_value_of($var_name);
56                         }
57                 } elsif ($l->{TYPE} eq "DATA") {
58                         if (Parse::Pidl::Typelist::scalar_is_reference($l->{DATA_TYPE})) {
59                                 return get_value_of($var_name) unless ($pointers or $arrays);
60                         }
61                 }
62         }
63         
64         return $var_name;
65 }
66
67 sub has_fast_array($$)
68 {
69         my ($e,$l) = @_;
70
71         return 0 if ($l->{TYPE} ne "ARRAY");
72
73         my $nl = GetNextLevel($e,$l);
74         return 0 unless ($nl->{TYPE} eq "DATA");
75         return 0 unless (hasType($nl->{DATA_TYPE}));
76
77         my $t = getType($nl->{DATA_TYPE});
78
79         # Only uint8 and string have fast array functions at the moment
80         return ($t->{NAME} eq "uint8") or ($t->{NAME} eq "string");
81 }
82
83
84 ####################################
85 # pidl() is our basic output routine
86 sub pidl($$)
87 {
88         my ($self, $d) = @_;
89         if ($d) {
90                 $self->{res} .= $self->{tabs};
91                 $self->{res} .= $d;
92         }
93         $self->{res} .="\n";
94 }
95
96 sub pidl_hdr($$) { my ($self, $d) = @_; $self->{res_hdr} .= "$d\n"; }
97
98 ####################################
99 # defer() is like pidl(), but adds to 
100 # a deferred buffer which is then added to the 
101 # output buffer at the end of the structure/union/function
102 # This is needed to cope with code that must be pushed back
103 # to the end of a block of elements
104 sub defer_indent($) { my ($self) = @_; $self->{defer_tabs}.="\t"; }
105 sub defer_deindent($) { my ($self) = @_; $self->{defer_tabs}=substr($self->{defer_tabs}, 0, -1); }
106
107 sub defer($$)
108 {
109         my ($self, $d) = @_;
110         if ($d) {
111                 push(@{$self->{deferred}}, $self->{defer_tabs}.$d);
112         }
113 }
114
115 ########################################
116 # add the deferred content to the current
117 # output
118 sub add_deferred($)
119 {
120         my ($self) = @_;
121         $self->pidl($_) foreach (@{$self->{deferred}});
122         $self->{deferred} = [];
123         $self->{defer_tabs} = "";
124 }
125
126 sub indent($)
127 {
128         my ($self) = @_;
129         $self->{tabs} .= "\t";
130 }
131
132 sub deindent($)
133 {
134         my ($self) = @_;
135         $self->{tabs} = substr($self->{tabs}, 0, -1);
136 }
137
138 #####################################################################
139 # declare a function public or static, depending on its attributes
140 sub fn_declare($$$$)
141 {
142         my ($self,$type,$fn,$decl) = @_;
143
144         if (has_property($fn, "no$type")) {
145                 $self->pidl_hdr("$decl;");
146                 return 0;
147         }
148
149         if (has_property($fn, "public")) {
150                 $self->pidl_hdr("$decl;");
151                 $self->pidl("_PUBLIC_ $decl");
152         } else {
153                 $self->pidl("static $decl");
154         }
155
156         return 1;
157 }
158
159 ###################################################################
160 # setup any special flags for an element or structure
161 sub start_flags($$$)
162 {
163         my ($self, $e, $ndr) = @_;
164         my $flags = has_property($e, "flag");
165         if (defined $flags) {
166                 $self->pidl("{");
167                 $self->indent;
168                 $self->pidl("uint32_t _flags_save_$e->{TYPE} = $ndr->flags;");
169                 $self->pidl("ndr_set_flags(&$ndr->flags, $flags);");
170         }
171 }
172
173 ###################################################################
174 # end any special flags for an element or structure
175 sub end_flags($$$)
176 {
177         my ($self, $e, $ndr) = @_;
178         my $flags = has_property($e, "flag");
179         if (defined $flags) {
180                 $self->pidl("$ndr->flags = _flags_save_$e->{TYPE};");
181                 $self->deindent;
182                 $self->pidl("}");
183         }
184 }
185
186 #####################################################################
187 # parse the data of an array - push side
188 sub ParseArrayPushHeader($$$$$$)
189 {
190         my ($self,$e,$l,$ndr,$var_name,$env) = @_;
191
192         my $size;
193         my $length;
194
195         if ($l->{IS_ZERO_TERMINATED}) {
196                 if (has_property($e, "charset")) {
197                         $size = $length = "ndr_charset_length($var_name, CH_$e->{PROPERTIES}->{charset})";
198                 } else {
199                         $size = $length = "ndr_string_length($var_name, sizeof(*$var_name))";
200                 }
201         } else {
202                 $size = ParseExpr($l->{SIZE_IS}, $env, $e);
203                 $length = ParseExpr($l->{LENGTH_IS}, $env, $e);
204         }
205
206         if ((!$l->{IS_SURROUNDING}) and $l->{IS_CONFORMANT}) {
207                 $self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, $size));");
208         }
209         
210         if ($l->{IS_VARYING}) {
211                 $self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, 0));");  # array offset
212                 $self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, $length));");
213         } 
214
215         return $length;
216 }
217
218 sub check_fully_dereferenced($$)
219 {
220         my ($element, $env) = @_;
221
222         return sub ($) {
223                 my $origvar = shift;
224                 my $check = 0;
225
226                 # Figure out the number of pointers in $ptr
227                 my $expandedvar = $origvar;
228                 $expandedvar =~ s/^(\**)//;
229                 my $ptr = $1;
230
231                 my $var = undef;
232                 foreach (keys %$env) {
233                         if ($env->{$_} eq $expandedvar) {
234                                 $var = $_;
235                                 last;
236                         }
237                 }
238                 
239                 return($origvar) unless (defined($var));
240                 my $e;
241                 foreach (@{$element->{PARENT}->{ELEMENTS}}) {
242                         if ($_->{NAME} eq $var) {
243                                 $e = $_;
244                                 last;
245                         }
246                 }
247
248                 $e or die("Environment doesn't match siblings");
249
250                 # See if pointer at pointer level $level
251                 # needs to be checked.
252                 my $nump = 0;
253                 foreach (@{$e->{LEVELS}}) {
254                         if ($_->{TYPE} eq "POINTER") {
255                                 $nump = $_->{POINTER_INDEX}+1;
256                         }
257                 }
258                 warning($element->{ORIGINAL}, "Got pointer for `$e->{NAME}', expected fully derefenced variable") if ($nump > length($ptr));
259                 return ($origvar);
260         }
261 }       
262
263 sub check_null_pointer($$$$)
264 {
265         my ($element, $env, $print_fn, $return) = @_;
266
267         return sub ($) {
268                 my $expandedvar = shift;
269                 my $check = 0;
270
271                 # Figure out the number of pointers in $ptr
272                 $expandedvar =~ s/^(\**)//;
273                 my $ptr = $1;
274
275                 my $var = undef;
276                 foreach (keys %$env) {
277                         if ($env->{$_} eq $expandedvar) {
278                                 $var = $_;
279                                 last;
280                         }
281                 }
282                 
283                 if (defined($var)) {
284                         my $e;
285                         # lookup ptr in $e
286                         foreach (@{$element->{PARENT}->{ELEMENTS}}) {
287                                 if ($_->{NAME} eq $var) {
288                                         $e = $_;
289                                         last;
290                                 }
291                         }
292
293                         $e or die("Environment doesn't match siblings");
294
295                         # See if pointer at pointer level $level
296                         # needs to be checked.
297                         foreach my $l (@{$e->{LEVELS}}) {
298                                 if ($l->{TYPE} eq "POINTER" and 
299                                         $l->{POINTER_INDEX} == length($ptr)) {
300                                         # No need to check ref pointers
301                                         $check = ($l->{POINTER_TYPE} ne "ref");
302                                         last;
303                                 }
304
305                                 if ($l->{TYPE} eq "DATA") {
306                                         warning($element, "too much dereferences for `$var'");
307                                 }
308                         }
309                 } else {
310                         warning($element, "unknown dereferenced expression `$expandedvar'");
311                         $check = 1;
312                 }
313                 
314                 $print_fn->("if ($ptr$expandedvar == NULL) $return") if $check;
315         }
316 }
317
318 #####################################################################
319 # parse an array - pull side
320 sub ParseArrayPullHeader($$$$$$)
321 {
322         my ($self,$e,$l,$ndr,$var_name,$env) = @_;
323
324         my $length;
325         my $size;
326
327         if ($l->{IS_CONFORMANT}) {
328                 $length = $size = "ndr_get_array_size($ndr, " . get_pointer_to($var_name) . ")";
329         } elsif ($l->{IS_ZERO_TERMINATED} and $l->{SIZE_IS} == 0 and $l->{LENGTH_IS} == 0) { # Noheader arrays
330                 $length = $size = "ndr_get_string_size($ndr, sizeof(*$var_name))";
331         } else {
332                 $length = $size = ParseExprExt($l->{SIZE_IS}, $env, $e->{ORIGINAL},
333                         check_null_pointer($e, $env, sub { $self->pidl(shift); },
334                                            "return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for size_is()\");"),
335                         check_fully_dereferenced($e, $env));
336         }
337
338         if ((!$l->{IS_SURROUNDING}) and $l->{IS_CONFORMANT}) {
339                 $self->pidl("NDR_CHECK(ndr_pull_array_size($ndr, " . get_pointer_to($var_name) . "));");
340         }
341
342         if ($l->{IS_VARYING}) {
343                 $self->pidl("NDR_CHECK(ndr_pull_array_length($ndr, " . get_pointer_to($var_name) . "));");
344                 $length = "ndr_get_array_length($ndr, " . get_pointer_to($var_name) .")";
345         }
346
347         if ($length ne $size) {
348                 $self->pidl("if ($length > $size) {");
349                 $self->indent;
350                 $self->pidl("return ndr_pull_error($ndr, NDR_ERR_ARRAY_SIZE, \"Bad array size %u should exceed array length %u\", $size, $length);");
351                 $self->deindent;
352                 $self->pidl("}");
353         }
354
355         if ($l->{IS_CONFORMANT} and not $l->{IS_ZERO_TERMINATED}) {
356                 $self->defer("if ($var_name) {");
357                 $self->defer_indent;
358                 my $size = ParseExprExt($l->{SIZE_IS}, $env, $e->{ORIGINAL},
359                         check_null_pointer($e, $env, sub { $self->defer(shift); },
360                                            "return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for size_is()\");"),
361                         check_fully_dereferenced($e, $env));
362                 $self->defer("NDR_CHECK(ndr_check_array_size($ndr, (void*)" . get_pointer_to($var_name) . ", $size));");
363                 $self->defer_deindent;
364                 $self->defer("}");
365         }
366
367         if ($l->{IS_VARYING} and not $l->{IS_ZERO_TERMINATED}) {
368                 $self->defer("if ($var_name) {");
369                 $self->defer_indent;
370                 my $length = ParseExprExt($l->{LENGTH_IS}, $env, $e->{ORIGINAL}, 
371                         check_null_pointer($e, $env, sub { $self->defer(shift); },
372                                            "return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for length_is()\");"),
373                         check_fully_dereferenced($e, $env));
374                 $self->defer("NDR_CHECK(ndr_check_array_length($ndr, (void*)" . get_pointer_to($var_name) . ", $length));");
375                 $self->defer_deindent;
376                 $self->defer("}");
377         }
378
379         if (ArrayDynamicallyAllocated($e,$l) and not is_charset_array($e,$l)) {
380                 $self->AllocateArrayLevel($e,$l,$ndr,$var_name,$size);
381         }
382
383         return $length;
384 }
385
386 sub compression_alg($$)
387 {
388         my ($e, $l) = @_;
389         my ($alg, $clen, $dlen) = split(/,/, $l->{COMPRESSION});
390
391         return $alg;
392 }
393
394 sub compression_clen($$$)
395 {
396         my ($e, $l, $env) = @_;
397         my ($alg, $clen, $dlen) = split(/,/, $l->{COMPRESSION});
398
399         return ParseExpr($clen, $env, $e->{ORIGINAL});
400 }
401
402 sub compression_dlen($$$)
403 {
404         my ($e,$l,$env) = @_;
405         my ($alg, $clen, $dlen) = split(/,/, $l->{COMPRESSION});
406
407         return ParseExpr($dlen, $env, $e->{ORIGINAL});
408 }
409
410 sub ParseCompressionPushStart($$$$$)
411 {
412         my ($self,$e,$l,$ndr,$env) = @_;
413         my $comndr = "$ndr\_compressed";
414         my $alg = compression_alg($e, $l);
415         my $dlen = compression_dlen($e, $l, $env);
416
417         $self->pidl("{");
418         $self->indent;
419         $self->pidl("struct ndr_push *$comndr;");
420         $self->pidl("NDR_CHECK(ndr_push_compression_start($ndr, &$comndr, $alg, $dlen));");
421
422         return $comndr;
423 }
424
425 sub ParseCompressionPushEnd($$$$$)
426 {
427         my ($self,$e,$l,$ndr,$env) = @_;
428         my $comndr = "$ndr\_compressed";
429         my $alg = compression_alg($e, $l);
430         my $dlen = compression_dlen($e, $l, $env);
431
432         $self->pidl("NDR_CHECK(ndr_push_compression_end($ndr, $comndr, $alg, $dlen));");
433         $self->deindent;
434         $self->pidl("}");
435 }
436
437 sub ParseCompressionPullStart($$$$$)
438 {
439         my ($self,$e,$l,$ndr,$env) = @_;
440         my $comndr = "$ndr\_compressed";
441         my $alg = compression_alg($e, $l);
442         my $dlen = compression_dlen($e, $l, $env);
443
444         $self->pidl("{");
445         $self->indent;
446         $self->pidl("struct ndr_pull *$comndr;");
447         $self->pidl("NDR_CHECK(ndr_pull_compression_start($ndr, &$comndr, $alg, $dlen));");
448
449         return $comndr;
450 }
451
452 sub ParseCompressionPullEnd($$$$$)
453 {
454         my ($self,$e,$l,$ndr,$env) = @_;
455         my $comndr = "$ndr\_compressed";
456         my $alg = compression_alg($e, $l);
457         my $dlen = compression_dlen($e, $l, $env);
458
459         $self->pidl("NDR_CHECK(ndr_pull_compression_end($ndr, $comndr, $alg, $dlen));");
460         $self->deindent;
461         $self->pidl("}");
462 }
463
464 sub ParseSubcontextPushStart($$$$$)
465 {
466         my ($self,$e,$l,$ndr,$env) = @_;
467         my $subndr = "_ndr_$e->{NAME}";
468         my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
469
470         $self->pidl("{");
471         $self->indent;
472         $self->pidl("struct ndr_push *$subndr;");
473         $self->pidl("NDR_CHECK(ndr_push_subcontext_start($ndr, &$subndr, $l->{HEADER_SIZE}, $subcontext_size));");
474
475         if (defined $l->{COMPRESSION}) {
476                 $subndr = $self->ParseCompressionPushStart($e, $l, $subndr, $env);
477         }
478
479         return $subndr;
480 }
481
482 sub ParseSubcontextPushEnd($$$$$)
483 {
484         my ($self,$e,$l,$ndr,$env) = @_;
485         my $subndr = "_ndr_$e->{NAME}";
486         my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
487
488         if (defined $l->{COMPRESSION}) {
489                 $self->ParseCompressionPushEnd($e, $l, $subndr, $env);
490         }
491
492         $self->pidl("NDR_CHECK(ndr_push_subcontext_end($ndr, $subndr, $l->{HEADER_SIZE}, $subcontext_size));");
493         $self->deindent;
494         $self->pidl("}");
495 }
496
497 sub ParseSubcontextPullStart($$$$$)
498 {
499         my ($self,$e,$l,$ndr,$env) = @_;
500         my $subndr = "_ndr_$e->{NAME}";
501         my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
502
503         $self->pidl("{");
504         $self->indent;
505         $self->pidl("struct ndr_pull *$subndr;");
506         $self->pidl("NDR_CHECK(ndr_pull_subcontext_start($ndr, &$subndr, $l->{HEADER_SIZE}, $subcontext_size));");
507
508         if (defined $l->{COMPRESSION}) {
509                 $subndr = $self->ParseCompressionPullStart($e, $l, $subndr, $env);
510         }
511
512         return $subndr;
513 }
514
515 sub ParseSubcontextPullEnd($$$$$)
516 {
517         my ($self,$e,$l,$ndr,$env) = @_;
518         my $subndr = "_ndr_$e->{NAME}";
519         my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
520
521         if (defined $l->{COMPRESSION}) {
522                 $self->ParseCompressionPullEnd($e, $l, $subndr, $env);
523         }
524
525         $self->pidl("NDR_CHECK(ndr_pull_subcontext_end($ndr, $subndr, $l->{HEADER_SIZE}, $subcontext_size));");
526         $self->deindent;
527         $self->pidl("}");
528 }
529
530 sub ParseElementPushLevel
531 {
532         my ($self,$e,$l,$ndr,$var_name,$env,$primitives,$deferred) = @_;
533
534         my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
535
536         if ($l->{TYPE} eq "ARRAY" and ($l->{IS_CONFORMANT} or $l->{IS_VARYING})) {
537                 $var_name = get_pointer_to($var_name);
538         }
539
540         if (defined($ndr_flags)) {
541                 if ($l->{TYPE} eq "SUBCONTEXT") {
542                         my $subndr = $self->ParseSubcontextPushStart($e, $l, $ndr, $env);
543                         $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $subndr, $var_name, $env, 1, 1);
544                         $self->ParseSubcontextPushEnd($e, $l, $ndr, $env);
545                 } elsif ($l->{TYPE} eq "POINTER") {
546                         $self->ParsePtrPush($e, $l, $ndr, $var_name);
547                 } elsif ($l->{TYPE} eq "ARRAY") {
548                         my $length = $self->ParseArrayPushHeader($e, $l, $ndr, $var_name, $env); 
549
550                         my $nl = GetNextLevel($e, $l);
551
552                         # Allow speedups for arrays of scalar types
553                         if (is_charset_array($e,$l)) {
554                                 $self->pidl("NDR_CHECK(ndr_push_charset($ndr, $ndr_flags, $var_name, $length, sizeof(" . mapTypeName($nl->{DATA_TYPE}) . "), CH_$e->{PROPERTIES}->{charset}));");
555                                 return;
556                         } elsif (has_fast_array($e,$l)) {
557                                 $self->pidl("NDR_CHECK(ndr_push_array_$nl->{DATA_TYPE}($ndr, $ndr_flags, $var_name, $length));");
558                                 return;
559                         } 
560                 } elsif ($l->{TYPE} eq "SWITCH") {
561                         $self->ParseSwitchPush($e, $l, $ndr, $var_name, $env);
562                 } elsif ($l->{TYPE} eq "DATA") {
563                         $self->ParseDataPush($e, $l, $ndr, $var_name, $primitives, $deferred);
564                 } elsif ($l->{TYPE} eq "TYPEDEF") {
565                         $typefamily{$e->{DATA}->{TYPE}}->{PUSH_FN_BODY}->($self, $e->{DATA}, $ndr, $var_name);
566                 }
567         }
568
569         if ($l->{TYPE} eq "POINTER" and $deferred) {
570                 if ($l->{POINTER_TYPE} ne "ref") {
571                         $self->pidl("if ($var_name) {");
572                         $self->indent;
573                         if ($l->{POINTER_TYPE} eq "relative") {
574                                 $self->pidl("NDR_CHECK(ndr_push_relative_ptr2($ndr, $var_name));");
575                         }
576                 }
577                 $var_name = get_value_of($var_name);
578                 $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 1, 1);
579
580                 if ($l->{POINTER_TYPE} ne "ref") {
581                         $self->deindent;
582                         $self->pidl("}");
583                 }
584         } elsif ($l->{TYPE} eq "ARRAY" and not has_fast_array($e,$l) and
585                 not is_charset_array($e, $l)) {
586                 my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
587                 my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
588
589                 my $array_pointless = ($length eq "0");
590
591                 if ($array_pointless) {
592                         warning($e->{ORIGINAL}, "pointless array `$e->{NAME}' will always have size 0");
593                 }
594
595                 $var_name = get_array_element($var_name, $counter);
596
597                 if ((($primitives and not $l->{IS_DEFERRED}) or ($deferred and $l->{IS_DEFERRED})) and not $array_pointless) {
598                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
599                         $self->indent;
600                         $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 1, 0);
601                         $self->deindent;
602                         $self->pidl("}");
603                 }
604
605                 if ($deferred and ContainsDeferred($e, $l) and not $array_pointless) {
606                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
607                         $self->indent;
608                         $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 0, 1);
609                         $self->deindent;
610                         $self->pidl("}");
611                 }       
612         } elsif ($l->{TYPE} eq "SWITCH") {
613                 $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, $primitives, $deferred);
614         }
615 }
616
617 #####################################################################
618 # parse scalars in a structure element
619 sub ParseElementPush($$$$$$)
620 {
621         my ($self,$e,$ndr,$env,$primitives,$deferred) = @_;
622         my $subndr = undef;
623
624         my $var_name = $env->{$e->{NAME}};
625
626         return unless $primitives or ($deferred and ContainsDeferred($e, $e->{LEVELS}[0]));
627
628         # Representation type is different from transmit_as
629         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
630                 $self->pidl("{");
631                 $self->indent;
632                 my $transmit_name = "_transmit_$e->{NAME}";
633                 $self->pidl(mapTypeName($e->{TYPE}) ." $transmit_name;");
634                 $self->pidl("NDR_CHECK(ndr_$e->{REPRESENTATION_TYPE}_to_$e->{TYPE}($var_name, " . get_pointer_to($transmit_name) . "));");
635                 $var_name = $transmit_name;
636         }
637
638         $var_name = append_prefix($e, $var_name);
639
640         $self->start_flags($e, $ndr);
641
642         if (defined(my $value = has_property($e, "value"))) {
643                 $var_name = ParseExpr($value, $env, $e->{ORIGINAL});
644         }
645
646         $self->ParseElementPushLevel($e, $e->{LEVELS}[0], $ndr, $var_name, $env, $primitives, $deferred);
647
648         $self->end_flags($e, $ndr);
649
650         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
651                 $self->deindent;
652                 $self->pidl("}");
653         }
654 }
655
656 #####################################################################
657 # parse a pointer in a struct element or function
658 sub ParsePtrPush($$$$$)
659 {
660         my ($self,$e,$l,$ndr,$var_name) = @_;
661
662         if ($l->{POINTER_TYPE} eq "ref") {
663                 $self->pidl("if ($var_name == NULL) {");
664                 $self->indent;
665                 $self->pidl("return ndr_push_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL [ref] pointer\");");
666                 $self->deindent;
667                 $self->pidl("}");
668                 if ($l->{LEVEL} eq "EMBEDDED") {
669                         $self->pidl("NDR_CHECK(ndr_push_ref_ptr(ndr));");
670                 }
671         } elsif ($l->{POINTER_TYPE} eq "relative") {
672                 $self->pidl("NDR_CHECK(ndr_push_relative_ptr1($ndr, $var_name));");
673         } elsif ($l->{POINTER_TYPE} eq "unique") {
674                 $self->pidl("NDR_CHECK(ndr_push_unique_ptr($ndr, $var_name));");
675         } elsif ($l->{POINTER_TYPE} eq "full") {
676                 $self->pidl("NDR_CHECK(ndr_push_full_ptr($ndr, $var_name));");
677         } else {
678                 die("Unhandled pointer type $l->{POINTER_TYPE}");
679         }
680 }
681
682 sub need_pointer_to($$$)
683 {
684         my ($e, $l, $scalar_only) = @_;
685
686         my $t;
687         if (ref($l->{DATA_TYPE})) {
688                 $t = "$l->{DATA_TYPE}->{TYPE}_$l->{DATA_TYPE}->{NAME}";
689         } else {
690                 $t = $l->{DATA_TYPE};
691         }
692
693         if (not Parse::Pidl::Typelist::is_scalar($t)) {
694                 return 1 if $scalar_only;
695         }
696
697         my $arrays = 0;
698
699         foreach my $tl (@{$e->{LEVELS}}) {
700                 last if $l == $tl;
701                 if ($tl->{TYPE} eq "ARRAY") {
702                         $arrays++;
703                 }
704         }
705
706         if (Parse::Pidl::Typelist::scalar_is_reference($t)) {
707                 return 1 unless $arrays;
708         }
709
710         return 0;
711 }
712
713 sub ParseDataPrint($$$$$)
714 {
715         my ($self, $e, $l, $ndr, $var_name) = @_;
716
717         if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
718
719                 if (need_pointer_to($e, $l, 1)) {
720                         $var_name = get_pointer_to($var_name);
721                 }
722
723                 $self->pidl(TypeFunctionName("ndr_print", $l->{DATA_TYPE})."($ndr, \"$e->{NAME}\", $var_name);");
724         } else {
725                 $self->ParseTypePrint($l->{DATA_TYPE}, $ndr, $var_name);
726         }
727 }
728
729 #####################################################################
730 # print scalars in a structure element
731 sub ParseElementPrint($$$$$)
732 {
733         my($self, $e, $ndr, $var_name, $env) = @_;
734
735         return if (has_property($e, "noprint"));
736
737         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
738                 $self->pidl("ndr_print_$e->{REPRESENTATION_TYPE}($ndr, \"$e->{NAME}\", $var_name);");
739                 return;
740         }
741
742         $var_name = append_prefix($e, $var_name);
743
744         if (defined(my $value = has_property($e, "value"))) {
745                 $var_name = "($ndr->flags & LIBNDR_PRINT_SET_VALUES)?" . ParseExpr($value,$env, $e->{ORIGINAL}) . ":$var_name";
746         }
747
748         foreach my $l (@{$e->{LEVELS}}) {
749                 if ($l->{TYPE} eq "POINTER") {
750                         $self->pidl("ndr_print_ptr($ndr, \"$e->{NAME}\", $var_name);");
751                         $self->pidl("$ndr->depth++;");
752                         if ($l->{POINTER_TYPE} ne "ref") {
753                                 $self->pidl("if ($var_name) {");
754                                 $self->indent;
755                         }
756                         $var_name = get_value_of($var_name);
757                 } elsif ($l->{TYPE} eq "ARRAY") {
758                         my $length;
759
760                         if ($l->{IS_CONFORMANT} or $l->{IS_VARYING}) {
761                                 $var_name = get_pointer_to($var_name); 
762                         }
763                         
764                         if ($l->{IS_ZERO_TERMINATED}) {
765                                 $length = "ndr_string_length($var_name, sizeof(*$var_name))";
766                         } else {
767                                 $length = ParseExprExt($l->{LENGTH_IS}, $env, $e->{ORIGINAL}, 
768                                                         check_null_pointer($e, $env, sub { $self->pidl(shift); }, "return;"), check_fully_dereferenced($e, $env));
769                         }
770
771                         if (is_charset_array($e,$l)) {
772                                 $self->pidl("ndr_print_string($ndr, \"$e->{NAME}\", $var_name);");
773                                 last;
774                         } elsif (has_fast_array($e, $l)) {
775                                 my $nl = GetNextLevel($e, $l);
776                                 $self->pidl("ndr_print_array_$nl->{DATA_TYPE}($ndr, \"$e->{NAME}\", $var_name, $length);");
777                                 last;
778                         } else {
779                                 my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
780
781                                 $self->pidl("$ndr->print($ndr, \"\%s: ARRAY(\%d)\", \"$e->{NAME}\", (int)$length);");
782                                 $self->pidl("$ndr->depth++;");
783                                 $self->pidl("for ($counter=0;$counter<$length;$counter++) {");
784                                 $self->indent;
785                                 $self->pidl("char *idx_$l->{LEVEL_INDEX}=NULL;");
786                                 $self->pidl("if (asprintf(&idx_$l->{LEVEL_INDEX}, \"[\%d]\", $counter) != -1) {");
787                                 $self->indent;
788
789                                 $var_name = get_array_element($var_name, $counter);
790                         }
791                 } elsif ($l->{TYPE} eq "DATA") {
792                         $self->ParseDataPrint($e, $l, $ndr, $var_name);
793                 } elsif ($l->{TYPE} eq "SWITCH") {
794                         my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL}, 
795                                                 check_null_pointer($e, $env, sub { $self->pidl(shift); }, "return;"), check_fully_dereferenced($e, $env));
796                         $self->pidl("ndr_print_set_switch_value($ndr, " . get_pointer_to($var_name) . ", $switch_var);");
797                 } 
798         }
799
800         foreach my $l (reverse @{$e->{LEVELS}}) {
801                 if ($l->{TYPE} eq "POINTER") {
802                         if ($l->{POINTER_TYPE} ne "ref") {
803                                 $self->deindent;
804                                 $self->pidl("}");
805                         }
806                         $self->pidl("$ndr->depth--;");
807                 } elsif (($l->{TYPE} eq "ARRAY")
808                         and not is_charset_array($e,$l)
809                         and not has_fast_array($e,$l)) {
810                         $self->pidl("free(idx_$l->{LEVEL_INDEX});");
811                         $self->deindent;
812                         $self->pidl("}");
813                         $self->deindent;
814                         $self->pidl("}");
815                         $self->pidl("$ndr->depth--;");
816                 }
817         }
818 }
819
820 #####################################################################
821 # parse scalars in a structure element - pull size
822 sub ParseSwitchPull($$$$$$)
823 {
824         my($self,$e,$l,$ndr,$var_name,$env) = @_;
825         my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL}, 
826                 check_null_pointer($e, $env, sub { $self->pidl(shift); },
827                                    "return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for switch_is()\");"),
828                 check_fully_dereferenced($e, $env));
829
830         $var_name = get_pointer_to($var_name);
831         $self->pidl("NDR_CHECK(ndr_pull_set_switch_value($ndr, $var_name, $switch_var));");
832 }
833
834 #####################################################################
835 # push switch element
836 sub ParseSwitchPush($$$$$$)
837 {
838         my($self,$e,$l,$ndr,$var_name,$env) = @_;
839         my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL}, 
840                 check_null_pointer($e, $env, sub { $self->pidl(shift); },
841                                    "return ndr_push_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for switch_is()\");"),
842                 check_fully_dereferenced($e, $env));
843
844         $var_name = get_pointer_to($var_name);
845         $self->pidl("NDR_CHECK(ndr_push_set_switch_value($ndr, $var_name, $switch_var));");
846 }
847
848 sub ParseDataPull($$$$$$$)
849 {
850         my ($self,$e,$l,$ndr,$var_name,$primitives,$deferred) = @_;
851
852         if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
853
854                 my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
855
856                 if (need_pointer_to($e, $l, 0)) {
857                         $var_name = get_pointer_to($var_name);
858                 }
859
860                 $var_name = get_pointer_to($var_name);
861
862                 $self->pidl("NDR_CHECK(".TypeFunctionName("ndr_pull", $l->{DATA_TYPE})."($ndr, $ndr_flags, $var_name));");
863
864                 if (my $range = has_property($e, "range")) {
865                         $var_name = get_value_of($var_name);
866                         my $signed = Parse::Pidl::Typelist::is_signed($l->{DATA_TYPE});
867                         my ($low, $high) = split(/,/, $range, 2);
868                         if ($low < 0 and not $signed) {
869                                 warning(0, "$low is invalid for the range of an unsigned type");
870                         }
871                         if ($low == 0 and not $signed) {
872                                 $self->pidl("if ($var_name > $high) {");
873                         } else {
874                                 $self->pidl("if ($var_name < $low || $var_name > $high) {");
875                         }
876                         $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_RANGE, \"value out of range\");");
877                         $self->pidl("}");
878                 }
879         } else {
880                 $self->ParseTypePull($l->{DATA_TYPE}, $ndr, $var_name, $primitives, $deferred);
881         }
882 }
883
884 sub ParseDataPush($$$$$$$)
885 {
886         my ($self,$e,$l,$ndr,$var_name,$primitives,$deferred) = @_;
887
888         if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
889
890                 my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
891
892                 # strings are passed by value rather than reference
893                 if (need_pointer_to($e, $l, 1)) {
894                         $var_name = get_pointer_to($var_name);
895                 }
896
897                 $self->pidl("NDR_CHECK(".TypeFunctionName("ndr_push", $l->{DATA_TYPE})."($ndr, $ndr_flags, $var_name));");
898         } else {
899                 $self->ParseTypePush($l->{DATA_TYPE}, $ndr, $var_name, $primitives, $deferred);
900         }
901 }
902
903 sub CalcNdrFlags($$$)
904 {
905         my ($l,$primitives,$deferred) = @_;
906
907         my $scalars = 0;
908         my $buffers = 0;
909
910         # Add NDR_SCALARS if this one is deferred 
911         # and deferreds may be pushed
912         $scalars = 1 if ($l->{IS_DEFERRED} and $deferred);
913
914         # Add NDR_SCALARS if this one is not deferred and 
915         # primitives may be pushed
916         $scalars = 1 if (!$l->{IS_DEFERRED} and $primitives);
917         
918         # Add NDR_BUFFERS if this one contains deferred stuff
919         # and deferreds may be pushed
920         $buffers = 1 if ($l->{CONTAINS_DEFERRED} and $deferred);
921
922         return "NDR_SCALARS|NDR_BUFFERS" if ($scalars and $buffers);
923         return "NDR_SCALARS" if ($scalars);
924         return "NDR_BUFFERS" if ($buffers);
925         return undef;
926 }
927
928 sub ParseMemCtxPullFlags($$$$)
929 {
930         my ($self, $e, $l) = @_;
931
932         return undef unless ($l->{TYPE} eq "POINTER" or $l->{TYPE} eq "ARRAY");
933
934         return undef unless ($l->{TYPE} ne "ARRAY" or ArrayDynamicallyAllocated($e,$l));
935         return undef if has_fast_array($e, $l);
936         return undef if is_charset_array($e, $l);
937
938         my $mem_flags = "0";
939
940         if (($l->{TYPE} eq "POINTER") and ($l->{POINTER_TYPE} eq "ref")) {
941                 my $nl = GetNextLevel($e, $l);
942                 my $next_is_array = ($nl->{TYPE} eq "ARRAY");
943                 my $next_is_string = (($nl->{TYPE} eq "DATA") and 
944                                         ($nl->{DATA_TYPE} eq "string"));
945                 if ($next_is_array or $next_is_string) {
946                         return undef;
947                 } elsif ($l->{LEVEL} eq "TOP") {
948                         $mem_flags = "LIBNDR_FLAG_REF_ALLOC";
949                 }
950         }
951
952         return $mem_flags;
953 }
954
955 sub ParseMemCtxPullStart($$$$$)
956 {
957         my ($self, $e, $l, $ndr, $ptr_name) = @_;
958
959         my $mem_r_ctx = "_mem_save_$e->{NAME}_$l->{LEVEL_INDEX}";
960         my $mem_c_ctx = $ptr_name;
961         my $mem_c_flags = $self->ParseMemCtxPullFlags($e, $l);
962
963         return unless defined($mem_c_flags);
964
965         $self->pidl("$mem_r_ctx = NDR_PULL_GET_MEM_CTX($ndr);");
966         $self->pidl("NDR_PULL_SET_MEM_CTX($ndr, $mem_c_ctx, $mem_c_flags);");
967 }
968
969 sub ParseMemCtxPullEnd($$$$)
970 {
971         my ($self, $e, $l, $ndr) = @_;
972
973         my $mem_r_ctx = "_mem_save_$e->{NAME}_$l->{LEVEL_INDEX}";
974         my $mem_r_flags = $self->ParseMemCtxPullFlags($e, $l);
975
976         return unless defined($mem_r_flags);
977
978         $self->pidl("NDR_PULL_SET_MEM_CTX($ndr, $mem_r_ctx, $mem_r_flags);");
979 }
980
981 sub CheckStringTerminator($$$$$)
982 {
983         my ($self,$ndr,$e,$l,$length) = @_;
984         my $nl = GetNextLevel($e, $l);
985
986         # Make sure last element is zero!
987         $self->pidl("NDR_CHECK(ndr_check_string_terminator($ndr, $length, sizeof($nl->{DATA_TYPE}_t)));");
988 }
989
990 sub ParseElementPullLevel
991 {
992         my($self,$e,$l,$ndr,$var_name,$env,$primitives,$deferred) = @_;
993
994         my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
995
996         if ($l->{TYPE} eq "ARRAY" and ($l->{IS_VARYING} or $l->{IS_CONFORMANT})) {
997                 $var_name = get_pointer_to($var_name);
998         }
999
1000         # Only pull something if there's actually something to be pulled
1001         if (defined($ndr_flags)) {
1002                 if ($l->{TYPE} eq "SUBCONTEXT") {
1003                         my $subndr = $self->ParseSubcontextPullStart($e, $l, $ndr, $env);
1004                         $self->ParseElementPullLevel($e, GetNextLevel($e,$l), $subndr, $var_name, $env, 1, 1);
1005                         $self->ParseSubcontextPullEnd($e, $l, $ndr, $env);
1006                 } elsif ($l->{TYPE} eq "ARRAY") {
1007                         my $length = $self->ParseArrayPullHeader($e, $l, $ndr, $var_name, $env);
1008
1009                         my $nl = GetNextLevel($e, $l);
1010
1011                         if (is_charset_array($e,$l)) {
1012                                 if ($l->{IS_ZERO_TERMINATED}) {
1013                                         $self->CheckStringTerminator($ndr, $e, $l, $length);
1014                                 }
1015                                 $self->pidl("NDR_CHECK(ndr_pull_charset($ndr, $ndr_flags, ".get_pointer_to($var_name).", $length, sizeof(" . mapTypeName($nl->{DATA_TYPE}) . "), CH_$e->{PROPERTIES}->{charset}));");
1016                                 return;
1017                         } elsif (has_fast_array($e, $l)) {
1018                                 if ($l->{IS_ZERO_TERMINATED}) {
1019                                         $self->CheckStringTerminator($ndr,$e,$l,$length);
1020                                 }
1021                                 $self->pidl("NDR_CHECK(ndr_pull_array_$nl->{DATA_TYPE}($ndr, $ndr_flags, $var_name, $length));");
1022                                 return;
1023                         }
1024                 } elsif ($l->{TYPE} eq "POINTER") {
1025                         $self->ParsePtrPull($e, $l, $ndr, $var_name);
1026                 } elsif ($l->{TYPE} eq "SWITCH") {
1027                         $self->ParseSwitchPull($e, $l, $ndr, $var_name, $env);
1028                 } elsif ($l->{TYPE} eq "DATA") {
1029                         $self->ParseDataPull($e, $l, $ndr, $var_name, $primitives, $deferred);
1030                 } elsif ($l->{TYPE} eq "TYPEDEF") {
1031                         $typefamily{$e->{DATA}->{TYPE}}->{PULL_FN_BODY}->($self, $e->{DATA}, $ndr, $var_name);
1032                 }
1033         }
1034
1035         # add additional constructions
1036         if ($l->{TYPE} eq "POINTER" and $deferred) {
1037                 if ($l->{POINTER_TYPE} ne "ref") {
1038                         $self->pidl("if ($var_name) {");
1039                         $self->indent;
1040
1041                         if ($l->{POINTER_TYPE} eq "relative") {
1042                                 $self->pidl("uint32_t _relative_save_offset;");
1043                                 $self->pidl("_relative_save_offset = $ndr->offset;");
1044                                 $self->pidl("NDR_CHECK(ndr_pull_relative_ptr2($ndr, $var_name));");
1045                         }
1046                 }
1047
1048                 $self->ParseMemCtxPullStart($e, $l, $ndr, $var_name);
1049
1050                 $var_name = get_value_of($var_name);
1051                 $self->ParseElementPullLevel($e, GetNextLevel($e,$l), $ndr, $var_name, $env, 1, 1);
1052
1053                 $self->ParseMemCtxPullEnd($e, $l, $ndr);
1054
1055                 if ($l->{POINTER_TYPE} ne "ref") {
1056                         if ($l->{POINTER_TYPE} eq "relative") {
1057                                 $self->pidl("if ($ndr->offset > $ndr->relative_highest_offset) {");
1058                                 $self->indent;
1059                                 $self->pidl("$ndr->relative_highest_offset = $ndr->offset;");
1060                                 $self->deindent;
1061                                 $self->pidl("}");
1062                                 $self->pidl("$ndr->offset = _relative_save_offset;");
1063                         }
1064                         $self->deindent;
1065                         $self->pidl("}");
1066                 }
1067         } elsif ($l->{TYPE} eq "ARRAY" and 
1068                         not has_fast_array($e,$l) and not is_charset_array($e, $l)) {
1069                 my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
1070                 my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
1071                 my $array_name = $var_name;
1072
1073                 if ($l->{IS_VARYING}) {
1074                         $length = "ndr_get_array_length($ndr, " . get_pointer_to($var_name) .")";
1075                 }
1076
1077                 $var_name = get_array_element($var_name, $counter);
1078
1079                 $self->ParseMemCtxPullStart($e, $l, $ndr, $array_name);
1080
1081                 if (($primitives and not $l->{IS_DEFERRED}) or ($deferred and $l->{IS_DEFERRED})) {
1082                         my $nl = GetNextLevel($e,$l);
1083
1084                         if ($l->{IS_ZERO_TERMINATED}) {
1085                                 $self->CheckStringTerminator($ndr,$e,$l,$length);
1086                         }
1087
1088                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
1089                         $self->indent;
1090                         $self->ParseElementPullLevel($e, $nl, $ndr, $var_name, $env, 1, 0);
1091                         $self->deindent;
1092                         $self->pidl("}");
1093                 }
1094
1095                 if ($deferred and ContainsDeferred($e, $l)) {
1096                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
1097                         $self->indent;
1098                         $self->ParseElementPullLevel($e,GetNextLevel($e,$l), $ndr, $var_name, $env, 0, 1);
1099                         $self->deindent;
1100                         $self->pidl("}");
1101                 }
1102
1103                 $self->ParseMemCtxPullEnd($e, $l, $ndr);
1104
1105         } elsif ($l->{TYPE} eq "SWITCH") {
1106                 $self->ParseElementPullLevel($e, GetNextLevel($e,$l), $ndr, $var_name, $env, $primitives, $deferred);
1107         }
1108 }
1109
1110 #####################################################################
1111 # parse scalars in a structure element - pull size
1112 sub ParseElementPull($$$$$$)
1113 {
1114         my($self,$e,$ndr,$env,$primitives,$deferred) = @_;
1115
1116         my $var_name = $env->{$e->{NAME}};
1117         my $represent_name;
1118         my $transmit_name;
1119
1120         return unless $primitives or ($deferred and ContainsDeferred($e, $e->{LEVELS}[0]));
1121
1122         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
1123                 $self->pidl("{");
1124                 $self->indent;
1125                 $represent_name = $var_name;
1126                 $transmit_name = "_transmit_$e->{NAME}";
1127                 $var_name = $transmit_name;
1128                 $self->pidl(mapTypeName($e->{TYPE})." $var_name;");
1129         }
1130
1131         $var_name = append_prefix($e, $var_name);
1132
1133         $self->start_flags($e, $ndr);
1134
1135         $self->ParseElementPullLevel($e,$e->{LEVELS}[0],$ndr,$var_name,$env,$primitives,$deferred);
1136
1137         $self->end_flags($e, $ndr);
1138
1139         # Representation type is different from transmit_as
1140         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
1141                 $self->pidl("NDR_CHECK(ndr_$e->{TYPE}_to_$e->{REPRESENTATION_TYPE}($transmit_name, ".get_pointer_to($represent_name)."));");
1142                 $self->deindent;
1143                 $self->pidl("}");
1144         }
1145 }
1146
1147 #####################################################################
1148 # parse a pointer in a struct element or function
1149 sub ParsePtrPull($$$$$)
1150 {
1151         my($self, $e,$l,$ndr,$var_name) = @_;
1152
1153         my $nl = GetNextLevel($e, $l);
1154         my $next_is_array = ($nl->{TYPE} eq "ARRAY");
1155         my $next_is_string = (($nl->{TYPE} eq "DATA") and 
1156                                                  ($nl->{DATA_TYPE} eq "string"));
1157
1158         if ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "TOP") {
1159
1160                 if (!$next_is_array and !$next_is_string) {
1161                         $self->pidl("if ($ndr->flags & LIBNDR_FLAG_REF_ALLOC) {");
1162                         $self->pidl("\tNDR_PULL_ALLOC($ndr, $var_name);"); 
1163                         $self->pidl("}");
1164                 }
1165                 
1166                 return;
1167         } elsif ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "EMBEDDED") {
1168                 $self->pidl("NDR_CHECK(ndr_pull_ref_ptr($ndr, &_ptr_$e->{NAME}));");
1169         } elsif (($l->{POINTER_TYPE} eq "unique") or 
1170                  ($l->{POINTER_TYPE} eq "relative") or
1171                  ($l->{POINTER_TYPE} eq "full")) {
1172                 $self->pidl("NDR_CHECK(ndr_pull_generic_ptr($ndr, &_ptr_$e->{NAME}));");
1173         } else {
1174                 die("Unhandled pointer type $l->{POINTER_TYPE}");
1175         }
1176
1177         $self->pidl("if (_ptr_$e->{NAME}) {");
1178         $self->indent;
1179
1180         # Don't do this for arrays, they're allocated at the actual level 
1181         # of the array
1182         unless ($next_is_array or $next_is_string) { 
1183                 $self->pidl("NDR_PULL_ALLOC($ndr, $var_name);"); 
1184         } else {
1185                 # FIXME: Yes, this is nasty.
1186                 # We allocate an array twice
1187                 # - once just to indicate that it's there,
1188                 # - then the real allocation...
1189                 $self->pidl("NDR_PULL_ALLOC($ndr, $var_name);");
1190         }
1191
1192         #$self->pidl("memset($var_name, 0, sizeof($var_name));");
1193         if ($l->{POINTER_TYPE} eq "relative") {
1194                 $self->pidl("NDR_CHECK(ndr_pull_relative_ptr1($ndr, $var_name, _ptr_$e->{NAME}));");
1195         }
1196         $self->deindent;
1197         $self->pidl("} else {");
1198         $self->pidl("\t$var_name = NULL;");
1199         $self->pidl("}");
1200 }
1201
1202 sub ParseStructPushPrimitives($$$$$)
1203 {
1204         my ($self, $struct, $ndr, $varname, $env) = @_;
1205
1206         # see if the structure contains a conformant array. If it
1207         # does, then it must be the last element of the structure, and
1208         # we need to push the conformant length early, as it fits on
1209         # the wire before the structure (and even before the structure
1210         # alignment)
1211         if (defined($struct->{SURROUNDING_ELEMENT})) {
1212                 my $e = $struct->{SURROUNDING_ELEMENT};
1213
1214                 if (defined($e->{LEVELS}[0]) and 
1215                         $e->{LEVELS}[0]->{TYPE} eq "ARRAY") {
1216                         my $size;
1217                         
1218                         if ($e->{LEVELS}[0]->{IS_ZERO_TERMINATED}) {
1219                                 if (has_property($e, "charset")) {
1220                                         $size = "ndr_charset_length($varname->$e->{NAME}, CH_$e->{PROPERTIES}->{charset})";
1221                                 } else {
1222                                         $size = "ndr_string_length($varname->$e->{NAME}, sizeof(*$varname->$e->{NAME}))";
1223                                 }
1224                         } else {
1225                                 $size = ParseExpr($e->{LEVELS}[0]->{SIZE_IS}, $env, $e->{ORIGINAL});
1226                         }
1227
1228                         $self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, $size));");
1229                 } else {
1230                         $self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, ndr_string_array_size($ndr, $varname->$e->{NAME})));");
1231                 }
1232         }
1233
1234         $self->pidl("NDR_CHECK(ndr_push_align($ndr, $struct->{ALIGN}));");
1235
1236         if (defined($struct->{PROPERTIES}{relative_base})) {
1237                 # set the current offset as base for relative pointers
1238                 # and store it based on the toplevel struct/union
1239                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1240         }
1241
1242         $self->ParseElementPush($_, $ndr, $env, 1, 0) foreach (@{$struct->{ELEMENTS}});
1243
1244         $self->pidl("NDR_CHECK(ndr_push_trailer_align($ndr, $struct->{ALIGN}));");
1245 }
1246
1247 sub ParseStructPushDeferred($$$$)
1248 {
1249         my ($self, $struct, $ndr, $varname, $env) = @_;
1250         if (defined($struct->{PROPERTIES}{relative_base})) {
1251                 # retrieve the current offset as base for relative pointers
1252                 # based on the toplevel struct/union
1253                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset2($ndr, $varname));");
1254         }
1255         $self->ParseElementPush($_, $ndr, $env, 0, 1) foreach (@{$struct->{ELEMENTS}});
1256 }
1257
1258 #####################################################################
1259 # parse a struct
1260 sub ParseStructPush($$$$)
1261 {
1262         my ($self, $struct, $ndr, $varname) = @_;
1263         
1264         return unless defined($struct->{ELEMENTS});
1265
1266         my $env = GenerateStructEnv($struct, $varname);
1267
1268         EnvSubstituteValue($env, $struct);
1269
1270         $self->DeclareArrayVariablesNoZero($_, $env) foreach (@{$struct->{ELEMENTS}});
1271
1272         $self->start_flags($struct, $ndr);
1273
1274         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1275         $self->indent;
1276         $self->ParseStructPushPrimitives($struct, $ndr, $varname, $env);
1277         $self->deindent;
1278         $self->pidl("}");
1279
1280         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1281         $self->indent;
1282         $self->ParseStructPushDeferred($struct, $ndr, $varname, $env);
1283         $self->deindent;
1284         $self->pidl("}");
1285
1286         $self->end_flags($struct, $ndr);
1287 }
1288
1289 #####################################################################
1290 # generate a push function for an enum
1291 sub ParseEnumPush($$$$)
1292 {
1293         my($self,$enum,$ndr,$varname) = @_;
1294         my($type_fn) = $enum->{BASE_TYPE};
1295
1296         $self->start_flags($enum, $ndr);
1297         $self->pidl("NDR_CHECK(ndr_push_enum_$type_fn($ndr, NDR_SCALARS, $varname));");
1298         $self->end_flags($enum, $ndr);
1299 }
1300
1301 #####################################################################
1302 # generate a pull function for an enum
1303 sub ParseEnumPull($$$$)
1304 {
1305         my($self,$enum,$ndr,$varname) = @_;
1306         my($type_fn) = $enum->{BASE_TYPE};
1307         my($type_v_decl) = mapTypeName($type_fn);
1308
1309         $self->pidl("$type_v_decl v;");
1310         $self->start_flags($enum, $ndr);
1311         $self->pidl("NDR_CHECK(ndr_pull_enum_$type_fn($ndr, NDR_SCALARS, &v));");
1312         $self->pidl("*$varname = v;");
1313
1314         $self->end_flags($enum, $ndr);
1315 }
1316
1317 #####################################################################
1318 # generate a print function for an enum
1319 sub ParseEnumPrint($$$$$)
1320 {
1321         my($self,$enum,$ndr,$name,$varname) = @_;
1322
1323         $self->pidl("const char *val = NULL;");
1324         $self->pidl("");
1325
1326         $self->start_flags($enum, $ndr);
1327
1328         $self->pidl("switch ($varname) {");
1329         $self->indent;
1330         my $els = \@{$enum->{ELEMENTS}};
1331         foreach my $i (0 .. $#{$els}) {
1332                 my $e = ${$els}[$i];
1333                 chomp $e;
1334                 if ($e =~ /^(.*)=/) {
1335                         $e = $1;
1336                 }
1337                 $self->pidl("case $e: val = \"$e\"; break;");
1338         }
1339
1340         $self->deindent;
1341         $self->pidl("}");
1342         
1343         $self->pidl("ndr_print_enum($ndr, name, \"$enum->{TYPE}\", val, $varname);");
1344
1345         $self->end_flags($enum, $ndr);
1346 }
1347
1348 sub DeclEnum($$$$)
1349 {
1350         my ($e,$t,$name,$varname) = @_;
1351         return "enum $name " . 
1352                 ($t eq "pull"?"*":"") . $varname;
1353 }
1354
1355 $typefamily{ENUM} = {
1356         DECL => \&DeclEnum,
1357         PUSH_FN_BODY => \&ParseEnumPush,
1358         PULL_FN_BODY => \&ParseEnumPull,
1359         PRINT_FN_BODY => \&ParseEnumPrint,
1360 };
1361
1362 #####################################################################
1363 # generate a push function for a bitmap
1364 sub ParseBitmapPush($$$$)
1365 {
1366         my($self,$bitmap,$ndr,$varname) = @_;
1367         my($type_fn) = $bitmap->{BASE_TYPE};
1368
1369         $self->start_flags($bitmap, $ndr);
1370
1371         $self->pidl("NDR_CHECK(ndr_push_$type_fn($ndr, NDR_SCALARS, $varname));");
1372
1373         $self->end_flags($bitmap, $ndr);
1374 }
1375
1376 #####################################################################
1377 # generate a pull function for an bitmap
1378 sub ParseBitmapPull($$$$)
1379 {
1380         my($self,$bitmap,$ndr,$varname) = @_;
1381         my $type_fn = $bitmap->{BASE_TYPE};
1382         my($type_decl) = mapTypeName($bitmap->{BASE_TYPE});
1383
1384         $self->pidl("$type_decl v;");
1385         $self->start_flags($bitmap, $ndr);
1386         $self->pidl("NDR_CHECK(ndr_pull_$type_fn($ndr, NDR_SCALARS, &v));");
1387         $self->pidl("*$varname = v;");
1388
1389         $self->end_flags($bitmap, $ndr);
1390 }
1391
1392 #####################################################################
1393 # generate a print function for an bitmap
1394 sub ParseBitmapPrintElement($$$$$$)
1395 {
1396         my($self,$e,$bitmap,$ndr,$name,$varname) = @_;
1397         my($type_decl) = mapTypeName($bitmap->{BASE_TYPE});
1398         my($type_fn) = $bitmap->{BASE_TYPE};
1399         my($flag);
1400
1401         if ($e =~ /^(\w+) .*$/) {
1402                 $flag = "$1";
1403         } else {
1404                 die "Bitmap: \"$name\" invalid Flag: \"$e\"";
1405         }
1406
1407         $self->pidl("ndr_print_bitmap_flag($ndr, sizeof($type_decl), \"$flag\", $flag, $varname);");
1408 }
1409
1410 #####################################################################
1411 # generate a print function for an bitmap
1412 sub ParseBitmapPrint($$$$$)
1413 {
1414         my($self,$bitmap,$ndr,$name,$varname) = @_;
1415         my($type_decl) = mapTypeName($bitmap->{TYPE});
1416         my($type_fn) = $bitmap->{BASE_TYPE};
1417
1418         $self->start_flags($bitmap, $ndr);
1419
1420         $self->pidl("ndr_print_$type_fn($ndr, name, $varname);");
1421
1422         $self->pidl("$ndr->depth++;");
1423         foreach my $e (@{$bitmap->{ELEMENTS}}) {
1424                 $self->ParseBitmapPrintElement($e, $bitmap, $ndr, $name, $varname);
1425         }
1426         $self->pidl("$ndr->depth--;");
1427
1428         $self->end_flags($bitmap, $ndr);
1429 }
1430
1431 sub DeclBitmap($$$$)
1432 {
1433         my ($e,$t,$name,$varname) = @_;
1434         return mapTypeName(Parse::Pidl::Typelist::bitmap_type_fn($e)) . 
1435                 ($t eq "pull"?" *":" ") . $varname;
1436 }
1437
1438 $typefamily{BITMAP} = {
1439         DECL => \&DeclBitmap,
1440         PUSH_FN_BODY => \&ParseBitmapPush,
1441         PULL_FN_BODY => \&ParseBitmapPull,
1442         PRINT_FN_BODY => \&ParseBitmapPrint,
1443 };
1444
1445 #####################################################################
1446 # generate a struct print function
1447 sub ParseStructPrint($$$$$)
1448 {
1449         my($self,$struct,$ndr,$name,$varname) = @_;
1450
1451         return unless defined $struct->{ELEMENTS};
1452
1453         my $env = GenerateStructEnv($struct, $varname);
1454
1455         $self->DeclareArrayVariables($_) foreach (@{$struct->{ELEMENTS}});
1456
1457         $self->pidl("ndr_print_struct($ndr, name, \"$name\");");
1458
1459         $self->start_flags($struct, $ndr);
1460
1461         $self->pidl("$ndr->depth++;");
1462         
1463         $self->ParseElementPrint($_, $ndr, $env->{$_->{NAME}}, $env)
1464                 foreach (@{$struct->{ELEMENTS}});
1465         $self->pidl("$ndr->depth--;");
1466
1467         $self->end_flags($struct, $ndr);
1468 }
1469
1470 sub DeclarePtrVariables($$)
1471 {
1472         my ($self,$e) = @_;
1473         foreach my $l (@{$e->{LEVELS}}) {
1474                 if ($l->{TYPE} eq "POINTER" and 
1475                         not ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "TOP")) {
1476                         $self->pidl("uint32_t _ptr_$e->{NAME};");
1477                         last;
1478                 }
1479         }
1480 }
1481
1482 sub DeclareArrayVariables($$)
1483 {
1484         my ($self,$e) = @_;
1485
1486         foreach my $l (@{$e->{LEVELS}}) {
1487                 next if has_fast_array($e,$l);
1488                 next if is_charset_array($e,$l);
1489                 if ($l->{TYPE} eq "ARRAY") {
1490                         $self->pidl("uint32_t cntr_$e->{NAME}_$l->{LEVEL_INDEX};");
1491                 }
1492         }
1493 }
1494
1495 sub DeclareArrayVariablesNoZero($$$)
1496 {
1497         my ($self,$e,$env) = @_;
1498
1499         foreach my $l (@{$e->{LEVELS}}) {
1500                 next if has_fast_array($e,$l);
1501                 next if is_charset_array($e,$l);
1502                 if ($l->{TYPE} eq "ARRAY") {
1503                     my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
1504                     if ($length eq "0") {
1505                         warning($e->{ORIGINAL}, "pointless array cntr: 'cntr_$e->{NAME}_$l->{LEVEL_INDEX}': length=$length");
1506                     } else {
1507                         $self->pidl("uint32_t cntr_$e->{NAME}_$l->{LEVEL_INDEX};");
1508                     }
1509                 }
1510         }
1511 }
1512
1513 sub DeclareMemCtxVariables($$)
1514 {
1515         my ($self,$e) = @_;
1516         foreach my $l (@{$e->{LEVELS}}) {
1517                 my $mem_flags = $self->ParseMemCtxPullFlags($e, $l);
1518                 if (defined($mem_flags)) {
1519                         $self->pidl("TALLOC_CTX *_mem_save_$e->{NAME}_$l->{LEVEL_INDEX};");
1520                 }
1521         }
1522 }
1523
1524 sub ParseStructPullPrimitives($$$$$)
1525 {
1526         my($self,$struct,$ndr,$varname,$env) = @_;
1527
1528         if (defined $struct->{SURROUNDING_ELEMENT}) {
1529                 $self->pidl("NDR_CHECK(ndr_pull_array_size($ndr, &$varname->$struct->{SURROUNDING_ELEMENT}->{NAME}));");
1530         }
1531
1532         $self->pidl("NDR_CHECK(ndr_pull_align($ndr, $struct->{ALIGN}));");
1533
1534         if (defined($struct->{PROPERTIES}{relative_base})) {
1535                 # set the current offset as base for relative pointers
1536                 # and store it based on the toplevel struct/union
1537                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1538         }
1539
1540         $self->ParseElementPull($_, $ndr, $env, 1, 0) foreach (@{$struct->{ELEMENTS}});
1541
1542         $self->add_deferred();
1543
1544         $self->pidl("NDR_CHECK(ndr_pull_trailer_align($ndr, $struct->{ALIGN}));");
1545 }
1546
1547 sub ParseStructPullDeferred($$$$$)
1548 {
1549         my ($self,$struct,$ndr,$varname,$env) = @_;
1550
1551         if (defined($struct->{PROPERTIES}{relative_base})) {
1552                 # retrieve the current offset as base for relative pointers
1553                 # based on the toplevel struct/union
1554                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset2($ndr, $varname));");
1555         }
1556         foreach my $e (@{$struct->{ELEMENTS}}) {
1557                 $self->ParseElementPull($e, $ndr, $env, 0, 1);
1558         }
1559
1560         $self->add_deferred();
1561 }
1562
1563 #####################################################################
1564 # parse a struct - pull side
1565 sub ParseStructPull($$$$)
1566 {
1567         my($self,$struct,$ndr,$varname) = @_;
1568
1569         return unless defined $struct->{ELEMENTS};
1570
1571         # declare any internal pointers we need
1572         foreach my $e (@{$struct->{ELEMENTS}}) {
1573                 $self->DeclarePtrVariables($e);
1574                 $self->DeclareArrayVariables($e);
1575                 $self->DeclareMemCtxVariables($e);
1576         }
1577
1578         $self->start_flags($struct, $ndr);
1579
1580         my $env = GenerateStructEnv($struct, $varname);
1581
1582         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1583         $self->indent;
1584         $self->ParseStructPullPrimitives($struct,$ndr,$varname,$env);
1585         $self->deindent;
1586         $self->pidl("}");
1587         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1588         $self->indent;
1589         $self->ParseStructPullDeferred($struct,$ndr,$varname,$env);
1590         $self->deindent;
1591         $self->pidl("}");
1592
1593         $self->end_flags($struct, $ndr);
1594 }
1595
1596 #####################################################################
1597 # calculate size of ndr struct
1598 sub ParseStructNdrSize($$$$)
1599 {
1600         my ($self,$t, $name, $varname) = @_;
1601         my $sizevar;
1602
1603         if (my $flags = has_property($t, "flag")) {
1604                 $self->pidl("flags |= $flags;");
1605         }
1606         $self->pidl("return ndr_size_struct($varname, flags, (ndr_push_flags_fn_t)ndr_push_$name, ic);");
1607 }
1608
1609 sub DeclStruct($$$$)
1610 {
1611         my ($e,$t,$name,$varname) = @_;
1612         return ($t ne "pull"?"const ":"") . "struct $name *$varname";
1613 }
1614
1615 sub ArgsStructNdrSize($$$)
1616 {
1617         my ($d, $name, $varname) = @_;
1618         return "const struct $name *$varname, struct smb_iconv_convenience *ic, int flags";
1619 }
1620
1621 $typefamily{STRUCT} = {
1622         PUSH_FN_BODY => \&ParseStructPush,
1623         DECL => \&DeclStruct,
1624         PULL_FN_BODY => \&ParseStructPull,
1625         PRINT_FN_BODY => \&ParseStructPrint,
1626         SIZE_FN_BODY => \&ParseStructNdrSize,
1627         SIZE_FN_ARGS => \&ArgsStructNdrSize,
1628 };
1629
1630 #####################################################################
1631 # calculate size of ndr struct
1632 sub ParseUnionNdrSize($$$)
1633 {
1634         my ($self, $t, $name, $varname) = @_;
1635         my $sizevar;
1636
1637         if (my $flags = has_property($t, "flag")) {
1638                 $self->pidl("flags |= $flags;");
1639         }
1640
1641         $self->pidl("return ndr_size_union($varname, flags, level, (ndr_push_flags_fn_t)ndr_push_$name, ic);");
1642 }
1643
1644 sub ParseUnionPushPrimitives($$$$)
1645 {
1646         my ($self, $e, $ndr ,$varname) = @_;
1647
1648         my $have_default = 0;
1649
1650         $self->pidl("int level = ndr_push_get_switch_value($ndr, $varname);");
1651
1652         if (defined($e->{SWITCH_TYPE})) {
1653                 $self->pidl("NDR_CHECK(ndr_push_$e->{SWITCH_TYPE}($ndr, NDR_SCALARS, level));");
1654         }
1655
1656         if (defined($e->{ALIGN})) {
1657                 $self->pidl("NDR_CHECK(ndr_push_union_align($ndr, $e->{ALIGN}));");
1658         }
1659
1660         $self->pidl("switch (level) {");
1661         $self->indent;
1662         foreach my $el (@{$e->{ELEMENTS}}) {
1663                 if ($el->{CASE} eq "default") {
1664                         $have_default = 1;
1665                 }
1666                 $self->pidl("$el->{CASE}: {");
1667
1668                 if ($el->{TYPE} ne "EMPTY") {
1669                         $self->indent;
1670                         if (defined($e->{PROPERTIES}{relative_base})) {
1671                                 $self->pidl("NDR_CHECK(ndr_push_align($ndr, $el->{ALIGN}));");
1672                                 # set the current offset as base for relative pointers
1673                                 # and store it based on the toplevel struct/union
1674                                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1675                         }
1676                         $self->DeclareArrayVariables($el);
1677                         $self->ParseElementPush($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 1, 0);
1678                         $self->deindent;
1679                 }
1680                 $self->pidl("break; }");
1681                 $self->pidl("");
1682         }
1683         if (! $have_default) {
1684                 $self->pidl("default:");
1685                 $self->pidl("\treturn ndr_push_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1686         }
1687         $self->deindent;
1688         $self->pidl("}");
1689 }
1690
1691 sub ParseUnionPushDeferred($$$$)
1692 {
1693         my ($self,$e,$ndr,$varname) = @_;
1694
1695         my $have_default = 0;
1696
1697         $self->pidl("int level = ndr_push_get_switch_value($ndr, $varname);");
1698         if (defined($e->{PROPERTIES}{relative_base})) {
1699                 # retrieve the current offset as base for relative pointers
1700                 # based on the toplevel struct/union
1701                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset2($ndr, $varname));");
1702         }
1703         $self->pidl("switch (level) {");
1704         $self->indent;
1705         foreach my $el (@{$e->{ELEMENTS}}) {
1706                 if ($el->{CASE} eq "default") {
1707                         $have_default = 1;
1708                 }
1709
1710                 $self->pidl("$el->{CASE}:");
1711                 if ($el->{TYPE} ne "EMPTY") {
1712                         $self->indent;
1713                         $self->ParseElementPush($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 0, 1);
1714                         $self->deindent;
1715                 }
1716                 $self->pidl("break;");
1717                 $self->pidl("");
1718         }
1719         if (! $have_default) {
1720                 $self->pidl("default:");
1721                 $self->pidl("\treturn ndr_push_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1722         }
1723         $self->deindent;
1724         $self->pidl("}");
1725 }
1726
1727 #####################################################################
1728 # parse a union - push side
1729 sub ParseUnionPush($$$$)
1730 {
1731         my ($self,$e,$ndr,$varname) = @_;
1732         my $have_default = 0;
1733
1734         $self->start_flags($e, $ndr);
1735
1736         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1737         $self->indent;
1738         $self->ParseUnionPushPrimitives($e, $ndr, $varname);
1739         $self->deindent;
1740         $self->pidl("}");
1741         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1742         $self->indent;
1743         $self->ParseUnionPushDeferred($e, $ndr, $varname);
1744         $self->deindent;
1745         $self->pidl("}");
1746         $self->end_flags($e, $ndr);
1747 }
1748
1749 #####################################################################
1750 # print a union
1751 sub ParseUnionPrint($$$$$)
1752 {
1753         my ($self,$e,$ndr,$name,$varname) = @_;
1754         my $have_default = 0;
1755
1756         $self->pidl("int level;");
1757         foreach my $el (@{$e->{ELEMENTS}}) {
1758                 $self->DeclareArrayVariables($el);
1759         }
1760
1761         $self->start_flags($e, $ndr);
1762
1763         $self->pidl("level = ndr_print_get_switch_value($ndr, $varname);");
1764
1765         $self->pidl("ndr_print_union($ndr, name, level, \"$name\");");
1766
1767         $self->pidl("switch (level) {");
1768         $self->indent;
1769         foreach my $el (@{$e->{ELEMENTS}}) {
1770                 if ($el->{CASE} eq "default") {
1771                         $have_default = 1;
1772                 }
1773                 $self->pidl("$el->{CASE}:");
1774                 if ($el->{TYPE} ne "EMPTY") {
1775                         $self->indent;
1776                         $self->ParseElementPrint($el, $ndr, "$varname->$el->{NAME}", {});
1777                         $self->deindent;
1778                 }
1779                 $self->pidl("break;");
1780                 $self->pidl("");
1781         }
1782         if (! $have_default) {
1783                 $self->pidl("default:");
1784                 $self->pidl("\tndr_print_bad_level($ndr, name, level);");
1785         }
1786         $self->deindent;
1787         $self->pidl("}");
1788
1789         $self->end_flags($e, $ndr);
1790 }
1791
1792 sub ParseUnionPullPrimitives($$$$$)
1793 {
1794         my ($self,$e,$ndr,$varname,$switch_type) = @_;
1795         my $have_default = 0;
1796
1797         if (defined($switch_type)) {
1798                 $self->pidl("NDR_CHECK(ndr_pull_$switch_type($ndr, NDR_SCALARS, &_level));");
1799                 $self->pidl("if (_level != level) {"); 
1800                 $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value %u for $varname at \%s\", _level, __location__);");
1801                 $self->pidl("}");
1802         }
1803
1804         if (defined($e->{ALIGN})) {
1805                 $self->pidl("NDR_CHECK(ndr_pull_union_align($ndr, $e->{ALIGN}));");
1806         }
1807
1808         $self->pidl("switch (level) {");
1809         $self->indent;
1810         foreach my $el (@{$e->{ELEMENTS}}) {
1811                 if ($el->{CASE} eq "default") {
1812                         $have_default = 1;
1813                 } 
1814                 $self->pidl("$el->{CASE}: {");
1815
1816                 if ($el->{TYPE} ne "EMPTY") {
1817                         $self->indent;
1818                         $self->DeclarePtrVariables($el);
1819                         $self->DeclareArrayVariables($el);
1820                         if (defined($e->{PROPERTIES}{relative_base})) {
1821                                 $self->pidl("NDR_CHECK(ndr_pull_align($ndr, $el->{ALIGN}));");
1822                                 # set the current offset as base for relative pointers
1823                                 # and store it based on the toplevel struct/union
1824                                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1825                         }
1826                         $self->ParseElementPull($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 1, 0);
1827                         $self->deindent;
1828                 }
1829                 $self->pidl("break; }");
1830                 $self->pidl("");
1831         }
1832         if (! $have_default) {
1833                 $self->pidl("default:");
1834                 $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1835         }
1836         $self->deindent;
1837         $self->pidl("}");
1838 }
1839
1840 sub ParseUnionPullDeferred($$$$)
1841 {
1842         my ($self,$e,$ndr,$varname) = @_;
1843         my $have_default = 0;
1844
1845         if (defined($e->{PROPERTIES}{relative_base})) {
1846                 # retrieve the current offset as base for relative pointers
1847                 # based on the toplevel struct/union
1848                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset2($ndr, $varname));");
1849         }
1850         $self->pidl("switch (level) {");
1851         $self->indent;
1852         foreach my $el (@{$e->{ELEMENTS}}) {
1853                 if ($el->{CASE} eq "default") {
1854                         $have_default = 1;
1855                 } 
1856
1857                 $self->pidl("$el->{CASE}:");
1858                 if ($el->{TYPE} ne "EMPTY") {
1859                         $self->indent;
1860                         $self->ParseElementPull($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 0, 1);
1861                         $self->deindent;
1862                 }
1863                 $self->pidl("break;");
1864                 $self->pidl("");
1865         }
1866         if (! $have_default) {
1867                 $self->pidl("default:");
1868                 $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1869         }
1870         $self->deindent;
1871         $self->pidl("}");
1872
1873
1874 }
1875
1876 #####################################################################
1877 # parse a union - pull side
1878 sub ParseUnionPull($$$$)
1879 {
1880         my ($self,$e,$ndr,$varname) = @_;
1881         my $switch_type = $e->{SWITCH_TYPE};
1882
1883         $self->pidl("int level;");
1884         if (defined($switch_type)) {
1885                 if (Parse::Pidl::Typelist::typeIs($switch_type, "ENUM")) {
1886                         $switch_type = Parse::Pidl::Typelist::enum_type_fn(getType($switch_type)->{DATA});
1887                 }
1888                 $self->pidl(mapTypeName($switch_type) . " _level;");
1889         }
1890
1891         my %double_cases = ();
1892         foreach my $el (@{$e->{ELEMENTS}}) {
1893                 next if ($el->{TYPE} eq "EMPTY");
1894                 next if ($double_cases{"$el->{NAME}"});
1895                 $self->DeclareMemCtxVariables($el);
1896                 $double_cases{"$el->{NAME}"} = 1;
1897         }
1898
1899         $self->start_flags($e, $ndr);
1900
1901         $self->pidl("level = ndr_pull_get_switch_value($ndr, $varname);");
1902
1903         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1904         $self->indent;
1905         $self->ParseUnionPullPrimitives($e,$ndr,$varname,$switch_type);
1906         $self->deindent;
1907         $self->pidl("}");
1908
1909         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1910         $self->indent;
1911         $self->ParseUnionPullDeferred($e,$ndr,$varname);
1912         $self->deindent;
1913         $self->pidl("}");
1914
1915         $self->add_deferred();
1916
1917         $self->end_flags($e, $ndr);
1918 }
1919
1920 sub DeclUnion($$$$)
1921 {
1922         my ($e,$t,$name,$varname) = @_;
1923         return ($t ne "pull"?"const ":"") . "union $name *$varname";
1924 }
1925
1926 sub ArgsUnionNdrSize($$)
1927 {
1928         my ($d,$name) = @_;
1929         return "const union $name *r, uint32_t level, struct smb_iconv_convenience *ic, int flags";
1930 }
1931
1932 $typefamily{UNION} = {
1933         PUSH_FN_BODY => \&ParseUnionPush,
1934         DECL => \&DeclUnion,
1935         PULL_FN_BODY => \&ParseUnionPull,
1936         PRINT_FN_BODY => \&ParseUnionPrint,
1937         SIZE_FN_ARGS => \&ArgsUnionNdrSize,
1938         SIZE_FN_BODY => \&ParseUnionNdrSize,
1939 };
1940         
1941 #####################################################################
1942 # parse a typedef - push side
1943 sub ParseTypedefPush($$$$)
1944 {
1945         my($self,$e,$ndr,$varname) = @_;
1946
1947         my $env;
1948
1949         $env->{$e->{NAME}} = $varname;
1950
1951         $self->ParseElementPushLevel($e, $e->{LEVELS}[0], $ndr, $varname, $env, 1, 1);
1952 }
1953
1954 #####################################################################
1955 # parse a typedef - pull side
1956 sub ParseTypedefPull($$$$)
1957 {
1958         my($self,$e,$ndr,$varname) = @_;
1959
1960         my $env;
1961
1962         $env->{$e->{NAME}} = $varname;
1963
1964         $self->ParseElementPullLevel($e, $e->{LEVELS}[0], $ndr, $varname, $env, 1, 1);
1965 }
1966
1967 #####################################################################
1968 # parse a typedef - print side
1969 sub ParseTypedefPrint($$$$$)
1970 {
1971         my($self,$e,$ndr,$name,$varname) = @_;
1972
1973         $typefamily{$e->{DATA}->{TYPE}}->{PRINT_FN_BODY}->($self, $e->{DATA}, $ndr, $name, $varname);
1974 }
1975
1976 #####################################################################
1977 ## calculate the size of a structure
1978 sub ParseTypedefNdrSize($$$$)
1979 {
1980         my($self,$t,$name,$varname) = @_;
1981
1982         $typefamily{$t->{DATA}->{TYPE}}->{SIZE_FN_BODY}->($self, $t->{DATA}, $name, $varname);
1983 }
1984
1985 sub DeclTypedef($$$$)
1986 {
1987         my ($e, $t, $name, $varname) = @_;
1988         
1989         return $typefamily{$e->{DATA}->{TYPE}}->{DECL}->($e->{DATA}, $t, $name, $varname);
1990 }
1991
1992 sub ArgsTypedefNdrSize($$$)
1993 {
1994         my ($d, $name, $varname) = @_;
1995         return $typefamily{$d->{DATA}->{TYPE}}->{SIZE_FN_ARGS}->($d->{DATA}, $name, $varname);
1996 }
1997
1998 $typefamily{TYPEDEF} = {
1999         PUSH_FN_BODY => \&ParseTypedefPush,
2000         DECL => \&DeclTypedef,
2001         PULL_FN_BODY => \&ParseTypedefPull,
2002         PRINT_FN_BODY => \&ParseTypedefPrint,
2003         SIZE_FN_ARGS => \&ArgsTypedefNdrSize,
2004         SIZE_FN_BODY => \&ParseTypedefNdrSize,
2005 };
2006
2007 #####################################################################
2008 # parse a function - print side
2009 sub ParseFunctionPrint($$)
2010 {
2011         my($self, $fn) = @_;
2012         my $ndr = "ndr";
2013
2014         $self->pidl_hdr("void ndr_print_$fn->{NAME}(struct ndr_print *$ndr, const char *name, int flags, const struct $fn->{NAME} *r);");
2015
2016         return if has_property($fn, "noprint");
2017
2018         $self->pidl("_PUBLIC_ void ndr_print_$fn->{NAME}(struct ndr_print *$ndr, const char *name, int flags, const struct $fn->{NAME} *r)");
2019         $self->pidl("{");
2020         $self->indent;
2021
2022         foreach my $e (@{$fn->{ELEMENTS}}) {
2023                 $self->DeclareArrayVariables($e);
2024         }
2025
2026         $self->pidl("ndr_print_struct($ndr, name, \"$fn->{NAME}\");");
2027         $self->pidl("$ndr->depth++;");
2028
2029         $self->pidl("if (flags & NDR_SET_VALUES) {");
2030         $self->pidl("\t$ndr->flags |= LIBNDR_PRINT_SET_VALUES;");
2031         $self->pidl("}");
2032
2033         $self->pidl("if (flags & NDR_IN) {");
2034         $self->indent;
2035         $self->pidl("ndr_print_struct($ndr, \"in\", \"$fn->{NAME}\");");
2036         $self->pidl("$ndr->depth++;");
2037
2038         my $env = GenerateFunctionInEnv($fn);
2039
2040         foreach my $e (@{$fn->{ELEMENTS}}) {
2041                 if (grep(/in/,@{$e->{DIRECTION}})) {
2042                         $self->ParseElementPrint($e, $ndr, $env->{$e->{NAME}}, $env);
2043                 }
2044         }
2045         $self->pidl("$ndr->depth--;");
2046         $self->deindent;
2047         $self->pidl("}");
2048         
2049         $self->pidl("if (flags & NDR_OUT) {");
2050         $self->indent;
2051         $self->pidl("ndr_print_struct($ndr, \"out\", \"$fn->{NAME}\");");
2052         $self->pidl("$ndr->depth++;");
2053
2054         $env = GenerateFunctionOutEnv($fn);
2055         foreach my $e (@{$fn->{ELEMENTS}}) {
2056                 if (grep(/out/,@{$e->{DIRECTION}})) {
2057                         $self->ParseElementPrint($e, $ndr, $env->{$e->{NAME}}, $env);
2058                 }
2059         }
2060         if ($fn->{RETURN_TYPE}) {
2061                 $self->pidl("ndr_print_$fn->{RETURN_TYPE}($ndr, \"result\", r->out.result);");
2062         }
2063         $self->pidl("$ndr->depth--;");
2064         $self->deindent;
2065         $self->pidl("}");
2066         
2067         $self->pidl("$ndr->depth--;");
2068         $self->deindent;
2069         $self->pidl("}");
2070         $self->pidl("");
2071 }
2072
2073 #####################################################################
2074 # parse a function
2075 sub ParseFunctionPush($$)
2076
2077         my($self, $fn) = @_;
2078         my $ndr = "ndr";
2079
2080         $self->fn_declare("push", $fn, "enum ndr_err_code ndr_push_$fn->{NAME}(struct ndr_push *$ndr, int flags, const struct $fn->{NAME} *r)") or return;
2081
2082         return if has_property($fn, "nopush");
2083
2084         $self->pidl("{");
2085         $self->indent;
2086
2087         foreach my $e (@{$fn->{ELEMENTS}}) { 
2088                 $self->DeclareArrayVariables($e);
2089         }
2090
2091         $self->pidl("if (flags & NDR_IN) {");
2092         $self->indent;
2093
2094         my $env = GenerateFunctionInEnv($fn);
2095
2096         EnvSubstituteValue($env, $fn);
2097
2098         foreach my $e (@{$fn->{ELEMENTS}}) {
2099                 if (grep(/in/,@{$e->{DIRECTION}})) {
2100                         $self->ParseElementPush($e, $ndr, $env, 1, 1);
2101                 }
2102         }
2103
2104         $self->deindent;
2105         $self->pidl("}");
2106
2107         $self->pidl("if (flags & NDR_OUT) {");
2108         $self->indent;
2109
2110         $env = GenerateFunctionOutEnv($fn);
2111         foreach my $e (@{$fn->{ELEMENTS}}) {
2112                 if (grep(/out/,@{$e->{DIRECTION}})) {
2113                         $self->ParseElementPush($e, $ndr, $env, 1, 1);
2114                 }
2115         }
2116
2117         if ($fn->{RETURN_TYPE}) {
2118                 $self->pidl("NDR_CHECK(ndr_push_$fn->{RETURN_TYPE}($ndr, NDR_SCALARS, r->out.result));");
2119         }
2120     
2121         $self->deindent;
2122         $self->pidl("}");
2123         $self->pidl("return NDR_ERR_SUCCESS;");
2124         $self->deindent;
2125         $self->pidl("}");
2126         $self->pidl("");
2127 }
2128
2129 sub AllocateArrayLevel($$$$$$)
2130 {
2131         my ($self,$e,$l,$ndr,$var,$size) = @_;
2132
2133         my $pl = GetPrevLevel($e, $l);
2134         if (defined($pl) and 
2135             $pl->{TYPE} eq "POINTER" and 
2136             $pl->{POINTER_TYPE} eq "ref"
2137             and not $l->{IS_ZERO_TERMINATED}) {
2138                 $self->pidl("if ($ndr->flags & LIBNDR_FLAG_REF_ALLOC) {");
2139                 $self->pidl("\tNDR_PULL_ALLOC_N($ndr, $var, $size);");
2140                 $self->pidl("}");
2141                 if (grep(/in/,@{$e->{DIRECTION}}) and
2142                     grep(/out/,@{$e->{DIRECTION}})) {
2143                         $self->pidl("memcpy(r->out.$e->{NAME}, r->in.$e->{NAME}, ($size) * sizeof(*r->in.$e->{NAME}));");
2144                 }
2145                 return;
2146         }
2147
2148         $self->pidl("NDR_PULL_ALLOC_N($ndr, $var, $size);");
2149 }
2150
2151 #####################################################################
2152 # parse a function
2153 sub ParseFunctionPull($$)
2154
2155         my($self,$fn) = @_;
2156         my $ndr = "ndr";
2157
2158         # pull function args
2159         $self->fn_declare("pull", $fn, "enum ndr_err_code ndr_pull_$fn->{NAME}(struct ndr_pull *$ndr, int flags, struct $fn->{NAME} *r)") or return;
2160
2161         $self->pidl("{");
2162         $self->indent;
2163
2164         # declare any internal pointers we need
2165         foreach my $e (@{$fn->{ELEMENTS}}) { 
2166                 $self->DeclarePtrVariables($e);
2167                 $self->DeclareArrayVariables($e);
2168         }
2169
2170         my %double_cases = ();
2171         foreach my $e (@{$fn->{ELEMENTS}}) {
2172                 next if ($e->{TYPE} eq "EMPTY");
2173                 next if ($double_cases{"$e->{NAME}"});
2174                 $self->DeclareMemCtxVariables($e);
2175                 $double_cases{"$e->{NAME}"} = 1;
2176         }
2177
2178         $self->pidl("if (flags & NDR_IN) {");
2179         $self->indent;
2180
2181         # auto-init the out section of a structure. I originally argued that
2182         # this was a bad idea as it hides bugs, but coping correctly
2183         # with initialisation and not wiping ref vars is turning
2184         # out to be too tricky (tridge)
2185         foreach my $e (@{$fn->{ELEMENTS}}) {
2186                 next unless grep(/out/, @{$e->{DIRECTION}});
2187                 $self->pidl("ZERO_STRUCT(r->out);");
2188                 $self->pidl("");
2189                 last;
2190         }
2191
2192         my $env = GenerateFunctionInEnv($fn);
2193
2194         foreach my $e (@{$fn->{ELEMENTS}}) {
2195                 next unless (grep(/in/, @{$e->{DIRECTION}}));
2196                 $self->ParseElementPull($e, $ndr, $env, 1, 1);
2197         }
2198
2199         # allocate the "simple" out ref variables. FIXME: Shouldn't this have it's
2200         # own flag rather than be in NDR_IN ?
2201
2202         foreach my $e (@{$fn->{ELEMENTS}}) {
2203                 next unless (grep(/out/, @{$e->{DIRECTION}}));
2204                 next unless ($e->{LEVELS}[0]->{TYPE} eq "POINTER" and 
2205                              $e->{LEVELS}[0]->{POINTER_TYPE} eq "ref");
2206                 next if (($e->{LEVELS}[1]->{TYPE} eq "DATA") and 
2207                                  ($e->{LEVELS}[1]->{DATA_TYPE} eq "string"));
2208                 next if (($e->{LEVELS}[1]->{TYPE} eq "ARRAY") 
2209                         and   $e->{LEVELS}[1]->{IS_ZERO_TERMINATED});
2210
2211                 if ($e->{LEVELS}[1]->{TYPE} eq "ARRAY") {
2212                         my $size = ParseExprExt($e->{LEVELS}[1]->{SIZE_IS}, $env, $e->{ORIGINAL},
2213                                 check_null_pointer($e, $env, sub { $self->pidl(shift); },
2214                                                    "return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for size_is()\");"),
2215                                 check_fully_dereferenced($e, $env));
2216                         $self->pidl("NDR_PULL_ALLOC_N($ndr, r->out.$e->{NAME}, $size);");
2217
2218                         if (grep(/in/, @{$e->{DIRECTION}})) {
2219                                 $self->pidl("memcpy(r->out.$e->{NAME}, r->in.$e->{NAME}, ($size) * sizeof(*r->in.$e->{NAME}));");
2220                         } else {
2221                                 $self->pidl("memset(r->out.$e->{NAME}, 0, ($size) * sizeof(*r->out.$e->{NAME}));");
2222                         }
2223                 } else {
2224                         $self->pidl("NDR_PULL_ALLOC($ndr, r->out.$e->{NAME});");
2225                 
2226                         if (grep(/in/, @{$e->{DIRECTION}})) {
2227                                 $self->pidl("*r->out.$e->{NAME} = *r->in.$e->{NAME};");
2228                         } else {
2229                                 $self->pidl("ZERO_STRUCTP(r->out.$e->{NAME});");
2230                         }
2231                 }
2232         }
2233
2234         $self->add_deferred();
2235         $self->deindent;
2236         $self->pidl("}");
2237         
2238         $self->pidl("if (flags & NDR_OUT) {");
2239         $self->indent;
2240
2241         $env = GenerateFunctionOutEnv($fn);
2242         foreach my $e (@{$fn->{ELEMENTS}}) {
2243                 next unless grep(/out/, @{$e->{DIRECTION}});
2244                 $self->ParseElementPull($e, $ndr, $env, 1, 1);
2245         }
2246
2247         if ($fn->{RETURN_TYPE}) {
2248                 $self->pidl("NDR_CHECK(ndr_pull_$fn->{RETURN_TYPE}($ndr, NDR_SCALARS, &r->out.result));");
2249         }
2250
2251         $self->add_deferred();
2252         $self->deindent;
2253         $self->pidl("}");
2254
2255         $self->pidl("return NDR_ERR_SUCCESS;");
2256         $self->deindent;
2257         $self->pidl("}");
2258         $self->pidl("");
2259 }
2260
2261 sub AuthServiceStruct($$$)
2262 {
2263         my ($self, $ifacename, $authservice) = @_;
2264         my @a = split /,/, $authservice;
2265         my $authservice_count = $#a + 1;
2266
2267         $self->pidl("static const char * const $ifacename\_authservice_strings[] = {");
2268         foreach my $ap (@a) {
2269                 $self->pidl("\t$ap, ");
2270         }
2271         $self->pidl("};");
2272         $self->pidl("");
2273
2274         $self->pidl("static const struct ndr_interface_string_array $ifacename\_authservices = {");
2275         $self->pidl("\t.count\t= $authservice_count,");
2276         $self->pidl("\t.names\t= $ifacename\_authservice_strings");
2277         $self->pidl("};");
2278         $self->pidl("");
2279 }
2280
2281 sub FunctionCallEntry($$)
2282 {
2283         my ($self, $d) = @_;
2284         return 0 if not defined($d->{OPNUM});
2285         $self->pidl("\t{");
2286         $self->pidl("\t\t\"$d->{NAME}\",");
2287         $self->pidl("\t\tsizeof(struct $d->{NAME}),");
2288         $self->pidl("\t\t(ndr_push_flags_fn_t) ndr_push_$d->{NAME},");
2289         $self->pidl("\t\t(ndr_pull_flags_fn_t) ndr_pull_$d->{NAME},");
2290         $self->pidl("\t\t(ndr_print_function_t) ndr_print_$d->{NAME},");
2291         $self->pidl("\t\t".($d->{ASYNC}?"true":"false").",");
2292         $self->pidl("\t},");
2293         return 1;
2294 }
2295
2296 #####################################################################
2297 # produce a function call table
2298 sub FunctionTable($$)
2299 {
2300         my($self,$interface) = @_;
2301         my $count = 0;
2302         my $uname = uc $interface->{NAME};
2303
2304         return if ($#{$interface->{FUNCTIONS}}+1 == 0);
2305         return unless defined ($interface->{PROPERTIES}->{uuid});
2306
2307         $self->pidl("static const struct ndr_interface_call $interface->{NAME}\_calls[] = {");
2308
2309         foreach my $d (@{$interface->{INHERITED_FUNCTIONS}},@{$interface->{FUNCTIONS}}) {
2310                 $count += $self->FunctionCallEntry($d);
2311         }
2312         $self->pidl("\t{ NULL, 0, NULL, NULL, NULL, false }");
2313         $self->pidl("};");
2314         $self->pidl("");
2315
2316         $self->pidl("static const char * const $interface->{NAME}\_endpoint_strings[] = {");
2317         foreach my $ep (@{$interface->{ENDPOINTS}}) {
2318                 $self->pidl("\t$ep, ");
2319         }
2320         my $endpoint_count = $#{$interface->{ENDPOINTS}}+1;
2321         
2322         $self->pidl("};");
2323         $self->pidl("");
2324
2325         $self->pidl("static const struct ndr_interface_string_array $interface->{NAME}\_endpoints = {");
2326         $self->pidl("\t.count\t= $endpoint_count,");
2327         $self->pidl("\t.names\t= $interface->{NAME}\_endpoint_strings");
2328         $self->pidl("};");
2329         $self->pidl("");
2330
2331         if (! defined $interface->{PROPERTIES}->{authservice}) {
2332                 $interface->{PROPERTIES}->{authservice} = "\"host\"";
2333         }
2334
2335         $self->AuthServiceStruct($interface->{NAME}, 
2336                                      $interface->{PROPERTIES}->{authservice});
2337
2338         $self->pidl("\nconst struct ndr_interface_table ndr_table_$interface->{NAME} = {");
2339         $self->pidl("\t.name\t\t= \"$interface->{NAME}\",");
2340         $self->pidl("\t.syntax_id\t= {");
2341         $self->pidl("\t\t" . print_uuid($interface->{UUID}) .",");
2342         $self->pidl("\t\tNDR_$uname\_VERSION");
2343         $self->pidl("\t},");
2344         $self->pidl("\t.helpstring\t= NDR_$uname\_HELPSTRING,");
2345         $self->pidl("\t.num_calls\t= $count,");
2346         $self->pidl("\t.calls\t\t= $interface->{NAME}\_calls,");
2347         $self->pidl("\t.endpoints\t= &$interface->{NAME}\_endpoints,");
2348         $self->pidl("\t.authservices\t= &$interface->{NAME}\_authservices");
2349         $self->pidl("};");
2350         $self->pidl("");
2351
2352 }
2353
2354 #####################################################################
2355 # generate include statements for imported idl files
2356 sub HeaderImport
2357 {
2358         my $self = shift;
2359         my @imports = @_;
2360         foreach (@imports) {
2361                 $_ = unmake_str($_);
2362                 s/\.idl$//;
2363                 $self->pidl(choose_header("librpc/gen_ndr/ndr_$_\.h", "gen_ndr/ndr_$_.h"));
2364         }
2365 }
2366
2367 #####################################################################
2368 # generate include statements for included header files
2369 sub HeaderInclude
2370 {
2371         my $self = shift;
2372         my @includes = @_;
2373         foreach (@includes) {
2374                 $self->pidl_hdr("#include $_");
2375         }
2376 }
2377
2378 #####################################################################
2379 # generate prototypes and defines for the interface definitions
2380 # FIXME: these prototypes are for the DCE/RPC client functions, not the 
2381 # NDR parser and so do not belong here, technically speaking
2382 sub HeaderInterface($$$)
2383 {
2384         my($self,$interface,$needed) = @_;
2385
2386         my $count = 0;
2387
2388         if ($needed->{"compression"}) {
2389                 $self->pidl(choose_header("librpc/ndr/ndr_compression.h", "ndr/compression.h"));
2390         }
2391
2392         if (has_property($interface, "object")) {
2393                 $self->pidl(choose_header("librpc/gen_ndr/ndr_orpc.h", "ndr/orpc.h"));
2394         }
2395
2396         if (defined $interface->{PROPERTIES}->{helper}) {
2397                 $self->HeaderInclude(split /,/, $interface->{PROPERTIES}->{helper});
2398         }
2399
2400         if (defined $interface->{PROPERTIES}->{uuid}) {
2401                 my $name = uc $interface->{NAME};
2402                 $self->pidl_hdr("#define NDR_$name\_UUID " . 
2403                 Parse::Pidl::Util::make_str(lc($interface->{PROPERTIES}->{uuid})));
2404
2405                 if(!defined $interface->{PROPERTIES}->{version}) { $interface->{PROPERTIES}->{version} = "0.0"; }
2406                 $self->pidl_hdr("#define NDR_$name\_VERSION $interface->{PROPERTIES}->{version}");
2407
2408                 $self->pidl_hdr("#define NDR_$name\_NAME \"$interface->{NAME}\"");
2409
2410                 if(!defined $interface->{PROPERTIES}->{helpstring}) { $interface->{PROPERTIES}->{helpstring} = "NULL"; }
2411                 $self->pidl_hdr("#define NDR_$name\_HELPSTRING $interface->{PROPERTIES}->{helpstring}");
2412
2413                 $self->pidl_hdr("extern const struct ndr_interface_table ndr_table_$interface->{NAME};");
2414         }
2415
2416         foreach (@{$interface->{FUNCTIONS}}) {
2417                 next if has_property($_, "noopnum");
2418                 next if grep(/^$_->{NAME}$/,@{$interface->{INHERITED_FUNCTIONS}});
2419                 my $u_name = uc $_->{NAME};
2420         
2421                 my $val = sprintf("0x%02x", $count);
2422                 if (defined($interface->{BASE})) {
2423                         $val .= " + NDR_" . uc $interface->{BASE} . "_CALL_COUNT";
2424                 }
2425                 
2426                 $self->pidl_hdr("#define NDR_$u_name ($val)");
2427
2428                 $self->pidl_hdr("");
2429                 $count++;
2430         }
2431
2432         my $val = $count;
2433
2434         if (defined($interface->{BASE})) {
2435                 $val .= " + NDR_" . uc $interface->{BASE} . "_CALL_COUNT";
2436         }
2437
2438         $self->pidl_hdr("#define NDR_" . uc $interface->{NAME} . "_CALL_COUNT ($val)");
2439
2440 }
2441
2442 sub ParseTypePush($$$$$$)
2443 {
2444         my ($self,$e, $ndr, $varname, $primitives, $deferred) = @_;
2445
2446         # save the old relative_base_offset
2447         $self->pidl("uint32_t _save_relative_base_offset = ndr_push_get_relative_base_offset($ndr);") if defined(has_property($e, "relative_base"));
2448         $typefamily{$e->{TYPE}}->{PUSH_FN_BODY}->($self, $e, $ndr, $varname);
2449         # restore the old relative_base_offset
2450         $self->pidl("ndr_push_restore_relative_base_offset($ndr, _save_relative_base_offset);") if defined(has_property($e, "relative_base"));
2451 }
2452
2453 sub ParseTypePushFunction($$$)
2454 {
2455         my ($self, $e, $varname) = @_;
2456         my $ndr = "ndr";
2457
2458         my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "push", $e->{NAME}, $varname);
2459
2460         $self->fn_declare("push", $e, "enum ndr_err_code ".TypeFunctionName("ndr_push", $e)."(struct ndr_push *$ndr, int ndr_flags, $args)") or return;
2461
2462         $self->pidl("{");
2463         $self->indent;
2464         $self->ParseTypePush($e, $ndr, $varname, 1, 1);
2465         $self->pidl("return NDR_ERR_SUCCESS;");
2466         $self->deindent;
2467         $self->pidl("}");
2468         $self->pidl("");;
2469 }
2470
2471 sub ParseTypePull($$$$$$)
2472 {
2473         my ($self, $e, $ndr, $varname, $primitives, $deferred) = @_;
2474
2475         # save the old relative_base_offset
2476         $self->pidl("uint32_t _save_relative_base_offset = ndr_pull_get_relative_base_offset($ndr);") if defined(has_property($e, "relative_base"));
2477         $typefamily{$e->{TYPE}}->{PULL_FN_BODY}->($self, $e, $ndr, $varname);
2478         # restore the old relative_base_offset
2479         $self->pidl("ndr_pull_restore_relative_base_offset($ndr, _save_relative_base_offset);") if defined(has_property($e, "relative_base"));
2480 }
2481
2482 sub ParseTypePullFunction($$)
2483 {
2484         my ($self, $e, $varname) = @_;
2485         my $ndr = "ndr";
2486
2487         my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "pull", $e->{NAME}, $varname);
2488
2489         $self->fn_declare("pull", $e, "enum ndr_err_code ".TypeFunctionName("ndr_pull", $e)."(struct ndr_pull *$ndr, int ndr_flags, $args)") or return;
2490
2491         $self->pidl("{");
2492         $self->indent;
2493         $self->ParseTypePull($e, $ndr, $varname, 1, 1);
2494         $self->pidl("return NDR_ERR_SUCCESS;");
2495         $self->deindent;
2496         $self->pidl("}");
2497         $self->pidl("");
2498 }
2499
2500 sub ParseTypePrint($$$$)
2501 {
2502         my ($self, $e, $ndr, $varname) = @_;
2503
2504         $typefamily{$e->{TYPE}}->{PRINT_FN_BODY}->($self, $e, $ndr, $e->{NAME}, $varname);
2505 }
2506
2507 sub ParseTypePrintFunction($$$)
2508 {
2509         my ($self, $e, $varname) = @_;
2510         my $ndr = "ndr";
2511
2512         my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "print", $e->{NAME}, $varname);
2513
2514         $self->pidl_hdr("void ".TypeFunctionName("ndr_print", $e)."(struct ndr_print *ndr, const char *name, $args);");
2515
2516         return if (has_property($e, "noprint"));
2517
2518         $self->pidl("_PUBLIC_ void ".TypeFunctionName("ndr_print", $e)."(struct ndr_print *$ndr, const char *name, $args)");
2519         $self->pidl("{");
2520         $self->indent;
2521         $self->ParseTypePrint($e, $ndr, $varname);
2522         $self->deindent;
2523         $self->pidl("}");
2524         $self->pidl("");
2525 }
2526
2527 sub ParseTypeNdrSize($$)
2528 {
2529         my ($self,$t) = @_;
2530
2531         my $varname = "r";
2532         my $tf = $typefamily{$t->{TYPE}};
2533         my $args = $tf->{SIZE_FN_ARGS}->($t, $t->{NAME}, $varname);
2534
2535         $self->fn_declare("size", $t, "size_t ndr_size_$t->{NAME}($args)") or return;
2536
2537         $self->pidl("{");
2538         $self->indent;
2539         $typefamily{$t->{TYPE}}->{SIZE_FN_BODY}->($self,$t, $t->{NAME}, $varname);
2540         $self->deindent;
2541         $self->pidl("}");
2542         $self->pidl("");
2543 }
2544
2545 #####################################################################
2546 # parse the interface definitions
2547 sub ParseInterface($$$)
2548 {
2549         my($self,$interface,$needed) = @_;
2550
2551         $self->pidl_hdr("#ifndef _HEADER_NDR_$interface->{NAME}");
2552         $self->pidl_hdr("#define _HEADER_NDR_$interface->{NAME}");
2553
2554         $self->pidl_hdr("");
2555
2556         $self->HeaderInterface($interface, $needed);
2557
2558         # Typedefs
2559         foreach my $d (@{$interface->{TYPES}}) {
2560                 next unless(typeHasBody($d));
2561
2562                 ($needed->{TypeFunctionName("ndr_push", $d)}) && $self->ParseTypePushFunction($d, "r");
2563                 ($needed->{TypeFunctionName("ndr_pull", $d)}) && $self->ParseTypePullFunction($d, "r");
2564                 ($needed->{TypeFunctionName("ndr_print", $d)}) && $self->ParseTypePrintFunction($d, "r");
2565
2566                 # Make sure we don't generate a function twice...
2567                 $needed->{TypeFunctionName("ndr_push", $d)} = 
2568                     $needed->{TypeFunctionName("ndr_pull", $d)} = 
2569                         $needed->{TypeFunctionName("ndr_print", $d)} = 0;
2570
2571                 ($needed->{"ndr_size_$d->{NAME}"}) && $self->ParseTypeNdrSize($d);
2572         }
2573
2574         # Functions
2575         foreach my $d (@{$interface->{FUNCTIONS}}) {
2576                 ($needed->{"ndr_push_$d->{NAME}"}) && $self->ParseFunctionPush($d);
2577                 ($needed->{"ndr_pull_$d->{NAME}"}) && $self->ParseFunctionPull($d);
2578                 ($needed->{"ndr_print_$d->{NAME}"}) && $self->ParseFunctionPrint($d);
2579
2580                 # Make sure we don't generate a function twice...
2581                 $needed->{"ndr_push_$d->{NAME}"} = $needed->{"ndr_pull_$d->{NAME}"} = 
2582                         $needed->{"ndr_print_$d->{NAME}"} = 0;
2583         }
2584
2585         $self->FunctionTable($interface);
2586
2587         $self->pidl_hdr("#endif /* _HEADER_NDR_$interface->{NAME} */");
2588 }
2589
2590 sub GenerateIncludes($)
2591 {
2592         my ($self) = @_;
2593         if (is_intree()) {
2594                 $self->pidl("#include \"includes.h\"");
2595         } else {
2596                 $self->pidl("#ifndef _GNU_SOURCE");
2597                 $self->pidl("#define _GNU_SOURCE");
2598                 $self->pidl("#endif");
2599                 $self->pidl("#include <stdint.h>");
2600                 $self->pidl("#include <stdlib.h>");
2601                 $self->pidl("#include <stdio.h>");
2602                 $self->pidl("#include <stdbool.h>");
2603                 $self->pidl("#include <stdarg.h>");
2604                 $self->pidl("#include <string.h>");
2605         }
2606 }
2607
2608 #####################################################################
2609 # parse a parsed IDL structure back into an IDL file
2610 sub Parse($$$$)
2611 {
2612         my($self, $ndr,$gen_header,$ndr_header) = @_;
2613
2614         $self->pidl_hdr("/* header auto-generated by pidl */");
2615         $self->pidl_hdr("");
2616         $self->pidl_hdr(choose_header("librpc/ndr/libndr.h", "ndr.h"));
2617         $self->pidl_hdr("#include \"$gen_header\"") if ($gen_header);
2618         $self->pidl_hdr("");
2619
2620         $self->pidl("/* parser auto-generated by pidl */");
2621         $self->pidl("");
2622         $self->GenerateIncludes();
2623         $self->pidl("#include \"$ndr_header\"") if ($ndr_header);
2624         $self->pidl("");
2625
2626         my %needed = ();
2627
2628         foreach (@{$ndr}) {
2629                 ($_->{TYPE} eq "INTERFACE") && NeededInterface($_, \%needed);
2630         }
2631
2632         foreach (@{$ndr}) {
2633                 ($_->{TYPE} eq "INTERFACE") && $self->ParseInterface($_, \%needed);
2634                 ($_->{TYPE} eq "IMPORT") && $self->HeaderImport(@{$_->{PATHS}});
2635                 ($_->{TYPE} eq "INCLUDE") && $self->HeaderInclude(@{$_->{PATHS}});
2636         }
2637
2638         return ($self->{res_hdr}, $self->{res});
2639 }
2640
2641 sub NeededElement($$$)
2642 {
2643         my ($e, $dir, $needed) = @_;
2644
2645         return if ($e->{TYPE} eq "EMPTY");
2646
2647         return if (ref($e->{TYPE}) eq "HASH" and 
2648                        not defined($e->{TYPE}->{NAME}));
2649
2650         my ($t, $rt);
2651         if (ref($e->{TYPE}) eq "HASH") {
2652                 $t = $e->{TYPE}->{TYPE}."_".$e->{TYPE}->{NAME};
2653         } else {
2654                 $t = $e->{TYPE};
2655         }
2656
2657         if (ref($e->{REPRESENTATION_TYPE}) eq "HASH") {
2658                 $rt = $e->{REPRESENTATION_TYPE}->{TYPE}."_".$e->{REPRESENTATION_TYPE}->{NAME};
2659         } else {
2660                 $rt = $e->{REPRESENTATION_TYPE};
2661         }
2662
2663         die ("$e->{NAME} $t, $rt FOO") unless ($rt ne "");
2664
2665         my @fn = ();
2666         if ($dir eq "print") {
2667                 push(@fn, TypeFunctionName("ndr_print", $e->{REPRESENTATION_TYPE}));
2668         } elsif ($dir eq "pull") {
2669                 push (@fn, TypeFunctionName("ndr_pull", $e->{TYPE}));
2670                 push (@fn, "ndr_$t\_to_$rt")
2671                         if ($rt ne $t);
2672         } elsif ($dir eq "push") {
2673                 push (@fn, TypeFunctionName("ndr_push", $e->{TYPE}));
2674                 push (@fn, "ndr_$rt\_to_$t")
2675                         if ($rt ne $t);
2676         } else {
2677                 die("invalid direction `$dir'");
2678         }
2679
2680         foreach (@fn) {
2681                 unless (defined($needed->{$_})) {
2682                         $needed->{$_} = 1;
2683                 }
2684         }
2685 }
2686
2687 sub NeededFunction($$)
2688 {
2689         my ($fn,$needed) = @_;
2690         $needed->{"ndr_pull_$fn->{NAME}"} = 1;
2691         $needed->{"ndr_push_$fn->{NAME}"} = 1;
2692         $needed->{"ndr_print_$fn->{NAME}"} = 1;
2693         foreach my $e (@{$fn->{ELEMENTS}}) {
2694                 $e->{PARENT} = $fn;
2695                 NeededElement($e, $_, $needed) foreach ("pull", "push", "print");
2696         }
2697 }
2698
2699 sub NeededType($$$)
2700 {
2701         sub NeededType($$$);
2702         my ($t,$needed,$req) = @_;
2703
2704         NeededType($t->{DATA}, $needed, $req) if ($t->{TYPE} eq "TYPEDEF");
2705
2706         if ($t->{TYPE} eq "STRUCT" or $t->{TYPE} eq "UNION") {
2707                 return unless defined($t->{ELEMENTS});
2708                 for my $e (@{$t->{ELEMENTS}}) {
2709                         $e->{PARENT} = $t;
2710                         if (has_property($e, "compression")) { 
2711                                 $needed->{"compression"} = 1;
2712                         }
2713                         NeededElement($e, $req, $needed);
2714                         NeededType($e->{TYPE}, $needed, $req) if (ref($e->{TYPE}) eq "HASH");
2715                 }
2716         }
2717 }
2718
2719 #####################################################################
2720 # work out what parse functions are needed
2721 sub NeededInterface($$)
2722 {
2723         my ($interface,$needed) = @_;
2724         NeededFunction($_, $needed) foreach (@{$interface->{FUNCTIONS}});
2725         foreach (reverse @{$interface->{TYPES}}) {
2726                 if (has_property($_, "public")) {
2727                         $needed->{TypeFunctionName("ndr_pull", $_)} = $needed->{TypeFunctionName("ndr_push", $_)} = 
2728                                 $needed->{TypeFunctionName("ndr_print", $_)} = 1;
2729                 }
2730
2731                 NeededType($_, $needed, "pull") if ($needed->{TypeFunctionName("ndr_pull", $_)});
2732                 NeededType($_, $needed, "push") if ($needed->{TypeFunctionName("ndr_push", $_)});
2733                 NeededType($_, $needed, "print") if ($needed->{TypeFunctionName("ndr_print", $_)});
2734                 if (has_property($_, "gensize")) {
2735                         $needed->{"ndr_size_$_->{NAME}"} = 1;
2736                 }
2737         }
2738 }
2739
2740 sub TypeFunctionName($$)
2741 {
2742         my ($prefix, $t) = @_;
2743
2744         return "$prefix\_$t->{NAME}" if (ref($t) eq "HASH" and 
2745                         $t->{TYPE} eq "TYPEDEF");
2746         return "$prefix\_$t->{TYPE}_$t->{NAME}" if (ref($t) eq "HASH");
2747         return "$prefix\_$t";
2748 }
2749
2750 1;