glapi: Generate GL API marshalling code from the XML.
[mesa.git] / src / mapi / glapi / gen / gl_marshal.py
1 #!/usr/bin/env python
2
3 # Copyright (C) 2012 Intel Corporation
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice (including the next
13 # paragraph) shall be included in all copies or substantial portions of the
14 # Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 # IN THE SOFTWARE.
23
24 import contextlib
25 import getopt
26 import gl_XML
27 import license
28 import marshal_XML
29 import sys
30
31 header = """
32 #include "api_exec.h"
33 #include "context.h"
34 #include "dispatch.h"
35 #include "glthread.h"
36 #include "marshal.h"
37 #include "marshal_generated.h"
38 """
39
40
41 current_indent = 0
42
43
44 def out(str):
45 if str:
46 print ' '*current_indent + str
47 else:
48 print ''
49
50
51 @contextlib.contextmanager
52 def indent(delta = 3):
53 global current_indent
54 current_indent += delta
55 yield
56 current_indent -= delta
57
58
59 class PrintCode(gl_XML.gl_print_base):
60 def __init__(self):
61 super(PrintCode, self).__init__()
62
63 self.name = 'gl_marshal.py'
64 self.license = license.bsd_license_template % (
65 'Copyright (C) 2012 Intel Corporation', 'INTEL CORPORATION')
66
67 def printRealHeader(self):
68 print header
69 print '#include <X11/Xlib-xcb.h>'
70 print
71 print 'static _X_INLINE int safe_mul(int a, int b)'
72 print '{'
73 print ' if (a < 0 || b < 0) return -1;'
74 print ' if (a == 0 || b == 0) return 0;'
75 print ' if (a > INT_MAX / b) return -1;'
76 print ' return a * b;'
77 print '}'
78 print
79
80 def printRealFooter(self):
81 pass
82
83 def print_sync_call(self, func):
84 call = 'CALL_{0}(ctx->CurrentServerDispatch, ({1}))'.format(
85 func.name, func.get_called_parameter_string())
86 if func.return_type == 'void':
87 out('{0};'.format(call))
88 else:
89 out('return {0};'.format(call))
90
91 def print_sync_dispatch(self, func):
92 out('_mesa_glthread_finish(ctx);')
93 self.print_sync_call(func)
94
95 def print_sync_body(self, func):
96 out('/* {0}: marshalled synchronously */'.format(func.name))
97 out('static {0} GLAPIENTRY'.format(func.return_type))
98 out('_mesa_marshal_{0}({1})'.format(func.name, func.get_parameter_string()))
99 out('{')
100 with indent():
101 out('GET_CURRENT_CONTEXT(ctx);')
102 out('_mesa_glthread_finish(ctx);')
103 out('debug_print_sync("{0}");'.format(func.name))
104 self.print_sync_call(func)
105 out('}')
106 out('')
107 out('')
108
109 def print_async_dispatch(self, func):
110 out('cmd = _mesa_glthread_allocate_command(ctx, '
111 'DISPATCH_CMD_{0}, cmd_size);'.format(func.name))
112 for p in func.fixed_params:
113 if p.count:
114 out('memcpy(cmd->{0}, {0}, {1});'.format(
115 p.name, p.size_string()))
116 else:
117 out('cmd->{0} = {0};'.format(p.name))
118 if func.variable_params:
119 out('char *variable_data = (char *) (cmd + 1);')
120 for p in func.variable_params:
121 out(('memcpy(variable_data, {0}, {1});').format(
122 p.name, p.size_string(False)))
123 out('variable_data += {0};'.format(
124 p.size_string(False)))
125 if not func.fixed_params and not func.variable_params:
126 out('(void) cmd;\n')
127 out('_mesa_post_marshal_hook(ctx);')
128
129 def print_async_struct(self, func):
130 out('struct marshal_cmd_{0}'.format(func.name))
131 out('{')
132 with indent():
133 out('struct marshal_cmd_base cmd_base;')
134 for p in func.fixed_params:
135 if p.count:
136 out('{0} {1}[{2}];'.format(
137 p.get_base_type_string(), p.name, p.count))
138 else:
139 out('{0} {1};'.format(p.type_string(), p.name))
140 for p in func.variable_params:
141 if p.count_scale != 1:
142 out(('/* Next {0} bytes are '
143 '{1} {2}[{3}][{4}] */').format(
144 p.size_string(), p.get_base_type_string(),
145 p.name, p.counter, p.count_scale))
146 else:
147 out(('/* Next {0} bytes are '
148 '{1} {2}[{3}] */').format(
149 p.size_string(), p.get_base_type_string(),
150 p.name, p.counter))
151 out('};')
152
153 def print_async_unmarshal(self, func):
154 out('static inline void')
155 out(('_mesa_unmarshal_{0}(struct gl_context *ctx, '
156 'const struct marshal_cmd_{0} *cmd)').format(func.name))
157 out('{')
158 with indent():
159 for p in func.fixed_params:
160 if p.count:
161 out('const {0} * {1} = cmd->{1};'.format(
162 p.get_base_type_string(), p.name))
163 else:
164 out('const {0} {1} = cmd->{1};'.format(
165 p.type_string(), p.name))
166 if func.variable_params:
167 for p in func.variable_params:
168 out('const {0} * {1};'.format(
169 p.get_base_type_string(), p.name))
170 out('const char *variable_data = (const char *) (cmd + 1);')
171 for p in func.variable_params:
172 out('{0} = (const {1} *) variable_data;'.format(
173 p.name, p.get_base_type_string()))
174 out('variable_data += {0};'.format(p.size_string(False)))
175 self.print_sync_call(func)
176 out('}')
177
178 def print_async_marshal(self, func):
179 out('static void GLAPIENTRY')
180 out('_mesa_marshal_{0}({1})'.format(
181 func.name, func.get_parameter_string()))
182 out('{')
183 with indent():
184 out('GET_CURRENT_CONTEXT(ctx);')
185 struct = 'struct marshal_cmd_{0}'.format(func.name)
186 size_terms = ['sizeof({0})'.format(struct)]
187 for p in func.variable_params:
188 size_terms.append(p.size_string())
189 out('size_t cmd_size = {0};'.format(' + '.join(size_terms)))
190 out('{0} *cmd;'.format(struct))
191
192 out('debug_print_marshal("{0}");'.format(func.name))
193
194 out('if (cmd_size <= MARSHAL_MAX_CMD_SIZE) {')
195 with indent():
196 self.print_async_dispatch(func)
197 out('} else {')
198 with indent():
199 self.print_sync_dispatch(func)
200 out('}')
201
202 out('}')
203
204 def print_async_body(self, func):
205 out('/* {0}: marshalled asynchronously */'.format(func.name))
206 self.print_async_struct(func)
207 self.print_async_unmarshal(func)
208 self.print_async_marshal(func)
209 out('')
210 out('')
211
212 def print_unmarshal_dispatch_cmd(self, api):
213 out('size_t')
214 out('_mesa_unmarshal_dispatch_cmd(struct gl_context *ctx, '
215 'const void *cmd)')
216 out('{')
217 with indent():
218 out('const struct marshal_cmd_base *cmd_base = cmd;')
219 out('switch (cmd_base->cmd_id) {')
220 for func in api.functionIterateAll():
221 flavor = func.marshal_flavor()
222 if flavor in ('skip', 'sync'):
223 continue
224 out('case DISPATCH_CMD_{0}:'.format(func.name))
225 with indent():
226 out('debug_print_unmarshal("{0}");'.format(func.name))
227 out(('_mesa_unmarshal_{0}(ctx, (const struct marshal_cmd_{0} *)'
228 ' cmd);').format(func.name))
229 out('break;')
230 out('default:')
231 with indent():
232 out('assert(!"Unrecognized command ID");')
233 out('break;')
234 out('}')
235 out('')
236 out('return cmd_base->cmd_size;')
237 out('}')
238 out('')
239 out('')
240
241 def print_create_marshal_table(self, api):
242 out('struct _glapi_table *')
243 out('_mesa_create_marshal_table(const struct gl_context *ctx)')
244 out('{')
245 with indent():
246 out('struct _glapi_table *table;')
247 out('')
248 out('table = _mesa_alloc_dispatch_table();')
249 out('if (table == NULL)')
250 with indent():
251 out('return NULL;')
252 out('')
253 for func in api.functionIterateAll():
254 if func.marshal_flavor() == 'skip':
255 continue
256 out('SET_{0}(table, _mesa_marshal_{0});'.format(func.name))
257 out('')
258 out('return table;')
259 out('}')
260 out('')
261 out('')
262
263 def printBody(self, api):
264 async_funcs = []
265 for func in api.functionIterateAll():
266 flavor = func.marshal_flavor()
267 if flavor in ('skip', 'custom'):
268 continue
269 elif flavor == 'async':
270 self.print_async_body(func)
271 async_funcs.append(func)
272 elif flavor == 'sync':
273 self.print_sync_body(func)
274 self.print_unmarshal_dispatch_cmd(api)
275 self.print_create_marshal_table(api)
276
277
278 def show_usage():
279 print 'Usage: %s [-f input_file_name]' % sys.argv[0]
280 sys.exit(1)
281
282
283 if __name__ == '__main__':
284 file_name = 'gl_API.xml'
285
286 try:
287 (args, trail) = getopt.getopt(sys.argv[1:], 'm:f:')
288 except Exception,e:
289 show_usage()
290
291 for (arg,val) in args:
292 if arg == '-f':
293 file_name = val
294
295 printer = PrintCode()
296
297 api = gl_XML.parse_GL_API(file_name, marshal_XML.marshal_item_factory())
298 printer.Print(api)