pidl:Samba4/Python: fix segfault when setting pointers to scalars.
[kai/samba.git] / pidl / lib / Parse / Pidl / Samba4 / Python.pm
1 ###################################################
2 # Python function wrapper generator
3 # Copyright jelmer@samba.org 2007-2008
4 # released under the GNU GPL
5
6 package Parse::Pidl::Samba4::Python;
7
8 use Exporter;
9 @ISA = qw(Exporter);
10
11 use strict;
12 use Parse::Pidl qw(warning fatal error);
13 use Parse::Pidl::Typelist qw(hasType resolveType getType mapTypeName expandAlias);
14 use Parse::Pidl::Util qw(has_property ParseExpr unmake_str);
15 use Parse::Pidl::NDR qw(GetPrevLevel GetNextLevel ContainsDeferred is_charset_array);
16 use Parse::Pidl::CUtil qw(get_value_of get_pointer_to);
17 use Parse::Pidl::Samba4 qw(ArrayDynamicallyAllocated);
18 use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
19
20 use vars qw($VERSION);
21 $VERSION = '0.01';
22
23 sub new($) {
24         my ($class) = @_;
25         my $self = { res => "", res_hdr => "", tabs => "", constants => {},
26                      module_methods => [], module_objects => [], ready_types => [],
27                                  module_imports => {}, type_imports => {},
28                                  patch_type_calls => [], prereadycode => [],
29                                  postreadycode => []};
30         bless($self, $class);
31 }
32
33 sub pidl_hdr ($$)
34 {
35         my $self = shift;
36         $self->{res_hdr} .= shift;
37 }
38
39 sub pidl($$)
40 {
41         my ($self, $d) = @_;
42         if ($d) {
43                 if ((!($d =~ /^#/))) {
44                         $self->{res} .= $self->{tabs};
45                 }
46                 $self->{res} .= $d;
47         }
48         $self->{res} .= "\n";
49 }
50
51 sub indent($)
52 {
53         my ($self) = @_;
54         $self->{tabs} .= "\t";
55 }
56
57 sub deindent($)
58 {
59         my ($self) = @_;
60         $self->{tabs} = substr($self->{tabs}, 0, -1);
61 }
62
63 sub PrettifyTypeName($$)
64 {
65         my ($name, $basename) = @_;
66
67         $basename =~ s/^.*\.([^.]+)$/\1/;
68
69         $name =~ s/^$basename\_//;
70
71
72         return $name;
73 }
74
75 sub Import
76 {
77         my $self = shift;
78         my @imports = @_;
79         foreach (@imports) {
80                 $_ = unmake_str($_);
81                 s/\.idl$//;
82                 $self->pidl_hdr("#include \"librpc/gen_ndr/$_\.h\"\n");
83                 $self->register_module_import("samba.dcerpc.$_");
84         }
85 }
86
87 sub Const($$)
88 {
89     my ($self, $const) = @_;
90         $self->register_constant($const->{NAME}, $const->{DTYPE}, $const->{VALUE});
91 }
92
93 sub register_constant($$$$)
94 {
95         my ($self, $name, $type, $value) = @_;
96
97         $self->{constants}->{$name} = [$type, $value];
98 }
99
100 sub EnumAndBitmapConsts($$$)
101 {
102         my ($self, $name, $d) = @_;
103
104         return unless (defined($d->{ELEMENTS}));
105
106         foreach my $e (@{$d->{ELEMENTS}}) {
107                 $e =~ /^([A-Za-z0-9_]+)/;
108                 my $cname = $1;
109                 
110                 $self->register_constant($cname, $d, $cname);
111         }
112 }
113
114 sub FromUnionToPythonFunction($$$$)
115 {
116         my ($self, $mem_ctx, $type, $switch, $name) = @_;
117
118         $self->pidl("PyObject *ret;");
119         $self->pidl("");
120
121         $self->pidl("switch ($switch) {");
122         $self->indent;
123
124         foreach my $e (@{$type->{ELEMENTS}}) {
125                 $self->pidl("$e->{CASE}:");
126
127                 $self->indent;
128
129                 if ($e->{NAME}) {
130                         $self->ConvertObjectToPython($mem_ctx, {}, $e, "$name->$e->{NAME}", "ret", "return NULL;");
131                 } else {
132                         $self->pidl("ret = Py_None;");
133                         $self->pidl("Py_INCREF(ret);");
134                 }
135
136                 $self->pidl("return ret;");
137                 $self->pidl("");
138
139                 $self->deindent;
140         }
141
142         $self->deindent;
143         $self->pidl("}");
144
145         $self->pidl("PyErr_SetString(PyExc_TypeError, \"unknown union level\");");
146         $self->pidl("return NULL;");
147 }
148
149 sub FromPythonToUnionFunction($$$$$)
150 {
151         my ($self, $type, $typename, $switch, $mem_ctx, $name) = @_;
152
153         my $has_default = 0;
154
155         $self->pidl("$typename *ret = talloc_zero($mem_ctx, $typename);");
156
157         $self->pidl("switch ($switch) {");
158         $self->indent;
159
160         foreach my $e (@{$type->{ELEMENTS}}) {
161                 $self->pidl("$e->{CASE}:");
162                 if ($e->{CASE} eq "default") { $has_default = 1; }
163                 $self->indent;
164                 if ($e->{NAME}) {
165                         $self->ConvertObjectFromPython({}, $mem_ctx, $e, $name, "ret->$e->{NAME}", "talloc_free(ret); return NULL;");
166                 }
167                 $self->pidl("break;");
168                 $self->deindent;
169                 $self->pidl("");
170         }
171
172         if (!$has_default) {
173                 $self->pidl("default:");
174                 $self->indent;
175                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"invalid union level value\");");
176                 $self->pidl("talloc_free(ret);");
177                 $self->pidl("ret = NULL;");
178                 $self->deindent;
179         }
180
181         $self->deindent;
182         $self->pidl("}");
183         $self->pidl("");
184         $self->pidl("return ret;");
185 }
186
187 sub PythonStruct($$$$$$)
188 {
189         my ($self, $modulename, $prettyname, $name, $cname, $d) = @_;
190
191         my $env = GenerateStructEnv($d, "object");
192
193         $self->pidl("");
194
195         my $getsetters = "NULL";
196
197         if ($#{$d->{ELEMENTS}} > -1) {
198                 foreach my $e (@{$d->{ELEMENTS}}) {
199                         my $varname = "object->$e->{NAME}";
200                         $self->pidl("static PyObject *py_$name\_get_$e->{NAME}(PyObject *obj, void *closure)");
201                         $self->pidl("{");
202                         $self->indent;
203                         $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(obj);");
204                         $self->pidl("PyObject *py_$e->{NAME};");
205                         $self->ConvertObjectToPython("py_talloc_get_mem_ctx(obj)", $env, $e, $varname, "py_$e->{NAME}", "return NULL;");
206                         $self->pidl("return py_$e->{NAME};");
207                         $self->deindent;
208                         $self->pidl("}");
209                         $self->pidl("");
210
211                         $self->pidl("static int py_$name\_set_$e->{NAME}(PyObject *py_obj, PyObject *value, void *closure)");
212                         $self->pidl("{");
213                         $self->indent;
214                         $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
215                         my $mem_ctx = "py_talloc_get_mem_ctx(py_obj)";
216                         my $l = $e->{LEVELS}[0];
217                         my $nl = GetNextLevel($e, $l);
218                         if ($l->{TYPE} eq "POINTER" and 
219                                 not ($nl->{TYPE} eq "ARRAY" and ($nl->{IS_FIXED} or is_charset_array($e, $nl))) and
220                                 not ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE}))) {
221                                 $self->pidl("talloc_unlink(py_talloc_get_mem_ctx(py_obj), $varname);");
222                         }
223                         $self->ConvertObjectFromPython($env, $mem_ctx, $e, "value", $varname, "return -1;");
224                         $self->pidl("return 0;");
225                         $self->deindent;
226                         $self->pidl("}");
227                         $self->pidl("");
228                 }
229
230                 $getsetters = "py_$name\_getsetters";
231                 $self->pidl("static PyGetSetDef ".$getsetters."[] = {");
232                 $self->indent;
233                 foreach my $e (@{$d->{ELEMENTS}}) {
234                         $self->pidl("{ discard_const_p(char, \"$e->{NAME}\"), py_$name\_get_$e->{NAME}, py_$name\_set_$e->{NAME} },");
235                 }
236                 $self->pidl("{ NULL }");
237                 $self->deindent;
238                 $self->pidl("};");
239                 $self->pidl("");
240         }
241
242         $self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
243         $self->pidl("{");
244         $self->indent;
245         $self->pidl("return py_talloc_new($cname, type);");
246         $self->deindent;
247         $self->pidl("}");
248         $self->pidl("");
249
250         my $py_methods = "NULL";
251
252         # If the struct is not public there ndr_pull/ndr_push functions will 
253         # be static so not callable from here
254         if (has_property($d, "public")) {
255                 $self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj)");
256                 $self->pidl("{");
257                 $self->indent;
258                 $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
259                 $self->pidl("DATA_BLOB blob;");
260                 $self->pidl("enum ndr_err_code err;");
261                 $self->pidl("err = ndr_push_struct_blob(&blob, py_talloc_get_mem_ctx(py_obj), object, (ndr_push_flags_fn_t)ndr_push_$name);");
262                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
263                 $self->indent;
264                 $self->pidl("PyErr_SetNdrError(err);");
265                 $self->pidl("return NULL;");
266                 $self->deindent;
267                 $self->pidl("}");
268                 $self->pidl("");
269                 $self->pidl("return PyString_FromStringAndSize((char *)blob.data, blob.length);");
270                 $self->deindent;
271                 $self->pidl("}");
272                 $self->pidl("");
273
274                 $self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, PyObject *args)");
275                 $self->pidl("{");
276                 $self->indent;
277                 $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
278                 $self->pidl("DATA_BLOB blob;");
279                 $self->pidl("enum ndr_err_code err;");
280                 $self->pidl("if (!PyArg_ParseTuple(args, \"s#:__ndr_unpack__\", &blob.data, &blob.length))");
281                 $self->pidl("\treturn NULL;");
282                 $self->pidl("");
283                 $self->pidl("err = ndr_pull_struct_blob_all(&blob, py_talloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
284                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
285                 $self->indent;
286                 $self->pidl("PyErr_SetNdrError(err);");
287                 $self->pidl("return NULL;");
288                 $self->deindent;
289                 $self->pidl("}");
290                 $self->pidl("");
291                 $self->pidl("Py_RETURN_NONE;");
292                 $self->deindent;
293                 $self->pidl("}");
294                 $self->pidl("");
295
296                 $self->pidl("static PyObject *py_$name\_ndr_print(PyObject *py_obj)");
297                 $self->pidl("{");
298                 $self->indent;
299                 $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
300                 $self->pidl("char *retstr;");
301                 $self->pidl("retstr = ndr_print_struct_string(py_talloc_get_mem_ctx(py_obj), (ndr_print_fn_t)ndr_print_$name, \"$name\", object);");
302                 $self->pidl("return PyString_FromString(retstr);");
303                 $self->deindent;
304                 $self->pidl("}");
305                 $self->pidl("");
306
307                 $py_methods = "py_$name\_methods";
308                 $self->pidl("static PyMethodDef $py_methods\[] = {");
309                 $self->indent;
310                 $self->pidl("{ \"__ndr_pack__\", (PyCFunction)py_$name\_ndr_pack, METH_NOARGS, \"S.ndr_pack(object) -> blob\\nNDR pack\" },");
311                 $self->pidl("{ \"__ndr_unpack__\", (PyCFunction)py_$name\_ndr_unpack, METH_VARARGS, \"S.ndr_unpack(class, blob) -> None\\nNDR unpack\" },");
312                 $self->pidl("{ \"__ndr_print__\", (PyCFunction)py_$name\_ndr_print, METH_VARARGS, \"S.ndr_print(object) -> None\\nNDR print\" },");
313                 $self->pidl("{ NULL, NULL, 0, NULL }");
314                 $self->deindent;
315                 $self->pidl("};");
316                 $self->pidl("");
317         }
318
319         $self->pidl_hdr("staticforward PyTypeObject $name\_Type;\n");
320         $self->pidl("");
321         my $docstring = $self->DocString($d, $name);
322         my $typeobject = "$name\_Type";
323         $self->pidl("static PyTypeObject $typeobject = {");
324         $self->indent;
325         $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
326         $self->pidl(".tp_name = \"$modulename.$prettyname\",");
327         $self->pidl(".tp_getset = $getsetters,");
328         if ($docstring) {
329                 $self->pidl(".tp_doc = $docstring,");
330         }
331         $self->pidl(".tp_methods = $py_methods,");
332         $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
333         $self->pidl(".tp_basicsize = sizeof(py_talloc_Object),");
334         $self->pidl(".tp_new = py_$name\_new,");
335         $self->deindent;
336         $self->pidl("};");
337
338         $self->pidl("");
339
340         my $talloc_typename = $self->import_type_variable("talloc", "Object");
341         $self->register_module_prereadycode(["$name\_Type.tp_base = $talloc_typename;", ""]);
342
343         return "&$typeobject";
344 }
345
346 sub get_metadata_var($)
347 {
348         my ($e) = @_;
349         sub get_var($) { my $x = shift; $x =~ s/\*//g; return $x; }
350
351          if (has_property($e, "length_is")) {
352                 return get_var($e->{PROPERTIES}->{length_is});
353          } elsif (has_property($e, "size_is")) {
354                 return get_var($e->{PROPERTIES}->{size_is});
355          }
356
357          return undef;
358 }
359
360 sub find_metadata_args($)
361 {
362         my ($fn) = @_;
363         my $metadata_args = { in => {}, out => {} };
364
365         # Determine arguments that are metadata for other arguments (size_is/length_is)
366         foreach my $e (@{$fn->{ELEMENTS}}) {
367                 foreach my $dir (@{$e->{DIRECTION}}) {
368                          my $main = get_metadata_var($e);
369                          if ($main) { 
370                                  $metadata_args->{$dir}->{$main} = $e->{NAME}; 
371                          }
372                  }
373         }
374
375         return $metadata_args;
376 }
377
378 sub PythonFunctionUnpackOut($$$)
379 {
380         my ($self, $fn, $fnname) = @_;
381
382         my $outfnname = "unpack_$fnname\_args_out";
383         my $signature = "";
384
385         my $metadata_args = find_metadata_args($fn);
386
387         my $env = GenerateFunctionOutEnv($fn, "r->");
388         my $result_size = 0;
389
390         $self->pidl("static PyObject *$outfnname(struct $fn->{NAME} *r)");
391         $self->pidl("{");
392         $self->indent;
393         $self->pidl("PyObject *result;");
394         foreach my $e (@{$fn->{ELEMENTS}}) {
395                 next unless (grep(/out/,@{$e->{DIRECTION}}));
396                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or 
397                          ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
398                 $self->pidl("PyObject *py_$e->{NAME};");
399                 $result_size++;
400         }
401
402         if ($fn->{RETURN_TYPE}) {
403                 $result_size++ unless ($fn->{RETURN_TYPE} eq "WERROR" or $fn->{RETURN_TYPE} eq "NTSTATUS");
404         }
405
406         my $i = 0;
407
408         if ($result_size > 1) {
409                 $self->pidl("result = PyTuple_New($result_size);");
410                 $signature .= "(";
411         } elsif ($result_size == 0) {
412                 $self->pidl("result = Py_None;");
413                 $self->pidl("Py_INCREF(result);");
414                 $signature .= "None";
415         }
416
417         foreach my $e (@{$fn->{ELEMENTS}}) {
418                 next if ($metadata_args->{out}->{$e->{NAME}});
419                 my $py_name = "py_$e->{NAME}";
420                 if (grep(/out/,@{$e->{DIRECTION}})) {
421                         $self->ConvertObjectToPython("r", $env, $e, "r->out.$e->{NAME}", $py_name, "return NULL;");
422                         if ($result_size > 1) {
423                                 $self->pidl("PyTuple_SetItem(result, $i, $py_name);");
424                                 $i++;
425                                 $signature .= "$e->{NAME}, ";
426                         } else {
427                                 $self->pidl("result = $py_name;");
428                                 $signature .= $e->{NAME};
429                         }
430                 }
431         }
432
433         if (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "NTSTATUS") {
434                 $self->handle_ntstatus("r->out.result", "NULL", undef);
435         } elsif (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "WERROR") {
436                 $self->handle_werror("r->out.result", "NULL", undef);
437         } elsif (defined($fn->{RETURN_TYPE})) {
438                 my $conv = $self->ConvertObjectToPythonData("r", $fn->{RETURN_TYPE}, "r->out.result", $fn);
439                 if ($result_size > 1) {
440                         $self->pidl("PyTuple_SetItem(result, $i, $conv);");
441                 } else {
442                         $self->pidl("result = $conv;");
443                 }
444                 $signature .= "result";
445         }
446
447         if (substr($signature, -2) eq ", ") {
448                 $signature = substr($signature, 0, -2);
449         }
450         if ($result_size > 1) {
451                 $signature .= ")";
452         }
453
454         $self->pidl("return result;");
455         $self->deindent;
456         $self->pidl("}");
457         $self->pidl("");
458
459         return ($outfnname, $signature);
460 }
461
462 sub PythonFunctionPackIn($$$)
463 {
464         my ($self, $fn, $fnname) = @_;
465         my $metadata_args = find_metadata_args($fn);
466
467         my $infnname = "pack_$fnname\_args_in";
468
469         $self->pidl("static bool $infnname(PyObject *args, PyObject *kwargs, struct $fn->{NAME} *r)");
470         $self->pidl("{");
471         $self->indent;
472         my $args_format = "";
473         my $args_string = "";
474         my $args_names = "";
475         my $signature = "";
476
477         foreach my $e (@{$fn->{ELEMENTS}}) {
478                 next unless (grep(/in/,@{$e->{DIRECTION}}));
479                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or 
480                                  ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
481                 $self->pidl("PyObject *py_$e->{NAME};");
482                 $args_format .= "O";
483                 $args_string .= ", &py_$e->{NAME}";
484                 $args_names .= "\"$e->{NAME}\", ";
485                 $signature .= "$e->{NAME}, ";
486         }
487         if (substr($signature, -2) eq ", ") {
488                 $signature = substr($signature, 0, -2);
489         }
490         $self->pidl("const char *kwnames[] = {");
491         $self->indent;
492         $self->pidl($args_names . "NULL");
493         $self->deindent;
494         $self->pidl("};");
495
496         $self->pidl("");
497         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"$args_format:$fn->{NAME}\", discard_const_p(char *, kwnames)$args_string)) {");
498         $self->indent;
499         $self->pidl("return false;");
500         $self->deindent;
501         $self->pidl("}");
502         $self->pidl("");
503
504         my $env = GenerateFunctionInEnv($fn, "r->");
505
506         my $fail = "return false;";
507         foreach my $e (@{$fn->{ELEMENTS}}) {
508                 next unless (grep(/in/,@{$e->{DIRECTION}}));
509                 if ($metadata_args->{in}->{$e->{NAME}}) {
510                         my $py_var = "py_".$metadata_args->{in}->{$e->{NAME}};
511                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
512                         my $val = "PyList_GET_SIZE($py_var)";
513                         if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
514                                 $self->pidl("r->in.$e->{NAME} = talloc_ptrtype(r, r->in.$e->{NAME});");
515                                 $self->pidl("*r->in.$e->{NAME} = $val;");
516                         } else {
517                                 $self->pidl("r->in.$e->{NAME} = $val;");
518                         }
519                 } else {
520                         $self->ConvertObjectFromPython($env, "r", $e, "py_$e->{NAME}", "r->in.$e->{NAME}", $fail);
521                 }
522         }
523         $self->pidl("return true;");
524         $self->deindent;
525         $self->pidl("}");
526         $self->pidl("");
527         return ($infnname, $signature);
528 }
529
530 sub PythonFunction($$$)
531 {
532         my ($self, $fn, $iface, $prettyname) = @_;
533
534         my $fnname = "py_$fn->{NAME}";
535         my $docstring = $self->DocString($fn, $fn->{NAME});
536
537         my ($infn, $insignature) = $self->PythonFunctionPackIn($fn, $fnname);
538         my ($outfn, $outsignature) = $self->PythonFunctionUnpackOut($fn, $fnname);
539         my $signature = "S.$prettyname($insignature) -> $outsignature";
540         if ($docstring) {
541                 $docstring = "\"$signature\\n\\n\"$docstring";
542         } else {
543                 $docstring = "\"$signature\"";
544         }
545
546         return ($infn, $outfn, $docstring);
547 }
548
549 sub handle_werror($$$$)
550 {
551         my ($self, $var, $retval, $mem_ctx) = @_;
552
553         $self->pidl("if (!W_ERROR_IS_OK($var)) {");
554         $self->indent;
555         $self->pidl("PyErr_SetWERROR($var);");
556         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
557         $self->pidl("return $retval;");
558         $self->deindent;
559         $self->pidl("}");
560         $self->pidl("");
561 }
562
563 sub handle_ntstatus($$$$)
564 {
565         my ($self, $var, $retval, $mem_ctx) = @_;
566
567         $self->pidl("if (NT_STATUS_IS_ERR($var)) {");
568         $self->indent;
569         $self->pidl("PyErr_SetNTSTATUS($var);");
570         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
571         $self->pidl("return $retval;");
572         $self->deindent;
573         $self->pidl("}");
574         $self->pidl("");
575 }
576
577 sub PythonType($$$$)
578 {
579         my ($self, $modulename, $d, $interface, $basename) = @_;
580
581         my $actual_ctype = $d;
582         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
583                 $actual_ctype = $actual_ctype->{DATA};
584         }
585
586         if ($actual_ctype->{TYPE} eq "STRUCT") {
587                 my $typeobject;
588                 my $fn_name = PrettifyTypeName($d->{NAME}, $basename);
589
590                 if ($d->{TYPE} eq "STRUCT") {
591                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d);
592                 } else {
593                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d->{DATA});
594                 }
595
596                 $self->register_module_typeobject($fn_name, $typeobject);
597         }
598
599         if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
600                 $self->EnumAndBitmapConsts($d->{NAME}, $d);
601         }
602
603         if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
604                 $self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
605         }
606
607         if ($actual_ctype->{TYPE} eq "UNION" and defined($actual_ctype->{ELEMENTS})) {
608                 $self->pidl("PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in)");
609                 $self->pidl("{");
610                 $self->indent;
611                 $self->FromUnionToPythonFunction("mem_ctx", $actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
612                 $self->deindent;
613                 $self->pidl("}");
614                 $self->pidl("");
615
616                 $self->pidl(mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
617                 $self->pidl("{");
618                 $self->indent;
619                 $self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
620                 $self->deindent;
621                 $self->pidl("}");
622                 $self->pidl("");
623         }
624 }
625
626 sub DocString($$$)
627 {
628         my ($self, $d, $name) = @_;
629         if (has_property($d, "helpstring")) {
630                 my $docstring = uc("py_doc_$name");
631                 $self->pidl("#define $docstring ".has_property($d, "helpstring"));
632                 return $docstring;
633         }
634
635         return undef;
636 }
637
638 sub Interface($$$)
639 {
640         my($self,$interface,$basename) = @_;
641
642         if (has_property($interface, "pyhelper")) {
643                 $self->pidl("#include \"".unmake_str($interface->{PROPERTIES}->{pyhelper})."\"\n");
644         }
645
646         $self->Const($_) foreach (@{$interface->{CONSTS}});
647
648         foreach my $d (@{$interface->{TYPES}}) {
649                 next if has_property($d, "nopython");
650
651                 $self->PythonType($basename, $d, $interface, $basename);
652         }
653
654         if (defined $interface->{PROPERTIES}->{uuid}) {
655                 $self->pidl_hdr("staticforward PyTypeObject $interface->{NAME}_InterfaceType;\n");
656                 $self->pidl("");
657
658                 my @fns = ();
659
660                 foreach my $d (@{$interface->{FUNCTIONS}}) {
661                         next if has_property($d, "noopnum");
662                         next if has_property($d, "nopython");
663                         next if has_property($d, "todo");
664
665                         my $prettyname = $d->{NAME};
666
667                         $prettyname =~ s/^$interface->{NAME}_//;
668                         $prettyname =~ s/^$basename\_//;
669
670                         my ($infn, $outfn, $fndocstring) = $self->PythonFunction($d, $interface->{NAME}, $prettyname);
671
672                         push (@fns, [$infn, $outfn, "dcerpc_$d->{NAME}_r", $prettyname, $fndocstring, $d->{OPNUM}]);
673                 }
674
675                 $self->pidl("const struct PyNdrRpcMethodDef py_ndr_$interface->{NAME}\_methods[] = {");
676                 $self->indent;
677                 foreach my $d (@fns) {
678                         my ($infn, $outfn, $callfn, $prettyname, $docstring, $opnum) = @$d;
679                         $self->pidl("{ \"$prettyname\", $docstring, (py_dcerpc_call_fn)$callfn, (py_data_pack_fn)$infn, (py_data_unpack_fn)$outfn, $opnum, &ndr_table_$interface->{NAME} },");
680                 }
681                 $self->pidl("{ NULL }");
682                 $self->deindent;
683                 $self->pidl("};");
684                 $self->pidl("");
685
686                 $self->pidl("static PyObject *interface_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
687                 $self->pidl("{");
688                 $self->indent;
689                 $self->pidl("return py_dcerpc_interface_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME});");
690                 $self->deindent;
691                 $self->pidl("}");
692         
693                 $self->pidl("");
694
695                 my $signature = 
696 "\"$interface->{NAME}(binding, lp_ctx=None, credentials=None) -> connection\\n\"
697 \"\\n\"
698 \"binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\\n\"
699 \"lp_ctx should be a path to a smb.conf file or a param.LoadParm object\\n\"
700 \"credentials should be a credentials.Credentials object.\\n\\n\"";
701
702                 my $docstring = $self->DocString($interface, $interface->{NAME});
703
704                 if ($docstring) {
705                         $docstring = "$signature$docstring";
706                 } else {
707                         $docstring = $signature;
708                 }
709
710                 my $if_typename = "$interface->{NAME}_InterfaceType";
711
712                 $self->pidl("static PyTypeObject $if_typename = {");
713                 $self->indent;
714                 $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
715                 $self->pidl(".tp_name = \"$basename.$interface->{NAME}\",");
716                 $self->pidl(".tp_basicsize = sizeof(dcerpc_InterfaceObject),");
717                 $self->pidl(".tp_doc = $docstring,");
718                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
719                 $self->pidl(".tp_new = interface_$interface->{NAME}_new,");
720                 $self->deindent;
721                 $self->pidl("};");
722
723                 $self->pidl("");
724
725                 $self->register_module_typeobject($interface->{NAME}, "&$if_typename");
726                 my $dcerpc_typename = $self->import_type_variable("samba.dcerpc.base", "ClientConnection");
727                 $self->register_module_prereadycode(["$if_typename.tp_base = $dcerpc_typename;", ""]);
728                 $self->register_module_postreadycode(["if (!PyInterface_AddNdrRpcMethods(&$if_typename, py_ndr_$interface->{NAME}\_methods))", "\treturn;", ""]);
729         }
730
731         $self->pidl_hdr("\n");
732 }
733
734 sub register_module_method($$$$$)
735 {
736         my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
737
738         push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
739 }
740
741 sub register_module_typeobject($$$)
742 {
743         my ($self, $name, $py_name) = @_;
744
745         $self->register_module_object($name, "(PyObject *)(void *)$py_name");
746
747         $self->check_ready_type($py_name);
748
749         $self->register_patch_type_call($name, $py_name);
750 }
751
752 sub check_ready_type($$)
753 {
754         my ($self, $py_name) = @_;
755         push (@{$self->{ready_types}}, $py_name) unless (grep(/^$py_name$/,@{$self->{ready_types}}));
756 }
757
758 sub register_module_import($$)
759 {
760         my ($self, $module_path) = @_;
761
762         my $var_name = $module_path;
763         $var_name =~ s/\./_/g;
764         $var_name = "dep_$var_name";
765
766         $self->{module_imports}->{$var_name} = $module_path;
767
768         return $var_name;
769 }
770
771 sub import_type_variable($$$)
772 {
773         my ($self, $module, $name) = @_;
774
775         $self->register_module_import($module);
776         unless (defined($self->{type_imports}->{$name})) {
777                 $self->{type_imports}->{$name} = $module;
778         }
779         return "$name\_Type";
780 }
781
782 sub use_type_variable($$)
783 {
784         my ($self, $orig_ctype) = @_;
785         # FIXME: Have a global lookup table for types that look different on the 
786         # wire than they are named in C?
787         if ($orig_ctype->{NAME} eq "dom_sid2" or $orig_ctype->{NAME} eq "dom_sid28") {
788                 $orig_ctype->{NAME} = "dom_sid";
789         }
790         my $ctype = resolveType($orig_ctype);
791         unless (defined($ctype->{BASEFILE})) {
792                 return undef;
793         }
794         # If this is an external type, make sure we do the right imports.
795         if (($ctype->{BASEFILE} ne $self->{BASENAME})) {
796                 return $self->import_type_variable("samba.dcerpc.$ctype->{BASEFILE}", $ctype->{NAME});
797         }
798         return "&$ctype->{NAME}_Type";
799 }
800
801 sub register_patch_type_call($$$)
802 {
803         my ($self, $typename, $cvar) = @_;
804
805         push(@{$self->{patch_type_calls}}, [$typename, $cvar]);
806
807 }
808
809 sub register_module_prereadycode($$)
810 {
811         my ($self, $code) = @_;
812
813         push (@{$self->{prereadycode}}, @$code);
814 }
815
816 sub register_module_postreadycode($$)
817 {
818         my ($self, $code) = @_;
819
820         push (@{$self->{postreadycode}}, @$code);
821 }
822
823 sub register_module_object($$$)
824 {
825         my ($self, $name, $py_name) = @_;
826
827         push (@{$self->{module_objects}}, [$name, $py_name])
828 }
829
830 sub assign($$$)
831 {
832         my ($self, $dest, $src) = @_;
833         if ($dest =~ /^\&/ and $src eq "NULL") {
834                 $self->pidl("memset($dest, 0, sizeof(" . get_value_of($dest) . "));");
835         } elsif ($dest =~ /^\&/) {
836                 my $destvar = get_value_of($dest);
837                 $self->pidl("$destvar = *$src;");
838         } else {
839                 $self->pidl("$dest = $src;");
840         }
841 }
842
843 sub ConvertObjectFromPythonData($$$$$$;$)
844 {
845         my ($self, $mem_ctx, $cvar, $ctype, $target, $fail, $location) = @_;
846
847         fatal($location, "undef type for $cvar") unless(defined($ctype));
848
849         $ctype = resolveType($ctype);
850
851         my $actual_ctype = $ctype;
852         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
853                 $actual_ctype = $actual_ctype->{DATA};
854         }
855
856         if ($actual_ctype->{TYPE} eq "ENUM" or $actual_ctype->{TYPE} eq "BITMAP") {
857                 $self->pidl("if (PyLong_Check($cvar)) {");
858                 $self->indent;
859                 $self->pidl("$target = PyLong_AsLongLong($cvar);");
860                 $self->deindent;
861                 $self->pidl("} else if (PyInt_Check($cvar)) {");
862                 $self->indent;
863                 $self->pidl("$target = PyInt_AsLong($cvar);");
864                 $self->deindent;
865                 $self->pidl("} else {");
866                 $self->indent;
867                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
868                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
869                 $self->pidl($fail);
870                 $self->deindent;
871                 $self->pidl("}");
872                 return;
873         }
874         if ($actual_ctype->{TYPE} eq "SCALAR" ) {
875                 if (expandAlias($actual_ctype->{NAME}) =~ /^(u?int64|hyper|dlong|udlong|udlongr|NTTIME_hyper|NTTIME|NTTIME_1sec)$/) {
876                         $self->pidl("if (PyLong_Check($cvar)) {");
877                         $self->indent;
878                         $self->pidl("$target = PyLong_AsLongLong($cvar);");
879                         $self->deindent;
880                         $self->pidl("} else if (PyInt_Check($cvar)) {");
881                         $self->indent;
882                         $self->pidl("$target = PyInt_AsLong($cvar);");
883                         $self->deindent;
884                         $self->pidl("} else {");
885                         $self->indent;
886                         $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
887                         $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
888                         $self->pidl($fail);
889                         $self->deindent;
890                         $self->pidl("}");
891                         return;
892                 }
893                 if (expandAlias($actual_ctype->{NAME}) =~ /^(char|u?int[0-9]*|time_t)$/) {
894                         $self->pidl("PY_CHECK_TYPE(&PyInt_Type, $cvar, $fail);");
895                         $self->pidl("$target = PyInt_AsLong($cvar);");
896                         return;
897                 }
898         }
899
900         if ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
901                 my $ctype_name = $self->use_type_variable($ctype);
902                 unless (defined ($ctype_name)) {
903                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
904                         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Can not convert C Type " . mapTypeName($ctype) . " from Python\");");
905                         return;
906                 }
907                 $self->pidl("PY_CHECK_TYPE($ctype_name, $cvar, $fail);");
908                 $self->pidl("if (talloc_reference($mem_ctx, py_talloc_get_mem_ctx($cvar)) == NULL) {");
909                 $self->indent;
910                 $self->pidl("PyErr_NoMemory();");
911                 $self->pidl("$fail");
912                 $self->deindent;
913                 $self->pidl("}");
914                 $self->assign($target, "(".mapTypeName($ctype)." *)py_talloc_get_ptr($cvar)");
915                 return;
916         }
917
918         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
919                 $self->pidl("$target = data_blob_talloc($mem_ctx, PyString_AS_STRING($cvar), PyString_GET_SIZE($cvar));");
920                 return;
921         }
922
923         if ($actual_ctype->{TYPE} eq "SCALAR" and 
924                 ($actual_ctype->{NAME} eq "string" or $actual_ctype->{NAME} eq "nbt_string" or $actual_ctype->{NAME} eq "nbt_name" or $actual_ctype->{NAME} eq "wrepl_nbt_name")) {
925                 $self->pidl("$target = talloc_strdup($mem_ctx, PyString_AS_STRING($cvar));");
926                 return;
927         }
928
929         if ($actual_ctype->{TYPE} eq "SCALAR" and ($actual_ctype->{NAME} eq "dns_string" or $actual_ctype->{NAME} eq "dns_name")) {
930                 $self->pidl("$target = talloc_strdup($mem_ctx, PyString_AS_STRING($cvar));");
931                 return;
932         }
933
934         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "ipv4address") {
935                 $self->pidl("$target = PyString_AS_STRING($cvar);");
936                 return;
937         }
938
939         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "ipv6address") {
940                 $self->pidl("$target = PyString_AsString($cvar);");
941                 return;
942         }
943
944         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "dnsp_name") {
945                 $self->pidl("$target = PyString_AS_STRING($cvar);");
946                 return;
947         }
948
949         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "dnsp_string") {
950                 $self->pidl("$target = PyString_AS_STRING($cvar);");
951                 return;
952         }
953
954         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
955                 $self->pidl("$target = NT_STATUS(PyInt_AsLong($cvar));");
956                 return;
957         }
958
959         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
960                 $self->pidl("$target = W_ERROR(PyInt_AsLong($cvar));");
961                 return;
962         }
963
964         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
965                 $self->pidl("$target = PyCObject_AsVoidPtr($cvar);");
966                 return;
967         }
968
969         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
970                 $self->assign($target, "PyCObject_AsVoidPtr($cvar)");
971                 return;
972         }
973
974         fatal($location, "unknown type `$actual_ctype->{TYPE}' for ".mapTypeName($ctype) . ": $cvar");
975
976 }
977
978 sub ConvertObjectFromPythonLevel($$$$$$$$)
979 {
980         my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail) = @_;
981         my $nl = GetNextLevel($e, $l);
982         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
983                 $nl = GetNextLevel($e, $nl);
984         }
985         my $pl = GetPrevLevel($e, $l);
986         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
987                 $pl = GetPrevLevel($e, $pl);
988         }
989
990         if ($l->{TYPE} eq "POINTER") {
991                 if ($l->{POINTER_TYPE} ne "ref") {
992                         $self->pidl("if ($py_var == Py_None) {");
993                         $self->indent;
994                         $self->pidl("$var_name = NULL;");
995                         $self->deindent;
996                         $self->pidl("} else {");
997                         $self->indent;
998                 }
999                 # if we want to handle more than one level of pointer in python interfaces
1000                 # then this is where we would need to allocate it
1001                 if ($l->{POINTER_TYPE} eq "ref") {
1002                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1003                 } elsif ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::is_scalar($nl->{DATA_TYPE})
1004                          and not Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1005                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1006                 } else {
1007                         $self->pidl("$var_name = NULL;");
1008                 }
1009                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1010                         $var_name = get_value_of($var_name);
1011                 }
1012                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail);
1013                 if ($l->{POINTER_TYPE} ne "ref") {
1014                         $self->deindent;
1015                         $self->pidl("}");
1016                 }
1017         } elsif ($l->{TYPE} eq "ARRAY") {
1018                 if ($pl && $pl->{TYPE} eq "POINTER") {
1019                         $var_name = get_pointer_to($var_name);
1020                 }
1021
1022                 if (is_charset_array($e, $l)) {
1023                         $self->pidl("if (PyUnicode_Check($py_var)) {");
1024                         $self->indent;
1025                         # FIXME: Use Unix charset setting rather than utf-8
1026                         $self->pidl($var_name . " = PyString_AS_STRING(PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\"));");
1027                         $self->deindent;
1028                         $self->pidl("} else if (PyString_Check($py_var)) {");
1029                         $self->indent;
1030                         $self->pidl($var_name . " = PyString_AS_STRING($py_var);");
1031                         $self->deindent;
1032                         $self->pidl("} else {");
1033                         $self->indent;
1034                         $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected string or unicode object, got %s\", Py_TYPE($py_var)->tp_name);");
1035                         $self->pidl("$fail;");
1036                         $self->deindent;
1037                         $self->pidl("}");
1038                 } else {
1039                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
1040                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
1041                         $self->pidl("{");
1042                         $self->indent;
1043                         $self->pidl("int $counter;");
1044                         if (ArrayDynamicallyAllocated($e, $l)) {
1045                                 $self->pidl("$var_name = talloc_array_ptrtype($mem_ctx, $var_name, PyList_GET_SIZE($py_var));");
1046                                 $self->pidl("if (!$var_name) { $fail; }");
1047                                 $self->pidl("talloc_set_name_const($var_name, \"ARRAY: $var_name\");");
1048                         }
1049                         $self->pidl("for ($counter = 0; $counter < PyList_GET_SIZE($py_var); $counter++) {");
1050                         $self->indent;
1051                         $self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GET_ITEM($py_var, $counter)", $e, $nl, $var_name."[$counter]", $fail);
1052                         $self->deindent;
1053                         $self->pidl("}");
1054                         $self->deindent;
1055                         $self->pidl("}");
1056                 }
1057         } elsif ($l->{TYPE} eq "DATA") {
1058                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
1059                         $var_name = get_pointer_to($var_name);
1060                 }
1061                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail, $e->{ORIGINAL});
1062         } elsif ($l->{TYPE} eq "SWITCH") {
1063                 $var_name = get_pointer_to($var_name);
1064                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
1065                 my $switch_ptr = "$e->{NAME}_switch_$l->{LEVEL_INDEX}";
1066                 $self->pidl("{");
1067                 $self->indent;
1068                 my $union_type = mapTypeName($nl->{DATA_TYPE});
1069                 $self->pidl("$union_type *$switch_ptr;");
1070                 $self->pidl("$switch_ptr = py_export_" . $nl->{DATA_TYPE} . "($mem_ctx, $switch, $py_var);");
1071                 $self->fail_on_null($switch_ptr, $fail);
1072                 $self->assign($var_name, "$switch_ptr");
1073                 $self->deindent;
1074                 $self->pidl("}");
1075         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
1076                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail);
1077         } else {
1078                 fatal($e->{ORIGINAL}, "unknown level type $l->{TYPE}");
1079         }
1080 }
1081
1082 sub ConvertObjectFromPython($$$$$$$)
1083 {
1084         my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
1085
1086         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail);
1087 }
1088
1089 sub ConvertScalarToPython($$$)
1090 {
1091         my ($self, $ctypename, $cvar) = @_;
1092
1093         die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
1094
1095         $ctypename = expandAlias($ctypename);
1096
1097         if ($ctypename =~ /^(u?int64|hyper|dlong|udlong|udlongr|NTTIME_hyper|NTTIME|NTTIME_1sec)$/) {
1098                 return "PyLong_FromLongLong($cvar)";
1099         }
1100
1101         if ($ctypename =~ /^(char|u?int[0-9]*|time_t)$/) {
1102                 return "PyInt_FromLong($cvar)";
1103         }
1104
1105         if ($ctypename eq "DATA_BLOB") {
1106                 return "PyString_FromStringAndSize((char *)($cvar).data, ($cvar).length)";
1107         }
1108
1109         if ($ctypename eq "NTSTATUS") {
1110                 return "PyErr_FromNTSTATUS($cvar)";
1111         }
1112
1113         if ($ctypename eq "WERROR") {
1114                 return "PyErr_FromWERROR($cvar)";
1115         }
1116
1117         if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
1118                 return "PyString_FromStringOrNULL($cvar)";
1119         }
1120
1121         if (($ctypename eq "dns_string" or $ctypename eq "dns_name")) {
1122                 return "PyString_FromStringOrNULL($cvar)";
1123         }
1124
1125         # Not yet supported
1126         if ($ctypename eq "string_array") { return "PyCObject_FromTallocPtr($cvar)"; }
1127         if ($ctypename eq "ipv4address") { return "PyString_FromStringOrNULL($cvar)"; }
1128         if ($ctypename eq "ipv6address") { return "PyString_FromStringOrNULL($cvar)"; }
1129         if ($ctypename eq "dnsp_name") { return "PyString_FromStringOrNULL($cvar)"; }
1130         if ($ctypename eq "dnsp_string") { return "PyString_FromStringOrNULL($cvar)"; }
1131         if ($ctypename eq "pointer") {
1132                 return "PyCObject_FromTallocPtr($cvar)";
1133         }
1134
1135         die("Unknown scalar type $ctypename");
1136 }
1137
1138 sub ConvertObjectToPythonData($$$$$;$)
1139 {
1140         my ($self, $mem_ctx, $ctype, $cvar, $location) = @_;
1141
1142         die("undef type for $cvar") unless(defined($ctype));
1143
1144         $ctype = resolveType($ctype);
1145
1146         my $actual_ctype = $ctype;
1147         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
1148                 $actual_ctype = $actual_ctype->{DATA};
1149         } 
1150         
1151         if ($actual_ctype->{TYPE} eq "ENUM") {
1152                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar);
1153         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
1154                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar);
1155         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
1156                 return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar);
1157         } elsif ($actual_ctype->{TYPE} eq "UNION") {
1158                 fatal($ctype, "union without discriminant: " . mapTypeName($ctype) . ": $cvar");
1159         } elsif ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
1160                 my $ctype_name = $self->use_type_variable($ctype);
1161                 unless (defined($ctype_name)) {
1162                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
1163                         return "NULL"; # FIXME!
1164                 }
1165                 return "py_talloc_reference_ex($ctype_name, $mem_ctx, $cvar)";
1166         }
1167
1168         fatal($location, "unknown type $actual_ctype->{TYPE} for ".mapTypeName($ctype) . ": $cvar");
1169 }
1170
1171 sub fail_on_null($$$)
1172 {
1173         my ($self, $var, $fail) = @_;
1174         $self->pidl("if ($var == NULL) {");
1175         $self->indent;
1176         $self->pidl($fail);
1177         $self->deindent;
1178         $self->pidl("}");
1179 }
1180
1181 sub ConvertObjectToPythonLevel($$$$$$)
1182 {
1183         my ($self, $mem_ctx, $env, $e, $l, $var_name, $py_var, $fail) = @_;
1184         my $nl = GetNextLevel($e, $l);
1185         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
1186                 $nl = GetNextLevel($e, $nl);
1187         }
1188         my $pl = GetPrevLevel($e, $l);
1189         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
1190                 $pl = GetPrevLevel($e, $pl);
1191         }
1192
1193         if ($l->{TYPE} eq "POINTER") {
1194                 if ($l->{POINTER_TYPE} ne "ref") {
1195                         $self->pidl("if ($var_name == NULL) {");
1196                         $self->indent;
1197                         $self->pidl("$py_var = Py_None;");
1198                         $self->pidl("Py_INCREF($py_var);");
1199                         $self->deindent;
1200                         $self->pidl("} else {");
1201                         $self->indent;
1202                 }
1203                 my $var_name2 = $var_name;
1204                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1205                         $var_name2 = get_value_of($var_name);
1206                 }
1207                 $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name2, $py_var, $fail);
1208                 if ($l->{POINTER_TYPE} ne "ref") {
1209                         $self->deindent;
1210                         $self->pidl("}");
1211                 }
1212         } elsif ($l->{TYPE} eq "ARRAY") {
1213                 if ($pl && $pl->{TYPE} eq "POINTER") {
1214                         $var_name = get_pointer_to($var_name);
1215                 }
1216
1217                 if (is_charset_array($e, $l)) {
1218                         # FIXME: Use Unix charset setting rather than utf-8
1219                         $self->pidl("if ($var_name == NULL) {");
1220                         $self->indent;
1221                         $self->pidl("$py_var = Py_None;");
1222                         $self->pidl("Py_INCREF($py_var);");
1223                         $self->deindent;
1224                         $self->pidl("} else {");
1225                         $self->indent;
1226                         $self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
1227                         $self->deindent;
1228                         $self->pidl("}");
1229                 } else {
1230                         die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
1231                         my $length = $l->{SIZE_IS};
1232                         if (defined($l->{LENGTH_IS})) {
1233                                 $length = $l->{LENGTH_IS};
1234                         }
1235
1236                         $length = ParseExpr($length, $env, $e);
1237                         $self->pidl("$py_var = PyList_New($length);");
1238                         $self->fail_on_null($py_var, $fail);
1239                         $self->pidl("{");
1240                         $self->indent;
1241                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
1242                         $self->pidl("int $counter;");
1243                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
1244                         $self->indent;
1245                         my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
1246                         $self->pidl("PyObject *$member_var;");
1247                         $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name."[$counter]", $member_var, $fail);
1248                         $self->pidl("PyList_SetItem($py_var, $counter, $member_var);");
1249                         $self->deindent;
1250                         $self->pidl("}");
1251                         $self->deindent;
1252                         $self->pidl("}");
1253                 }
1254         } elsif ($l->{TYPE} eq "SWITCH") {
1255                 $var_name = get_pointer_to($var_name);
1256                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
1257                 $self->pidl("$py_var = py_import_" . $nl->{DATA_TYPE} . "($mem_ctx, $switch, $var_name);");
1258                 $self->fail_on_null($py_var, $fail);
1259
1260         } elsif ($l->{TYPE} eq "DATA") {
1261                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
1262                         $var_name = get_pointer_to($var_name);
1263                 }
1264                 my $conv = $self->ConvertObjectToPythonData($mem_ctx, $l->{DATA_TYPE}, $var_name, $e->{ORIGINAL});
1265                 $self->pidl("$py_var = $conv;");
1266         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
1267                 $self->ConvertObjectToPythonLevel($mem_ctx, $env, $e, $nl, $var_name, $py_var, $fail);
1268         } else {
1269                 fatal($e->{ORIGINAL}, "Unknown level type $l->{TYPE} $var_name");
1270         }
1271 }
1272
1273 sub ConvertObjectToPython($$$$$$)
1274 {
1275         my ($self, $mem_ctx, $env, $ctype, $cvar, $py_var, $fail) = @_;
1276
1277         $self->ConvertObjectToPythonLevel($mem_ctx, $env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var, $fail);
1278 }
1279
1280 sub Parse($$$$$)
1281 {
1282     my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
1283
1284         $self->{BASENAME} = $basename;
1285
1286     $self->pidl_hdr("
1287 /* Python wrapper functions auto-generated by pidl */
1288 #include <Python.h>
1289 #include \"includes.h\"
1290 #include <pytalloc.h>
1291 #include \"librpc/rpc/pyrpc.h\"
1292 #include \"librpc/rpc/pyrpc_util.h\"
1293 #include \"$hdr\"
1294 #include \"$ndr_hdr\"
1295
1296 ");
1297
1298         foreach my $x (@$ndr) {
1299                 ($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
1300             ($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
1301         }
1302         
1303         $self->pidl("static PyMethodDef $basename\_methods[] = {");
1304         $self->indent;
1305         foreach (@{$self->{module_methods}}) {
1306                 my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
1307                 $self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
1308         }
1309
1310         $self->pidl("{ NULL, NULL, 0, NULL }");
1311         $self->deindent;
1312         $self->pidl("};");
1313
1314         $self->pidl("");
1315
1316         $self->pidl_hdr("void init$basename(void);");
1317         $self->pidl("void init$basename(void)");
1318         $self->pidl("{");
1319         $self->indent;
1320         $self->pidl("PyObject *m;");
1321         foreach (keys %{$self->{module_imports}}) {
1322                 $self->pidl("PyObject *$_;");
1323         }
1324         $self->pidl("");
1325
1326         foreach (keys %{$self->{module_imports}}) {
1327                 my $var_name = $_;
1328                 my $module_path = $self->{module_imports}->{$var_name};
1329                 $self->pidl("$var_name = PyImport_ImportModule(\"$module_path\");");
1330                 $self->pidl("if ($var_name == NULL)");
1331                 $self->pidl("\treturn;");
1332                 $self->pidl("");
1333         }
1334
1335         foreach (keys %{$self->{type_imports}}) {
1336                 my $type_var = "$_\_Type";
1337                 my $module_path = $self->{type_imports}->{$_};
1338                 $self->pidl_hdr("static PyTypeObject *$type_var;\n");
1339                 my $pretty_name = PrettifyTypeName($_, $module_path);
1340                 my $module_var = "dep_$module_path";
1341                 $module_var =~ s/\./_/g;
1342                 $self->pidl("$type_var = (PyTypeObject *)PyObject_GetAttrString($module_var, \"$pretty_name\");");
1343                 $self->pidl("if ($type_var == NULL)");
1344                 $self->pidl("\treturn;");
1345                 $self->pidl("");
1346         }
1347
1348         $self->pidl($_) foreach (@{$self->{prereadycode}});
1349
1350         foreach (@{$self->{ready_types}}) {
1351                 $self->pidl("if (PyType_Ready($_) < 0)");
1352                 $self->pidl("\treturn;");
1353         }
1354
1355         $self->pidl($_) foreach (@{$self->{postreadycode}});
1356
1357         foreach (@{$self->{patch_type_calls}}) {
1358                 my ($typename, $cvar) = @$_;
1359                 $self->pidl("#ifdef PY_".uc($typename)."_PATCH");
1360                 $self->pidl("PY_".uc($typename)."_PATCH($cvar);");
1361                 $self->pidl("#endif");
1362         }
1363
1364         $self->pidl("");
1365
1366         $self->pidl("m = Py_InitModule3(\"$basename\", $basename\_methods, \"$basename DCE/RPC\");");
1367         $self->pidl("if (m == NULL)");
1368         $self->pidl("\treturn;");
1369         $self->pidl("");
1370         foreach my $name (keys %{$self->{constants}}) {
1371                 my $py_obj;
1372                 my ($ctype, $cvar) = @{$self->{constants}->{$name}};
1373                 if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
1374                         $py_obj = "PyInt_FromLong($cvar)";
1375                 } elsif ($cvar =~ /^".*"$/) {
1376                         $py_obj = "PyString_FromString($cvar)";
1377                 } else {
1378                         $py_obj = $self->ConvertObjectToPythonData("NULL", expandAlias($ctype), $cvar, undef);
1379                 }
1380
1381                 $self->pidl("PyModule_AddObject(m, \"$name\", $py_obj);");
1382         }
1383
1384         foreach (@{$self->{module_objects}}) {
1385                 my ($object_name, $c_name) = @$_;
1386                 $self->pidl("Py_INCREF($c_name);");
1387                 $self->pidl("PyModule_AddObject(m, \"$object_name\", $c_name);");
1388         }
1389
1390         $self->pidl("#ifdef PY_MOD_".uc($basename)."_PATCH");
1391         $self->pidl("PY_MOD_".uc($basename)."_PATCH(m);");
1392         $self->pidl("#endif");
1393
1394         $self->pidl("");
1395         $self->deindent;
1396         $self->pidl("}");
1397     return ($self->{res_hdr} . $self->{res});
1398 }
1399
1400 1;