pidl:NDR/Parser: simplify logic in ParseMemCtxPullFlags()
[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                 my $rel_var_name = $var_name;
571                 if ($l->{POINTER_TYPE} ne "ref") {
572                         $self->pidl("if ($var_name) {");
573                         $self->indent;
574                         if ($l->{POINTER_TYPE} eq "relative") {
575                                 $self->pidl("NDR_CHECK(ndr_push_relative_ptr2_start($ndr, $rel_var_name));");
576                         }
577                         if ($l->{POINTER_TYPE} eq "relative_short") {
578                                 $self->pidl("NDR_CHECK(ndr_push_short_relative_ptr2($ndr, $var_name));");
579                         }
580                 }
581                 $var_name = get_value_of($var_name);
582                 $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 1, 1);
583
584                 if ($l->{POINTER_TYPE} ne "ref") {
585                         if ($l->{POINTER_TYPE} eq "relative") {
586                                 $self->pidl("NDR_CHECK(ndr_push_relative_ptr2_end($ndr, $rel_var_name));");
587                         }
588                         $self->deindent;
589                         $self->pidl("}");
590                 }
591         } elsif ($l->{TYPE} eq "ARRAY" and not has_fast_array($e,$l) and
592                 not is_charset_array($e, $l)) {
593                 my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
594                 my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
595
596                 my $array_pointless = ($length eq "0");
597
598                 if ($array_pointless) {
599                         warning($e->{ORIGINAL}, "pointless array `$e->{NAME}' will always have size 0");
600                 }
601
602                 $var_name = get_array_element($var_name, $counter);
603
604                 if ((($primitives and not $l->{IS_DEFERRED}) or ($deferred and $l->{IS_DEFERRED})) and not $array_pointless) {
605                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
606                         $self->indent;
607                         $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 1, 0);
608                         $self->deindent;
609                         $self->pidl("}");
610                 }
611
612                 if ($deferred and ContainsDeferred($e, $l) and not $array_pointless) {
613                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
614                         $self->indent;
615                         $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 0, 1);
616                         $self->deindent;
617                         $self->pidl("}");
618                 }       
619         } elsif ($l->{TYPE} eq "SWITCH") {
620                 $self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, $primitives, $deferred);
621         }
622 }
623
624 #####################################################################
625 # parse scalars in a structure element
626 sub ParseElementPush($$$$$$)
627 {
628         my ($self,$e,$ndr,$env,$primitives,$deferred) = @_;
629         my $subndr = undef;
630
631         my $var_name = $env->{$e->{NAME}};
632
633         return unless $primitives or ($deferred and ContainsDeferred($e, $e->{LEVELS}[0]));
634
635         # Representation type is different from transmit_as
636         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
637                 $self->pidl("{");
638                 $self->indent;
639                 my $transmit_name = "_transmit_$e->{NAME}";
640                 $self->pidl(mapTypeName($e->{TYPE}) ." $transmit_name;");
641                 $self->pidl("NDR_CHECK(ndr_$e->{REPRESENTATION_TYPE}_to_$e->{TYPE}($var_name, " . get_pointer_to($transmit_name) . "));");
642                 $var_name = $transmit_name;
643         }
644
645         $var_name = append_prefix($e, $var_name);
646
647         $self->start_flags($e, $ndr);
648
649         if (defined(my $value = has_property($e, "value"))) {
650                 $var_name = ParseExpr($value, $env, $e->{ORIGINAL});
651         }
652
653         $self->ParseElementPushLevel($e, $e->{LEVELS}[0], $ndr, $var_name, $env, $primitives, $deferred);
654
655         $self->end_flags($e, $ndr);
656
657         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
658                 $self->deindent;
659                 $self->pidl("}");
660         }
661 }
662
663 #####################################################################
664 # parse a pointer in a struct element or function
665 sub ParsePtrPush($$$$$)
666 {
667         my ($self,$e,$l,$ndr,$var_name) = @_;
668
669         if ($l->{POINTER_TYPE} eq "ref") {
670                 $self->pidl("if ($var_name == NULL) {");
671                 $self->indent;
672                 $self->pidl("return ndr_push_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL [ref] pointer\");");
673                 $self->deindent;
674                 $self->pidl("}");
675                 if ($l->{LEVEL} eq "EMBEDDED") {
676                         $self->pidl("NDR_CHECK(ndr_push_ref_ptr(ndr));");
677                 }
678         } elsif ($l->{POINTER_TYPE} eq "relative") {
679                 $self->pidl("NDR_CHECK(ndr_push_relative_ptr1($ndr, $var_name));");
680         } elsif ($l->{POINTER_TYPE} eq "relative_short") {
681                 $self->pidl("NDR_CHECK(ndr_push_short_relative_ptr1($ndr, $var_name));");
682         } elsif ($l->{POINTER_TYPE} eq "unique") {
683                 $self->pidl("NDR_CHECK(ndr_push_unique_ptr($ndr, $var_name));");
684         } elsif ($l->{POINTER_TYPE} eq "full") {
685                 $self->pidl("NDR_CHECK(ndr_push_full_ptr($ndr, $var_name));");
686         } else {
687                 die("Unhandled pointer type $l->{POINTER_TYPE}");
688         }
689 }
690
691 sub need_pointer_to($$$)
692 {
693         my ($e, $l, $scalar_only) = @_;
694
695         my $t;
696         if (ref($l->{DATA_TYPE})) {
697                 $t = "$l->{DATA_TYPE}->{TYPE}_$l->{DATA_TYPE}->{NAME}";
698         } else {
699                 $t = $l->{DATA_TYPE};
700         }
701
702         if (not Parse::Pidl::Typelist::is_scalar($t)) {
703                 return 1 if $scalar_only;
704         }
705
706         my $arrays = 0;
707
708         foreach my $tl (@{$e->{LEVELS}}) {
709                 last if $l == $tl;
710                 if ($tl->{TYPE} eq "ARRAY") {
711                         $arrays++;
712                 }
713         }
714
715         if (Parse::Pidl::Typelist::scalar_is_reference($t)) {
716                 return 1 unless $arrays;
717         }
718
719         return 0;
720 }
721
722 sub ParseDataPrint($$$$$)
723 {
724         my ($self, $e, $l, $ndr, $var_name) = @_;
725
726         if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
727
728                 if (need_pointer_to($e, $l, 1)) {
729                         $var_name = get_pointer_to($var_name);
730                 }
731
732                 $self->pidl(TypeFunctionName("ndr_print", $l->{DATA_TYPE})."($ndr, \"$e->{NAME}\", $var_name);");
733         } else {
734                 $self->ParseTypePrint($l->{DATA_TYPE}, $ndr, $var_name);
735         }
736 }
737
738 #####################################################################
739 # print scalars in a structure element
740 sub ParseElementPrint($$$$$)
741 {
742         my($self, $e, $ndr, $var_name, $env) = @_;
743
744         return if (has_property($e, "noprint"));
745
746         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
747                 $self->pidl("ndr_print_$e->{REPRESENTATION_TYPE}($ndr, \"$e->{NAME}\", $var_name);");
748                 return;
749         }
750
751         $var_name = append_prefix($e, $var_name);
752
753         if (defined(my $value = has_property($e, "value"))) {
754                 $var_name = "($ndr->flags & LIBNDR_PRINT_SET_VALUES)?" . ParseExpr($value,$env, $e->{ORIGINAL}) . ":$var_name";
755         }
756
757         foreach my $l (@{$e->{LEVELS}}) {
758                 if ($l->{TYPE} eq "POINTER") {
759                         $self->pidl("ndr_print_ptr($ndr, \"$e->{NAME}\", $var_name);");
760                         $self->pidl("$ndr->depth++;");
761                         if ($l->{POINTER_TYPE} ne "ref") {
762                                 $self->pidl("if ($var_name) {");
763                                 $self->indent;
764                         }
765                         $var_name = get_value_of($var_name);
766                 } elsif ($l->{TYPE} eq "ARRAY") {
767                         my $length;
768
769                         if ($l->{IS_CONFORMANT} or $l->{IS_VARYING}) {
770                                 $var_name = get_pointer_to($var_name); 
771                         }
772                         
773                         if ($l->{IS_ZERO_TERMINATED}) {
774                                 $length = "ndr_string_length($var_name, sizeof(*$var_name))";
775                         } else {
776                                 $length = ParseExprExt($l->{LENGTH_IS}, $env, $e->{ORIGINAL}, 
777                                                         check_null_pointer($e, $env, sub { $self->pidl(shift); }, "return;"), check_fully_dereferenced($e, $env));
778                         }
779
780                         if (is_charset_array($e,$l)) {
781                                 $self->pidl("ndr_print_string($ndr, \"$e->{NAME}\", $var_name);");
782                                 last;
783                         } elsif (has_fast_array($e, $l)) {
784                                 my $nl = GetNextLevel($e, $l);
785                                 $self->pidl("ndr_print_array_$nl->{DATA_TYPE}($ndr, \"$e->{NAME}\", $var_name, $length);");
786                                 last;
787                         } else {
788                                 my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
789
790                                 $self->pidl("$ndr->print($ndr, \"\%s: ARRAY(\%d)\", \"$e->{NAME}\", (int)$length);");
791                                 $self->pidl("$ndr->depth++;");
792                                 $self->pidl("for ($counter=0;$counter<$length;$counter++) {");
793                                 $self->indent;
794                                 $self->pidl("char *idx_$l->{LEVEL_INDEX}=NULL;");
795                                 $self->pidl("if (asprintf(&idx_$l->{LEVEL_INDEX}, \"[\%d]\", $counter) != -1) {");
796                                 $self->indent;
797
798                                 $var_name = get_array_element($var_name, $counter);
799                         }
800                 } elsif ($l->{TYPE} eq "DATA") {
801                         $self->ParseDataPrint($e, $l, $ndr, $var_name);
802                 } elsif ($l->{TYPE} eq "SWITCH") {
803                         my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL}, 
804                                                 check_null_pointer($e, $env, sub { $self->pidl(shift); }, "return;"), check_fully_dereferenced($e, $env));
805                         $self->pidl("ndr_print_set_switch_value($ndr, " . get_pointer_to($var_name) . ", $switch_var);");
806                 } 
807         }
808
809         foreach my $l (reverse @{$e->{LEVELS}}) {
810                 if ($l->{TYPE} eq "POINTER") {
811                         if ($l->{POINTER_TYPE} ne "ref") {
812                                 $self->deindent;
813                                 $self->pidl("}");
814                         }
815                         $self->pidl("$ndr->depth--;");
816                 } elsif (($l->{TYPE} eq "ARRAY")
817                         and not is_charset_array($e,$l)
818                         and not has_fast_array($e,$l)) {
819                         $self->pidl("free(idx_$l->{LEVEL_INDEX});");
820                         $self->deindent;
821                         $self->pidl("}");
822                         $self->deindent;
823                         $self->pidl("}");
824                         $self->pidl("$ndr->depth--;");
825                 }
826         }
827 }
828
829 #####################################################################
830 # parse scalars in a structure element - pull size
831 sub ParseSwitchPull($$$$$$)
832 {
833         my($self,$e,$l,$ndr,$var_name,$env) = @_;
834         my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL}, 
835                 check_null_pointer($e, $env, sub { $self->pidl(shift); },
836                                    "return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for switch_is()\");"),
837                 check_fully_dereferenced($e, $env));
838
839         $var_name = get_pointer_to($var_name);
840         $self->pidl("NDR_CHECK(ndr_pull_set_switch_value($ndr, $var_name, $switch_var));");
841 }
842
843 #####################################################################
844 # push switch element
845 sub ParseSwitchPush($$$$$$)
846 {
847         my($self,$e,$l,$ndr,$var_name,$env) = @_;
848         my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL}, 
849                 check_null_pointer($e, $env, sub { $self->pidl(shift); },
850                                    "return ndr_push_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for switch_is()\");"),
851                 check_fully_dereferenced($e, $env));
852
853         $var_name = get_pointer_to($var_name);
854         $self->pidl("NDR_CHECK(ndr_push_set_switch_value($ndr, $var_name, $switch_var));");
855 }
856
857 sub ParseDataPull($$$$$$$)
858 {
859         my ($self,$e,$l,$ndr,$var_name,$primitives,$deferred) = @_;
860
861         if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
862
863                 my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
864
865                 if (need_pointer_to($e, $l, 0)) {
866                         $var_name = get_pointer_to($var_name);
867                 }
868
869                 $var_name = get_pointer_to($var_name);
870
871                 $self->pidl("NDR_CHECK(".TypeFunctionName("ndr_pull", $l->{DATA_TYPE})."($ndr, $ndr_flags, $var_name));");
872
873                 my $pl = GetPrevLevel($e, $l);
874
875                 my $range = has_property($e, "range");
876                 if ($range and $pl->{TYPE} ne "ARRAY") {
877                         $var_name = get_value_of($var_name);
878                         my $signed = Parse::Pidl::Typelist::is_signed($l->{DATA_TYPE});
879                         my ($low, $high) = split(/,/, $range, 2);
880                         if ($low < 0 and not $signed) {
881                                 warning(0, "$low is invalid for the range of an unsigned type");
882                         }
883                         if ($low == 0 and not $signed) {
884                                 $self->pidl("if ($var_name > $high) {");
885                         } else {
886                                 $self->pidl("if ($var_name < $low || $var_name > $high) {");
887                         }
888                         $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_RANGE, \"value out of range\");");
889                         $self->pidl("}");
890                 }
891         } else {
892                 $self->ParseTypePull($l->{DATA_TYPE}, $ndr, $var_name, $primitives, $deferred);
893         }
894 }
895
896 sub ParseDataPush($$$$$$$)
897 {
898         my ($self,$e,$l,$ndr,$var_name,$primitives,$deferred) = @_;
899
900         if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
901
902                 my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
903
904                 # strings are passed by value rather than reference
905                 if (need_pointer_to($e, $l, 1)) {
906                         $var_name = get_pointer_to($var_name);
907                 }
908
909                 $self->pidl("NDR_CHECK(".TypeFunctionName("ndr_push", $l->{DATA_TYPE})."($ndr, $ndr_flags, $var_name));");
910         } else {
911                 $self->ParseTypePush($l->{DATA_TYPE}, $ndr, $var_name, $primitives, $deferred);
912         }
913 }
914
915 sub CalcNdrFlags($$$)
916 {
917         my ($l,$primitives,$deferred) = @_;
918
919         my $scalars = 0;
920         my $buffers = 0;
921
922         # Add NDR_SCALARS if this one is deferred 
923         # and deferreds may be pushed
924         $scalars = 1 if ($l->{IS_DEFERRED} and $deferred);
925
926         # Add NDR_SCALARS if this one is not deferred and 
927         # primitives may be pushed
928         $scalars = 1 if (!$l->{IS_DEFERRED} and $primitives);
929         
930         # Add NDR_BUFFERS if this one contains deferred stuff
931         # and deferreds may be pushed
932         $buffers = 1 if ($l->{CONTAINS_DEFERRED} and $deferred);
933
934         return "NDR_SCALARS|NDR_BUFFERS" if ($scalars and $buffers);
935         return "NDR_SCALARS" if ($scalars);
936         return "NDR_BUFFERS" if ($buffers);
937         return undef;
938 }
939
940 sub ParseMemCtxPullFlags($$$$)
941 {
942         my ($self, $e, $l) = @_;
943
944         return undef unless ($l->{TYPE} eq "POINTER" or $l->{TYPE} eq "ARRAY");
945
946         return undef unless ($l->{TYPE} ne "ARRAY" or ArrayDynamicallyAllocated($e,$l));
947         return undef if has_fast_array($e, $l);
948         return undef if is_charset_array($e, $l);
949
950         my $mem_flags = "0";
951
952         if (($l->{TYPE} eq "POINTER") and ($l->{POINTER_TYPE} eq "ref")) {
953                 my $nl = GetNextLevel($e, $l);
954                 return undef if ($nl->{TYPE} eq "ARRAY");
955                 return undef if (($nl->{TYPE} eq "DATA") and ($nl->{DATA_TYPE} eq "string"));
956
957                 if ($l->{LEVEL} eq "TOP") {
958                         $mem_flags = "LIBNDR_FLAG_REF_ALLOC";
959                 }
960         }
961
962         return $mem_flags;
963 }
964
965 sub ParseMemCtxPullStart($$$$$)
966 {
967         my ($self, $e, $l, $ndr, $ptr_name) = @_;
968
969         my $mem_r_ctx = "_mem_save_$e->{NAME}_$l->{LEVEL_INDEX}";
970         my $mem_c_ctx = $ptr_name;
971         my $mem_c_flags = $self->ParseMemCtxPullFlags($e, $l);
972
973         return unless defined($mem_c_flags);
974
975         $self->pidl("$mem_r_ctx = NDR_PULL_GET_MEM_CTX($ndr);");
976         $self->pidl("NDR_PULL_SET_MEM_CTX($ndr, $mem_c_ctx, $mem_c_flags);");
977 }
978
979 sub ParseMemCtxPullEnd($$$$)
980 {
981         my ($self, $e, $l, $ndr) = @_;
982
983         my $mem_r_ctx = "_mem_save_$e->{NAME}_$l->{LEVEL_INDEX}";
984         my $mem_r_flags = $self->ParseMemCtxPullFlags($e, $l);
985
986         return unless defined($mem_r_flags);
987
988         $self->pidl("NDR_PULL_SET_MEM_CTX($ndr, $mem_r_ctx, $mem_r_flags);");
989 }
990
991 sub CheckStringTerminator($$$$$)
992 {
993         my ($self,$ndr,$e,$l,$length) = @_;
994         my $nl = GetNextLevel($e, $l);
995
996         # Make sure last element is zero!
997         $self->pidl("NDR_CHECK(ndr_check_string_terminator($ndr, $length, sizeof($nl->{DATA_TYPE}_t)));");
998 }
999
1000 sub ParseElementPullLevel
1001 {
1002         my($self,$e,$l,$ndr,$var_name,$env,$primitives,$deferred) = @_;
1003
1004         my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
1005
1006         if ($l->{TYPE} eq "ARRAY" and ($l->{IS_VARYING} or $l->{IS_CONFORMANT})) {
1007                 $var_name = get_pointer_to($var_name);
1008         }
1009
1010         # Only pull something if there's actually something to be pulled
1011         if (defined($ndr_flags)) {
1012                 if ($l->{TYPE} eq "SUBCONTEXT") {
1013                         my $subndr = $self->ParseSubcontextPullStart($e, $l, $ndr, $env);
1014                         $self->ParseElementPullLevel($e, GetNextLevel($e,$l), $subndr, $var_name, $env, 1, 1);
1015                         $self->ParseSubcontextPullEnd($e, $l, $ndr, $env);
1016                 } elsif ($l->{TYPE} eq "ARRAY") {
1017                         my $length = $self->ParseArrayPullHeader($e, $l, $ndr, $var_name, $env);
1018
1019                         if (my $range = has_property($e, "range")) {
1020                                 my ($low, $high) = split(/,/, $range, 2);
1021                                 if ($low < 0) {
1022                                         warning(0, "$low is invalid for the range of an array size");
1023                                 }
1024                                 if ($low == 0) {
1025                                         $self->pidl("if ($length > $high) {");
1026                                 } else {
1027                                         $self->pidl("if ($length < $low || $length > $high) {");
1028                                 }
1029                                 $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_RANGE, \"value out of range\");");
1030                                 $self->pidl("}");
1031                         }
1032
1033                         my $nl = GetNextLevel($e, $l);
1034
1035                         if (is_charset_array($e,$l)) {
1036                                 if ($l->{IS_ZERO_TERMINATED}) {
1037                                         $self->CheckStringTerminator($ndr, $e, $l, $length);
1038                                 }
1039                                 $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}));");
1040                                 return;
1041                         } elsif (has_fast_array($e, $l)) {
1042                                 if ($l->{IS_ZERO_TERMINATED}) {
1043                                         $self->CheckStringTerminator($ndr,$e,$l,$length);
1044                                 }
1045                                 $self->pidl("NDR_CHECK(ndr_pull_array_$nl->{DATA_TYPE}($ndr, $ndr_flags, $var_name, $length));");
1046                                 return;
1047                         }
1048                 } elsif ($l->{TYPE} eq "POINTER") {
1049                         $self->ParsePtrPull($e, $l, $ndr, $var_name);
1050                 } elsif ($l->{TYPE} eq "SWITCH") {
1051                         $self->ParseSwitchPull($e, $l, $ndr, $var_name, $env);
1052                 } elsif ($l->{TYPE} eq "DATA") {
1053                         $self->ParseDataPull($e, $l, $ndr, $var_name, $primitives, $deferred);
1054                 } elsif ($l->{TYPE} eq "TYPEDEF") {
1055                         $typefamily{$e->{DATA}->{TYPE}}->{PULL_FN_BODY}->($self, $e->{DATA}, $ndr, $var_name);
1056                 }
1057         }
1058
1059         # add additional constructions
1060         if ($l->{TYPE} eq "POINTER" and $deferred) {
1061                 if ($l->{POINTER_TYPE} ne "ref") {
1062                         $self->pidl("if ($var_name) {");
1063                         $self->indent;
1064
1065                         if ($l->{POINTER_TYPE} eq "relative" or $l->{POINTER_TYPE} eq "relative_short") {
1066                                 $self->pidl("uint32_t _relative_save_offset;");
1067                                 $self->pidl("_relative_save_offset = $ndr->offset;");
1068                                 $self->pidl("NDR_CHECK(ndr_pull_relative_ptr2($ndr, $var_name));");
1069                         }
1070                 }
1071
1072                 $self->ParseMemCtxPullStart($e, $l, $ndr, $var_name);
1073
1074                 $var_name = get_value_of($var_name);
1075                 $self->ParseElementPullLevel($e, GetNextLevel($e,$l), $ndr, $var_name, $env, 1, 1);
1076
1077                 $self->ParseMemCtxPullEnd($e, $l, $ndr);
1078
1079                 if ($l->{POINTER_TYPE} ne "ref") {
1080                         if ($l->{POINTER_TYPE} eq "relative") {
1081                                 $self->pidl("if ($ndr->offset > $ndr->relative_highest_offset) {");
1082                                 $self->indent;
1083                                 $self->pidl("$ndr->relative_highest_offset = $ndr->offset;");
1084                                 $self->deindent;
1085                                 $self->pidl("}");
1086                                 $self->pidl("$ndr->offset = _relative_save_offset;");
1087                         }
1088                         $self->deindent;
1089                         $self->pidl("}");
1090                 }
1091         } elsif ($l->{TYPE} eq "ARRAY" and 
1092                         not has_fast_array($e,$l) and not is_charset_array($e, $l)) {
1093                 my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
1094                 my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
1095                 my $array_name = $var_name;
1096
1097                 if ($l->{IS_VARYING}) {
1098                         $length = "ndr_get_array_length($ndr, " . get_pointer_to($var_name) .")";
1099                 }
1100
1101                 if (my $range = has_property($e, "range")) {
1102                         my ($low, $high) = split(/,/, $range, 2);
1103                         if ($low < 0) {
1104                                 warning(0, "$low is invalid for the range of an array size");
1105                         }
1106                         if ($low == 0) {
1107                                 $self->pidl("if ($length > $high) {");
1108                         } else {
1109                                 $self->pidl("if ($length < $low || $length > $high) {");
1110                         }
1111                         $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_RANGE, \"value out of range\");");
1112                         $self->pidl("}");
1113                 }
1114
1115                 $var_name = get_array_element($var_name, $counter);
1116
1117                 $self->ParseMemCtxPullStart($e, $l, $ndr, $array_name);
1118
1119                 if (($primitives and not $l->{IS_DEFERRED}) or ($deferred and $l->{IS_DEFERRED})) {
1120                         my $nl = GetNextLevel($e,$l);
1121
1122                         if ($l->{IS_ZERO_TERMINATED}) {
1123                                 $self->CheckStringTerminator($ndr,$e,$l,$length);
1124                         }
1125
1126                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
1127                         $self->indent;
1128                         $self->ParseElementPullLevel($e, $nl, $ndr, $var_name, $env, 1, 0);
1129                         $self->deindent;
1130                         $self->pidl("}");
1131                 }
1132
1133                 if ($deferred and ContainsDeferred($e, $l)) {
1134                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
1135                         $self->indent;
1136                         $self->ParseElementPullLevel($e,GetNextLevel($e,$l), $ndr, $var_name, $env, 0, 1);
1137                         $self->deindent;
1138                         $self->pidl("}");
1139                 }
1140
1141                 $self->ParseMemCtxPullEnd($e, $l, $ndr);
1142
1143         } elsif ($l->{TYPE} eq "SWITCH") {
1144                 $self->ParseElementPullLevel($e, GetNextLevel($e,$l), $ndr, $var_name, $env, $primitives, $deferred);
1145         }
1146 }
1147
1148 #####################################################################
1149 # parse scalars in a structure element - pull size
1150 sub ParseElementPull($$$$$$)
1151 {
1152         my($self,$e,$ndr,$env,$primitives,$deferred) = @_;
1153
1154         my $var_name = $env->{$e->{NAME}};
1155         my $represent_name;
1156         my $transmit_name;
1157
1158         return unless $primitives or ($deferred and ContainsDeferred($e, $e->{LEVELS}[0]));
1159
1160         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
1161                 $self->pidl("{");
1162                 $self->indent;
1163                 $represent_name = $var_name;
1164                 $transmit_name = "_transmit_$e->{NAME}";
1165                 $var_name = $transmit_name;
1166                 $self->pidl(mapTypeName($e->{TYPE})." $var_name;");
1167         }
1168
1169         $var_name = append_prefix($e, $var_name);
1170
1171         $self->start_flags($e, $ndr);
1172
1173         $self->ParseElementPullLevel($e,$e->{LEVELS}[0],$ndr,$var_name,$env,$primitives,$deferred);
1174
1175         $self->end_flags($e, $ndr);
1176
1177         # Representation type is different from transmit_as
1178         if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
1179                 $self->pidl("NDR_CHECK(ndr_$e->{TYPE}_to_$e->{REPRESENTATION_TYPE}($transmit_name, ".get_pointer_to($represent_name)."));");
1180                 $self->deindent;
1181                 $self->pidl("}");
1182         }
1183 }
1184
1185 #####################################################################
1186 # parse a pointer in a struct element or function
1187 sub ParsePtrPull($$$$$)
1188 {
1189         my($self, $e,$l,$ndr,$var_name) = @_;
1190
1191         my $nl = GetNextLevel($e, $l);
1192         my $next_is_array = ($nl->{TYPE} eq "ARRAY");
1193         my $next_is_string = (($nl->{TYPE} eq "DATA") and 
1194                                                  ($nl->{DATA_TYPE} eq "string"));
1195
1196         if ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "TOP") {
1197
1198                 if (!$next_is_array and !$next_is_string) {
1199                         $self->pidl("if ($ndr->flags & LIBNDR_FLAG_REF_ALLOC) {");
1200                         $self->pidl("\tNDR_PULL_ALLOC($ndr, $var_name);"); 
1201                         $self->pidl("}");
1202                 }
1203                 
1204                 return;
1205         } elsif ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "EMBEDDED") {
1206                 $self->pidl("NDR_CHECK(ndr_pull_ref_ptr($ndr, &_ptr_$e->{NAME}));");
1207         } elsif (($l->{POINTER_TYPE} eq "unique") or 
1208                  ($l->{POINTER_TYPE} eq "relative") or
1209                  ($l->{POINTER_TYPE} eq "full")) {
1210                 $self->pidl("NDR_CHECK(ndr_pull_generic_ptr($ndr, &_ptr_$e->{NAME}));");
1211         } elsif ($l->{POINTER_TYPE} eq "relative_short") {
1212                 $self->pidl("NDR_CHECK(ndr_pull_relative_ptr_short($ndr, &_ptr_$e->{NAME}));");
1213         } else {
1214                 die("Unhandled pointer type $l->{POINTER_TYPE}");
1215         }
1216
1217         $self->pidl("if (_ptr_$e->{NAME}) {");
1218         $self->indent;
1219
1220         # Don't do this for arrays, they're allocated at the actual level 
1221         # of the array
1222         unless ($next_is_array or $next_is_string) { 
1223                 $self->pidl("NDR_PULL_ALLOC($ndr, $var_name);"); 
1224         } else {
1225                 # FIXME: Yes, this is nasty.
1226                 # We allocate an array twice
1227                 # - once just to indicate that it's there,
1228                 # - then the real allocation...
1229                 $self->pidl("NDR_PULL_ALLOC($ndr, $var_name);");
1230         }
1231
1232         #$self->pidl("memset($var_name, 0, sizeof($var_name));");
1233         if ($l->{POINTER_TYPE} eq "relative" or $l->{POINTER_TYPE} eq "relative_short") {
1234                 $self->pidl("NDR_CHECK(ndr_pull_relative_ptr1($ndr, $var_name, _ptr_$e->{NAME}));");
1235         }
1236         $self->deindent;
1237         $self->pidl("} else {");
1238         $self->pidl("\t$var_name = NULL;");
1239         $self->pidl("}");
1240 }
1241
1242 sub ParseStructPushPrimitives($$$$$)
1243 {
1244         my ($self, $struct, $ndr, $varname, $env) = @_;
1245
1246         # see if the structure contains a conformant array. If it
1247         # does, then it must be the last element of the structure, and
1248         # we need to push the conformant length early, as it fits on
1249         # the wire before the structure (and even before the structure
1250         # alignment)
1251         if (defined($struct->{SURROUNDING_ELEMENT})) {
1252                 my $e = $struct->{SURROUNDING_ELEMENT};
1253
1254                 if (defined($e->{LEVELS}[0]) and 
1255                         $e->{LEVELS}[0]->{TYPE} eq "ARRAY") {
1256                         my $size;
1257                         
1258                         if ($e->{LEVELS}[0]->{IS_ZERO_TERMINATED}) {
1259                                 if (has_property($e, "charset")) {
1260                                         $size = "ndr_charset_length($varname->$e->{NAME}, CH_$e->{PROPERTIES}->{charset})";
1261                                 } else {
1262                                         $size = "ndr_string_length($varname->$e->{NAME}, sizeof(*$varname->$e->{NAME}))";
1263                                 }
1264                         } else {
1265                                 $size = ParseExpr($e->{LEVELS}[0]->{SIZE_IS}, $env, $e->{ORIGINAL});
1266                         }
1267
1268                         $self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, $size));");
1269                 } else {
1270                         $self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, ndr_string_array_size($ndr, $varname->$e->{NAME})));");
1271                 }
1272         }
1273
1274         $self->pidl("NDR_CHECK(ndr_push_align($ndr, $struct->{ALIGN}));");
1275
1276         if (defined($struct->{PROPERTIES}{relative_base})) {
1277                 # set the current offset as base for relative pointers
1278                 # and store it based on the toplevel struct/union
1279                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1280         }
1281
1282         $self->ParseElementPush($_, $ndr, $env, 1, 0) foreach (@{$struct->{ELEMENTS}});
1283
1284         $self->pidl("NDR_CHECK(ndr_push_trailer_align($ndr, $struct->{ALIGN}));");
1285 }
1286
1287 sub ParseStructPushDeferred($$$$)
1288 {
1289         my ($self, $struct, $ndr, $varname, $env) = @_;
1290         if (defined($struct->{PROPERTIES}{relative_base})) {
1291                 # retrieve the current offset as base for relative pointers
1292                 # based on the toplevel struct/union
1293                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset2($ndr, $varname));");
1294         }
1295         $self->ParseElementPush($_, $ndr, $env, 0, 1) foreach (@{$struct->{ELEMENTS}});
1296 }
1297
1298 #####################################################################
1299 # parse a struct
1300 sub ParseStructPush($$$$)
1301 {
1302         my ($self, $struct, $ndr, $varname) = @_;
1303         
1304         return unless defined($struct->{ELEMENTS});
1305
1306         my $env = GenerateStructEnv($struct, $varname);
1307
1308         EnvSubstituteValue($env, $struct);
1309
1310         $self->DeclareArrayVariablesNoZero($_, $env) foreach (@{$struct->{ELEMENTS}});
1311
1312         $self->start_flags($struct, $ndr);
1313
1314         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1315         $self->indent;
1316         $self->ParseStructPushPrimitives($struct, $ndr, $varname, $env);
1317         $self->deindent;
1318         $self->pidl("}");
1319
1320         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1321         $self->indent;
1322         $self->ParseStructPushDeferred($struct, $ndr, $varname, $env);
1323         $self->deindent;
1324         $self->pidl("}");
1325
1326         $self->end_flags($struct, $ndr);
1327 }
1328
1329 #####################################################################
1330 # generate a push function for an enum
1331 sub ParseEnumPush($$$$)
1332 {
1333         my($self,$enum,$ndr,$varname) = @_;
1334         my($type_fn) = $enum->{BASE_TYPE};
1335
1336         $self->start_flags($enum, $ndr);
1337         $self->pidl("NDR_CHECK(ndr_push_enum_$type_fn($ndr, NDR_SCALARS, $varname));");
1338         $self->end_flags($enum, $ndr);
1339 }
1340
1341 #####################################################################
1342 # generate a pull function for an enum
1343 sub ParseEnumPull($$$$)
1344 {
1345         my($self,$enum,$ndr,$varname) = @_;
1346         my($type_fn) = $enum->{BASE_TYPE};
1347         my($type_v_decl) = mapTypeName($type_fn);
1348
1349         $self->pidl("$type_v_decl v;");
1350         $self->start_flags($enum, $ndr);
1351         $self->pidl("NDR_CHECK(ndr_pull_enum_$type_fn($ndr, NDR_SCALARS, &v));");
1352         $self->pidl("*$varname = v;");
1353
1354         $self->end_flags($enum, $ndr);
1355 }
1356
1357 #####################################################################
1358 # generate a print function for an enum
1359 sub ParseEnumPrint($$$$$)
1360 {
1361         my($self,$enum,$ndr,$name,$varname) = @_;
1362
1363         $self->pidl("const char *val = NULL;");
1364         $self->pidl("");
1365
1366         $self->start_flags($enum, $ndr);
1367
1368         $self->pidl("switch ($varname) {");
1369         $self->indent;
1370         my $els = \@{$enum->{ELEMENTS}};
1371         foreach my $i (0 .. $#{$els}) {
1372                 my $e = ${$els}[$i];
1373                 chomp $e;
1374                 if ($e =~ /^(.*)=/) {
1375                         $e = $1;
1376                 }
1377                 $self->pidl("case $e: val = \"$e\"; break;");
1378         }
1379
1380         $self->deindent;
1381         $self->pidl("}");
1382         
1383         $self->pidl("ndr_print_enum($ndr, name, \"$enum->{TYPE}\", val, $varname);");
1384
1385         $self->end_flags($enum, $ndr);
1386 }
1387
1388 sub DeclEnum($$$$)
1389 {
1390         my ($e,$t,$name,$varname) = @_;
1391         return "enum $name " . 
1392                 ($t eq "pull"?"*":"") . $varname;
1393 }
1394
1395 $typefamily{ENUM} = {
1396         DECL => \&DeclEnum,
1397         PUSH_FN_BODY => \&ParseEnumPush,
1398         PULL_FN_BODY => \&ParseEnumPull,
1399         PRINT_FN_BODY => \&ParseEnumPrint,
1400 };
1401
1402 #####################################################################
1403 # generate a push function for a bitmap
1404 sub ParseBitmapPush($$$$)
1405 {
1406         my($self,$bitmap,$ndr,$varname) = @_;
1407         my($type_fn) = $bitmap->{BASE_TYPE};
1408
1409         $self->start_flags($bitmap, $ndr);
1410
1411         $self->pidl("NDR_CHECK(ndr_push_$type_fn($ndr, NDR_SCALARS, $varname));");
1412
1413         $self->end_flags($bitmap, $ndr);
1414 }
1415
1416 #####################################################################
1417 # generate a pull function for an bitmap
1418 sub ParseBitmapPull($$$$)
1419 {
1420         my($self,$bitmap,$ndr,$varname) = @_;
1421         my $type_fn = $bitmap->{BASE_TYPE};
1422         my($type_decl) = mapTypeName($bitmap->{BASE_TYPE});
1423
1424         $self->pidl("$type_decl v;");
1425         $self->start_flags($bitmap, $ndr);
1426         $self->pidl("NDR_CHECK(ndr_pull_$type_fn($ndr, NDR_SCALARS, &v));");
1427         $self->pidl("*$varname = v;");
1428
1429         $self->end_flags($bitmap, $ndr);
1430 }
1431
1432 #####################################################################
1433 # generate a print function for an bitmap
1434 sub ParseBitmapPrintElement($$$$$$)
1435 {
1436         my($self,$e,$bitmap,$ndr,$name,$varname) = @_;
1437         my($type_decl) = mapTypeName($bitmap->{BASE_TYPE});
1438         my($type_fn) = $bitmap->{BASE_TYPE};
1439         my($flag);
1440
1441         if ($e =~ /^(\w+) .*$/) {
1442                 $flag = "$1";
1443         } else {
1444                 die "Bitmap: \"$name\" invalid Flag: \"$e\"";
1445         }
1446
1447         $self->pidl("ndr_print_bitmap_flag($ndr, sizeof($type_decl), \"$flag\", $flag, $varname);");
1448 }
1449
1450 #####################################################################
1451 # generate a print function for an bitmap
1452 sub ParseBitmapPrint($$$$$)
1453 {
1454         my($self,$bitmap,$ndr,$name,$varname) = @_;
1455         my($type_decl) = mapTypeName($bitmap->{TYPE});
1456         my($type_fn) = $bitmap->{BASE_TYPE};
1457
1458         $self->start_flags($bitmap, $ndr);
1459
1460         $self->pidl("ndr_print_$type_fn($ndr, name, $varname);");
1461
1462         $self->pidl("$ndr->depth++;");
1463         foreach my $e (@{$bitmap->{ELEMENTS}}) {
1464                 $self->ParseBitmapPrintElement($e, $bitmap, $ndr, $name, $varname);
1465         }
1466         $self->pidl("$ndr->depth--;");
1467
1468         $self->end_flags($bitmap, $ndr);
1469 }
1470
1471 sub DeclBitmap($$$$)
1472 {
1473         my ($e,$t,$name,$varname) = @_;
1474         return mapTypeName(Parse::Pidl::Typelist::bitmap_type_fn($e)) . 
1475                 ($t eq "pull"?" *":" ") . $varname;
1476 }
1477
1478 $typefamily{BITMAP} = {
1479         DECL => \&DeclBitmap,
1480         PUSH_FN_BODY => \&ParseBitmapPush,
1481         PULL_FN_BODY => \&ParseBitmapPull,
1482         PRINT_FN_BODY => \&ParseBitmapPrint,
1483 };
1484
1485 #####################################################################
1486 # generate a struct print function
1487 sub ParseStructPrint($$$$$)
1488 {
1489         my($self,$struct,$ndr,$name,$varname) = @_;
1490
1491         return unless defined $struct->{ELEMENTS};
1492
1493         my $env = GenerateStructEnv($struct, $varname);
1494
1495         $self->DeclareArrayVariables($_) foreach (@{$struct->{ELEMENTS}});
1496
1497         $self->pidl("ndr_print_struct($ndr, name, \"$name\");");
1498         $self->pidl("if (r == NULL) { ndr_print_null($ndr); return; }");
1499
1500         $self->start_flags($struct, $ndr);
1501
1502         $self->pidl("$ndr->depth++;");
1503         
1504         $self->ParseElementPrint($_, $ndr, $env->{$_->{NAME}}, $env)
1505                 foreach (@{$struct->{ELEMENTS}});
1506         $self->pidl("$ndr->depth--;");
1507
1508         $self->end_flags($struct, $ndr);
1509 }
1510
1511 sub DeclarePtrVariables($$)
1512 {
1513         my ($self,$e) = @_;
1514         foreach my $l (@{$e->{LEVELS}}) {
1515                 my $size = 32;
1516                 if ($l->{TYPE} eq "POINTER" and 
1517                         not ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "TOP")) {
1518                         if ($l->{POINTER_TYPE} eq "relative_short") {
1519                                 $size = 16;
1520                         }
1521                         $self->pidl("uint${size}_t _ptr_$e->{NAME};");
1522                         last;
1523                 }
1524         }
1525 }
1526
1527 sub DeclareArrayVariables($$)
1528 {
1529         my ($self,$e) = @_;
1530
1531         foreach my $l (@{$e->{LEVELS}}) {
1532                 next if has_fast_array($e,$l);
1533                 next if is_charset_array($e,$l);
1534                 if ($l->{TYPE} eq "ARRAY") {
1535                         $self->pidl("uint32_t cntr_$e->{NAME}_$l->{LEVEL_INDEX};");
1536                 }
1537         }
1538 }
1539
1540 sub DeclareArrayVariablesNoZero($$$)
1541 {
1542         my ($self,$e,$env) = @_;
1543
1544         foreach my $l (@{$e->{LEVELS}}) {
1545                 next if has_fast_array($e,$l);
1546                 next if is_charset_array($e,$l);
1547                 if ($l->{TYPE} eq "ARRAY") {
1548                     my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
1549                     if ($length eq "0") {
1550                         warning($e->{ORIGINAL}, "pointless array cntr: 'cntr_$e->{NAME}_$l->{LEVEL_INDEX}': length=$length");
1551                     } else {
1552                         $self->pidl("uint32_t cntr_$e->{NAME}_$l->{LEVEL_INDEX};");
1553                     }
1554                 }
1555         }
1556 }
1557
1558 sub DeclareMemCtxVariables($$)
1559 {
1560         my ($self,$e) = @_;
1561         foreach my $l (@{$e->{LEVELS}}) {
1562                 my $mem_flags = $self->ParseMemCtxPullFlags($e, $l);
1563                 if (defined($mem_flags)) {
1564                         $self->pidl("TALLOC_CTX *_mem_save_$e->{NAME}_$l->{LEVEL_INDEX};");
1565                 }
1566         }
1567 }
1568
1569 sub ParseStructPullPrimitives($$$$$)
1570 {
1571         my($self,$struct,$ndr,$varname,$env) = @_;
1572
1573         if (defined $struct->{SURROUNDING_ELEMENT}) {
1574                 $self->pidl("NDR_CHECK(ndr_pull_array_size($ndr, &$varname->$struct->{SURROUNDING_ELEMENT}->{NAME}));");
1575         }
1576
1577         $self->pidl("NDR_CHECK(ndr_pull_align($ndr, $struct->{ALIGN}));");
1578
1579         if (defined($struct->{PROPERTIES}{relative_base})) {
1580                 # set the current offset as base for relative pointers
1581                 # and store it based on the toplevel struct/union
1582                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1583         }
1584
1585         $self->ParseElementPull($_, $ndr, $env, 1, 0) foreach (@{$struct->{ELEMENTS}});
1586
1587         $self->add_deferred();
1588
1589         $self->pidl("NDR_CHECK(ndr_pull_trailer_align($ndr, $struct->{ALIGN}));");
1590 }
1591
1592 sub ParseStructPullDeferred($$$$$)
1593 {
1594         my ($self,$struct,$ndr,$varname,$env) = @_;
1595
1596         if (defined($struct->{PROPERTIES}{relative_base})) {
1597                 # retrieve the current offset as base for relative pointers
1598                 # based on the toplevel struct/union
1599                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset2($ndr, $varname));");
1600         }
1601         foreach my $e (@{$struct->{ELEMENTS}}) {
1602                 $self->ParseElementPull($e, $ndr, $env, 0, 1);
1603         }
1604
1605         $self->add_deferred();
1606 }
1607
1608 #####################################################################
1609 # parse a struct - pull side
1610 sub ParseStructPull($$$$)
1611 {
1612         my($self,$struct,$ndr,$varname) = @_;
1613
1614         return unless defined $struct->{ELEMENTS};
1615
1616         # declare any internal pointers we need
1617         foreach my $e (@{$struct->{ELEMENTS}}) {
1618                 $self->DeclarePtrVariables($e);
1619                 $self->DeclareArrayVariables($e);
1620                 $self->DeclareMemCtxVariables($e);
1621         }
1622
1623         $self->start_flags($struct, $ndr);
1624
1625         my $env = GenerateStructEnv($struct, $varname);
1626
1627         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1628         $self->indent;
1629         $self->ParseStructPullPrimitives($struct,$ndr,$varname,$env);
1630         $self->deindent;
1631         $self->pidl("}");
1632         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1633         $self->indent;
1634         $self->ParseStructPullDeferred($struct,$ndr,$varname,$env);
1635         $self->deindent;
1636         $self->pidl("}");
1637
1638         $self->end_flags($struct, $ndr);
1639 }
1640
1641 #####################################################################
1642 # calculate size of ndr struct
1643 sub ParseStructNdrSize($$$$)
1644 {
1645         my ($self,$t, $name, $varname) = @_;
1646         my $sizevar;
1647
1648         if (my $flags = has_property($t, "flag")) {
1649                 $self->pidl("flags |= $flags;");
1650         }
1651         $self->pidl("return ndr_size_struct($varname, flags, (ndr_push_flags_fn_t)ndr_push_$name);");
1652 }
1653
1654 sub DeclStruct($$$$)
1655 {
1656         my ($e,$t,$name,$varname) = @_;
1657         return ($t ne "pull"?"const ":"") . "struct $name *$varname";
1658 }
1659
1660 sub ArgsStructNdrSize($$$)
1661 {
1662         my ($d, $name, $varname) = @_;
1663         return "const struct $name *$varname, int flags";
1664 }
1665
1666 $typefamily{STRUCT} = {
1667         PUSH_FN_BODY => \&ParseStructPush,
1668         DECL => \&DeclStruct,
1669         PULL_FN_BODY => \&ParseStructPull,
1670         PRINT_FN_BODY => \&ParseStructPrint,
1671         SIZE_FN_BODY => \&ParseStructNdrSize,
1672         SIZE_FN_ARGS => \&ArgsStructNdrSize,
1673 };
1674
1675 #####################################################################
1676 # calculate size of ndr struct
1677 sub ParseUnionNdrSize($$$)
1678 {
1679         my ($self, $t, $name, $varname) = @_;
1680         my $sizevar;
1681
1682         if (my $flags = has_property($t, "flag")) {
1683                 $self->pidl("flags |= $flags;");
1684         }
1685
1686         $self->pidl("return ndr_size_union($varname, flags, level, (ndr_push_flags_fn_t)ndr_push_$name);");
1687 }
1688
1689 sub ParseUnionPushPrimitives($$$$)
1690 {
1691         my ($self, $e, $ndr ,$varname) = @_;
1692
1693         my $have_default = 0;
1694
1695         $self->pidl("int level = ndr_push_get_switch_value($ndr, $varname);");
1696
1697         if (defined($e->{SWITCH_TYPE})) {
1698                 $self->pidl("NDR_CHECK(ndr_push_$e->{SWITCH_TYPE}($ndr, NDR_SCALARS, level));");
1699         }
1700
1701         if (defined($e->{ALIGN})) {
1702                 $self->pidl("NDR_CHECK(ndr_push_union_align($ndr, $e->{ALIGN}));");
1703         }
1704
1705         $self->pidl("switch (level) {");
1706         $self->indent;
1707         foreach my $el (@{$e->{ELEMENTS}}) {
1708                 if ($el->{CASE} eq "default") {
1709                         $have_default = 1;
1710                 }
1711                 $self->pidl("$el->{CASE}: {");
1712
1713                 if ($el->{TYPE} ne "EMPTY") {
1714                         $self->indent;
1715                         if (defined($e->{PROPERTIES}{relative_base})) {
1716                                 $self->pidl("NDR_CHECK(ndr_push_align($ndr, $el->{ALIGN}));");
1717                                 # set the current offset as base for relative pointers
1718                                 # and store it based on the toplevel struct/union
1719                                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1720                         }
1721                         $self->DeclareArrayVariables($el);
1722                         $self->ParseElementPush($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 1, 0);
1723                         $self->deindent;
1724                 }
1725                 $self->pidl("break; }");
1726                 $self->pidl("");
1727         }
1728         if (! $have_default) {
1729                 $self->pidl("default:");
1730                 $self->pidl("\treturn ndr_push_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1731         }
1732         $self->deindent;
1733         $self->pidl("}");
1734 }
1735
1736 sub ParseUnionPushDeferred($$$$)
1737 {
1738         my ($self,$e,$ndr,$varname) = @_;
1739
1740         my $have_default = 0;
1741
1742         $self->pidl("int level = ndr_push_get_switch_value($ndr, $varname);");
1743         if (defined($e->{PROPERTIES}{relative_base})) {
1744                 # retrieve the current offset as base for relative pointers
1745                 # based on the toplevel struct/union
1746                 $self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset2($ndr, $varname));");
1747         }
1748         $self->pidl("switch (level) {");
1749         $self->indent;
1750         foreach my $el (@{$e->{ELEMENTS}}) {
1751                 if ($el->{CASE} eq "default") {
1752                         $have_default = 1;
1753                 }
1754
1755                 $self->pidl("$el->{CASE}:");
1756                 if ($el->{TYPE} ne "EMPTY") {
1757                         $self->indent;
1758                         $self->ParseElementPush($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 0, 1);
1759                         $self->deindent;
1760                 }
1761                 $self->pidl("break;");
1762                 $self->pidl("");
1763         }
1764         if (! $have_default) {
1765                 $self->pidl("default:");
1766                 $self->pidl("\treturn ndr_push_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1767         }
1768         $self->deindent;
1769         $self->pidl("}");
1770 }
1771
1772 #####################################################################
1773 # parse a union - push side
1774 sub ParseUnionPush($$$$)
1775 {
1776         my ($self,$e,$ndr,$varname) = @_;
1777         my $have_default = 0;
1778
1779         $self->start_flags($e, $ndr);
1780
1781         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1782         $self->indent;
1783         $self->ParseUnionPushPrimitives($e, $ndr, $varname);
1784         $self->deindent;
1785         $self->pidl("}");
1786         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1787         $self->indent;
1788         $self->ParseUnionPushDeferred($e, $ndr, $varname);
1789         $self->deindent;
1790         $self->pidl("}");
1791         $self->end_flags($e, $ndr);
1792 }
1793
1794 #####################################################################
1795 # print a union
1796 sub ParseUnionPrint($$$$$)
1797 {
1798         my ($self,$e,$ndr,$name,$varname) = @_;
1799         my $have_default = 0;
1800
1801         $self->pidl("int level;");
1802         foreach my $el (@{$e->{ELEMENTS}}) {
1803                 $self->DeclareArrayVariables($el);
1804         }
1805
1806         $self->start_flags($e, $ndr);
1807
1808         $self->pidl("level = ndr_print_get_switch_value($ndr, $varname);");
1809
1810         $self->pidl("ndr_print_union($ndr, name, level, \"$name\");");
1811
1812         $self->pidl("switch (level) {");
1813         $self->indent;
1814         foreach my $el (@{$e->{ELEMENTS}}) {
1815                 if ($el->{CASE} eq "default") {
1816                         $have_default = 1;
1817                 }
1818                 $self->pidl("$el->{CASE}:");
1819                 if ($el->{TYPE} ne "EMPTY") {
1820                         $self->indent;
1821                         $self->ParseElementPrint($el, $ndr, "$varname->$el->{NAME}", {});
1822                         $self->deindent;
1823                 }
1824                 $self->pidl("break;");
1825                 $self->pidl("");
1826         }
1827         if (! $have_default) {
1828                 $self->pidl("default:");
1829                 $self->pidl("\tndr_print_bad_level($ndr, name, level);");
1830         }
1831         $self->deindent;
1832         $self->pidl("}");
1833
1834         $self->end_flags($e, $ndr);
1835 }
1836
1837 sub ParseUnionPullPrimitives($$$$$)
1838 {
1839         my ($self,$e,$ndr,$varname,$switch_type) = @_;
1840         my $have_default = 0;
1841
1842         if (defined($switch_type)) {
1843                 $self->pidl("NDR_CHECK(ndr_pull_$switch_type($ndr, NDR_SCALARS, &_level));");
1844                 $self->pidl("if (_level != level) {"); 
1845                 $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value %u for $varname at \%s\", _level, __location__);");
1846                 $self->pidl("}");
1847         }
1848
1849         if (defined($e->{ALIGN})) {
1850                 $self->pidl("NDR_CHECK(ndr_pull_union_align($ndr, $e->{ALIGN}));");
1851         }
1852
1853         $self->pidl("switch (level) {");
1854         $self->indent;
1855         foreach my $el (@{$e->{ELEMENTS}}) {
1856                 if ($el->{CASE} eq "default") {
1857                         $have_default = 1;
1858                 } 
1859                 $self->pidl("$el->{CASE}: {");
1860
1861                 if ($el->{TYPE} ne "EMPTY") {
1862                         $self->indent;
1863                         $self->DeclarePtrVariables($el);
1864                         $self->DeclareArrayVariables($el);
1865                         if (defined($e->{PROPERTIES}{relative_base})) {
1866                                 $self->pidl("NDR_CHECK(ndr_pull_align($ndr, $el->{ALIGN}));");
1867                                 # set the current offset as base for relative pointers
1868                                 # and store it based on the toplevel struct/union
1869                                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
1870                         }
1871                         $self->ParseElementPull($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 1, 0);
1872                         $self->deindent;
1873                 }
1874                 $self->pidl("break; }");
1875                 $self->pidl("");
1876         }
1877         if (! $have_default) {
1878                 $self->pidl("default:");
1879                 $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1880         }
1881         $self->deindent;
1882         $self->pidl("}");
1883 }
1884
1885 sub ParseUnionPullDeferred($$$$)
1886 {
1887         my ($self,$e,$ndr,$varname) = @_;
1888         my $have_default = 0;
1889
1890         if (defined($e->{PROPERTIES}{relative_base})) {
1891                 # retrieve the current offset as base for relative pointers
1892                 # based on the toplevel struct/union
1893                 $self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset2($ndr, $varname));");
1894         }
1895         $self->pidl("switch (level) {");
1896         $self->indent;
1897         foreach my $el (@{$e->{ELEMENTS}}) {
1898                 if ($el->{CASE} eq "default") {
1899                         $have_default = 1;
1900                 } 
1901
1902                 $self->pidl("$el->{CASE}:");
1903                 if ($el->{TYPE} ne "EMPTY") {
1904                         $self->indent;
1905                         $self->ParseElementPull($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 0, 1);
1906                         $self->deindent;
1907                 }
1908                 $self->pidl("break;");
1909                 $self->pidl("");
1910         }
1911         if (! $have_default) {
1912                 $self->pidl("default:");
1913                 $self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
1914         }
1915         $self->deindent;
1916         $self->pidl("}");
1917
1918
1919 }
1920
1921 #####################################################################
1922 # parse a union - pull side
1923 sub ParseUnionPull($$$$)
1924 {
1925         my ($self,$e,$ndr,$varname) = @_;
1926         my $switch_type = $e->{SWITCH_TYPE};
1927
1928         $self->pidl("int level;");
1929         if (defined($switch_type)) {
1930                 if (Parse::Pidl::Typelist::typeIs($switch_type, "ENUM")) {
1931                         $switch_type = Parse::Pidl::Typelist::enum_type_fn(getType($switch_type)->{DATA});
1932                 }
1933                 $self->pidl(mapTypeName($switch_type) . " _level;");
1934         }
1935
1936         my %double_cases = ();
1937         foreach my $el (@{$e->{ELEMENTS}}) {
1938                 next if ($el->{TYPE} eq "EMPTY");
1939                 next if ($double_cases{"$el->{NAME}"});
1940                 $self->DeclareMemCtxVariables($el);
1941                 $double_cases{"$el->{NAME}"} = 1;
1942         }
1943
1944         $self->start_flags($e, $ndr);
1945
1946         $self->pidl("level = ndr_pull_get_switch_value($ndr, $varname);");
1947
1948         $self->pidl("if (ndr_flags & NDR_SCALARS) {");
1949         $self->indent;
1950         $self->ParseUnionPullPrimitives($e,$ndr,$varname,$switch_type);
1951         $self->deindent;
1952         $self->pidl("}");
1953
1954         $self->pidl("if (ndr_flags & NDR_BUFFERS) {");
1955         $self->indent;
1956         $self->ParseUnionPullDeferred($e,$ndr,$varname);
1957         $self->deindent;
1958         $self->pidl("}");
1959
1960         $self->add_deferred();
1961
1962         $self->end_flags($e, $ndr);
1963 }
1964
1965 sub DeclUnion($$$$)
1966 {
1967         my ($e,$t,$name,$varname) = @_;
1968         return ($t ne "pull"?"const ":"") . "union $name *$varname";
1969 }
1970
1971 sub ArgsUnionNdrSize($$)
1972 {
1973         my ($d,$name) = @_;
1974         return "const union $name *r, uint32_t level, int flags";
1975 }
1976
1977 $typefamily{UNION} = {
1978         PUSH_FN_BODY => \&ParseUnionPush,
1979         DECL => \&DeclUnion,
1980         PULL_FN_BODY => \&ParseUnionPull,
1981         PRINT_FN_BODY => \&ParseUnionPrint,
1982         SIZE_FN_ARGS => \&ArgsUnionNdrSize,
1983         SIZE_FN_BODY => \&ParseUnionNdrSize,
1984 };
1985         
1986 #####################################################################
1987 # parse a typedef - push side
1988 sub ParseTypedefPush($$$$)
1989 {
1990         my($self,$e,$ndr,$varname) = @_;
1991
1992         my $env;
1993
1994         $env->{$e->{NAME}} = $varname;
1995
1996         $self->ParseElementPushLevel($e, $e->{LEVELS}[0], $ndr, $varname, $env, 1, 1);
1997 }
1998
1999 #####################################################################
2000 # parse a typedef - pull side
2001 sub ParseTypedefPull($$$$)
2002 {
2003         my($self,$e,$ndr,$varname) = @_;
2004
2005         my $env;
2006
2007         $env->{$e->{NAME}} = $varname;
2008
2009         $self->ParseElementPullLevel($e, $e->{LEVELS}[0], $ndr, $varname, $env, 1, 1);
2010 }
2011
2012 #####################################################################
2013 # parse a typedef - print side
2014 sub ParseTypedefPrint($$$$$)
2015 {
2016         my($self,$e,$ndr,$name,$varname) = @_;
2017
2018         $typefamily{$e->{DATA}->{TYPE}}->{PRINT_FN_BODY}->($self, $e->{DATA}, $ndr, $name, $varname);
2019 }
2020
2021 #####################################################################
2022 ## calculate the size of a structure
2023 sub ParseTypedefNdrSize($$$$)
2024 {
2025         my($self,$t,$name,$varname) = @_;
2026
2027         $typefamily{$t->{DATA}->{TYPE}}->{SIZE_FN_BODY}->($self, $t->{DATA}, $name, $varname);
2028 }
2029
2030 sub DeclTypedef($$$$)
2031 {
2032         my ($e, $t, $name, $varname) = @_;
2033         
2034         return $typefamily{$e->{DATA}->{TYPE}}->{DECL}->($e->{DATA}, $t, $name, $varname);
2035 }
2036
2037 sub ArgsTypedefNdrSize($$$)
2038 {
2039         my ($d, $name, $varname) = @_;
2040         return $typefamily{$d->{DATA}->{TYPE}}->{SIZE_FN_ARGS}->($d->{DATA}, $name, $varname);
2041 }
2042
2043 $typefamily{TYPEDEF} = {
2044         PUSH_FN_BODY => \&ParseTypedefPush,
2045         DECL => \&DeclTypedef,
2046         PULL_FN_BODY => \&ParseTypedefPull,
2047         PRINT_FN_BODY => \&ParseTypedefPrint,
2048         SIZE_FN_ARGS => \&ArgsTypedefNdrSize,
2049         SIZE_FN_BODY => \&ParseTypedefNdrSize,
2050 };
2051
2052 #####################################################################
2053 # parse a function - print side
2054 sub ParseFunctionPrint($$)
2055 {
2056         my($self, $fn) = @_;
2057         my $ndr = "ndr";
2058
2059         $self->pidl_hdr("void ndr_print_$fn->{NAME}(struct ndr_print *$ndr, const char *name, int flags, const struct $fn->{NAME} *r);");
2060
2061         return if has_property($fn, "noprint");
2062
2063         $self->pidl("_PUBLIC_ void ndr_print_$fn->{NAME}(struct ndr_print *$ndr, const char *name, int flags, const struct $fn->{NAME} *r)");
2064         $self->pidl("{");
2065         $self->indent;
2066
2067         foreach my $e (@{$fn->{ELEMENTS}}) {
2068                 $self->DeclareArrayVariables($e);
2069         }
2070
2071         $self->pidl("ndr_print_struct($ndr, name, \"$fn->{NAME}\");");
2072         $self->pidl("if (r == NULL) { ndr_print_null($ndr); return; }");
2073         $self->pidl("$ndr->depth++;");
2074
2075         $self->pidl("if (flags & NDR_SET_VALUES) {");
2076         $self->pidl("\t$ndr->flags |= LIBNDR_PRINT_SET_VALUES;");
2077         $self->pidl("}");
2078
2079         $self->pidl("if (flags & NDR_IN) {");
2080         $self->indent;
2081         $self->pidl("ndr_print_struct($ndr, \"in\", \"$fn->{NAME}\");");
2082         $self->pidl("$ndr->depth++;");
2083
2084         my $env = GenerateFunctionInEnv($fn);
2085
2086         foreach my $e (@{$fn->{ELEMENTS}}) {
2087                 if (grep(/in/,@{$e->{DIRECTION}})) {
2088                         $self->ParseElementPrint($e, $ndr, $env->{$e->{NAME}}, $env);
2089                 }
2090         }
2091         $self->pidl("$ndr->depth--;");
2092         $self->deindent;
2093         $self->pidl("}");
2094         
2095         $self->pidl("if (flags & NDR_OUT) {");
2096         $self->indent;
2097         $self->pidl("ndr_print_struct($ndr, \"out\", \"$fn->{NAME}\");");
2098         $self->pidl("$ndr->depth++;");
2099
2100         $env = GenerateFunctionOutEnv($fn);
2101         foreach my $e (@{$fn->{ELEMENTS}}) {
2102                 if (grep(/out/,@{$e->{DIRECTION}})) {
2103                         $self->ParseElementPrint($e, $ndr, $env->{$e->{NAME}}, $env);
2104                 }
2105         }
2106         if ($fn->{RETURN_TYPE}) {
2107                 $self->pidl("ndr_print_$fn->{RETURN_TYPE}($ndr, \"result\", r->out.result);");
2108         }
2109         $self->pidl("$ndr->depth--;");
2110         $self->deindent;
2111         $self->pidl("}");
2112         
2113         $self->pidl("$ndr->depth--;");
2114         $self->deindent;
2115         $self->pidl("}");
2116         $self->pidl("");
2117 }
2118
2119 #####################################################################
2120 # parse a function
2121 sub ParseFunctionPush($$)
2122
2123         my($self, $fn) = @_;
2124         my $ndr = "ndr";
2125
2126         $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;
2127
2128         return if has_property($fn, "nopush");
2129
2130         $self->pidl("{");
2131         $self->indent;
2132
2133         foreach my $e (@{$fn->{ELEMENTS}}) { 
2134                 $self->DeclareArrayVariables($e);
2135         }
2136
2137         $self->pidl("if (flags & NDR_IN) {");
2138         $self->indent;
2139
2140         my $env = GenerateFunctionInEnv($fn);
2141
2142         EnvSubstituteValue($env, $fn);
2143
2144         foreach my $e (@{$fn->{ELEMENTS}}) {
2145                 if (grep(/in/,@{$e->{DIRECTION}})) {
2146                         $self->ParseElementPush($e, $ndr, $env, 1, 1);
2147                 }
2148         }
2149
2150         $self->deindent;
2151         $self->pidl("}");
2152
2153         $self->pidl("if (flags & NDR_OUT) {");
2154         $self->indent;
2155
2156         $env = GenerateFunctionOutEnv($fn);
2157         foreach my $e (@{$fn->{ELEMENTS}}) {
2158                 if (grep(/out/,@{$e->{DIRECTION}})) {
2159                         $self->ParseElementPush($e, $ndr, $env, 1, 1);
2160                 }
2161         }
2162
2163         if ($fn->{RETURN_TYPE}) {
2164                 $self->pidl("NDR_CHECK(ndr_push_$fn->{RETURN_TYPE}($ndr, NDR_SCALARS, r->out.result));");
2165         }
2166     
2167         $self->deindent;
2168         $self->pidl("}");
2169         $self->pidl("return NDR_ERR_SUCCESS;");
2170         $self->deindent;
2171         $self->pidl("}");
2172         $self->pidl("");
2173 }
2174
2175 sub AllocateArrayLevel($$$$$$)
2176 {
2177         my ($self,$e,$l,$ndr,$var,$size) = @_;
2178
2179         my $pl = GetPrevLevel($e, $l);
2180         if (defined($pl) and 
2181             $pl->{TYPE} eq "POINTER" and 
2182             $pl->{POINTER_TYPE} eq "ref"
2183             and not $l->{IS_ZERO_TERMINATED}) {
2184                 $self->pidl("if ($ndr->flags & LIBNDR_FLAG_REF_ALLOC) {");
2185                 $self->pidl("\tNDR_PULL_ALLOC_N($ndr, $var, $size);");
2186                 $self->pidl("}");
2187                 if (grep(/in/,@{$e->{DIRECTION}}) and
2188                     grep(/out/,@{$e->{DIRECTION}})) {
2189                         $self->pidl("memcpy(r->out.$e->{NAME}, r->in.$e->{NAME}, ($size) * sizeof(*r->in.$e->{NAME}));");
2190                 }
2191                 return;
2192         }
2193
2194         $self->pidl("NDR_PULL_ALLOC_N($ndr, $var, $size);");
2195 }
2196
2197 #####################################################################
2198 # parse a function
2199 sub ParseFunctionPull($$)
2200
2201         my($self,$fn) = @_;
2202         my $ndr = "ndr";
2203
2204         # pull function args
2205         $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;
2206
2207         $self->pidl("{");
2208         $self->indent;
2209
2210         # declare any internal pointers we need
2211         foreach my $e (@{$fn->{ELEMENTS}}) { 
2212                 $self->DeclarePtrVariables($e);
2213                 $self->DeclareArrayVariables($e);
2214         }
2215
2216         my %double_cases = ();
2217         foreach my $e (@{$fn->{ELEMENTS}}) {
2218                 next if ($e->{TYPE} eq "EMPTY");
2219                 next if ($double_cases{"$e->{NAME}"});
2220                 $self->DeclareMemCtxVariables($e);
2221                 $double_cases{"$e->{NAME}"} = 1;
2222         }
2223
2224         $self->pidl("if (flags & NDR_IN) {");
2225         $self->indent;
2226
2227         # auto-init the out section of a structure. I originally argued that
2228         # this was a bad idea as it hides bugs, but coping correctly
2229         # with initialisation and not wiping ref vars is turning
2230         # out to be too tricky (tridge)
2231         foreach my $e (@{$fn->{ELEMENTS}}) {
2232                 next unless grep(/out/, @{$e->{DIRECTION}});
2233                 $self->pidl("ZERO_STRUCT(r->out);");
2234                 $self->pidl("");
2235                 last;
2236         }
2237
2238         my $env = GenerateFunctionInEnv($fn);
2239
2240         foreach my $e (@{$fn->{ELEMENTS}}) {
2241                 next unless (grep(/in/, @{$e->{DIRECTION}}));
2242                 $self->ParseElementPull($e, $ndr, $env, 1, 1);
2243         }
2244
2245         # allocate the "simple" out ref variables. FIXME: Shouldn't this have it's
2246         # own flag rather than be in NDR_IN ?
2247
2248         foreach my $e (@{$fn->{ELEMENTS}}) {
2249                 next unless (grep(/out/, @{$e->{DIRECTION}}));
2250                 next unless ($e->{LEVELS}[0]->{TYPE} eq "POINTER" and 
2251                              $e->{LEVELS}[0]->{POINTER_TYPE} eq "ref");
2252                 next if (($e->{LEVELS}[1]->{TYPE} eq "DATA") and 
2253                                  ($e->{LEVELS}[1]->{DATA_TYPE} eq "string"));
2254                 next if (($e->{LEVELS}[1]->{TYPE} eq "ARRAY") 
2255                         and   $e->{LEVELS}[1]->{IS_ZERO_TERMINATED});
2256
2257                 if ($e->{LEVELS}[1]->{TYPE} eq "ARRAY") {
2258                         my $size = ParseExprExt($e->{LEVELS}[1]->{SIZE_IS}, $env, $e->{ORIGINAL},
2259                                 check_null_pointer($e, $env, sub { $self->pidl(shift); },
2260                                                    "return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for size_is()\");"),
2261                                 check_fully_dereferenced($e, $env));
2262                         $self->pidl("NDR_PULL_ALLOC_N($ndr, r->out.$e->{NAME}, $size);");
2263
2264                         if (grep(/in/, @{$e->{DIRECTION}})) {
2265                                 $self->pidl("memcpy(r->out.$e->{NAME}, r->in.$e->{NAME}, ($size) * sizeof(*r->in.$e->{NAME}));");
2266                         } else {
2267                                 $self->pidl("memset(r->out.$e->{NAME}, 0, ($size) * sizeof(*r->out.$e->{NAME}));");
2268                         }
2269                 } else {
2270                         $self->pidl("NDR_PULL_ALLOC($ndr, r->out.$e->{NAME});");
2271                 
2272                         if (grep(/in/, @{$e->{DIRECTION}})) {
2273                                 $self->pidl("*r->out.$e->{NAME} = *r->in.$e->{NAME};");
2274                         } else {
2275                                 $self->pidl("ZERO_STRUCTP(r->out.$e->{NAME});");
2276                         }
2277                 }
2278         }
2279
2280         $self->add_deferred();
2281         $self->deindent;
2282         $self->pidl("}");
2283         
2284         $self->pidl("if (flags & NDR_OUT) {");
2285         $self->indent;
2286
2287         $env = GenerateFunctionOutEnv($fn);
2288         foreach my $e (@{$fn->{ELEMENTS}}) {
2289                 next unless grep(/out/, @{$e->{DIRECTION}});
2290                 $self->ParseElementPull($e, $ndr, $env, 1, 1);
2291         }
2292
2293         if ($fn->{RETURN_TYPE}) {
2294                 $self->pidl("NDR_CHECK(ndr_pull_$fn->{RETURN_TYPE}($ndr, NDR_SCALARS, &r->out.result));");
2295         }
2296
2297         $self->add_deferred();
2298         $self->deindent;
2299         $self->pidl("}");
2300
2301         $self->pidl("return NDR_ERR_SUCCESS;");
2302         $self->deindent;
2303         $self->pidl("}");
2304         $self->pidl("");
2305 }
2306
2307 sub AuthServiceStruct($$$)
2308 {
2309         my ($self, $ifacename, $authservice) = @_;
2310         my @a = split /,/, $authservice;
2311         my $authservice_count = $#a + 1;
2312
2313         $self->pidl("static const char * const $ifacename\_authservice_strings[] = {");
2314         foreach my $ap (@a) {
2315                 $self->pidl("\t$ap, ");
2316         }
2317         $self->pidl("};");
2318         $self->pidl("");
2319
2320         $self->pidl("static const struct ndr_interface_string_array $ifacename\_authservices = {");
2321         $self->pidl("\t.count\t= $authservice_count,");
2322         $self->pidl("\t.names\t= $ifacename\_authservice_strings");
2323         $self->pidl("};");
2324         $self->pidl("");
2325 }
2326
2327 sub FunctionCallEntry($$)
2328 {
2329         my ($self, $d) = @_;
2330         return 0 if not defined($d->{OPNUM});
2331         $self->pidl("\t{");
2332         $self->pidl("\t\t\"$d->{NAME}\",");
2333         $self->pidl("\t\tsizeof(struct $d->{NAME}),");
2334         $self->pidl("\t\t(ndr_push_flags_fn_t) ndr_push_$d->{NAME},");
2335         $self->pidl("\t\t(ndr_pull_flags_fn_t) ndr_pull_$d->{NAME},");
2336         $self->pidl("\t\t(ndr_print_function_t) ndr_print_$d->{NAME},");
2337         $self->pidl("\t},");
2338         return 1;
2339 }
2340
2341 #####################################################################
2342 # produce a function call table
2343 sub FunctionTable($$)
2344 {
2345         my($self,$interface) = @_;
2346         my $count = 0;
2347         my $uname = uc $interface->{NAME};
2348
2349         return if ($#{$interface->{FUNCTIONS}}+1 == 0);
2350         return unless defined ($interface->{PROPERTIES}->{uuid});
2351
2352         $self->pidl("static const struct ndr_interface_call $interface->{NAME}\_calls[] = {");
2353
2354         foreach my $d (@{$interface->{INHERITED_FUNCTIONS}},@{$interface->{FUNCTIONS}}) {
2355                 $count += $self->FunctionCallEntry($d);
2356         }
2357         $self->pidl("\t{ NULL, 0, NULL, NULL, NULL }");
2358         $self->pidl("};");
2359         $self->pidl("");
2360
2361         $self->pidl("static const char * const $interface->{NAME}\_endpoint_strings[] = {");
2362         foreach my $ep (@{$interface->{ENDPOINTS}}) {
2363                 $self->pidl("\t$ep, ");
2364         }
2365         my $endpoint_count = $#{$interface->{ENDPOINTS}}+1;
2366         
2367         $self->pidl("};");
2368         $self->pidl("");
2369
2370         $self->pidl("static const struct ndr_interface_string_array $interface->{NAME}\_endpoints = {");
2371         $self->pidl("\t.count\t= $endpoint_count,");
2372         $self->pidl("\t.names\t= $interface->{NAME}\_endpoint_strings");
2373         $self->pidl("};");
2374         $self->pidl("");
2375
2376         if (! defined $interface->{PROPERTIES}->{authservice}) {
2377                 $interface->{PROPERTIES}->{authservice} = "\"host\"";
2378         }
2379
2380         $self->AuthServiceStruct($interface->{NAME}, 
2381                                      $interface->{PROPERTIES}->{authservice});
2382
2383         $self->pidl("\nconst struct ndr_interface_table ndr_table_$interface->{NAME} = {");
2384         $self->pidl("\t.name\t\t= \"$interface->{NAME}\",");
2385         $self->pidl("\t.syntax_id\t= {");
2386         $self->pidl("\t\t" . print_uuid($interface->{UUID}) .",");
2387         $self->pidl("\t\tNDR_$uname\_VERSION");
2388         $self->pidl("\t},");
2389         $self->pidl("\t.helpstring\t= NDR_$uname\_HELPSTRING,");
2390         $self->pidl("\t.num_calls\t= $count,");
2391         $self->pidl("\t.calls\t\t= $interface->{NAME}\_calls,");
2392         $self->pidl("\t.endpoints\t= &$interface->{NAME}\_endpoints,");
2393         $self->pidl("\t.authservices\t= &$interface->{NAME}\_authservices");
2394         $self->pidl("};");
2395         $self->pidl("");
2396
2397 }
2398
2399 #####################################################################
2400 # generate include statements for imported idl files
2401 sub HeaderImport
2402 {
2403         my $self = shift;
2404         my @imports = @_;
2405         foreach (@imports) {
2406                 $_ = unmake_str($_);
2407                 s/\.idl$//;
2408                 $self->pidl(choose_header("librpc/gen_ndr/ndr_$_\.h", "gen_ndr/ndr_$_.h"));
2409         }
2410 }
2411
2412 #####################################################################
2413 # generate include statements for included header files
2414 sub HeaderInclude
2415 {
2416         my $self = shift;
2417         my @includes = @_;
2418         foreach (@includes) {
2419                 $self->pidl_hdr("#include $_");
2420         }
2421 }
2422
2423 #####################################################################
2424 # generate prototypes and defines for the interface definitions
2425 # FIXME: these prototypes are for the DCE/RPC client functions, not the 
2426 # NDR parser and so do not belong here, technically speaking
2427 sub HeaderInterface($$$)
2428 {
2429         my($self,$interface,$needed) = @_;
2430
2431         my $count = 0;
2432
2433         if ($needed->{"compression"}) {
2434                 $self->pidl(choose_header("librpc/ndr/ndr_compression.h", "ndr/compression.h"));
2435         }
2436
2437         if (has_property($interface, "object")) {
2438                 $self->pidl(choose_header("librpc/gen_ndr/ndr_orpc.h", "ndr/orpc.h"));
2439         }
2440
2441         if (defined $interface->{PROPERTIES}->{helper}) {
2442                 $self->HeaderInclude(split /,/, $interface->{PROPERTIES}->{helper});
2443         }
2444
2445         if (defined $interface->{PROPERTIES}->{uuid}) {
2446                 my $name = uc $interface->{NAME};
2447                 $self->pidl_hdr("#define NDR_$name\_UUID " . 
2448                 Parse::Pidl::Util::make_str(lc($interface->{PROPERTIES}->{uuid})));
2449
2450                 if(!defined $interface->{PROPERTIES}->{version}) { $interface->{PROPERTIES}->{version} = "0.0"; }
2451                 $self->pidl_hdr("#define NDR_$name\_VERSION $interface->{PROPERTIES}->{version}");
2452
2453                 $self->pidl_hdr("#define NDR_$name\_NAME \"$interface->{NAME}\"");
2454
2455                 if(!defined $interface->{PROPERTIES}->{helpstring}) { $interface->{PROPERTIES}->{helpstring} = "NULL"; }
2456                 $self->pidl_hdr("#define NDR_$name\_HELPSTRING $interface->{PROPERTIES}->{helpstring}");
2457
2458                 $self->pidl_hdr("extern const struct ndr_interface_table ndr_table_$interface->{NAME};");
2459         }
2460
2461         foreach (@{$interface->{FUNCTIONS}}) {
2462                 next if has_property($_, "noopnum");
2463                 next if grep(/^$_->{NAME}$/,@{$interface->{INHERITED_FUNCTIONS}});
2464                 my $u_name = uc $_->{NAME};
2465         
2466                 my $val = sprintf("0x%02x", $count);
2467                 if (defined($interface->{BASE})) {
2468                         $val .= " + NDR_" . uc $interface->{BASE} . "_CALL_COUNT";
2469                 }
2470                 
2471                 $self->pidl_hdr("#define NDR_$u_name ($val)");
2472
2473                 $self->pidl_hdr("");
2474                 $count++;
2475         }
2476
2477         my $val = $count;
2478
2479         if (defined($interface->{BASE})) {
2480                 $val .= " + NDR_" . uc $interface->{BASE} . "_CALL_COUNT";
2481         }
2482
2483         $self->pidl_hdr("#define NDR_" . uc $interface->{NAME} . "_CALL_COUNT ($val)");
2484
2485 }
2486
2487 sub ParseTypePush($$$$$$)
2488 {
2489         my ($self,$e, $ndr, $varname, $primitives, $deferred) = @_;
2490
2491         # save the old relative_base_offset
2492         $self->pidl("uint32_t _save_relative_base_offset = ndr_push_get_relative_base_offset($ndr);") if defined(has_property($e, "relative_base"));
2493         $typefamily{$e->{TYPE}}->{PUSH_FN_BODY}->($self, $e, $ndr, $varname);
2494         # restore the old relative_base_offset
2495         $self->pidl("ndr_push_restore_relative_base_offset($ndr, _save_relative_base_offset);") if defined(has_property($e, "relative_base"));
2496 }
2497
2498 sub ParseTypePushFunction($$$)
2499 {
2500         my ($self, $e, $varname) = @_;
2501         my $ndr = "ndr";
2502
2503         my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "push", $e->{NAME}, $varname);
2504
2505         $self->fn_declare("push", $e, "enum ndr_err_code ".TypeFunctionName("ndr_push", $e)."(struct ndr_push *$ndr, int ndr_flags, $args)") or return;
2506
2507         $self->pidl("{");
2508         $self->indent;
2509         $self->ParseTypePush($e, $ndr, $varname, 1, 1);
2510         $self->pidl("return NDR_ERR_SUCCESS;");
2511         $self->deindent;
2512         $self->pidl("}");
2513         $self->pidl("");;
2514 }
2515
2516 sub ParseTypePull($$$$$$)
2517 {
2518         my ($self, $e, $ndr, $varname, $primitives, $deferred) = @_;
2519
2520         # save the old relative_base_offset
2521         $self->pidl("uint32_t _save_relative_base_offset = ndr_pull_get_relative_base_offset($ndr);") if defined(has_property($e, "relative_base"));
2522         $typefamily{$e->{TYPE}}->{PULL_FN_BODY}->($self, $e, $ndr, $varname);
2523         # restore the old relative_base_offset
2524         $self->pidl("ndr_pull_restore_relative_base_offset($ndr, _save_relative_base_offset);") if defined(has_property($e, "relative_base"));
2525 }
2526
2527 sub ParseTypePullFunction($$)
2528 {
2529         my ($self, $e, $varname) = @_;
2530         my $ndr = "ndr";
2531
2532         my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "pull", $e->{NAME}, $varname);
2533
2534         $self->fn_declare("pull", $e, "enum ndr_err_code ".TypeFunctionName("ndr_pull", $e)."(struct ndr_pull *$ndr, int ndr_flags, $args)") or return;
2535
2536         $self->pidl("{");
2537         $self->indent;
2538         $self->ParseTypePull($e, $ndr, $varname, 1, 1);
2539         $self->pidl("return NDR_ERR_SUCCESS;");
2540         $self->deindent;
2541         $self->pidl("}");
2542         $self->pidl("");
2543 }
2544
2545 sub ParseTypePrint($$$$)
2546 {
2547         my ($self, $e, $ndr, $varname) = @_;
2548
2549         $typefamily{$e->{TYPE}}->{PRINT_FN_BODY}->($self, $e, $ndr, $e->{NAME}, $varname);
2550 }
2551
2552 sub ParseTypePrintFunction($$$)
2553 {
2554         my ($self, $e, $varname) = @_;
2555         my $ndr = "ndr";
2556
2557         my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "print", $e->{NAME}, $varname);
2558
2559         $self->pidl_hdr("void ".TypeFunctionName("ndr_print", $e)."(struct ndr_print *ndr, const char *name, $args);");
2560
2561         return if (has_property($e, "noprint"));
2562
2563         $self->pidl("_PUBLIC_ void ".TypeFunctionName("ndr_print", $e)."(struct ndr_print *$ndr, const char *name, $args)");
2564         $self->pidl("{");
2565         $self->indent;
2566         $self->ParseTypePrint($e, $ndr, $varname);
2567         $self->deindent;
2568         $self->pidl("}");
2569         $self->pidl("");
2570 }
2571
2572 sub ParseTypeNdrSize($$)
2573 {
2574         my ($self,$t) = @_;
2575
2576         my $varname = "r";
2577         my $tf = $typefamily{$t->{TYPE}};
2578         my $args = $tf->{SIZE_FN_ARGS}->($t, $t->{NAME}, $varname);
2579
2580         $self->fn_declare("size", $t, "size_t ndr_size_$t->{NAME}($args)") or return;
2581
2582         $self->pidl("{");
2583         $self->indent;
2584         $typefamily{$t->{TYPE}}->{SIZE_FN_BODY}->($self,$t, $t->{NAME}, $varname);
2585         $self->deindent;
2586         $self->pidl("}");
2587         $self->pidl("");
2588 }
2589
2590 #####################################################################
2591 # parse the interface definitions
2592 sub ParseInterface($$$)
2593 {
2594         my($self,$interface,$needed) = @_;
2595
2596         $self->pidl_hdr("#ifndef _HEADER_NDR_$interface->{NAME}");
2597         $self->pidl_hdr("#define _HEADER_NDR_$interface->{NAME}");
2598
2599         $self->pidl_hdr("");
2600
2601         $self->HeaderInterface($interface, $needed);
2602
2603         # Typedefs
2604         foreach my $d (@{$interface->{TYPES}}) {
2605                 next unless(typeHasBody($d));
2606
2607                 ($needed->{TypeFunctionName("ndr_push", $d)}) && $self->ParseTypePushFunction($d, "r");
2608                 ($needed->{TypeFunctionName("ndr_pull", $d)}) && $self->ParseTypePullFunction($d, "r");
2609                 ($needed->{TypeFunctionName("ndr_print", $d)}) && $self->ParseTypePrintFunction($d, "r");
2610
2611                 # Make sure we don't generate a function twice...
2612                 $needed->{TypeFunctionName("ndr_push", $d)} = 
2613                     $needed->{TypeFunctionName("ndr_pull", $d)} = 
2614                         $needed->{TypeFunctionName("ndr_print", $d)} = 0;
2615
2616                 ($needed->{"ndr_size_$d->{NAME}"}) && $self->ParseTypeNdrSize($d);
2617         }
2618
2619         # Functions
2620         foreach my $d (@{$interface->{FUNCTIONS}}) {
2621                 ($needed->{"ndr_push_$d->{NAME}"}) && $self->ParseFunctionPush($d);
2622                 ($needed->{"ndr_pull_$d->{NAME}"}) && $self->ParseFunctionPull($d);
2623                 ($needed->{"ndr_print_$d->{NAME}"}) && $self->ParseFunctionPrint($d);
2624
2625                 # Make sure we don't generate a function twice...
2626                 $needed->{"ndr_push_$d->{NAME}"} = $needed->{"ndr_pull_$d->{NAME}"} = 
2627                         $needed->{"ndr_print_$d->{NAME}"} = 0;
2628         }
2629
2630         $self->FunctionTable($interface);
2631
2632         $self->pidl_hdr("#endif /* _HEADER_NDR_$interface->{NAME} */");
2633 }
2634
2635 sub GenerateIncludes($)
2636 {
2637         my ($self) = @_;
2638         if (is_intree()) {
2639                 $self->pidl("#include \"includes.h\"");
2640         } else {
2641                 $self->pidl("#ifndef _GNU_SOURCE");
2642                 $self->pidl("#define _GNU_SOURCE");
2643                 $self->pidl("#endif");
2644                 $self->pidl("#include <stdint.h>");
2645                 $self->pidl("#include <stdlib.h>");
2646                 $self->pidl("#include <stdio.h>");
2647                 $self->pidl("#include <stdbool.h>");
2648                 $self->pidl("#include <stdarg.h>");
2649                 $self->pidl("#include <string.h>");
2650         }
2651 }
2652
2653 #####################################################################
2654 # parse a parsed IDL structure back into an IDL file
2655 sub Parse($$$$)
2656 {
2657         my($self, $ndr,$gen_header,$ndr_header) = @_;
2658
2659         $self->pidl_hdr("/* header auto-generated by pidl */");
2660         $self->pidl_hdr("");
2661         $self->pidl_hdr(choose_header("librpc/ndr/libndr.h", "ndr.h"));
2662         $self->pidl_hdr("#include \"$gen_header\"") if ($gen_header);
2663         $self->pidl_hdr("");
2664
2665         $self->pidl("/* parser auto-generated by pidl */");
2666         $self->pidl("");
2667         $self->GenerateIncludes();
2668         $self->pidl("#include \"$ndr_header\"") if ($ndr_header);
2669         $self->pidl("");
2670
2671         my %needed = ();
2672
2673         foreach (@{$ndr}) {
2674                 ($_->{TYPE} eq "INTERFACE") && NeededInterface($_, \%needed);
2675         }
2676
2677         foreach (@{$ndr}) {
2678                 ($_->{TYPE} eq "INTERFACE") && $self->ParseInterface($_, \%needed);
2679                 ($_->{TYPE} eq "IMPORT") && $self->HeaderImport(@{$_->{PATHS}});
2680                 ($_->{TYPE} eq "INCLUDE") && $self->HeaderInclude(@{$_->{PATHS}});
2681         }
2682
2683         return ($self->{res_hdr}, $self->{res});
2684 }
2685
2686 sub NeededElement($$$)
2687 {
2688         my ($e, $dir, $needed) = @_;
2689
2690         return if ($e->{TYPE} eq "EMPTY");
2691
2692         return if (ref($e->{TYPE}) eq "HASH" and 
2693                        not defined($e->{TYPE}->{NAME}));
2694
2695         my ($t, $rt);
2696         if (ref($e->{TYPE}) eq "HASH") {
2697                 $t = $e->{TYPE}->{TYPE}."_".$e->{TYPE}->{NAME};
2698         } else {
2699                 $t = $e->{TYPE};
2700         }
2701
2702         if (ref($e->{REPRESENTATION_TYPE}) eq "HASH") {
2703                 $rt = $e->{REPRESENTATION_TYPE}->{TYPE}."_".$e->{REPRESENTATION_TYPE}->{NAME};
2704         } else {
2705                 $rt = $e->{REPRESENTATION_TYPE};
2706         }
2707
2708         die ("$e->{NAME} $t, $rt FOO") unless ($rt ne "");
2709
2710         my @fn = ();
2711         if ($dir eq "print") {
2712                 push(@fn, TypeFunctionName("ndr_print", $e->{REPRESENTATION_TYPE}));
2713         } elsif ($dir eq "pull") {
2714                 push (@fn, TypeFunctionName("ndr_pull", $e->{TYPE}));
2715                 push (@fn, "ndr_$t\_to_$rt")
2716                         if ($rt ne $t);
2717         } elsif ($dir eq "push") {
2718                 push (@fn, TypeFunctionName("ndr_push", $e->{TYPE}));
2719                 push (@fn, "ndr_$rt\_to_$t")
2720                         if ($rt ne $t);
2721         } else {
2722                 die("invalid direction `$dir'");
2723         }
2724
2725         foreach (@fn) {
2726                 unless (defined($needed->{$_})) {
2727                         $needed->{$_} = 1;
2728                 }
2729         }
2730 }
2731
2732 sub NeededFunction($$)
2733 {
2734         my ($fn,$needed) = @_;
2735         $needed->{"ndr_pull_$fn->{NAME}"} = 1;
2736         $needed->{"ndr_push_$fn->{NAME}"} = 1;
2737         $needed->{"ndr_print_$fn->{NAME}"} = 1;
2738         foreach my $e (@{$fn->{ELEMENTS}}) {
2739                 $e->{PARENT} = $fn;
2740                 NeededElement($e, $_, $needed) foreach ("pull", "push", "print");
2741         }
2742 }
2743
2744 sub NeededType($$$)
2745 {
2746         sub NeededType($$$);
2747         my ($t,$needed,$req) = @_;
2748
2749         NeededType($t->{DATA}, $needed, $req) if ($t->{TYPE} eq "TYPEDEF");
2750
2751         if ($t->{TYPE} eq "STRUCT" or $t->{TYPE} eq "UNION") {
2752                 return unless defined($t->{ELEMENTS});
2753                 for my $e (@{$t->{ELEMENTS}}) {
2754                         $e->{PARENT} = $t;
2755                         if (has_property($e, "compression")) { 
2756                                 $needed->{"compression"} = 1;
2757                         }
2758                         NeededElement($e, $req, $needed);
2759                         NeededType($e->{TYPE}, $needed, $req) if (ref($e->{TYPE}) eq "HASH");
2760                 }
2761         }
2762 }
2763
2764 #####################################################################
2765 # work out what parse functions are needed
2766 sub NeededInterface($$)
2767 {
2768         my ($interface,$needed) = @_;
2769         NeededFunction($_, $needed) foreach (@{$interface->{FUNCTIONS}});
2770         foreach (reverse @{$interface->{TYPES}}) {
2771                 if (has_property($_, "public")) {
2772                         $needed->{TypeFunctionName("ndr_pull", $_)} = $needed->{TypeFunctionName("ndr_push", $_)} = 
2773                                 $needed->{TypeFunctionName("ndr_print", $_)} = 1;
2774                 }
2775
2776                 NeededType($_, $needed, "pull") if ($needed->{TypeFunctionName("ndr_pull", $_)});
2777                 NeededType($_, $needed, "push") if ($needed->{TypeFunctionName("ndr_push", $_)});
2778                 NeededType($_, $needed, "print") if ($needed->{TypeFunctionName("ndr_print", $_)});
2779                 if (has_property($_, "gensize")) {
2780                         $needed->{"ndr_size_$_->{NAME}"} = 1;
2781                 }
2782         }
2783 }
2784
2785 sub TypeFunctionName($$)
2786 {
2787         my ($prefix, $t) = @_;
2788
2789         return "$prefix\_$t->{NAME}" if (ref($t) eq "HASH" and 
2790                         $t->{TYPE} eq "TYPEDEF");
2791         return "$prefix\_$t->{TYPE}_$t->{NAME}" if (ref($t) eq "HASH");
2792         return "$prefix\_$t";
2793 }
2794
2795 1;