errors/gen_ntstatus: generate error codes in specified files
[sfrench/samba-autobuild/.git] / source4 / scripting / bin / gen_ntstatus.py
1 #!/usr/bin/env python
2
3 #
4 # Unix SMB/CIFS implementation.
5 #
6 # HRESULT Error definitions
7 #
8 # Copyright (C) Noel Power <noel.power@suse.com> 2014
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program 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
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23
24 import sys, os.path, io, string
25
26 # parsed error data
27 Errors = []
28
29 # error data model
30 class ErrorDef:
31
32     def __init__(self):
33         self.err_code = None
34         self.err_define = None
35         self.err_string = ""
36         self.linenum = ""
37
38 def escapeString( input ):
39     output = input.replace('"','\\"')
40     output = output.replace("\\<","\\\\<")
41     output = output.replace('\t',"")
42     return output
43
44 def transformErrorName( error_name ):
45     new_name = error_name
46     if error_name.startswith("STATUS_"):
47         error_name = error_name.replace("STATUS_","",1)
48     elif error_name.startswith("RPC_NT_"):
49         error_name = error_name.replace("RPC_NT_","RPC_",1)
50     elif error_name.startswith("EPT_NT_"):
51         error_name = error_name.replace("EPT_NT_","EPT_",1)
52     new_name = "NT_STATUS_" + error_name
53     return new_name
54
55 def parseErrorDescriptions( file_contents, isWinError ):
56     count = 0
57     for line in file_contents:
58         if line == None or line == '\t' or line == "" or line == '\n':
59             continue
60         content = line.strip().split(None,1)
61         # start new error definition ?
62         if line.startswith("0x"):
63             newError = ErrorDef()
64             newError.err_code = int(content[0],0)
65             # escape the usual suspects
66             if len(content) > 1:
67                 newError.err_string = escapeString(content[1])
68             newError.linenum = count
69             newError.isWinError = isWinError
70             Errors.append(newError)
71         else:
72             if len(Errors) == 0:
73                 # It's the license
74                 continue
75             err = Errors[-1]
76             if err.err_define == None:
77                 err.err_define = transformErrorName(content[0])
78             else:
79                 if len(content) > 0:
80                     desc =  escapeString(line.strip())
81                     if len(desc):
82                         if err.err_string == "":
83                             err.err_string = desc
84                         else:
85                             err.err_string = err.err_string + " " + desc
86             count = count + 1
87     print "parsed %d lines generated %d error definitions"%(count,len(Errors))
88
89 def generateHeaderFile(out_file):
90     out_file.write("/*\n")
91     out_file.write(" * Descriptions for errors generated from\n")
92     out_file.write(" * [MS-ERREF] http://msdn.microsoft.com/en-us/library/cc704588.aspx\n")
93     out_file.write(" */\n\n")
94     out_file.write("#ifndef _NTSTATUS_GEN_H\n")
95     out_file.write("#define _NTSTATUS_GEN_H\n")
96     for err in Errors:
97         line = "#define %s NT_STATUS(%s)\n" % (err.err_define, hex(err.err_code))
98         out_file.write(line)
99     out_file.write("\n#endif /* _NTSTATUS_GEN_H */\n")
100
101 def generateSourceFile(out_file):
102     out_file.write("/*\n")
103     out_file.write(" * Names for errors generated from\n")
104     out_file.write(" * [MS-ERREF] http://msdn.microsoft.com/en-us/library/cc704588.aspx\n")
105     out_file.write(" */\n")
106
107     out_file.write("static const nt_err_code_struct nt_errs[] = \n")
108     out_file.write("{\n")
109     for err in Errors:
110         out_file.write("\t{ \"%s\", %s },\n" % (err.err_define, err.err_define))
111     out_file.write("{ 0, NT_STATUS(0) }\n")
112     out_file.write("};\n")
113
114     out_file.write("\n/*\n")
115     out_file.write(" * Descriptions for errors generated from\n")
116     out_file.write(" * [MS-ERREF] http://msdn.microsoft.com/en-us/library/cc704588.aspx\n")
117     out_file.write(" */\n")
118
119     out_file.write("static const nt_err_code_struct nt_err_desc[] = \n")
120     out_file.write("{\n")
121     for err in Errors:
122         # Account for the possibility that some errors may not have descriptions
123         if err.err_string == "":
124             continue
125         out_file.write("\t{ N_(\"%s\"), %s },\n"%(err.err_string, err.err_define))
126     out_file.write("{ 0, NT_STATUS(0) }\n")
127     out_file.write("};")
128
129 def generatePythonFile(out_file):
130     out_file.write("/*\n")
131     out_file.write(" * New descriptions for existing errors generated from\n")
132     out_file.write(" * [MS-ERREF] http://msdn.microsoft.com/en-us/library/cc704588.aspx\n")
133     out_file.write(" */\n")
134     out_file.write("#include <Python.h>\n")
135     out_file.write("#include \"includes.h\"\n\n")
136     out_file.write("static inline PyObject *ndr_PyLong_FromUnsignedLongLong(unsigned long long v)\n");
137     out_file.write("{\n");
138     out_file.write("\tif (v > LONG_MAX) {\n");
139     out_file.write("\t\treturn PyLong_FromUnsignedLongLong(v);\n");
140     out_file.write("\t} else {\n");
141     out_file.write("\t\treturn PyInt_FromLong(v);\n");
142     out_file.write("\t}\n");
143     out_file.write("}\n\n");
144     # This is needed to avoid a missing prototype error from the C
145     # compiler. There is never a prototype for this function, it is a
146     # module loaded by python with dlopen() and found with dlsym().
147     out_file.write("void initntstatus(void);\n")
148     out_file.write("void initntstatus(void)\n")
149     out_file.write("{\n")
150     out_file.write("\tPyObject *m;\n\n")
151     out_file.write("\tm = Py_InitModule3(\"ntstatus\", NULL, \"NTSTATUS error defines\");\n");
152     out_file.write("\tif (m == NULL)\n");
153     out_file.write("\t\treturn;\n\n");
154     for err in Errors:
155         line = """\tPyModule_AddObject(m, \"%s\", 
156                   \t\tndr_PyLong_FromUnsignedLongLong(NT_STATUS_V(%s)));\n""" % (err.err_define, err.err_define)
157         out_file.write(line)
158     out_file.write("}\n");
159
160 # Very simple script to generate files nterr_gen.c & ntstatus_gen.h.
161 # These files contain generated definitions.
162 # This script takes four inputs:
163 # [1]: The name of the text file which is the content of an HTML table
164 #      (e.g. the one found at http://msdn.microsoft.com/en-us/library/cc231200.aspx)
165 #      copied and pasted.
166 # [2]: The name of the output generated header file with NTStatus #defines
167 # [3]: The name of the output generated source file with C arrays
168 # [4]: The name of the output generated python file
169 def main ():
170     input_file = None;
171
172     if len(sys.argv) == 5:
173         input_file =  sys.argv[1]
174         gen_headerfile_name = sys.argv[2]
175         gen_sourcefile_name = sys.argv[3]
176         gen_pythonfile_name = sys.argv[4]
177     else:
178         print "usage: %s winerrorfile headerfile sourcefile pythonfile" % (sys.argv[0])
179         sys.exit()
180
181     # read in the data
182     file_contents = open(input_file, "r")
183     parseErrorDescriptions(file_contents, False)
184
185     print "writing new header file: %s" % gen_headerfile_name
186     out_file = open(gen_headerfile_name, "w")
187     generateHeaderFile(out_file)
188     out_file.close()
189     print "writing new source file: %s" % gen_sourcefile_name
190     out_file = open(gen_sourcefile_name, "w")
191     generateSourceFile(out_file)
192     out_file.close()
193     print "writing new python file: %s" % gen_pythonfile_name
194     out_file = open(gen_pythonfile_name, "w")
195     generatePythonFile(out_file)
196     out_file.close()
197
198 if __name__ == '__main__':
199
200     main()