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