pyldb: avoid segfault when adding an element with no name
[sfrench/samba-autobuild/.git] / script / generate_param.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) 2014 Catalyst.Net Ltd
3 #
4 # Auto generate param_functions.c
5 #
6 #   ** NOTE! The following LGPL license applies to the ldb
7 #   ** library. This does NOT imply that all of Samba is released
8 #   ** under the LGPL
9 #
10 #  This library is free software; you can redistribute it and/or
11 #  modify it under the terms of the GNU Lesser General Public
12 #  License as published by the Free Software Foundation; either
13 #  version 3 of the License, or (at your option) any later version.
14 #
15 #  This library is distributed in the hope that it will be useful,
16 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 #  Lesser General Public License for more details.
19 #
20 #  You should have received a copy of the GNU Lesser General Public
21 #  License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 #
23
24 import os
25 import xml.etree.ElementTree as ET
26 import optparse
27
28 # parse command line arguments
29 parser = optparse.OptionParser()
30 parser.add_option("-f", "--file", dest="filename",
31                   help="input file", metavar="FILE")
32 parser.add_option("-o", "--output", dest="output",
33                   help='output file', metavar="FILE")
34 parser.add_option("--mode", type="choice", metavar="<FUNCTIONS|S3PROTO|LIBPROTO|PARAMDEFS|PARAMTABLE>",
35                   choices=["FUNCTIONS", "S3PROTO", "LIBPROTO", "PARAMDEFS", "PARAMTABLE"], default="FUNCTIONS")
36 parser.add_option("--scope", metavar="<GLOBAL|LOCAL>",
37                   choices=["GLOBAL", "LOCAL"], default="GLOBAL")
38
39 (options, args) = parser.parse_args()
40
41 if options.filename is None:
42     parser.error("No input file specified")
43 if options.output is None:
44     parser.error("No output file specified")
45
46
47 def iterate_all(path):
48     """Iterate and yield all the parameters.
49
50     :param path: path to parameters xml file
51     """
52
53     try:
54         p = open(path, 'r')
55     except IOError as e:
56         raise Exception("Error opening parameters file")
57     out = p.read()
58
59     # parse the parameters xml file
60     root = ET.fromstring(out)
61     for parameter in root:
62         name = parameter.attrib.get("name")
63         param_type = parameter.attrib.get("type")
64         context = parameter.attrib.get("context")
65         func = parameter.attrib.get("function")
66         synonym = parameter.attrib.get("synonym")
67         removed = parameter.attrib.get("removed")
68         generated = parameter.attrib.get("generated_function")
69         handler = parameter.attrib.get("handler")
70         enumlist = parameter.attrib.get("enumlist")
71         deprecated = parameter.attrib.get("deprecated")
72         synonyms = parameter.findall('synonym')
73
74         if removed == "1":
75             continue
76
77         constant = parameter.attrib.get("constant")
78         parm = parameter.attrib.get("parm")
79         if name is None or param_type is None or context is None:
80             raise Exception("Error parsing parameter: " + name)
81         if func is None:
82             func = name.replace(" ", "_").lower()
83         if enumlist is None:
84             enumlist = "NULL"
85         if handler is None:
86             handler = "NULL"
87         yield {'name': name,
88                'type': param_type,
89                'context': context,
90                'function': func,
91                'constant': (constant == '1'),
92                'parm': (parm == '1'),
93                'synonym' : synonym,
94                'generated' : generated,
95                'enumlist' : enumlist,
96                'handler' : handler,
97                'deprecated' : deprecated,
98                'synonyms' : synonyms }
99
100
101 # map doc attributes to a section of the generated function
102 context_dict = {"G": "_GLOBAL", "S": "_LOCAL"}
103 param_type_dict = {
104                     "boolean"      : "_BOOL",
105                     "list"         : "_LIST",
106                     "string"       : "_STRING",
107                     "integer"      : "_INTEGER",
108                     "enum"         : "_INTEGER",
109                     "char"         : "_CHAR",
110                     "boolean-auto" : "_INTEGER",
111                     "cmdlist"      : "_LIST",
112                     "bytes"        : "_INTEGER",
113                     "octal"        : "_INTEGER",
114                     "ustring"      : "_STRING",
115                   }
116
117
118 def generate_functions(path_in, path_out):
119     f = open(path_out, 'w')
120     try:
121         f.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
122         for parameter in iterate_all(options.filename):
123             # filter out parameteric options
124             if ':' in parameter['name']:
125                 continue
126             if parameter['synonym'] == "1":
127                 continue
128             if parameter['generated'] == "0":
129                 continue
130
131             output_string = "FN"
132             temp = context_dict.get(parameter['context'])
133             if temp is None:
134                 raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
135             output_string += temp
136             if parameter['constant']:
137                 output_string += "_CONST"
138             if parameter['parm']:
139                 output_string += "_PARM"
140             temp = param_type_dict.get(parameter['type'])
141             if temp is None:
142                 raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
143             output_string += temp
144             f.write(output_string + "(" + parameter['function'] + ", " + parameter['function'] + ')\n')
145     finally:
146         f.close()
147
148
149 mapping = {
150             'boolean'      : 'bool ',
151             'string'       : 'char *',
152             'integer'      : 'int ',
153             'char'         : 'char ',
154             'list'         : 'const char **',
155             'enum'         : 'int ',
156             'boolean-auto' : 'int ',
157             'cmdlist'      : 'const char **',
158             'bytes'        : 'int ',
159             'octal'        : 'int ',
160             'ustring'      : 'char *',
161           }
162
163
164 def make_s3_param_proto(path_in, path_out):
165     file_out = open(path_out, 'w')
166     try:
167         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
168         header = get_header(path_out)
169         file_out.write("#ifndef %s\n" % header)
170         file_out.write("#define %s\n\n" % header)
171         for parameter in iterate_all(path_in):
172             # filter out parameteric options
173             if ':' in parameter['name']:
174                 continue
175             if parameter['synonym'] == "1":
176                 continue
177             if parameter['generated'] == "0":
178                 continue
179
180             output_string = ""
181             if parameter['constant']:
182                 output_string += 'const '
183             param_type = mapping.get(parameter['type'])
184             if param_type is None:
185                 raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
186             output_string += param_type
187             output_string += "lp_%s" % parameter['function']
188
189             param = None
190             if parameter['parm']:
191                 param = "const struct share_params *p"
192             else:
193                 param = "int"
194
195             if parameter['type'] == 'string' and not parameter['constant']:
196                 if parameter['context'] == 'G':
197                     output_string += '(TALLOC_CTX *ctx);\n'
198                 elif parameter['context'] == 'S':
199                     output_string += '(TALLOC_CTX *ctx, %s);\n' % param
200                 else:
201                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
202             else:
203                 if parameter['context'] == 'G':
204                     output_string += '(void);\n'
205                 elif parameter['context'] == 'S':
206                     output_string += '(%s);\n' % param
207                 else:
208                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
209
210             file_out.write(output_string)
211
212         file_out.write("\n#endif /* %s */\n\n" % header)
213     finally:
214         file_out.close()
215
216
217 def make_lib_proto(path_in, path_out):
218     file_out = open(path_out, 'w')
219     try:
220         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
221         for parameter in iterate_all(path_in):
222             # filter out parameteric options
223             if ':' in parameter['name']:
224                 continue
225             if parameter['synonym'] == "1":
226                 continue
227             if parameter['generated'] == "0":
228                 continue
229
230             output_string = ""
231             if parameter['constant']:
232                 output_string += 'const '
233             param_type = mapping.get(parameter['type'])
234             if param_type is None:
235                 raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
236             output_string += param_type
237
238             output_string += "lpcfg_%s" % parameter['function']
239
240             if parameter['type'] == 'string' and not parameter['constant']:
241                 if parameter['context'] == 'G':
242                     output_string += '(struct loadparm_context *, TALLOC_CTX *ctx);\n'
243                 elif parameter['context'] == 'S':
244                     output_string += '(struct loadparm_service *, struct loadparm_service *, TALLOC_CTX *ctx);\n'
245                 else:
246                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
247             else:
248                 if parameter['context'] == 'G':
249                     output_string += '(struct loadparm_context *);\n'
250                 elif parameter['context'] == 'S':
251                     output_string += '(struct loadparm_service *, struct loadparm_service *);\n'
252                 else:
253                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
254
255             file_out.write(output_string)
256     finally:
257         file_out.close()
258
259
260 def get_header(path):
261     header = os.path.basename(path).upper()
262     header = header.replace(".", "_").replace("\\", "_").replace("-", "_")
263     return "__%s__" % header
264
265
266 def make_param_defs(path_in, path_out, scope):
267     file_out = open(path_out, 'w')
268     try:
269         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
270         header = get_header(path_out)
271         file_out.write("#ifndef %s\n" % header)
272         file_out.write("#define %s\n\n" % header)
273         if scope == "GLOBAL":
274             file_out.write("/**\n")
275             file_out.write(" * This structure describes global (ie., server-wide) parameters.\n")
276             file_out.write(" */\n")
277             file_out.write("struct loadparm_global \n")
278             file_out.write("{\n")
279             file_out.write("\tTALLOC_CTX *ctx; /* Context for talloced members */\n")
280         elif scope == "LOCAL":
281             file_out.write("/**\n")
282             file_out.write(" * This structure describes a single service.\n")
283             file_out.write(" */\n")
284             file_out.write("struct loadparm_service \n")
285             file_out.write("{\n")
286             file_out.write("\tbool   autoloaded;\n")
287
288         for parameter in iterate_all(path_in):
289             # filter out parameteric options
290             if ':' in parameter['name']:
291                 continue
292             if parameter['synonym'] == "1":
293                 continue
294
295             if (scope == "GLOBAL" and parameter['context'] != "G" or
296                 scope == "LOCAL" and parameter['context'] != "S"):
297                 continue
298
299             output_string = "\t"
300             param_type = mapping.get(parameter['type'])
301             if param_type is None:
302                 raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
303             output_string += param_type
304
305             output_string += "  %s;\n" % parameter['function']
306             file_out.write(output_string)
307
308         file_out.write("LOADPARM_EXTRA_%sS\n" % scope)
309         file_out.write("};\n")
310         file_out.write("\n#endif /* %s */\n\n" % header)
311     finally:
312         file_out.close()
313
314
315 type_dict = {
316               "boolean"      : "P_BOOL",
317               "boolean-rev"  : "P_BOOLREV",
318               "boolean-auto" : "P_ENUM",
319               "list"         : "P_LIST",
320               "string"       : "P_STRING",
321               "integer"      : "P_INTEGER",
322               "enum"         : "P_ENUM",
323               "char"         : "P_CHAR",
324               "cmdlist"      : "P_CMDLIST",
325               "bytes"        : "P_BYTES",
326               "octal"        : "P_OCTAL",
327               "ustring"      : "P_USTRING",
328             }
329
330
331 def make_param_table(path_in, path_out):
332     file_out = open(path_out, 'w')
333     try:
334         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
335         header = get_header(path_out)
336         file_out.write("#ifndef %s\n" % header)
337         file_out.write("#define %s\n\n" % header)
338
339         file_out.write("struct parm_struct parm_table[] = {\n")
340
341         for parameter in iterate_all(path_in):
342             # filter out parameteric options
343             if ':' in parameter['name']:
344                 continue
345             if parameter['context'] == 'G':
346                 p_class = "P_GLOBAL"
347             else:
348                 p_class = "P_LOCAL"
349
350             p_type = type_dict.get(parameter['type'])
351
352             if parameter['context'] == 'G':
353                 temp = "GLOBAL"
354             else:
355                 temp = "LOCAL"
356             offset = "%s_VAR(%s)" % (temp, parameter['function'])
357
358             enumlist = parameter['enumlist']
359             handler = parameter['handler']
360             synonym = parameter['synonym']
361             deprecated = parameter['deprecated']
362             flags_list = []
363             if synonym == "1":
364                 flags_list.append("FLAG_SYNONYM")
365             if deprecated == "1":
366                 flags_list.append("FLAG_DEPRECATED")
367             flags = "|".join(flags_list)
368             synonyms = parameter['synonyms']
369
370             file_out.write("\t{\n")
371             file_out.write("\t\t.label\t\t= \"%s\",\n" % parameter['name'])
372             file_out.write("\t\t.type\t\t= %s,\n" % p_type)
373             file_out.write("\t\t.p_class\t= %s,\n" % p_class)
374             file_out.write("\t\t.offset\t\t= %s,\n" % offset)
375             file_out.write("\t\t.special\t= %s,\n" % handler)
376             file_out.write("\t\t.enum_list\t= %s,\n" % enumlist)
377             if flags != "":
378                 file_out.write("\t\t.flags\t\t= %s,\n" % flags)
379             file_out.write("\t},\n")
380
381             if synonyms is not None:
382                 # for synonyms, we only list the synonym flag:
383                 flags = "FLAG_SYNONYM"
384                 for syn in synonyms:
385                     file_out.write("\t{\n")
386                     file_out.write("\t\t.label\t\t= \"%s\",\n" % syn.text)
387                     file_out.write("\t\t.type\t\t= %s,\n" % p_type)
388                     file_out.write("\t\t.p_class\t= %s,\n" % p_class)
389                     file_out.write("\t\t.offset\t\t= %s,\n" % offset)
390                     file_out.write("\t\t.special\t= %s,\n" % handler)
391                     file_out.write("\t\t.enum_list\t= %s,\n" % enumlist)
392                     if flags != "":
393                         file_out.write("\t\t.flags\t\t= %s,\n" % flags)
394                     file_out.write("\t},\n")
395
396         file_out.write("\n\t{ .label = NULL }\n")
397         file_out.write("};\n")
398         file_out.write("\n#endif /* %s */\n\n" % header)
399     finally:
400         file_out.close()
401
402
403 if options.mode == 'FUNCTIONS':
404     generate_functions(options.filename, options.output)
405 elif options.mode == 'S3PROTO':
406     make_s3_param_proto(options.filename, options.output)
407 elif options.mode == 'LIBPROTO':
408     make_lib_proto(options.filename, options.output)
409 elif options.mode == 'PARAMDEFS':
410     make_param_defs(options.filename, options.output, options.scope)
411 elif options.mode == 'PARAMTABLE':
412     make_param_table(options.filename, options.output)