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