blob: 610e25edf154f99187dba759364815feefa25f4b [file] [log] [blame]
Tobin Ehlis12076fc2014-10-22 09:06:33 -06001#!/usr/bin/env python3
2#
3# XGL
4#
5# Copyright (C) 2014 LunarG, Inc.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a
8# copy of this software and associated documentation files (the "Software"),
9# to deal in the Software without restriction, including without limitation
10# the rights to use, copy, modify, merge, publish, distribute, sublicense,
11# and/or sell copies of the Software, and to permit persons to whom the
12# Software is furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included
15# in all copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23# DEALINGS IN THE SOFTWARE.
24#
25# Authors:
26# Chia-I Wu <olv@lunarg.com>
27
28import sys
29
30import xgl
31
32class Subcommand(object):
33 def __init__(self, argv):
34 self.argv = argv
35 self.protos = ()
36 self.headers = ()
37
38 def run(self):
39 self.protos = xgl.core + xgl.ext_wsi_x11
40 self.headers = xgl.core_headers + xgl.ext_wsi_x11_headers
41 print(self.generate())
42
43 def generate(self):
44 copyright = self.generate_copyright()
45 header = self.generate_header()
46 body = self.generate_body()
47 footer = self.generate_footer()
48
49 contents = []
50 if copyright:
51 contents.append(copyright)
52 if header:
53 contents.append(header)
54 if body:
55 contents.append(body)
56 if footer:
57 contents.append(footer)
58
59 return "\n\n".join(contents)
60
61 def generate_copyright(self):
62 return """/* THIS FILE IS GENERATED. DO NOT EDIT. */
63
64/*
65 * XGL
66 *
67 * Copyright (C) 2014 LunarG, Inc.
68 *
69 * Permission is hereby granted, free of charge, to any person obtaining a
70 * copy of this software and associated documentation files (the "Software"),
71 * to deal in the Software without restriction, including without limitation
72 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
73 * and/or sell copies of the Software, and to permit persons to whom the
74 * Software is furnished to do so, subject to the following conditions:
75 *
76 * The above copyright notice and this permission notice shall be included
77 * in all copies or substantial portions of the Software.
78 *
79 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
80 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
81 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
82 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
83 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
84 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
85 * DEALINGS IN THE SOFTWARE.
86 */"""
87
88 def generate_header(self):
89 return "\n".join(["#include <" + h + ">" for h in self.headers])
90
91 def generate_body(self):
92 pass
93
94 def generate_footer(self):
95 pass
96
97 # Return set of printf '%' qualifier and input to that qualifier
98 def _get_printf_params(self, xgl_type, name, last_create):
99 # TODO : Need ENUM and STRUCT checks here
100 if "_TYPE" in xgl_type: # TODO : This should be generic ENUM check
101 return ("%s", "string_%s(%s)" % (xgl_type.strip('const ').strip('*'), name))
102 if "XGL_CHAR*" == xgl_type:
103 return ("%s", name)
104 if "UINT64" in xgl_type:
105 if '*' in xgl_type:
106 return ("%lu", "*%s" % name)
107 return ("%lu", name)
108 if "FLOAT" in xgl_type:
109 if '[' in xgl_type: # handle array, current hard-coded to 4 (TODO: Make this dynamic)
110 return ("[%f, %f, %f, %f]", "%s[0], %s[1], %s[2], %s[3]" % (name, name, name, name))
111 return ("%f", name)
112 if "BOOL" in xgl_type:
113 return ("%u", name)
114 if True in [t in xgl_type for t in ["INT", "SIZE", "FLAGS", "MASK"]]:
115 if '[' in xgl_type: # handle array, current hard-coded to 4 (TODO: Make this dynamic)
116 return ("[%i, %i, %i, %i]", "%s[0], %s[1], %s[2], %s[3]" % (name, name, name, name))
117 if '*' in xgl_type:
118 return ("%i", "*%s" % name)
119 return ("%i", name)
120 if last_create:
121 return ("%p", "(void*)*%s" % name)
122 return ("%p", "(void*)%s" % name)
123
124 def _generate_icd_dispatch_table(self):
125 proto_map = {}
126 for proto in self.protos:
127 proto_map[proto.name] = proto
128
129 entries = []
130 for name in xgl.icd_dispatch_table:
131 proto = proto_map[name]
132 entries.append(proto.c_typedef(attr="XGLAPI"))
133
134 return """struct icd_dispatch_table {
135 %s;
136};""" % ";\n ".join(entries)
137
138 def _generate_dispatch_entrypoints(self, qual="", layer="generic"):
139 if qual:
140 qual += " "
141
142 funcs = []
143 for proto in self.protos:
144 if proto.name != "GetProcAddr" and proto.name != "InitAndEnumerateGpus":
145 if "generic" == layer:
146 decl = proto.c_func(prefix="xgl", attr="XGLAPI")
147 param0_name = proto.params[0].name
148 ret_val = ''
149 stmt = ''
150 if proto.ret != "XGL_VOID":
151 ret_val = "XGL_RESULT result = "
152 stmt = " return result;\n"
153 if proto.params[0].ty != "XGL_PHYSICAL_GPU":
154 funcs.append('%s%s\n'
155 '{\n'
156 ' %snextTable.%s;\n'
157 '%s'
158 '}' % (qual, decl, ret_val, proto.c_call(), stmt))
159 else:
160 c_call = proto.c_call().replace("(" + proto.params[0].name, "((XGL_PHYSICAL_GPU)gpuw->nextObject", 1)
161 funcs.append('%s%s\n'
162 '{\n'
163 ' XGL_BASE_LAYER_OBJECT* gpuw = (XGL_BASE_LAYER_OBJECT *) %s;\n'
164 ' printf("At start of layered %s\\n");\n'
165 ' pCurObj = gpuw;\n'
166 ' pthread_once(&tabOnce, initLayerTable);\n'
167 ' %snextTable.%s;\n'
168 ' printf("Completed layered %s\\n");\n'
169 '%s'
170 '}' % (qual, decl, proto.params[0].name, proto.name, ret_val, c_call, proto.name, stmt))
171 elif "apidump" == layer:
172 decl = proto.c_func(prefix="xgl", attr="XGLAPI")
173 param0_name = proto.params[0].name
174 ret_val = ''
175 stmt = ''
176 cis_param_index = -1 # Store index when func has pCreateInfo param
177 create_func = False
178 if 'Create' in proto.name:
179 create_func = True
180 if proto.ret != "XGL_VOID":
181 ret_val = "XGL_RESULT result = "
182 stmt = " return result;\n"
183 log_func = 'printf("xgl%s(' % proto.name
184 print_vals = ''
185 pindex = 0
186 for p in proto.params:
187 if p.name == proto.params[-1].name and create_func: # last param of create func
188 (pft, pfi) = self._get_printf_params(p.ty, p.name, True)
189 else:
190 (pft, pfi) = self._get_printf_params(p.ty, p.name, False)
191 log_func += '%s = %s, ' % (p.name, pft)
192 print_vals += ', %s' % (pfi)
193 if "pCreateInfo" in p.name:
194 cis_param_index = pindex
195 pindex += 1
196 log_func = log_func.strip(', ')
197 if proto.ret != "XGL_VOID":
198 log_func += ') = %s\\n"'
199 print_vals += ', string_XGL_RESULT(result)'
200 else:
201 log_func += ')\\n"'
202 log_func = '%s%s);' % (log_func, print_vals)
203 if cis_param_index >= 0:
204 cis_print_func = 'xgl_print_%s' % (proto.params[cis_param_index].ty.strip('const ').strip('*').lower())
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600205 log_func += '\n char *pTmpStr = %s(pCreateInfo, " ");' % (cis_print_func)
206 log_func += '\n printf(" pCreateInfo (%p)\\n%s\\n", (void*)pCreateInfo, pTmpStr);'
207 log_func += '\n free(pTmpStr);'
Tobin Ehlis12076fc2014-10-22 09:06:33 -0600208 if proto.params[0].ty != "XGL_PHYSICAL_GPU":
209 funcs.append('%s%s\n'
210 '{\n'
211 ' %snextTable.%s;\n'
212 ' %s\n'
213 '%s'
214 '}' % (qual, decl, ret_val, proto.c_call(), log_func, stmt))
215 else:
216 c_call = proto.c_call().replace("(" + proto.params[0].name, "((XGL_PHYSICAL_GPU)gpuw->nextObject", 1)
217 funcs.append('%s%s\n'
218 '{\n'
219 ' XGL_BASE_LAYER_OBJECT* gpuw = (XGL_BASE_LAYER_OBJECT *) %s;\n'
220 ' pCurObj = gpuw;\n'
221 ' pthread_once(&tabOnce, initLayerTable);\n'
222 ' %snextTable.%s;\n'
223 ' %s\n'
224 '%s'
225 '}' % (qual, decl, proto.params[0].name, ret_val, c_call, log_func, stmt))
226 elif "objecttracker" == layer:
227 decl = proto.c_func(prefix="xgl", attr="XGLAPI")
228 param0_name = proto.params[0].name
229 create_line = ''
230 destroy_line = ''
231 using_line = ' ll_increment_use_count((XGL_VOID*)%s);\n printf("OBJ[%%llu] : USING %s object %%p (%%lu total uses)\\n", object_track_index++, (void*)%s, ll_get_obj_uses((XGL_VOID*)%s));\n' % (param0_name, param0_name, param0_name, param0_name)
232 if 'Create' in proto.name:
233 create_line = ' printf("OBJ[%%llu] : CREATE %s object %%p\\n", object_track_index++, (void*)*%s);\n ll_insert_obj((XGL_VOID*)*%s, "%s");\n' % (proto.params[-1].ty.strip('*'), proto.params[-1].name, proto.params[-1].name, proto.params[-1].ty.strip('*'))
234 if 'Destroy' in proto.name:
235 destroy_line = ' printf("OBJ[%%llu] : DESTROY %s object %%p\\n", object_track_index++, (void*)%s);\n ll_remove_obj((XGL_VOID*)%s);\n' % (param0_name, param0_name, param0_name)
236 using_line = ''
237 ret_val = ''
238 stmt = ''
239 if proto.ret != "XGL_VOID":
240 ret_val = "XGL_RESULT result = "
241 stmt = " return result;\n"
242 if proto.params[0].ty != "XGL_PHYSICAL_GPU":
243 funcs.append('%s%s\n'
244 '{\n'
245 '%s'
246 ' %snextTable.%s;\n'
247 '%s%s'
248 '%s'
249 '}' % (qual, decl, using_line, ret_val, proto.c_call(), create_line, destroy_line, stmt))
250 else:
251 c_call = proto.c_call().replace("(" + proto.params[0].name, "((XGL_PHYSICAL_GPU)gpuw->nextObject", 1)
252 funcs.append('%s%s\n'
253 '{\n'
254 ' XGL_BASE_LAYER_OBJECT* gpuw = (XGL_BASE_LAYER_OBJECT *) %s;\n'
255 '%s'
256 ' pCurObj = gpuw;\n'
257 ' pthread_once(&tabOnce, initLayerTable);\n'
258 ' %snextTable.%s;\n'
259 '%s%s'
260 '%s'
261 '}' % (qual, decl, proto.params[0].name, using_line, ret_val, c_call, create_line, destroy_line, stmt))
262
263 # TODO : Put this code somewhere so it gets called at the end if objects not deleted :
264 # // Report any remaining objects in LL
265 # objNode *pTrav = pObjLLHead;
266 # while (pTrav) {
267 # printf("WARN : %s object %p has not been destroyed.\n", pTrav->objType, pTrav->pObj);
268 # }
269
270 return "\n\n".join(funcs)
271
272 def _generate_layer_gpa_function(self, prefix="xgl"):
273 func_body = []
274 func_body.append("XGL_LAYER_EXPORT XGL_VOID* XGLAPI xglGetProcAddr(XGL_PHYSICAL_GPU gpu, const XGL_CHAR* funcName)\n"
275 "{\n"
276 " XGL_BASE_LAYER_OBJECT* gpuw = (XGL_BASE_LAYER_OBJECT *) gpu;\n"
277 " if (gpu == NULL)\n"
278 " return NULL;\n"
279 " pCurObj = gpuw;\n"
280 " pthread_once(&tabOnce, initLayerTable);\n\n"
281 ' if (!strncmp("xglGetProcAddr", (const char *) funcName, sizeof("xglGetProcAddr")))\n'
282 ' return xglGetProcAddr;')
283 for name in xgl.icd_dispatch_table:
284 if name == "GetProcAddr":
285 continue
286 if name == "InitAndEnumerateGpus":
287 func_body.append(' else if (!strncmp("%s%s", (const char *) funcName, sizeof("%s%s")))\n'
288 ' return nextTable.%s;' % (prefix, name, prefix, name, name))
289 else:
290 func_body.append(' else if (!strncmp("%s%s", (const char *) funcName, sizeof("%s%s")))\n'
291 ' return %s%s;' % (prefix, name, prefix, name, prefix, name))
292
293 func_body.append(" else {\n"
294 " XGL_BASE_LAYER_OBJECT* gpuw = (XGL_BASE_LAYER_OBJECT *) gpu;\n"
295 " if (gpuw->pGPA == NULL)\n"
296 " return NULL;\n"
297 " return gpuw->pGPA(gpuw->nextObject, funcName);\n"
298 " }\n"
299 "}\n")
300 return "\n".join(func_body)
301
302 def _generate_layer_dispatch_table(self, prefix='xgl'):
303 func_body = []
304 func_body.append('static void initLayerTable()\n'
305 '{\n'
306 ' GetProcAddrType fpNextGPA;\n'
307 ' fpNextGPA = pCurObj->pGPA;\n'
308 ' assert(fpNextGPA);\n');
309
310 for name in xgl.icd_dispatch_table:
311 func_body.append(' %sType fp%s = fpNextGPA((XGL_PHYSICAL_GPU) pCurObj->nextObject, (XGL_CHAR *) "%s%s");\n'
312 ' nextTable.%s = fp%s;' % (name, name, prefix, name, name, name))
313
314 func_body.append("}\n")
315 return "\n".join(func_body)
316
317class LayerFuncsSubcommand(Subcommand):
318 def generate_header(self):
319 return '#include <xglLayer.h>\n#include "loader.h"'
320
321 def generate_body(self):
322 return self._generate_dispatch_entrypoints("static", True)
323
324class LayerDispatchSubcommand(Subcommand):
325 def generate_header(self):
326 return '#include "layer_wrappers.h"'
327
328 def generate_body(self):
329 return self._generate_layer_dispatch_table()
330
331class GenericLayerSubcommand(Subcommand):
332 def generate_header(self):
333 return '#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <pthread.h>\n#include "xglLayer.h"\n\nstatic XGL_LAYER_DISPATCH_TABLE nextTable;\nstatic XGL_BASE_LAYER_OBJECT *pCurObj;\nstatic pthread_once_t tabOnce = PTHREAD_ONCE_INIT;\n'
334
335 def generate_body(self):
336 body = [self._generate_layer_dispatch_table(),
337 self._generate_dispatch_entrypoints("XGL_LAYER_EXPORT", "generic"),
338 self._generate_layer_gpa_function()]
339
340 return "\n\n".join(body)
341
342class ApiDumpSubcommand(Subcommand):
343 def generate_header(self):
344 return '#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <pthread.h>\n#include "xglLayer.h"\n#include "xgl_string_helper.h"\n#include "xgl_struct_string_helper.h"\n\nstatic XGL_LAYER_DISPATCH_TABLE nextTable;\nstatic XGL_BASE_LAYER_OBJECT *pCurObj;\nstatic pthread_once_t tabOnce = PTHREAD_ONCE_INIT;\n'
345
346 def generate_body(self):
347 body = [self._generate_layer_dispatch_table(),
348 self._generate_dispatch_entrypoints("XGL_LAYER_EXPORT", "apidump"),
349 self._generate_layer_gpa_function()]
350
351 return "\n\n".join(body)
352
353class ObjectTrackerSubcommand(Subcommand):
354 def generate_header(self):
355 header_txt = []
356 header_txt.append('#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <pthread.h>')
357 header_txt.append('#include "xglLayer.h"\n\nstatic XGL_LAYER_DISPATCH_TABLE nextTable;\nstatic XGL_BASE_LAYER_OBJECT *pCurObj;')
358 header_txt.append('static pthread_once_t tabOnce = PTHREAD_ONCE_INIT;\nstatic long long unsigned int object_track_index = 0;\n')
359 header_txt.append('typedef struct _objNode {')
360 header_txt.append(' XGL_VOID *pObj;')
361 header_txt.append(' const char *objType;')
362 header_txt.append(' uint64_t numUses;')
363 header_txt.append(' struct _objNode *pNext;')
364 header_txt.append('} objNode;\n')
365 header_txt.append('static objNode *pObjLLHead = NULL;\n')
366 header_txt.append('static void ll_insert_obj(XGL_VOID* pObj, const char* type) {')
367 header_txt.append(' objNode* pNewObjNode = (objNode*)malloc(sizeof(objNode));')
368 header_txt.append(' pNewObjNode->pObj = pObj;')
369 header_txt.append(' pNewObjNode->objType = type;')
370 header_txt.append(' pNewObjNode->numUses = 0;')
371 header_txt.append(' pNewObjNode->pNext = pObjLLHead;')
372 header_txt.append(' pObjLLHead = pNewObjNode;')
373 header_txt.append('}\n')
374 header_txt.append('static void ll_increment_use_count(XGL_VOID* pObj) {')
375 header_txt.append(' objNode *pTrav = pObjLLHead;')
376 header_txt.append(' while (pTrav) {')
377 header_txt.append(' if (pTrav->pObj == pObj) {')
378 header_txt.append(' pTrav->numUses++;')
379 header_txt.append(' return;')
380 header_txt.append(' }')
381 header_txt.append(' pTrav = pTrav->pNext;')
382 header_txt.append(' }')
383 header_txt.append(' // If we do not find obj, insert it and then intrement count')
384 header_txt.append(' printf("INFO : Unable to increment count for obj %p, will add to list as UNKNOWN type and increment count\\n", pObj);')
385 header_txt.append(' ll_insert_obj(pObj, "UNKNOWN");')
386 header_txt.append(' ll_increment_use_count(pObj);')
387 header_txt.append('}')
388 header_txt.append('static uint64_t ll_get_obj_uses(XGL_VOID* pObj) {')
389 header_txt.append(' objNode *pTrav = pObjLLHead;')
390 header_txt.append(' while (pTrav) {')
391 header_txt.append(' if (pTrav->pObj == pObj) {')
392 header_txt.append(' return pTrav->numUses;')
393 header_txt.append(' }')
394 header_txt.append(' pTrav = pTrav->pNext;')
395 header_txt.append(' }')
396 header_txt.append(' return 0;')
397 header_txt.append('}')
398 header_txt.append('static void ll_remove_obj(XGL_VOID* pObj) {')
399 header_txt.append(' objNode *pTrav = pObjLLHead;')
400 header_txt.append(' objNode *pPrev = pObjLLHead;')
401 header_txt.append(' while (pTrav) {')
402 header_txt.append(' if (pTrav->pObj == pObj) {')
403 header_txt.append(' pPrev->pNext = pTrav->pNext;')
404 header_txt.append(' if (pObjLLHead == pTrav)')
405 header_txt.append(' pObjLLHead = pTrav->pNext;')
406 header_txt.append(' printf("OBJ_STAT Removed %s obj %p that was used %lu times.\\n", pTrav->objType, pTrav->pObj, pTrav->numUses);')
407 header_txt.append(' free(pTrav);')
408 header_txt.append(' return;')
409 header_txt.append(' }')
410 header_txt.append(' pPrev = pTrav;')
411 header_txt.append(' pTrav = pTrav->pNext;')
412 header_txt.append(' }')
413 header_txt.append(' printf("ERROR : Unable to remove obj %p\\n", pObj);')
414 header_txt.append('}')
415
416 return "\n".join(header_txt)
417
418 def generate_body(self):
419 body = [self._generate_layer_dispatch_table(),
420 self._generate_dispatch_entrypoints("XGL_LAYER_EXPORT", "objecttracker"),
421 self._generate_layer_gpa_function()]
422
423 return "\n\n".join(body)
424
425def main():
426 subcommands = {
427 "layer-funcs" : LayerFuncsSubcommand,
428 "layer-dispatch" : LayerDispatchSubcommand,
429 "generic-layer" : GenericLayerSubcommand,
430 "api-dump" : ApiDumpSubcommand,
431 "object-tracker" : ObjectTrackerSubcommand,
432 }
433
434 if len(sys.argv) < 2 or sys.argv[1] not in subcommands:
435 print("Usage: %s <subcommand> [options]" % sys.argv[0])
436 print
437 print("Available sucommands are: %s" % " ".join(subcommands))
438 exit(1)
439
440 subcmd = subcommands[sys.argv[1]](sys.argv[2:])
441 subcmd.run()
442
443if __name__ == "__main__":
444 main()