165275904ff920d657f6b16c4db2af047033818c
[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 if p.img_null_flag:
122 out('cmd->{0}_null = !{0};'.format(p.name))
123 out('if (!cmd->{0}_null) {{'.format(p.name))
124 with indent():
125 out(('memcpy(variable_data, {0}, {1});').format(
126 p.name, p.size_string(False)))
127 out('variable_data += {0};'.format(
128 p.size_string(False)))
129 out('}')
130 else:
131 out(('memcpy(variable_data, {0}, {1});').format(
132 p.name, p.size_string(False)))
133 out('variable_data += {0};'.format(
134 p.size_string(False)))
135
136 if not func.fixed_params and not func.variable_params:
137 out('(void) cmd;\n')
138 out('_mesa_post_marshal_hook(ctx);')
139
140 def print_async_struct(self, func):
141 out('struct marshal_cmd_{0}'.format(func.name))
142 out('{')
143 with indent():
144 out('struct marshal_cmd_base cmd_base;')
145 for p in func.fixed_params:
146 if p.count:
147 out('{0} {1}[{2}];'.format(
148 p.get_base_type_string(), p.name, p.count))
149 else:
150 out('{0} {1};'.format(p.type_string(), p.name))
151
152 for p in func.variable_params:
153 if p.img_null_flag:
154 out('bool {0}_null; /* If set, no data follows '
155 'for "{0}" */'.format(p.name))
156
157 for p in func.variable_params:
158 if p.count_scale != 1:
159 out(('/* Next {0} bytes are '
160 '{1} {2}[{3}][{4}] */').format(
161 p.size_string(), p.get_base_type_string(),
162 p.name, p.counter, p.count_scale))
163 else:
164 out(('/* Next {0} bytes are '
165 '{1} {2}[{3}] */').format(
166 p.size_string(), p.get_base_type_string(),
167 p.name, p.counter))
168 out('};')
169
170 def print_async_unmarshal(self, func):
171 out('static inline void')
172 out(('_mesa_unmarshal_{0}(struct gl_context *ctx, '
173 'const struct marshal_cmd_{0} *cmd)').format(func.name))
174 out('{')
175 with indent():
176 for p in func.fixed_params:
177 if p.count:
178 out('const {0} * {1} = cmd->{1};'.format(
179 p.get_base_type_string(), p.name))
180 else:
181 out('const {0} {1} = cmd->{1};'.format(
182 p.type_string(), p.name))
183 if func.variable_params:
184 for p in func.variable_params:
185 out('const {0} * {1};'.format(
186 p.get_base_type_string(), p.name))
187 out('const char *variable_data = (const char *) (cmd + 1);')
188 for p in func.variable_params:
189 out('{0} = (const {1} *) variable_data;'.format(
190 p.name, p.get_base_type_string()))
191
192 if p.img_null_flag:
193 out('if (cmd->{0}_null)'.format(p.name))
194 with indent():
195 out('{0} = NULL;'.format(p.name))
196 out('else')
197 with indent():
198 out('variable_data += {0};'.format(p.size_string(False)))
199 else:
200 out('variable_data += {0};'.format(p.size_string(False)))
201
202 self.print_sync_call(func)
203 out('}')
204
205 def validate_count_or_return(self, func):
206 # Check that any counts for variable-length arguments might be < 0, in
207 # which case the command alloc or the memcpy would blow up before we
208 # get to the validation in Mesa core.
209 for p in func.parameters:
210 if p.is_variable_length():
211 out('if (unlikely({0} < 0)) {{'.format(p.size_string()))
212 with indent():
213 out('_mesa_glthread_finish(ctx);')
214 out('_mesa_error(ctx, GL_INVALID_VALUE, "{0}({1} < 0)");'.format(func.name, p.size_string()))
215 out('return;')
216 out('}')
217
218 def print_async_marshal(self, func):
219 out('static void GLAPIENTRY')
220 out('_mesa_marshal_{0}({1})'.format(
221 func.name, func.get_parameter_string()))
222 out('{')
223 with indent():
224 out('GET_CURRENT_CONTEXT(ctx);')
225 struct = 'struct marshal_cmd_{0}'.format(func.name)
226 size_terms = ['sizeof({0})'.format(struct)]
227 for p in func.variable_params:
228 size = p.size_string()
229 if p.img_null_flag:
230 size = '({0} ? {1} : 0)'.format(p.name, size)
231 size_terms.append(size)
232 out('size_t cmd_size = {0};'.format(' + '.join(size_terms)))
233 out('{0} *cmd;'.format(struct))
234
235 out('debug_print_marshal("{0}");'.format(func.name))
236
237 self.validate_count_or_return(func)
238
239 if func.marshal_fail:
240 out('if ({0}) {{'.format(func.marshal_fail))
241 with indent():
242 out('_mesa_glthread_destroy(ctx);')
243 self.print_sync_dispatch(func)
244 out('return;')
245 out('}')
246
247 out('if (cmd_size <= MARSHAL_MAX_CMD_SIZE) {')
248 with indent():
249 self.print_async_dispatch(func)
250 out('} else {')
251 with indent():
252 self.print_sync_dispatch(func)
253 out('}')
254
255 out('}')
256
257 def print_async_body(self, func):
258 out('/* {0}: marshalled asynchronously */'.format(func.name))
259 self.print_async_struct(func)
260 self.print_async_unmarshal(func)
261 self.print_async_marshal(func)
262 out('')
263 out('')
264
265 def print_unmarshal_dispatch_cmd(self, api):
266 out('size_t')
267 out('_mesa_unmarshal_dispatch_cmd(struct gl_context *ctx, '
268 'const void *cmd)')
269 out('{')
270 with indent():
271 out('const struct marshal_cmd_base *cmd_base = cmd;')
272 out('switch (cmd_base->cmd_id) {')
273 for func in api.functionIterateAll():
274 flavor = func.marshal_flavor()
275 if flavor in ('skip', 'sync'):
276 continue
277 out('case DISPATCH_CMD_{0}:'.format(func.name))
278 with indent():
279 out('debug_print_unmarshal("{0}");'.format(func.name))
280 out(('_mesa_unmarshal_{0}(ctx, (const struct marshal_cmd_{0} *)'
281 ' cmd);').format(func.name))
282 out('break;')
283 out('default:')
284 with indent():
285 out('assert(!"Unrecognized command ID");')
286 out('break;')
287 out('}')
288 out('')
289 out('return cmd_base->cmd_size;')
290 out('}')
291 out('')
292 out('')
293
294 def print_create_marshal_table(self, api):
295 out('struct _glapi_table *')
296 out('_mesa_create_marshal_table(const struct gl_context *ctx)')
297 out('{')
298 with indent():
299 out('struct _glapi_table *table;')
300 out('')
301 out('table = _mesa_alloc_dispatch_table();')
302 out('if (table == NULL)')
303 with indent():
304 out('return NULL;')
305 out('')
306 for func in api.functionIterateAll():
307 if func.marshal_flavor() == 'skip':
308 continue
309 out('SET_{0}(table, _mesa_marshal_{0});'.format(func.name))
310 out('')
311 out('return table;')
312 out('}')
313 out('')
314 out('')
315
316 def printBody(self, api):
317 async_funcs = []
318 for func in api.functionIterateAll():
319 flavor = func.marshal_flavor()
320 if flavor in ('skip', 'custom'):
321 continue
322 elif flavor == 'async':
323 self.print_async_body(func)
324 async_funcs.append(func)
325 elif flavor == 'sync':
326 self.print_sync_body(func)
327 self.print_unmarshal_dispatch_cmd(api)
328 self.print_create_marshal_table(api)
329
330
331 def show_usage():
332 print 'Usage: %s [-f input_file_name]' % sys.argv[0]
333 sys.exit(1)
334
335
336 if __name__ == '__main__':
337 file_name = 'gl_API.xml'
338
339 try:
340 (args, trail) = getopt.getopt(sys.argv[1:], 'm:f:')
341 except Exception,e:
342 show_usage()
343
344 for (arg,val) in args:
345 if arg == '-f':
346 file_name = val
347
348 printer = PrintCode()
349
350 api = gl_XML.parse_GL_API(file_name, marshal_XML.marshal_item_factory())
351 printer.Print(api)