glthread: check the size of all variable params and clean up the code
[mesa.git] / src / mapi / glapi / gen / gl_marshal.py
1
2 # Copyright (C) 2012 Intel Corporation
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining a
5 # copy of this software and associated documentation files (the "Software"),
6 # to deal in the Software without restriction, including without limitation
7 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Software, and to permit persons to whom the
9 # Software is furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice (including the next
12 # paragraph) shall be included in all copies or substantial portions of the
13 # Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 # IN THE SOFTWARE.
22
23 from __future__ import print_function
24
25 import contextlib
26 import getopt
27 import gl_XML
28 import license
29 import marshal_XML
30 import sys
31
32 header = """
33 #include "api_exec.h"
34 #include "context.h"
35 #include "dispatch.h"
36 #include "glthread.h"
37 #include "marshal.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('static inline int safe_mul(int a, int b)')
70 print('{')
71 print(' if (a < 0 || b < 0) return -1;')
72 print(' if (a == 0 || b == 0) return 0;')
73 print(' if (a > INT_MAX / b) return -1;')
74 print(' return a * b;')
75 print('}')
76 print()
77
78 def printRealFooter(self):
79 pass
80
81 def print_sync_call(self, func):
82 call = 'CALL_{0}(ctx->CurrentServerDispatch, ({1}))'.format(
83 func.name, func.get_called_parameter_string())
84 if func.return_type == 'void':
85 out('{0};'.format(call))
86 else:
87 out('return {0};'.format(call))
88
89 def print_sync_dispatch(self, func):
90 self.print_sync_call(func)
91
92 def print_sync_body(self, func):
93 out('/* {0}: marshalled synchronously */'.format(func.name))
94 out('static {0} GLAPIENTRY'.format(func.return_type))
95 out('_mesa_marshal_{0}({1})'.format(func.name, func.get_parameter_string()))
96 out('{')
97 with indent():
98 out('GET_CURRENT_CONTEXT(ctx);')
99 out('_mesa_glthread_finish_before(ctx, "{0}");'.format(func.name))
100 self.print_sync_call(func)
101 out('}')
102 out('')
103 out('')
104
105 def print_async_dispatch(self, func):
106 out('cmd = _mesa_glthread_allocate_command(ctx, '
107 'DISPATCH_CMD_{0}, cmd_size);'.format(func.name))
108 for p in func.fixed_params:
109 if p.count:
110 out('memcpy(cmd->{0}, {0}, {1});'.format(
111 p.name, p.size_string()))
112 else:
113 out('cmd->{0} = {0};'.format(p.name))
114 if func.variable_params:
115 out('char *variable_data = (char *) (cmd + 1);')
116 i = 1
117 for p in func.variable_params:
118 if p.img_null_flag:
119 out('cmd->{0}_null = !{0};'.format(p.name))
120 out('if (!cmd->{0}_null) {{'.format(p.name))
121 with indent():
122 out(('memcpy(variable_data, {0}, {0}_size);').format(p.name))
123 if i < len(func.variable_params):
124 out('variable_data += {0}_size;'.format(p.name))
125 out('}')
126 else:
127 out(('memcpy(variable_data, {0}, {0}_size);').format(p.name))
128 if i < len(func.variable_params):
129 out('variable_data += {0}_size;'.format(p.name))
130 i += 1
131
132 if not func.fixed_params and not func.variable_params:
133 out('(void) cmd;\n')
134
135 # Uncomment this if you want to call _mesa_glthread_finish for debugging
136 #out('_mesa_glthread_finish(ctx);')
137
138 def print_async_struct(self, func):
139 out('struct marshal_cmd_{0}'.format(func.name))
140 out('{')
141 with indent():
142 out('struct marshal_cmd_base cmd_base;')
143 for p in func.fixed_params:
144 if p.count:
145 out('{0} {1}[{2}];'.format(
146 p.get_base_type_string(), p.name, p.count))
147 else:
148 out('{0} {1};'.format(p.type_string(), p.name))
149
150 for p in func.variable_params:
151 if p.img_null_flag:
152 out('bool {0}_null; /* If set, no data follows '
153 'for "{0}" */'.format(p.name))
154
155 for p in func.variable_params:
156 if p.count_scale != 1:
157 out(('/* Next {0} bytes are '
158 '{1} {2}[{3}][{4}] */').format(
159 p.size_string(), p.get_base_type_string(),
160 p.name, p.counter, p.count_scale))
161 else:
162 out(('/* Next {0} bytes are '
163 '{1} {2}[{3}] */').format(
164 p.size_string(), p.get_base_type_string(),
165 p.name, p.counter))
166 out('};')
167
168 def print_async_unmarshal(self, func):
169 out('static inline void')
170 out(('_mesa_unmarshal_{0}(struct gl_context *ctx, '
171 'const struct marshal_cmd_{0} *cmd)').format(func.name))
172 out('{')
173 with indent():
174 for p in func.fixed_params:
175 if p.count:
176 p_decl = '{0} * {1} = cmd->{1};'.format(
177 p.get_base_type_string(), p.name)
178 else:
179 p_decl = '{0} {1} = cmd->{1};'.format(
180 p.type_string(), p.name)
181
182 if not p_decl.startswith('const '):
183 # Declare all local function variables as const, even if
184 # the original parameter is not const.
185 p_decl = 'const ' + p_decl
186
187 out(p_decl)
188
189 if func.variable_params:
190 for p in func.variable_params:
191 out('{0} * {1};'.format(
192 p.get_base_type_string(), p.name))
193 out('const char *variable_data = (const char *) (cmd + 1);')
194 i = 1
195 for p in func.variable_params:
196 out('{0} = ({1} *) variable_data;'.format(
197 p.name, p.get_base_type_string()))
198
199 if p.img_null_flag:
200 out('if (cmd->{0}_null)'.format(p.name))
201 with indent():
202 out('{0} = NULL;'.format(p.name))
203 if i < len(func.variable_params):
204 out('else')
205 with indent():
206 out('variable_data += {0};'.format(p.size_string(False)))
207 elif i < len(func.variable_params):
208 out('variable_data += {0};'.format(p.size_string(False)))
209 i += 1
210
211 self.print_sync_call(func)
212 out('}')
213
214 def validate_count_or_fallback(self, func):
215 # Check that any counts for variable-length arguments might be < 0, in
216 # which case the command alloc or the memcpy would blow up before we
217 # get to the validation in Mesa core.
218 list = []
219 for p in func.parameters:
220 if p.is_variable_length():
221 list.append('{0}_size < 0'.format(p.name))
222
223 if len(list) == 0:
224 return
225
226 list.append('(unsigned)cmd_size > MARSHAL_MAX_CMD_SIZE')
227
228 out('if (unlikely({0})) {{'.format(' || '.join(list)))
229 with indent():
230 out('_mesa_glthread_finish_before(ctx, "{0}");'.format(func.name))
231 self.print_sync_dispatch(func)
232 out('return;')
233 out('}')
234
235 def print_async_marshal(self, func):
236 out('static void GLAPIENTRY')
237 out('_mesa_marshal_{0}({1})'.format(
238 func.name, func.get_parameter_string()))
239 out('{')
240 with indent():
241 out('GET_CURRENT_CONTEXT(ctx);')
242 for p in func.variable_params:
243 out('int {0}_size = {1};'.format(p.name, p.size_string()))
244
245 struct = 'struct marshal_cmd_{0}'.format(func.name)
246 size_terms = ['sizeof({0})'.format(struct)]
247 for p in func.variable_params:
248 if p.img_null_flag:
249 size_terms.append('({0} ? {0}_size : 0)'.format(p.name))
250 else:
251 size_terms.append('{0}_size'.format(p.name))
252 out('int cmd_size = {0};'.format(' + '.join(size_terms)))
253 out('{0} *cmd;'.format(struct))
254
255 out('debug_print_marshal("{0}");'.format(func.name))
256
257 self.validate_count_or_fallback(func)
258
259 if func.marshal_fail:
260 out('if ({0}) {{'.format(func.marshal_fail))
261 with indent():
262 out('_mesa_glthread_disable(ctx, "{0}");'.format(func.name))
263 self.print_sync_dispatch(func)
264 out('return;')
265 out('}')
266
267 with indent():
268 self.print_async_dispatch(func)
269 out('}')
270
271 def print_async_body(self, func):
272 out('/* {0}: marshalled asynchronously */'.format(func.name))
273 self.print_async_struct(func)
274 self.print_async_unmarshal(func)
275 self.print_async_marshal(func)
276 out('')
277 out('')
278
279 def print_unmarshal_dispatch_cmd(self, api):
280 out('const _mesa_unmarshal_func _mesa_unmarshal_dispatch[NUM_DISPATCH_CMD] = {')
281 with indent():
282 for func in api.functionIterateAll():
283 flavor = func.marshal_flavor()
284 if flavor in ('skip', 'sync'):
285 continue
286 out('[DISPATCH_CMD_{0}] = (_mesa_unmarshal_func)_mesa_unmarshal_{0},'.format(func.name))
287 out('};')
288 out('')
289 out('')
290
291 def print_create_marshal_table(self, api):
292 out('struct _glapi_table *')
293 out('_mesa_create_marshal_table(const struct gl_context *ctx)')
294 out('{')
295 with indent():
296 out('struct _glapi_table *table;')
297 out('')
298 out('table = _mesa_alloc_dispatch_table();')
299 out('if (table == NULL)')
300 with indent():
301 out('return NULL;')
302 out('')
303 for func in api.functionIterateAll():
304 if func.marshal_flavor() == 'skip':
305 continue
306 out('SET_{0}(table, _mesa_marshal_{0});'.format(func.name))
307 out('')
308 out('return table;')
309 out('}')
310 out('')
311 out('')
312
313 def printBody(self, api):
314 async_funcs = []
315 for func in api.functionIterateAll():
316 flavor = func.marshal_flavor()
317 if flavor in ('skip', 'custom'):
318 continue
319 elif flavor == 'async':
320 self.print_async_body(func)
321 async_funcs.append(func)
322 elif flavor == 'sync':
323 self.print_sync_body(func)
324 self.print_unmarshal_dispatch_cmd(api)
325 self.print_create_marshal_table(api)
326
327
328 def show_usage():
329 print('Usage: %s [-f input_file_name]' % sys.argv[0])
330 sys.exit(1)
331
332
333 if __name__ == '__main__':
334 file_name = 'gl_API.xml'
335
336 try:
337 (args, trail) = getopt.getopt(sys.argv[1:], 'm:f:')
338 except Exception:
339 show_usage()
340
341 for (arg,val) in args:
342 if arg == '-f':
343 file_name = val
344
345 printer = PrintCode()
346
347 api = gl_XML.parse_GL_API(file_name, marshal_XML.marshal_item_factory())
348 printer.Print(api)