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