Python pidl: avoid segfault with "del obj->attr"
[sfrench/samba-autobuild/.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 bitmap_type_fn enum_type_fn);
14 use Parse::Pidl::Util qw(has_property ParseExpr unmake_str);
15 use Parse::Pidl::NDR qw(GetPrevLevel GetNextLevel ContainsDeferred ContainsPipe 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 => "",
26                                  constants => [], constants_uniq => {},
27                      module_methods => [], module_objects => [], ready_types => [],
28                                  module_imports => [], module_imports_uniq => {},
29                                  type_imports => [], type_imports_uniq => {},
30                                  patch_type_calls => [], prereadycode => [],
31                                  postreadycode => []};
32         bless($self, $class);
33 }
34
35 sub pidl_hdr ($$)
36 {
37         my $self = shift;
38         $self->{res_hdr} .= shift;
39 }
40
41 sub pidl($$)
42 {
43         my ($self, $d) = @_;
44         if ($d) {
45                 if ((!($d =~ /^#/))) {
46                         $self->{res} .= $self->{tabs};
47                 }
48                 $self->{res} .= $d;
49         }
50         $self->{res} .= "\n";
51 }
52
53 sub indent($)
54 {
55         my ($self) = @_;
56         $self->{tabs} .= "\t";
57 }
58
59 sub deindent($)
60 {
61         my ($self) = @_;
62         $self->{tabs} = substr($self->{tabs}, 0, -1);
63 }
64
65 sub PrettifyTypeName($$)
66 {
67         my ($name, $basename) = @_;
68
69         $basename =~ s/^.*\.([^.]+)$/\1/;
70
71         $name =~ s/^$basename\_//;
72
73
74         return $name;
75 }
76
77 sub Import
78 {
79         my $self = shift;
80         my @imports = @_;
81         foreach (@imports) {
82                 $_ = unmake_str($_);
83                 s/\.idl$//;
84                 $self->pidl_hdr("#include \"librpc/gen_ndr/$_\.h\"\n");
85                 $self->register_module_import("samba.dcerpc.$_");
86         }
87 }
88
89 sub Const($$)
90 {
91     my ($self, $const) = @_;
92         $self->register_constant($const->{NAME}, $const->{DTYPE}, $const->{VALUE});
93 }
94
95 sub register_constant($$$$)
96 {
97         my ($self, $name, $type, $value) = @_;
98
99         unless (defined $self->{constants_uniq}->{$name}) {
100                 my $h = {"key" => $name, "val" => [$type, $value]};
101                 push @{$self->{constants}}, $h;
102                 $self->{constants_uniq}->{$name} = $h;
103         }
104 }
105
106 sub EnumAndBitmapConsts($$$)
107 {
108         my ($self, $name, $d) = @_;
109
110         return unless (defined($d->{ELEMENTS}));
111
112         foreach my $e (@{$d->{ELEMENTS}}) {
113                 $e =~ /^([A-Za-z0-9_]+)/;
114                 my $cname = $1;
115
116                 $self->register_constant($cname, $d, $cname);
117         }
118 }
119
120 sub FromUnionToPythonFunction($$$$)
121 {
122         my ($self, $mem_ctx, $type, $switch, $name) = @_;
123
124         $self->pidl("PyObject *ret;");
125         $self->pidl("");
126
127         $self->pidl("switch ($switch) {");
128         $self->indent;
129
130         foreach my $e (@{$type->{ELEMENTS}}) {
131                 $self->pidl("$e->{CASE}:");
132
133                 $self->indent;
134
135                 if ($e->{NAME}) {
136                         $self->ConvertObjectToPython($mem_ctx, {}, $e, "$name->$e->{NAME}", "ret", "return NULL;");
137                 } else {
138                         $self->pidl("ret = Py_None;");
139                         $self->pidl("Py_INCREF(ret);");
140                 }
141
142                 $self->pidl("return ret;");
143                 $self->pidl("");
144
145                 $self->deindent;
146         }
147
148         $self->deindent;
149         $self->pidl("}");
150
151         $self->pidl("PyErr_SetString(PyExc_TypeError, \"unknown union level\");");
152         $self->pidl("return NULL;");
153 }
154
155 sub FromPythonToUnionFunction($$$$$)
156 {
157         my ($self, $type, $typename, $switch, $mem_ctx, $name) = @_;
158
159         my $has_default = 0;
160
161         $self->pidl("$typename *ret = talloc_zero($mem_ctx, $typename);");
162
163         $self->pidl("switch ($switch) {");
164         $self->indent;
165
166         foreach my $e (@{$type->{ELEMENTS}}) {
167                 $self->pidl("$e->{CASE}:");
168                 if ($e->{CASE} eq "default") { $has_default = 1; }
169                 $self->indent;
170                 if ($e->{NAME}) {
171                         $self->ConvertObjectFromPython({}, $mem_ctx, $e, $name, "ret->$e->{NAME}", "talloc_free(ret); return NULL;");
172                 }
173                 $self->pidl("break;");
174                 $self->deindent;
175                 $self->pidl("");
176         }
177
178         if (!$has_default) {
179                 $self->pidl("default:");
180                 $self->indent;
181                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"invalid union level value\");");
182                 $self->pidl("talloc_free(ret);");
183                 $self->pidl("ret = NULL;");
184                 $self->deindent;
185         }
186
187         $self->deindent;
188         $self->pidl("}");
189         $self->pidl("");
190         $self->pidl("return ret;");
191 }
192
193 sub PythonStruct($$$$$$)
194 {
195         my ($self, $modulename, $prettyname, $name, $cname, $d) = @_;
196
197         my $env = GenerateStructEnv($d, "object");
198
199         $self->pidl("");
200
201         my $getsetters = "NULL";
202
203         if ($#{$d->{ELEMENTS}} > -1) {
204                 foreach my $e (@{$d->{ELEMENTS}}) {
205                         my $varname = "object->$e->{NAME}";
206                         $self->pidl("static PyObject *py_$name\_get_$e->{NAME}(PyObject *obj, void *closure)");
207                         $self->pidl("{");
208                         $self->indent;
209                         $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(obj);");
210                         $self->pidl("PyObject *py_$e->{NAME};");
211                         $self->ConvertObjectToPython("pytalloc_get_mem_ctx(obj)", $env, $e, $varname, "py_$e->{NAME}", "return NULL;");
212                         $self->pidl("return py_$e->{NAME};");
213                         $self->deindent;
214                         $self->pidl("}");
215                         $self->pidl("");
216
217                         $self->pidl("static int py_$name\_set_$e->{NAME}(PyObject *py_obj, PyObject *value, void *closure)");
218                         $self->pidl("{");
219                         $self->indent;
220                         $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
221                         my $mem_ctx = "pytalloc_get_mem_ctx(py_obj)";
222                         my $l = $e->{LEVELS}[0];
223                         my $nl = GetNextLevel($e, $l);
224                         if ($l->{TYPE} eq "POINTER" and
225                                 not ($nl->{TYPE} eq "ARRAY" and ($nl->{IS_FIXED} or is_charset_array($e, $nl))) and
226                                 not ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE}))) {
227                                 $self->pidl("talloc_unlink($mem_ctx, discard_const($varname));");
228                         }
229                         $self->ConvertObjectFromPython($env, $mem_ctx, $e, "value", $varname, "return -1;");
230                         $self->pidl("return 0;");
231                         $self->deindent;
232                         $self->pidl("}");
233                         $self->pidl("");
234                 }
235
236                 $getsetters = "py_$name\_getsetters";
237                 $self->pidl("static PyGetSetDef ".$getsetters."[] = {");
238                 $self->indent;
239                 foreach my $e (@{$d->{ELEMENTS}}) {
240                         $self->pidl("{");
241                         $self->indent;
242                         $self->pidl(".name = discard_const_p(char, \"$e->{NAME}\"),");
243                         $self->pidl(".get = py_$name\_get_$e->{NAME},");
244                         $self->pidl(".set = py_$name\_set_$e->{NAME},");
245                         $self->pidl(".doc = discard_const_p(char, \"PIDL-generated element $e->{NAME}\")");
246                         $self->deindent;
247                         $self->pidl("},");
248                 }
249                 $self->pidl("{ .name = NULL }");
250                 $self->deindent;
251                 $self->pidl("};");
252                 $self->pidl("");
253         }
254
255         $self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
256         $self->pidl("{");
257         $self->indent;
258         $self->pidl("return pytalloc_new($cname, type);");
259         $self->deindent;
260         $self->pidl("}");
261         $self->pidl("");
262
263         my $py_methods = "NULL";
264
265         # If the struct is not public there ndr_pull/ndr_push functions will
266         # be static so not callable from here
267         if (has_property($d, "public")) {
268                 $self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj)");
269                 $self->pidl("{");
270                 $self->indent;
271                 $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
272                 $self->pidl("PyObject *ret = NULL;");
273                 $self->pidl("DATA_BLOB blob;");
274                 $self->pidl("enum ndr_err_code err;");
275                 $self->pidl("TALLOC_CTX *tmp_ctx = talloc_new(pytalloc_get_mem_ctx(py_obj));");
276                 $self->pidl("if (tmp_ctx == NULL) {");
277                 $self->indent;
278                 $self->pidl("PyErr_SetNdrError(NDR_ERR_ALLOC);");
279                 $self->pidl("return NULL;");
280                 $self->deindent;
281                 $self->pidl("}");
282                 $self->pidl("err = ndr_push_struct_blob(&blob, tmp_ctx, object, (ndr_push_flags_fn_t)ndr_push_$name);");
283                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
284                 $self->indent;
285                 $self->pidl("TALLOC_FREE(tmp_ctx);");
286                 $self->pidl("PyErr_SetNdrError(err);");
287                 $self->pidl("return NULL;");
288                 $self->deindent;
289                 $self->pidl("}");
290                 $self->pidl("");
291                 $self->pidl("ret = PyString_FromStringAndSize((char *)blob.data, blob.length);");
292                 $self->pidl("TALLOC_FREE(tmp_ctx);");
293                 $self->pidl("return ret;");
294                 $self->deindent;
295                 $self->pidl("}");
296                 $self->pidl("");
297
298                 $self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
299                 $self->pidl("{");
300                 $self->indent;
301                 $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
302                 $self->pidl("DATA_BLOB blob;");
303                 $self->pidl("Py_ssize_t blob_length = 0;");
304                 $self->pidl("enum ndr_err_code err;");
305                 $self->pidl("const char * const kwnames[] = { \"data_blob\", \"allow_remaining\", NULL };");
306                 $self->pidl("PyObject *allow_remaining_obj = NULL;");
307                 $self->pidl("bool allow_remaining = false;");
308                 $self->pidl("");
309                 $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"s#|O:__ndr_unpack__\",");
310                 $self->indent;
311                 $self->pidl("discard_const_p(char *, kwnames),");
312                 $self->pidl("&blob.data, &blob_length,");
313                 $self->pidl("&allow_remaining_obj)) {");
314                 $self->deindent;
315                 $self->indent;
316                 $self->pidl("return NULL;");
317                 $self->deindent;
318                 $self->pidl("}");
319                 $self->pidl("blob.length = blob_length;");
320                 $self->pidl("");
321                 $self->pidl("if (allow_remaining_obj && PyObject_IsTrue(allow_remaining_obj)) {");
322                 $self->indent;
323                 $self->pidl("allow_remaining = true;");
324                 $self->deindent;
325                 $self->pidl("}");
326                 $self->pidl("");
327                 $self->pidl("if (allow_remaining) {");
328                 $self->indent;
329                 $self->pidl("err = ndr_pull_struct_blob(&blob, pytalloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
330                 $self->deindent;
331                 $self->pidl("} else {");
332                 $self->indent;
333                 $self->pidl("err = ndr_pull_struct_blob_all(&blob, pytalloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
334                 $self->deindent;
335                 $self->pidl("}");
336                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
337                 $self->indent;
338                 $self->pidl("PyErr_SetNdrError(err);");
339                 $self->pidl("return NULL;");
340                 $self->deindent;
341                 $self->pidl("}");
342                 $self->pidl("");
343                 $self->pidl("Py_RETURN_NONE;");
344                 $self->deindent;
345                 $self->pidl("}");
346                 $self->pidl("");
347
348                 $self->pidl("static PyObject *py_$name\_ndr_print(PyObject *py_obj)");
349                 $self->pidl("{");
350                 $self->indent;
351                 $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
352                 $self->pidl("PyObject *ret;");
353                 $self->pidl("char *retstr;");
354                 $self->pidl("");
355                 $self->pidl("retstr = ndr_print_struct_string(pytalloc_get_mem_ctx(py_obj), (ndr_print_fn_t)ndr_print_$name, \"$name\", object);");
356                 $self->pidl("ret = PyString_FromString(retstr);");
357                 $self->pidl("talloc_free(retstr);");
358                 $self->pidl("");
359                 $self->pidl("return ret;");
360                 $self->deindent;
361                 $self->pidl("}");
362                 $self->pidl("");
363
364                 $py_methods = "py_$name\_methods";
365                 $self->pidl("static PyMethodDef $py_methods\[] = {");
366                 $self->indent;
367                 $self->pidl("{ \"__ndr_pack__\", (PyCFunction)py_$name\_ndr_pack, METH_NOARGS, \"S.ndr_pack(object) -> blob\\nNDR pack\" },");
368                 $self->pidl("{ \"__ndr_unpack__\", (PyCFunction)py_$name\_ndr_unpack, METH_VARARGS|METH_KEYWORDS, \"S.ndr_unpack(class, blob, allow_remaining=False) -> None\\nNDR unpack\" },");
369                 $self->pidl("{ \"__ndr_print__\", (PyCFunction)py_$name\_ndr_print, METH_VARARGS, \"S.ndr_print(object) -> None\\nNDR print\" },");
370                 $self->pidl("{ NULL, NULL, 0, NULL }");
371                 $self->deindent;
372                 $self->pidl("};");
373                 $self->pidl("");
374         }
375
376         $self->pidl_hdr("static PyTypeObject $name\_Type;\n");
377         $self->pidl("");
378         my $docstring = $self->DocString($d, $name);
379         my $typeobject = "$name\_Type";
380         $self->pidl("static PyTypeObject $typeobject = {");
381         $self->indent;
382         $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
383         $self->pidl(".tp_name = \"$modulename.$prettyname\",");
384         $self->pidl(".tp_getset = $getsetters,");
385         if ($docstring) {
386                 $self->pidl(".tp_doc = $docstring,");
387         }
388         $self->pidl(".tp_methods = $py_methods,");
389         $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
390         $self->pidl(".tp_new = py_$name\_new,");
391         $self->deindent;
392         $self->pidl("};");
393
394         $self->pidl("");
395
396         my $talloc_typename = $self->import_type_variable("talloc", "BaseObject");
397         $self->register_module_prereadycode(["$name\_Type.tp_base = $talloc_typename;",
398                                              "$name\_Type.tp_basicsize = pytalloc_BaseObject_size();",
399                                              ""]);
400
401         return "&$typeobject";
402 }
403
404 sub get_metadata_var($)
405 {
406         my ($e) = @_;
407         sub get_var($) { my $x = shift; $x =~ s/\*//g; return $x; }
408
409          if (has_property($e, "length_is")) {
410                 return get_var($e->{PROPERTIES}->{length_is});
411          } elsif (has_property($e, "size_is")) {
412                 return get_var($e->{PROPERTIES}->{size_is});
413          }
414
415          return undef;
416 }
417
418 sub find_metadata_args($)
419 {
420         my ($fn) = @_;
421         my $metadata_args = { in => {}, out => {} };
422
423         # Determine arguments that are metadata for other arguments (size_is/length_is)
424         foreach my $e (@{$fn->{ELEMENTS}}) {
425                 foreach my $dir (@{$e->{DIRECTION}}) {
426                          my $main = get_metadata_var($e);
427                          if ($main) {
428                                  $metadata_args->{$dir}->{$main} = $e->{NAME};
429                          }
430                  }
431         }
432
433         return $metadata_args;
434 }
435
436 sub PythonFunctionUnpackOut($$$)
437 {
438         my ($self, $fn, $fnname) = @_;
439
440         my $outfnname = "unpack_$fnname\_args_out";
441         my $signature = "";
442
443         my $metadata_args = find_metadata_args($fn);
444
445         my $env = GenerateFunctionOutEnv($fn, "r->");
446         my $result_size = 0;
447
448         $self->pidl("static PyObject *$outfnname(struct $fn->{NAME} *r)");
449         $self->pidl("{");
450         $self->indent;
451         $self->pidl("PyObject *result;");
452         foreach my $e (@{$fn->{ELEMENTS}}) {
453                 next unless (grep(/out/,@{$e->{DIRECTION}}));
454                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or
455                          ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
456                 $self->pidl("PyObject *py_$e->{NAME};");
457                 $result_size++;
458         }
459
460         if ($fn->{RETURN_TYPE}) {
461                 $result_size++ unless ($fn->{RETURN_TYPE} eq "WERROR" or $fn->{RETURN_TYPE} eq "NTSTATUS");
462         }
463
464         my $i = 0;
465
466         if ($result_size > 1) {
467                 $self->pidl("result = PyTuple_New($result_size);");
468                 $signature .= "(";
469         } elsif ($result_size == 0) {
470                 $self->pidl("result = Py_None;");
471                 $self->pidl("Py_INCREF(result);");
472                 $signature .= "None";
473         }
474
475         foreach my $e (@{$fn->{ELEMENTS}}) {
476                 next if ($metadata_args->{out}->{$e->{NAME}});
477                 my $py_name = "py_$e->{NAME}";
478                 if (grep(/out/,@{$e->{DIRECTION}})) {
479                         $self->ConvertObjectToPython("r", $env, $e, "r->out.$e->{NAME}", $py_name, "return NULL;");
480                         if ($result_size > 1) {
481                                 $self->pidl("PyTuple_SetItem(result, $i, $py_name);");
482                                 $i++;
483                                 $signature .= "$e->{NAME}, ";
484                         } else {
485                                 $self->pidl("result = $py_name;");
486                                 $signature .= $e->{NAME};
487                         }
488                 }
489         }
490
491         if (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "NTSTATUS") {
492                 $self->handle_ntstatus("r->out.result", "NULL", undef);
493         } elsif (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "WERROR") {
494                 $self->handle_werror("r->out.result", "NULL", undef);
495         } elsif (defined($fn->{RETURN_TYPE})) {
496                 my $conv = $self->ConvertObjectToPythonData("r", $fn->{RETURN_TYPE}, "r->out.result", $fn);
497                 if ($result_size > 1) {
498                         $self->pidl("PyTuple_SetItem(result, $i, $conv);");
499                 } else {
500                         $self->pidl("result = $conv;");
501                 }
502                 $signature .= "result";
503         }
504
505         if (substr($signature, -2) eq ", ") {
506                 $signature = substr($signature, 0, -2);
507         }
508         if ($result_size > 1) {
509                 $signature .= ")";
510         }
511
512         $self->pidl("return result;");
513         $self->deindent;
514         $self->pidl("}");
515         $self->pidl("");
516
517         return ($outfnname, $signature);
518 }
519
520 sub PythonFunctionPackIn($$$)
521 {
522         my ($self, $fn, $fnname) = @_;
523         my $metadata_args = find_metadata_args($fn);
524
525         my $infnname = "pack_$fnname\_args_in";
526
527         $self->pidl("static bool $infnname(PyObject *args, PyObject *kwargs, struct $fn->{NAME} *r)");
528         $self->pidl("{");
529         $self->indent;
530         my $args_format = "";
531         my $args_string = "";
532         my $args_names = "";
533         my $signature = "";
534
535         foreach my $e (@{$fn->{ELEMENTS}}) {
536                 next unless (grep(/in/,@{$e->{DIRECTION}}));
537                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or
538                                  ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
539                 $self->pidl("PyObject *py_$e->{NAME};");
540                 $args_format .= "O";
541                 $args_string .= ", &py_$e->{NAME}";
542                 $args_names .= "\"$e->{NAME}\", ";
543                 $signature .= "$e->{NAME}, ";
544         }
545         if (substr($signature, -2) eq ", ") {
546                 $signature = substr($signature, 0, -2);
547         }
548         $self->pidl("const char *kwnames[] = {");
549         $self->indent;
550         $self->pidl($args_names . "NULL");
551         $self->deindent;
552         $self->pidl("};");
553
554         $self->pidl("");
555         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"$args_format:$fn->{NAME}\", discard_const_p(char *, kwnames)$args_string)) {");
556         $self->indent;
557         $self->pidl("return false;");
558         $self->deindent;
559         $self->pidl("}");
560         $self->pidl("");
561
562         my $env = GenerateFunctionInEnv($fn, "r->");
563
564         my $fail = "return false;";
565         foreach my $e (@{$fn->{ELEMENTS}}) {
566                 next unless (grep(/in/,@{$e->{DIRECTION}}));
567                 if ($metadata_args->{in}->{$e->{NAME}}) {
568                         my $py_var = "py_".$metadata_args->{in}->{$e->{NAME}};
569                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
570                         my $val = "PyList_GET_SIZE($py_var)";
571                         if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
572                                 $self->pidl("r->in.$e->{NAME} = talloc_ptrtype(r, r->in.$e->{NAME});");
573                                 $self->pidl("*r->in.$e->{NAME} = $val;");
574                         } else {
575                                 $self->pidl("r->in.$e->{NAME} = $val;");
576                         }
577                 } else {
578                         $self->ConvertObjectFromPython($env, "r", $e, "py_$e->{NAME}", "r->in.$e->{NAME}", $fail);
579                 }
580         }
581         $self->pidl("return true;");
582         $self->deindent;
583         $self->pidl("}");
584         $self->pidl("");
585         return ($infnname, $signature);
586 }
587
588 sub PythonFunction($$$)
589 {
590         my ($self, $fn, $iface, $prettyname) = @_;
591
592         my $fnname = "py_$fn->{NAME}";
593         my $docstring = $self->DocString($fn, $fn->{NAME});
594
595         my ($infn, $insignature) = $self->PythonFunctionPackIn($fn, $fnname);
596         my ($outfn, $outsignature) = $self->PythonFunctionUnpackOut($fn, $fnname);
597         my $signature = "S.$prettyname($insignature) -> $outsignature";
598         if ($docstring) {
599                 $docstring = "\"$signature\\n\\n\"$docstring";
600         } else {
601                 $docstring = "\"$signature\"";
602         }
603
604         return ($infn, $outfn, $docstring);
605 }
606
607 sub handle_werror($$$$)
608 {
609         my ($self, $var, $retval, $mem_ctx) = @_;
610
611         $self->pidl("if (!W_ERROR_IS_OK($var)) {");
612         $self->indent;
613         $self->pidl("PyErr_SetWERROR($var);");
614         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
615         $self->pidl("return $retval;");
616         $self->deindent;
617         $self->pidl("}");
618         $self->pidl("");
619 }
620
621 sub handle_ntstatus($$$$)
622 {
623         my ($self, $var, $retval, $mem_ctx) = @_;
624
625         $self->pidl("if (NT_STATUS_IS_ERR($var)) {");
626         $self->indent;
627         $self->pidl("PyErr_SetNTSTATUS($var);");
628         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
629         $self->pidl("return $retval;");
630         $self->deindent;
631         $self->pidl("}");
632         $self->pidl("");
633 }
634
635 sub PythonType($$$$)
636 {
637         my ($self, $modulename, $d, $interface, $basename) = @_;
638
639         my $actual_ctype = $d;
640         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
641                 $actual_ctype = $actual_ctype->{DATA};
642         }
643
644         if ($actual_ctype->{TYPE} eq "STRUCT") {
645                 my $typeobject;
646                 my $fn_name = PrettifyTypeName($d->{NAME}, $basename);
647
648                 if ($d->{TYPE} eq "STRUCT") {
649                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d);
650                 } else {
651                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d->{DATA});
652                 }
653
654                 $self->register_module_typeobject($fn_name, $typeobject);
655         }
656
657         if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
658                 $self->EnumAndBitmapConsts($d->{NAME}, $d);
659         }
660
661         if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
662                 $self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
663         }
664
665         if ($actual_ctype->{TYPE} eq "UNION" and defined($actual_ctype->{ELEMENTS})) {
666                 $self->pidl("PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in)");
667                 $self->pidl_hdr("PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in);\n");
668                 $self->pidl("{");
669                 $self->indent;
670                 $self->FromUnionToPythonFunction("mem_ctx", $actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
671                 $self->deindent;
672                 $self->pidl("}");
673                 $self->pidl("");
674
675                 $self->pidl(mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
676                 $self->pidl_hdr(mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in);\n");
677                 $self->pidl("{");
678                 $self->indent;
679                 $self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
680                 $self->deindent;
681                 $self->pidl("}");
682                 $self->pidl("");
683         }
684 }
685
686 sub DocString($$$)
687 {
688         my ($self, $d, $name) = @_;
689         if (has_property($d, "helpstring")) {
690                 my $docstring = uc("py_doc_$name");
691                 $self->pidl("#define $docstring ".has_property($d, "helpstring"));
692                 return $docstring;
693         }
694
695         return undef;
696 }
697
698 sub Interface($$$)
699 {
700         my($self,$interface,$basename) = @_;
701
702         if (has_property($interface, "pyhelper")) {
703                 $self->pidl("#include \"".unmake_str($interface->{PROPERTIES}->{pyhelper})."\"\n");
704         }
705
706         $self->Const($_) foreach (@{$interface->{CONSTS}});
707
708         foreach my $d (@{$interface->{TYPES}}) {
709                 next if has_property($d, "nopython");
710
711                 $self->PythonType($basename, $d, $interface, $basename);
712         }
713
714         if (defined $interface->{PROPERTIES}->{uuid}) {
715                 $self->pidl_hdr("static PyTypeObject $interface->{NAME}_InterfaceType;\n");
716                 $self->pidl("");
717
718                 my @fns = ();
719
720                 foreach my $d (@{$interface->{FUNCTIONS}}) {
721                         next if has_property($d, "noopnum");
722                         next if has_property($d, "nopython");
723                         next if has_property($d, "todo");
724
725                         my $skip = 0;
726                         foreach my $e (@{$d->{ELEMENTS}}) {
727                                 if (ContainsPipe($e, $e->{LEVELS}[0])) {
728                                         $skip = 1;
729                                         last;
730                                 }
731                         }
732                         next if $skip;
733
734                         my $prettyname = $d->{NAME};
735
736                         $prettyname =~ s/^$interface->{NAME}_//;
737                         $prettyname =~ s/^$basename\_//;
738
739                         my ($infn, $outfn, $fndocstring) = $self->PythonFunction($d, $interface->{NAME}, $prettyname);
740
741                         push (@fns, [$infn, $outfn, "dcerpc_$d->{NAME}_r", $prettyname, $fndocstring, $d->{OPNUM}]);
742                 }
743
744                 $self->pidl("const struct PyNdrRpcMethodDef py_ndr_$interface->{NAME}\_methods[] = {");
745                 $self->indent;
746                 foreach my $d (@fns) {
747                         my ($infn, $outfn, $callfn, $prettyname, $docstring, $opnum) = @$d;
748                         $self->pidl("{ \"$prettyname\", $docstring, (py_dcerpc_call_fn)$callfn, (py_data_pack_fn)$infn, (py_data_unpack_fn)$outfn, $opnum, &ndr_table_$interface->{NAME} },");
749                 }
750                 $self->pidl("{ NULL }");
751                 $self->deindent;
752                 $self->pidl("};");
753                 $self->pidl("");
754
755                 $self->pidl("static PyObject *interface_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
756                 $self->pidl("{");
757                 $self->indent;
758                 $self->pidl("return py_dcerpc_interface_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME});");
759                 $self->deindent;
760                 $self->pidl("}");
761
762                 $self->pidl("");
763
764                 my $signature =
765 "\"$interface->{NAME}(binding, lp_ctx=None, credentials=None) -> connection\\n\"
766 \"\\n\"
767 \"binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\\n\"
768 \"lp_ctx should be a path to a smb.conf file or a param.LoadParm object\\n\"
769 \"credentials should be a credentials.Credentials object.\\n\\n\"";
770
771                 my $docstring = $self->DocString($interface, $interface->{NAME});
772
773                 if ($docstring) {
774                         $docstring = "$signature$docstring";
775                 } else {
776                         $docstring = $signature;
777                 }
778
779                 my $if_typename = "$interface->{NAME}_InterfaceType";
780
781                 $self->pidl("static PyTypeObject $if_typename = {");
782                 $self->indent;
783                 $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
784                 $self->pidl(".tp_name = \"$basename.$interface->{NAME}\",");
785                 $self->pidl(".tp_basicsize = sizeof(dcerpc_InterfaceObject),");
786                 $self->pidl(".tp_doc = $docstring,");
787                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
788                 $self->pidl(".tp_new = interface_$interface->{NAME}_new,");
789                 $self->deindent;
790                 $self->pidl("};");
791
792                 $self->pidl("");
793
794                 $self->register_module_typeobject($interface->{NAME}, "&$if_typename");
795                 my $dcerpc_typename = $self->import_type_variable("samba.dcerpc.base", "ClientConnection");
796                 $self->register_module_prereadycode(["$if_typename.tp_base = $dcerpc_typename;", ""]);
797                 $self->register_module_postreadycode(["if (!PyInterface_AddNdrRpcMethods(&$if_typename, py_ndr_$interface->{NAME}\_methods))", "\treturn;", ""]);
798
799
800                 $self->pidl("static PyObject *syntax_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
801                 $self->pidl("{");
802                 $self->indent;
803                 $self->pidl("return py_dcerpc_syntax_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME}.syntax_id);");
804                 $self->deindent;
805                 $self->pidl("}");
806
807                 $self->pidl("");
808
809                 my $signature = "\"abstract_syntax()\\n\"";
810
811                 my $docstring = $self->DocString($interface, $interface->{NAME}."_syntax");
812
813                 if ($docstring) {
814                         $docstring = "$signature$docstring";
815                 } else {
816                         $docstring = $signature;
817                 }
818
819                 my $syntax_typename = "$interface->{NAME}_SyntaxType";
820
821                 $self->pidl("static PyTypeObject $syntax_typename = {");
822                 $self->indent;
823                 $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
824                 $self->pidl(".tp_name = \"$basename.$interface->{NAME}\",");
825                 $self->pidl(".tp_doc = $docstring,");
826                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
827                 $self->pidl(".tp_new = syntax_$interface->{NAME}_new,");
828                 $self->deindent;
829                 $self->pidl("};");
830
831                 $self->pidl("");
832
833                 $self->register_module_typeobject("abstract_syntax", "&$syntax_typename");
834                 my $ndr_typename = $self->import_type_variable("samba.dcerpc.misc", "ndr_syntax_id");
835                 $self->register_module_prereadycode(["$syntax_typename.tp_base = $ndr_typename;",
836                                                      "$syntax_typename.tp_basicsize = pytalloc_BaseObject_size();",
837                                                      ""]);
838         }
839
840         $self->pidl_hdr("\n");
841 }
842
843 sub register_module_method($$$$$)
844 {
845         my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
846
847         push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
848 }
849
850 sub register_module_typeobject($$$)
851 {
852         my ($self, $name, $py_name) = @_;
853
854         $self->register_module_object($name, "(PyObject *)(void *)$py_name");
855
856         $self->check_ready_type($py_name);
857
858         $self->register_patch_type_call($name, $py_name);
859 }
860
861 sub check_ready_type($$)
862 {
863         my ($self, $py_name) = @_;
864         push (@{$self->{ready_types}}, $py_name) unless (grep(/^$py_name$/,@{$self->{ready_types}}));
865 }
866
867 sub register_module_import($$)
868 {
869         my ($self, $module_path) = @_;
870
871         my $var_name = $module_path;
872         $var_name =~ s/\./_/g;
873         $var_name = "dep_$var_name";
874
875         unless (defined $self->{module_imports_uniq}->{$var_name}) {
876                 my $h = { "key" => $var_name, "val" => $module_path};
877                 push @{$self->{module_imports}}, $h;
878                 $self->{module_imports_uniq}->{$var_name} = $h;
879         }
880         return $var_name;
881 }
882
883 sub import_type_variable($$$)
884 {
885         my ($self, $module, $name) = @_;
886
887         $self->register_module_import($module);
888         unless (defined $self->{type_imports_uniq}->{$name}) {
889                 my $h = { "key" => $name, "val" => $module};
890                 push @{$self->{type_imports}}, $h;
891                 $self->{type_imports_uniq}->{$name} = $h;
892         }
893         return "$name\_Type";
894 }
895
896 sub use_type_variable($$)
897 {
898         my ($self, $orig_ctype) = @_;
899         # FIXME: Have a global lookup table for types that look different on the
900         # wire than they are named in C?
901         if ($orig_ctype->{NAME} eq "dom_sid2" or
902             $orig_ctype->{NAME} eq "dom_sid28" or
903             $orig_ctype->{NAME} eq "dom_sid0") {
904                 $orig_ctype->{NAME} = "dom_sid";
905         }
906         if ($orig_ctype->{NAME} eq "spoolss_security_descriptor") {
907                 $orig_ctype->{NAME} = "security_descriptor";
908         }
909
910         my $ctype = resolveType($orig_ctype);
911         unless (defined($ctype->{BASEFILE})) {
912                 return undef;
913         }
914         # If this is an external type, make sure we do the right imports.
915         if (($ctype->{BASEFILE} ne $self->{BASENAME})) {
916                 return $self->import_type_variable("samba.dcerpc.$ctype->{BASEFILE}", $ctype->{NAME});
917         }
918         return "&$ctype->{NAME}_Type";
919 }
920
921 sub register_patch_type_call($$$)
922 {
923         my ($self, $typename, $cvar) = @_;
924
925         push(@{$self->{patch_type_calls}}, [$typename, $cvar]);
926
927 }
928
929 sub register_module_prereadycode($$)
930 {
931         my ($self, $code) = @_;
932
933         push (@{$self->{prereadycode}}, @$code);
934 }
935
936 sub register_module_postreadycode($$)
937 {
938         my ($self, $code) = @_;
939
940         push (@{$self->{postreadycode}}, @$code);
941 }
942
943 sub register_module_object($$$)
944 {
945         my ($self, $name, $py_name) = @_;
946
947         push (@{$self->{module_objects}}, [$name, $py_name])
948 }
949
950 sub assign($$$)
951 {
952         my ($self, $dest, $src) = @_;
953         if ($dest =~ /^\&/ and $src eq "NULL") {
954                 $self->pidl("memset($dest, 0, sizeof(" . get_value_of($dest) . "));");
955         } elsif ($dest =~ /^\&/) {
956                 my $destvar = get_value_of($dest);
957                 $self->pidl("$destvar = *$src;");
958         } else {
959                 $self->pidl("$dest = $src;");
960         }
961 }
962
963 sub ConvertStringFromPythonData($$$$$)
964 {
965         my ($self, $mem_ctx, $py_var, $target, $fail) = @_;
966
967         $self->pidl("{");
968         $self->indent;
969         $self->pidl("const char *test_str;");
970         $self->pidl("const char *talloc_str;");
971         $self->pidl("PyObject *unicode = NULL;");
972         $self->pidl("if (PyUnicode_Check($py_var)) {");
973         $self->indent;
974         # FIXME: Use Unix charset setting rather than utf-8
975         $self->pidl("unicode = PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\");");
976         $self->pidl("if (unicode == NULL) {");
977         $self->indent;
978         $self->pidl("PyErr_NoMemory();");
979         $self->pidl("$fail");
980         $self->deindent;
981         $self->pidl("}");
982
983         $self->pidl("test_str = PyString_AS_STRING(unicode);");
984         $self->deindent;
985         $self->pidl("} else if (PyString_Check($py_var)) {");
986         $self->indent;
987         $self->pidl("test_str = PyString_AS_STRING($py_var);");
988         $self->deindent;
989         $self->pidl("} else {");
990         $self->indent;
991         $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected string or unicode object, got %s\", Py_TYPE($py_var)->tp_name);");
992         $self->pidl("$fail");
993         $self->deindent;
994         $self->pidl("}");
995         $self->pidl("talloc_str = talloc_strdup($mem_ctx, test_str);");
996         $self->pidl("if (unicode != NULL) {");
997         $self->indent;
998         $self->pidl("Py_DECREF(unicode);");
999         $self->deindent;
1000         $self->pidl("}");
1001         $self->pidl("if (talloc_str == NULL) {");
1002         $self->indent;
1003         $self->pidl("PyErr_NoMemory();");
1004         $self->pidl("$fail");
1005         $self->deindent;
1006         $self->pidl("}");
1007         $self->pidl("$target = talloc_str;");
1008         $self->deindent;
1009         $self->pidl("}");
1010 }
1011
1012 sub ConvertObjectFromPythonData($$$$$$;$)
1013 {
1014         my ($self, $mem_ctx, $cvar, $ctype, $target, $fail, $location) = @_;
1015
1016         fatal($location, "undef type for $cvar") unless(defined($ctype));
1017
1018         $ctype = resolveType($ctype);
1019
1020         my $actual_ctype = $ctype;
1021         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
1022                 $actual_ctype = $actual_ctype->{DATA};
1023         }
1024
1025         # We need to cover ENUMs, BITMAPS and SCALAR values here, as
1026         # all could otherwise be assigned invalid integer values
1027         my $ctype_alias = "";
1028         my $uint_max = "";
1029         if ($actual_ctype->{TYPE} eq "ENUM") {
1030                 # Importantly, ENUM values are unsigned in pidl, and
1031                 # typically map to uint32
1032                 $ctype_alias = enum_type_fn($actual_ctype);
1033         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
1034                 $ctype_alias = bitmap_type_fn($actual_ctype);
1035         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
1036                 $ctype_alias = expandAlias($actual_ctype->{NAME});
1037         }
1038
1039         # This is the unsigned Python Integer -> C integer validation
1040         # case.  The signed case is below.
1041         if ($ctype_alias  =~ /^(uint[0-9]*|hyper|udlong|udlongr
1042                                 |NTTIME_hyper|NTTIME|NTTIME_1sec
1043                                 |uid_t|gid_t)$/x) {
1044                 $self->pidl("{");
1045                 $self->indent;
1046                 $self->pidl("const unsigned long long uint_max = ndr_sizeof2uintmax(sizeof($target));");
1047                 $self->pidl("if (PyLong_Check($cvar)) {");
1048                 $self->indent;
1049                 $self->pidl("unsigned long long test_var;");
1050                 $self->pidl("test_var = PyLong_AsUnsignedLongLong($cvar);");
1051                 $self->pidl("if (PyErr_Occurred() != NULL) {");
1052                 $self->indent;
1053                 $self->pidl($fail);
1054                 $self->deindent;
1055                 $self->pidl("}");
1056                 $self->pidl("if (test_var > uint_max) {");
1057                 $self->indent;
1058                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range 0 - %llu, got %llu\",\\");
1059                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, uint_max, test_var);");
1060                 $self->pidl($fail);
1061                 $self->deindent;
1062                 $self->pidl("}");
1063                 $self->pidl("$target = test_var;");
1064                 $self->deindent;
1065                 $self->pidl("} else if (PyInt_Check($cvar)) {");
1066                 $self->indent;
1067                 $self->pidl("long test_var;");
1068                 $self->pidl("test_var = PyInt_AsLong($cvar);");
1069                 $self->pidl("if (test_var < 0 || test_var > uint_max) {");
1070                 $self->indent;
1071                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range 0 - %llu, got %ld\",\\");
1072                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, uint_max, test_var);");
1073                 $self->pidl($fail);
1074                 $self->deindent;
1075                 $self->pidl("}");
1076                 $self->pidl("$target = test_var;");
1077                 $self->deindent;
1078                 $self->pidl("} else {");
1079                 $self->indent;
1080                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
1081                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
1082                 $self->pidl($fail);
1083                 $self->deindent;
1084                 $self->pidl("}");
1085                 $self->deindent;
1086                 $self->pidl("}");
1087                 return;
1088         }
1089
1090         # Confirm the signed python integer fits in the C type
1091         # correctly.  It is subtly different from the unsigned case
1092         # above, so while it looks like a duplicate, it is not
1093         # actually a duplicate.
1094         if ($ctype_alias  =~ /^(dlong|char|int[0-9]*|time_t)$/x) {
1095                 $self->pidl("{");
1096                 $self->indent;
1097                 $self->pidl("const long long int_max = ndr_sizeof2intmax(sizeof($target));");
1098                 $self->pidl("const long long int_min = -int_max - 1;");
1099                 $self->pidl("if (PyLong_Check($cvar)) {");
1100                 $self->indent;
1101                 $self->pidl("long long test_var;");
1102                 $self->pidl("test_var = PyLong_AsLongLong($cvar);");
1103                 $self->pidl("if (PyErr_Occurred() != NULL) {");
1104                 $self->indent;
1105                 $self->pidl($fail);
1106                 $self->deindent;
1107                 $self->pidl("}");
1108                 $self->pidl("if (test_var < int_min || test_var > int_max) {");
1109                 $self->indent;
1110                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range %lld - %lld, got %lld\",\\");
1111                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, int_min, int_max, test_var);");
1112                 $self->pidl($fail);
1113                 $self->deindent;
1114                 $self->pidl("}");
1115                 $self->pidl("$target = test_var;");
1116                 $self->deindent;
1117                 $self->pidl("} else if (PyInt_Check($cvar)) {");
1118                 $self->indent;
1119                 $self->pidl("long test_var;");
1120                 $self->pidl("test_var = PyInt_AsLong($cvar);");
1121                 $self->pidl("if (test_var < int_min || test_var > int_max) {");
1122                 $self->indent;
1123                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range %lld - %lld, got %ld\",\\");
1124                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, int_min, int_max, test_var);");
1125                 $self->pidl($fail);
1126                 $self->deindent;
1127                 $self->pidl("}");
1128                 $self->pidl("$target = test_var;");
1129                 $self->deindent;
1130                 $self->pidl("} else {");
1131                 $self->indent;
1132                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
1133                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
1134                 $self->pidl($fail);
1135                 $self->deindent;
1136                 $self->pidl("}");
1137                 $self->deindent;
1138                 $self->pidl("}");
1139                 return;
1140         }
1141
1142         if ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
1143                 my $ctype_name = $self->use_type_variable($ctype);
1144                 unless (defined ($ctype_name)) {
1145                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
1146                         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Can not convert C Type " . mapTypeName($ctype) . " from Python\");");
1147                         return;
1148                 }
1149                 $self->pidl("PY_CHECK_TYPE($ctype_name, $cvar, $fail);");
1150                 $self->pidl("if (talloc_reference($mem_ctx, pytalloc_get_mem_ctx($cvar)) == NULL) {");
1151                 $self->indent;
1152                 $self->pidl("PyErr_NoMemory();");
1153                 $self->pidl("$fail");
1154                 $self->deindent;
1155                 $self->pidl("}");
1156                 $self->assign($target, "(".mapTypeName($ctype)." *)pytalloc_get_ptr($cvar)");
1157                 return;
1158         }
1159
1160         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
1161                 $self->pidl("$target = data_blob_talloc($mem_ctx, PyString_AS_STRING($cvar), PyString_GET_SIZE($cvar));");
1162                 return;
1163         }
1164
1165         if ($actual_ctype->{TYPE} eq "SCALAR" and
1166                 ($actual_ctype->{NAME} eq "string"
1167                  or $actual_ctype->{NAME} eq "nbt_string"
1168                  or $actual_ctype->{NAME} eq "nbt_name"
1169                  or $actual_ctype->{NAME} eq "wrepl_nbt_name"
1170                  or $actual_ctype->{NAME} eq "dns_string"
1171                  or $actual_ctype->{NAME} eq "dnsp_string"
1172                  or $actual_ctype->{NAME} eq "dns_name"
1173                  or $actual_ctype->{NAME} eq "ipv4address"
1174                  or $actual_ctype->{NAME} eq "ipv6address"
1175                  or $actual_ctype->{NAME} eq "dnsp_name")) {
1176                 $self->ConvertStringFromPythonData($mem_ctx, $cvar, $target, $fail);
1177                 return;
1178         }
1179
1180         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
1181                 $self->pidl("$target = NT_STATUS(PyInt_AsLong($cvar));");
1182                 return;
1183         }
1184
1185         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
1186                 $self->pidl("$target = W_ERROR(PyInt_AsLong($cvar));");
1187                 return;
1188         }
1189
1190         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "HRESULT") {
1191                 $self->pidl("$target = HRES_ERROR(PyInt_AsLong($cvar));");
1192                 return;
1193         }
1194
1195         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
1196                 $self->pidl("$target = PyCObject_AsVoidPtr($cvar);");
1197                 return;
1198         }
1199
1200         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
1201                 $self->assign($target, "PyCObject_AsVoidPtr($cvar)");
1202                 return;
1203         }
1204
1205         fatal($location, "unknown type `$actual_ctype->{TYPE}' for ".mapTypeName($ctype) . ": $cvar");
1206
1207 }
1208
1209 sub ConvertObjectFromPythonLevel($$$$$$$$)
1210 {
1211         my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail) = @_;
1212         my $nl = GetNextLevel($e, $l);
1213         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
1214                 $nl = GetNextLevel($e, $nl);
1215         }
1216         my $pl = GetPrevLevel($e, $l);
1217         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
1218                 $pl = GetPrevLevel($e, $pl);
1219         }
1220
1221         $self->pidl("if ($py_var == NULL) {");
1222         $self->indent;
1223         $self->pidl("PyErr_Format(PyExc_AttributeError, \"Cannot delete NDR object: " .
1224                     mapTypeName($var_name) . "\");");
1225         $self->pidl($fail);
1226         $self->deindent;
1227         $self->pidl("}");
1228
1229         if ($l->{TYPE} eq "POINTER") {
1230                 if ($l->{POINTER_TYPE} ne "ref") {
1231                         $self->pidl("if ($py_var == Py_None) {");
1232                         $self->indent;
1233                         $self->pidl("$var_name = NULL;");
1234                         $self->deindent;
1235                         $self->pidl("} else {");
1236                         $self->indent;
1237                 }
1238                 # if we want to handle more than one level of pointer in python interfaces
1239                 # then this is where we would need to allocate it
1240                 if ($l->{POINTER_TYPE} eq "ref") {
1241                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1242                 } elsif ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::is_scalar($nl->{DATA_TYPE})
1243                          and not Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1244                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1245                 } else {
1246                         $self->pidl("$var_name = NULL;");
1247                 }
1248                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1249                         $var_name = get_value_of($var_name);
1250                 }
1251                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail);
1252                 if ($l->{POINTER_TYPE} ne "ref") {
1253                         $self->deindent;
1254                         $self->pidl("}");
1255                 }
1256         } elsif ($l->{TYPE} eq "ARRAY") {
1257                 if ($pl && $pl->{TYPE} eq "POINTER") {
1258                         $var_name = get_pointer_to($var_name);
1259                 }
1260
1261                 if (is_charset_array($e, $l)) {
1262                         $self->ConvertStringFromPythonData($mem_ctx, $py_var, $var_name, $fail);
1263                 } else {
1264                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
1265                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
1266                         $self->pidl("{");
1267                         $self->indent;
1268                         $self->pidl("int $counter;");
1269                         if (ArrayDynamicallyAllocated($e, $l)) {
1270                                 $self->pidl("$var_name = talloc_array_ptrtype($mem_ctx, $var_name, PyList_GET_SIZE($py_var));");
1271                                 $self->pidl("if (!$var_name) { $fail; }");
1272                                 $self->pidl("talloc_set_name_const($var_name, \"ARRAY: $var_name\");");
1273                         } else {
1274                                 $self->pidl("if (ARRAY_SIZE($var_name) != PyList_GET_SIZE($py_var)) {");
1275                                 $self->indent;
1276                                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected list of type %s, length %zu, got %zd\", Py_TYPE($py_var)->tp_name, ARRAY_SIZE($var_name),  PyList_GET_SIZE($py_var));");
1277                                 $self->pidl("$fail");
1278                                 $self->deindent;
1279                                 $self->pidl("}");
1280                         }
1281                         $self->pidl("for ($counter = 0; $counter < PyList_GET_SIZE($py_var); $counter++) {");
1282                         $self->indent;
1283                         $self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GET_ITEM($py_var, $counter)", $e, $nl, $var_name."[$counter]", $fail);
1284                         $self->deindent;
1285                         $self->pidl("}");
1286                         $self->deindent;
1287                         $self->pidl("}");
1288                 }
1289         } elsif ($l->{TYPE} eq "DATA") {
1290                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
1291                         $var_name = get_pointer_to($var_name);
1292                 }
1293                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail, $e->{ORIGINAL});
1294         } elsif ($l->{TYPE} eq "SWITCH") {
1295                 $var_name = get_pointer_to($var_name);
1296                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
1297                 my $switch_ptr = "$e->{NAME}_switch_$l->{LEVEL_INDEX}";
1298                 $self->pidl("{");
1299                 $self->indent;
1300                 my $union_type = mapTypeName($nl->{DATA_TYPE});
1301                 $self->pidl("$union_type *$switch_ptr;");
1302                 $self->pidl("$switch_ptr = py_export_" . $nl->{DATA_TYPE} . "($mem_ctx, $switch, $py_var);");
1303                 $self->fail_on_null($switch_ptr, $fail);
1304                 $self->assign($var_name, "$switch_ptr");
1305                 $self->deindent;
1306                 $self->pidl("}");
1307         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
1308                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail);
1309         } else {
1310                 fatal($e->{ORIGINAL}, "unknown level type $l->{TYPE}");
1311         }
1312 }
1313
1314 sub ConvertObjectFromPython($$$$$$$)
1315 {
1316         my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
1317
1318         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail);
1319 }
1320
1321 sub ConvertScalarToPython($$$)
1322 {
1323         my ($self, $ctypename, $cvar) = @_;
1324
1325         die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
1326
1327         $ctypename = expandAlias($ctypename);
1328
1329         if ($ctypename =~ /^(int64|dlong)$/) {
1330                 return "ndr_PyLong_FromLongLong($cvar)";
1331         }
1332
1333         if ($ctypename =~ /^(uint64|hyper|NTTIME_hyper|NTTIME|NTTIME_1sec|udlong|udlongr|uid_t|gid_t)$/) {
1334                 return "ndr_PyLong_FromUnsignedLongLong($cvar)";
1335         }
1336
1337         if ($ctypename =~ /^(char|int|int8|int16|int32|time_t)$/) {
1338                 return "PyInt_FromLong($cvar)";
1339         }
1340
1341         # Needed to ensure unsigned values in a 32 or 16 bit enum is
1342         # cast correctly to a uint32_t, not sign extended to a a
1343         # possibly 64 bit unsigned long.  (enums are signed in C,
1344         # unsigned in NDR)
1345         if ($ctypename =~ /^(uint32|uint3264)$/) {
1346                 return "ndr_PyLong_FromUnsignedLongLong((uint32_t)$cvar)";
1347         }
1348
1349         if ($ctypename =~ /^(uint|uint8|uint16|uint1632)$/) {
1350                 return "PyInt_FromLong((uint16_t)$cvar)";
1351         }
1352
1353         if ($ctypename eq "DATA_BLOB") {
1354                 return "PyString_FromStringAndSize((char *)($cvar).data, ($cvar).length)";
1355         }
1356
1357         if ($ctypename eq "NTSTATUS") {
1358                 return "PyErr_FromNTSTATUS($cvar)";
1359         }
1360
1361         if ($ctypename eq "WERROR") {
1362                 return "PyErr_FromWERROR($cvar)";
1363         }
1364
1365         if ($ctypename eq "HRESULT") {
1366                 return "PyErr_FromHRESULT($cvar)";
1367         }
1368
1369         if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
1370                 return "PyString_FromStringOrNULL($cvar)";
1371         }
1372
1373         if (($ctypename eq "dns_string" or $ctypename eq "dns_name")) {
1374                 return "PyString_FromStringOrNULL($cvar)";
1375         }
1376
1377         # Not yet supported
1378         if ($ctypename eq "string_array") { return "pytalloc_CObject_FromTallocPtr($cvar)"; }
1379         if ($ctypename eq "ipv4address") { return "PyString_FromStringOrNULL($cvar)"; }
1380         if ($ctypename eq "ipv6address") { return "PyString_FromStringOrNULL($cvar)"; }
1381         if ($ctypename eq "dnsp_name") { return "PyString_FromStringOrNULL($cvar)"; }
1382         if ($ctypename eq "dnsp_string") { return "PyString_FromStringOrNULL($cvar)"; }
1383         if ($ctypename eq "pointer") {
1384                 return "pytalloc_CObject_FromTallocPtr($cvar)";
1385         }
1386
1387         die("Unknown scalar type $ctypename");
1388 }
1389
1390 sub ConvertObjectToPythonData($$$$$;$)
1391 {
1392         my ($self, $mem_ctx, $ctype, $cvar, $location) = @_;
1393
1394         die("undef type for $cvar") unless(defined($ctype));
1395
1396         $ctype = resolveType($ctype);
1397
1398         my $actual_ctype = $ctype;
1399         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
1400                 $actual_ctype = $actual_ctype->{DATA};
1401         }
1402
1403         if ($actual_ctype->{TYPE} eq "ENUM") {
1404                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar);
1405         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
1406                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar);
1407         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
1408                 return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar);
1409         } elsif ($actual_ctype->{TYPE} eq "UNION") {
1410                 fatal($ctype, "union without discriminant: " . mapTypeName($ctype) . ": $cvar");
1411         } elsif ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
1412                 my $ctype_name = $self->use_type_variable($ctype);
1413                 unless (defined($ctype_name)) {
1414                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
1415                         return "NULL"; # FIXME!
1416                 }
1417                 return "pytalloc_reference_ex($ctype_name, $mem_ctx, $cvar)";
1418         }
1419
1420         fatal($location, "unknown type $actual_ctype->{TYPE} for ".mapTypeName($ctype) . ": $cvar");
1421 }
1422
1423 sub fail_on_null($$$)
1424 {
1425         my ($self, $var, $fail) = @_;
1426         $self->pidl("if ($var == NULL) {");
1427         $self->indent;
1428         $self->pidl($fail);
1429         $self->deindent;
1430         $self->pidl("}");
1431 }
1432
1433 sub ConvertObjectToPythonLevel($$$$$$)
1434 {
1435         my ($self, $mem_ctx, $env, $e, $l, $var_name, $py_var, $fail) = @_;
1436         my $nl = GetNextLevel($e, $l);
1437         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
1438                 $nl = GetNextLevel($e, $nl);
1439         }
1440         my $pl = GetPrevLevel($e, $l);
1441         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
1442                 $pl = GetPrevLevel($e, $pl);
1443         }
1444
1445         if ($l->{TYPE} eq "POINTER") {
1446                 if ($l->{POINTER_TYPE} ne "ref") {
1447                         $self->pidl("if ($var_name == NULL) {");
1448                         $self->indent;
1449                         $self->pidl("$py_var = Py_None;");
1450                         $self->pidl("Py_INCREF($py_var);");
1451                         $self->deindent;
1452                         $self->pidl("} else {");
1453                         $self->indent;
1454                 }
1455                 my $var_name2 = $var_name;
1456                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1457                         $var_name2 = get_value_of($var_name);
1458                 }
1459                 $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name2, $py_var, $fail);
1460                 if ($l->{POINTER_TYPE} ne "ref") {
1461                         $self->deindent;
1462                         $self->pidl("}");
1463                 }
1464         } elsif ($l->{TYPE} eq "ARRAY") {
1465                 if ($pl && $pl->{TYPE} eq "POINTER") {
1466                         $var_name = get_pointer_to($var_name);
1467                 }
1468
1469                 if (is_charset_array($e, $l)) {
1470                         # FIXME: Use Unix charset setting rather than utf-8
1471                         $self->pidl("if ($var_name == NULL) {");
1472                         $self->indent;
1473                         $self->pidl("$py_var = Py_None;");
1474                         $self->pidl("Py_INCREF($py_var);");
1475                         $self->deindent;
1476                         $self->pidl("} else {");
1477                         $self->indent;
1478                         $self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
1479                         $self->deindent;
1480                         $self->pidl("}");
1481                 } else {
1482                         die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
1483                         my $length = $l->{SIZE_IS};
1484                         if (defined($l->{LENGTH_IS})) {
1485                                 $length = $l->{LENGTH_IS};
1486                         }
1487
1488                         $length = ParseExpr($length, $env, $e);
1489                         $self->pidl("$py_var = PyList_New($length);");
1490                         $self->fail_on_null($py_var, $fail);
1491                         $self->pidl("{");
1492                         $self->indent;
1493                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
1494                         $self->pidl("int $counter;");
1495                         $self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
1496                         $self->indent;
1497                         my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
1498                         $self->pidl("PyObject *$member_var;");
1499                         $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name."[$counter]", $member_var, $fail);
1500                         $self->pidl("PyList_SetItem($py_var, $counter, $member_var);");
1501                         $self->deindent;
1502                         $self->pidl("}");
1503                         $self->deindent;
1504                         $self->pidl("}");
1505                 }
1506         } elsif ($l->{TYPE} eq "SWITCH") {
1507                 $var_name = get_pointer_to($var_name);
1508                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
1509                 $self->pidl("$py_var = py_import_" . $nl->{DATA_TYPE} . "($mem_ctx, $switch, $var_name);");
1510                 $self->fail_on_null($py_var, $fail);
1511
1512         } elsif ($l->{TYPE} eq "DATA") {
1513                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
1514                         $var_name = get_pointer_to($var_name);
1515                 }
1516                 my $conv = $self->ConvertObjectToPythonData($mem_ctx, $l->{DATA_TYPE}, $var_name, $e->{ORIGINAL});
1517                 $self->pidl("$py_var = $conv;");
1518         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
1519                 $self->ConvertObjectToPythonLevel($mem_ctx, $env, $e, $nl, $var_name, $py_var, $fail);
1520         } else {
1521                 fatal($e->{ORIGINAL}, "Unknown level type $l->{TYPE} $var_name");
1522         }
1523 }
1524
1525 sub ConvertObjectToPython($$$$$$)
1526 {
1527         my ($self, $mem_ctx, $env, $ctype, $cvar, $py_var, $fail) = @_;
1528
1529         $self->ConvertObjectToPythonLevel($mem_ctx, $env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var, $fail);
1530 }
1531
1532 sub Parse($$$$$)
1533 {
1534     my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
1535
1536         $self->{BASENAME} = $basename;
1537
1538     $self->pidl_hdr("
1539 /* Python wrapper functions auto-generated by pidl */
1540 #define PY_SSIZE_T_CLEAN 1 /* We use Py_ssize_t for PyArg_ParseTupleAndKeywords */
1541 #include <Python.h>
1542 #include \"includes.h\"
1543 #include <pytalloc.h>
1544 #include \"librpc/rpc/pyrpc.h\"
1545 #include \"librpc/rpc/pyrpc_util.h\"
1546 #include \"$hdr\"
1547 #include \"$ndr_hdr\"
1548
1549 /*
1550  * These functions are here to ensure they can be optomised out by
1551  * the compiler based on the constant input values
1552  */
1553
1554 static inline unsigned long long ndr_sizeof2uintmax(size_t var_size)
1555 {
1556         switch (var_size) {
1557         case 8:
1558                 return UINT64_MAX;
1559         case 4:
1560                 return UINT32_MAX;
1561         case 2:
1562                 return UINT16_MAX;
1563         case 1:
1564                 return UINT8_MAX;
1565         }
1566
1567         return 0;
1568 }
1569
1570 static inline long long ndr_sizeof2intmax(size_t var_size)
1571 {
1572         switch (var_size) {
1573         case 8:
1574                 return INT64_MAX;
1575         case 4:
1576                 return INT32_MAX;
1577         case 2:
1578                 return INT16_MAX;
1579         case 1:
1580                 return INT8_MAX;
1581         }
1582
1583         return 0;
1584 }
1585
1586 static inline PyObject *ndr_PyLong_FromLongLong(long long v)
1587 {
1588         if (v > LONG_MAX || v < LONG_MIN) {
1589                 return PyLong_FromLongLong(v);
1590         } else {
1591                 return PyInt_FromLong(v);
1592         }
1593 }
1594
1595 static inline PyObject *ndr_PyLong_FromUnsignedLongLong(unsigned long long v)
1596 {
1597         if (v > LONG_MAX) {
1598                 return PyLong_FromUnsignedLongLong(v);
1599         } else {
1600                 return PyInt_FromLong(v);
1601         }
1602 }
1603
1604 ");
1605
1606         foreach my $x (@$ndr) {
1607                 ($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
1608             ($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
1609         }
1610
1611         $self->pidl("static PyMethodDef $basename\_methods[] = {");
1612         $self->indent;
1613         foreach (@{$self->{module_methods}}) {
1614                 my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
1615                 $self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
1616         }
1617
1618         $self->pidl("{ NULL, NULL, 0, NULL }");
1619         $self->deindent;
1620         $self->pidl("};");
1621
1622         $self->pidl("");
1623
1624         $self->pidl_hdr("void init$basename(void);");
1625         $self->pidl("void init$basename(void)");
1626         $self->pidl("{");
1627         $self->indent;
1628         $self->pidl("PyObject *m;");
1629         foreach my $h (@{$self->{module_imports}}) {
1630                 $self->pidl("PyObject *$h->{'key'};");
1631         }
1632         $self->pidl("");
1633
1634         foreach my $h (@{$self->{module_imports}}) {
1635                 my $var_name = $h->{'key'};
1636                 my $module_path = $h->{'val'};
1637                 $self->pidl("$var_name = PyImport_ImportModule(\"$module_path\");");
1638                 $self->pidl("if ($var_name == NULL)");
1639                 $self->pidl("\treturn;");
1640                 $self->pidl("");
1641         }
1642
1643         foreach my $h (@{$self->{type_imports}}) {
1644                 my $type_var = "$h->{'key'}\_Type";
1645                 my $module_path = $h->{'val'};
1646                 $self->pidl_hdr("static PyTypeObject *$type_var;\n");
1647                 my $pretty_name = PrettifyTypeName($h->{'key'}, $module_path);
1648                 my $module_var = "dep_$module_path";
1649                 $module_var =~ s/\./_/g;
1650                 $self->pidl("$type_var = (PyTypeObject *)PyObject_GetAttrString($module_var, \"$pretty_name\");");
1651                 $self->pidl("if ($type_var == NULL)");
1652                 $self->pidl("\treturn;");
1653                 $self->pidl("");
1654         }
1655
1656         $self->pidl($_) foreach (@{$self->{prereadycode}});
1657
1658         foreach (@{$self->{ready_types}}) {
1659                 $self->pidl("if (PyType_Ready($_) < 0)");
1660                 $self->pidl("\treturn;");
1661         }
1662
1663         $self->pidl($_) foreach (@{$self->{postreadycode}});
1664
1665         foreach (@{$self->{patch_type_calls}}) {
1666                 my ($typename, $cvar) = @$_;
1667                 $self->pidl("#ifdef PY_".uc($typename)."_PATCH");
1668                 $self->pidl("PY_".uc($typename)."_PATCH($cvar);");
1669                 $self->pidl("#endif");
1670         }
1671
1672         $self->pidl("");
1673
1674         $self->pidl("m = Py_InitModule3(\"$basename\", $basename\_methods, \"$basename DCE/RPC\");");
1675         $self->pidl("if (m == NULL)");
1676         $self->pidl("\treturn;");
1677         $self->pidl("");
1678         foreach my $h (@{$self->{constants}}) {
1679                 my $name = $h->{'key'};
1680                 my $py_obj;
1681                 my ($ctype, $cvar) = @{$h->{'val'}};
1682                 if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
1683                         $py_obj = "ndr_PyLong_FromUnsignedLongLong($cvar)";
1684                 } elsif ($cvar =~ /^".*"$/) {
1685                         $py_obj = "PyString_FromString($cvar)";
1686                 } else {
1687                         $py_obj = $self->ConvertObjectToPythonData("NULL", expandAlias($ctype), $cvar, undef);
1688                 }
1689
1690                 $self->pidl("PyModule_AddObject(m, \"$name\", $py_obj);");
1691         }
1692
1693         foreach (@{$self->{module_objects}}) {
1694                 my ($object_name, $c_name) = @$_;
1695                 $self->pidl("Py_INCREF($c_name);");
1696                 $self->pidl("PyModule_AddObject(m, \"$object_name\", $c_name);");
1697         }
1698
1699         $self->pidl("#ifdef PY_MOD_".uc($basename)."_PATCH");
1700         $self->pidl("PY_MOD_".uc($basename)."_PATCH(m);");
1701         $self->pidl("#endif");
1702
1703         $self->pidl("");
1704         $self->deindent;
1705         $self->pidl("}");
1706     return ($self->{res_hdr} . $self->{res});
1707 }
1708
1709 1;