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