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