glthread: don't increment variable_data if it's the last variable-size param
[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}, {1});').format(
123 p.name, p.size_string(False)))
124 if i < len(func.variable_params):
125 out('variable_data += {0};'.format(
126 p.size_string(False)))
127 out('}')
128 else:
129 out(('memcpy(variable_data, {0}, {1});').format(
130 p.name, p.size_string(False)))
131 if i < len(func.variable_params):
132 out('variable_data += {0};'.format(
133 p.size_string(False)))
134 i += 1
135
136 if not func.fixed_params and not func.variable_params:
137 out('(void) cmd;\n')
138
139 # Uncomment this if you want to call _mesa_glthread_finish for debugging
140 #out('_mesa_glthread_finish(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 p_decl = '{0} * {1} = cmd->{1};'.format(
181 p.get_base_type_string(), p.name)
182 else:
183 p_decl = '{0} {1} = cmd->{1};'.format(
184 p.type_string(), p.name)
185
186 if not p_decl.startswith('const '):
187 # Declare all local function variables as const, even if
188 # the original parameter is not const.
189 p_decl = 'const ' + p_decl
190
191 out(p_decl)
192
193 if func.variable_params:
194 for p in func.variable_params:
195 out('{0} * {1};'.format(
196 p.get_base_type_string(), p.name))
197 out('const char *variable_data = (const char *) (cmd + 1);')
198 i = 1
199 for p in func.variable_params:
200 out('{0} = ({1} *) variable_data;'.format(
201 p.name, p.get_base_type_string()))
202
203 if p.img_null_flag:
204 out('if (cmd->{0}_null)'.format(p.name))
205 with indent():
206 out('{0} = NULL;'.format(p.name))
207 if i < len(func.variable_params):
208 out('else')
209 with indent():
210 out('variable_data += {0};'.format(p.size_string(False)))
211 elif i < len(func.variable_params):
212 out('variable_data += {0};'.format(p.size_string(False)))
213 i += 1
214
215 self.print_sync_call(func)
216 out('}')
217
218 def validate_count_or_fallback(self, func):
219 # Check that any counts for variable-length arguments might be < 0, in
220 # which case the command alloc or the memcpy would blow up before we
221 # get to the validation in Mesa core.
222 for p in func.parameters:
223 if p.is_variable_length():
224 out('if (unlikely({0} < 0)) {{'.format(p.size_string()))
225 with indent():
226 out('goto fallback_to_sync;')
227 out('}')
228 return True
229 return False
230
231
232 def print_async_marshal(self, func):
233 need_fallback_sync = False
234 out('static void GLAPIENTRY')
235 out('_mesa_marshal_{0}({1})'.format(
236 func.name, func.get_parameter_string()))
237 out('{')
238 with indent():
239 out('GET_CURRENT_CONTEXT(ctx);')
240 struct = 'struct marshal_cmd_{0}'.format(func.name)
241 size_terms = ['sizeof({0})'.format(struct)]
242 for p in func.variable_params:
243 size = p.size_string()
244 if p.img_null_flag:
245 size = '({0} ? {1} : 0)'.format(p.name, size)
246 size_terms.append(size)
247 out('int cmd_size = {0};'.format(' + '.join(size_terms)))
248 out('{0} *cmd;'.format(struct))
249
250 out('debug_print_marshal("{0}");'.format(func.name))
251
252 need_fallback_sync = self.validate_count_or_fallback(func)
253
254 if func.marshal_fail:
255 out('if ({0}) {{'.format(func.marshal_fail))
256 with indent():
257 out('_mesa_glthread_disable(ctx, "{0}");'.format(func.name))
258 self.print_sync_dispatch(func)
259 out('return;')
260 out('}')
261
262 if len(func.variable_params) > 0:
263 with indent():
264 out('if (cmd_size <= MARSHAL_MAX_CMD_SIZE) {')
265 with indent():
266 self.print_async_dispatch(func)
267 out('return;')
268 out('}')
269 out('')
270 if need_fallback_sync:
271 out('fallback_to_sync:')
272 with indent():
273 out('_mesa_glthread_finish_before(ctx, "{0}");'.format(func.name))
274 self.print_sync_dispatch(func)
275 else:
276 with indent():
277 self.print_async_dispatch(func)
278 assert not need_fallback_sync
279 out('}')
280
281 def print_async_body(self, func):
282 out('/* {0}: marshalled asynchronously */'.format(func.name))
283 self.print_async_struct(func)
284 self.print_async_unmarshal(func)
285 self.print_async_marshal(func)
286 out('')
287 out('')
288
289 def print_unmarshal_dispatch_cmd(self, api):
290 out('const _mesa_unmarshal_func _mesa_unmarshal_dispatch[NUM_DISPATCH_CMD] = {')
291 with indent():
292 for func in api.functionIterateAll():
293 flavor = func.marshal_flavor()
294 if flavor in ('skip', 'sync'):
295 continue
296 out('[DISPATCH_CMD_{0}] = (_mesa_unmarshal_func)_mesa_unmarshal_{0},'.format(func.name))
297 out('};')
298 out('')
299 out('')
300
301 def print_create_marshal_table(self, api):
302 out('struct _glapi_table *')
303 out('_mesa_create_marshal_table(const struct gl_context *ctx)')
304 out('{')
305 with indent():
306 out('struct _glapi_table *table;')
307 out('')
308 out('table = _mesa_alloc_dispatch_table();')
309 out('if (table == NULL)')
310 with indent():
311 out('return NULL;')
312 out('')
313 for func in api.functionIterateAll():
314 if func.marshal_flavor() == 'skip':
315 continue
316 out('SET_{0}(table, _mesa_marshal_{0});'.format(func.name))
317 out('')
318 out('return table;')
319 out('}')
320 out('')
321 out('')
322
323 def printBody(self, api):
324 async_funcs = []
325 for func in api.functionIterateAll():
326 flavor = func.marshal_flavor()
327 if flavor in ('skip', 'custom'):
328 continue
329 elif flavor == 'async':
330 self.print_async_body(func)
331 async_funcs.append(func)
332 elif flavor == 'sync':
333 self.print_sync_body(func)
334 self.print_unmarshal_dispatch_cmd(api)
335 self.print_create_marshal_table(api)
336
337
338 def show_usage():
339 print('Usage: %s [-f input_file_name]' % sys.argv[0])
340 sys.exit(1)
341
342
343 if __name__ == '__main__':
344 file_name = 'gl_API.xml'
345
346 try:
347 (args, trail) = getopt.getopt(sys.argv[1:], 'm:f:')
348 except Exception:
349 show_usage()
350
351 for (arg,val) in args:
352 if arg == '-f':
353 file_name = val
354
355 printer = PrintCode()
356
357 api = gl_XML.parse_GL_API(file_name, marshal_XML.marshal_item_factory())
358 printer.Print(api)