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