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