blob: fd88909cf7217f4d3948efdc6cd8bb3f9a6ae1b6 [file] [log] [blame]
Mark Lobodzinskiff910992016-10-11 14:29:52 -06001#!/usr/bin/python3 -i
2#
3# Copyright (c) 2015-2016 The Khronos Group Inc.
4# Copyright (c) 2015-2016 Valve Corporation
5# Copyright (c) 2015-2016 LunarG, Inc.
6# Copyright (c) 2015-2016 Google Inc.
7#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Mike Stroyan <stroyan@google.com>
Mark Lobodzinskid3b439e2017-06-07 13:08:41 -060021# Author: Mark Lobodzinski <mark@lunarg.com>
Mark Lobodzinskiff910992016-10-11 14:29:52 -060022
23import os,re,sys
24from generator import *
Mark Lobodzinski62f71562017-10-24 13:41:18 -060025from common_codegen import *
Mark Lobodzinskiff910992016-10-11 14:29:52 -060026
27# ThreadGeneratorOptions - subclass of GeneratorOptions.
28#
29# Adds options used by ThreadOutputGenerator objects during threading
30# layer generation.
31#
32# Additional members
33# prefixText - list of strings to prefix generated header with
34# (usually a copyright statement + calling convention macros).
35# protectFile - True if multiple inclusion protection should be
36# generated (based on the filename) around the entire header.
37# protectFeature - True if #ifndef..#endif protection should be
38# generated around a feature interface in the header file.
39# genFuncPointers - True if function pointer typedefs should be
40# generated
41# protectProto - If conditional protection should be generated
42# around prototype declarations, set to either '#ifdef'
43# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
44# to require opt-out (#ifndef protectProtoStr). Otherwise
45# set to None.
46# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
47# declarations, if protectProto is set
48# apicall - string to use for the function declaration prefix,
49# such as APICALL on Windows.
50# apientry - string to use for the calling convention macro,
51# in typedefs, such as APIENTRY.
52# apientryp - string to use for the calling convention macro
53# in function pointer typedefs, such as APIENTRYP.
54# indentFuncProto - True if prototype declarations should put each
55# parameter on a separate line
56# indentFuncPointer - True if typedefed function pointers should put each
57# parameter on a separate line
58# alignFuncParam - if nonzero and parameters are being put on a
59# separate line, align parameter names at the specified column
60class ThreadGeneratorOptions(GeneratorOptions):
61 def __init__(self,
62 filename = None,
63 directory = '.',
64 apiname = None,
65 profile = None,
66 versions = '.*',
67 emitversions = '.*',
68 defaultExtensions = None,
69 addExtensions = None,
70 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060071 emitExtensions = None,
Mark Lobodzinskiff910992016-10-11 14:29:52 -060072 sortProcedure = regSortFeatures,
73 prefixText = "",
74 genFuncPointers = True,
75 protectFile = True,
76 protectFeature = True,
Mark Lobodzinskiff910992016-10-11 14:29:52 -060077 apicall = '',
78 apientry = '',
79 apientryp = '',
80 indentFuncProto = True,
81 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060082 alignFuncParam = 0,
83 expandEnumerants = True):
Mark Lobodzinskiff910992016-10-11 14:29:52 -060084 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
85 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060086 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskiff910992016-10-11 14:29:52 -060087 self.prefixText = prefixText
88 self.genFuncPointers = genFuncPointers
89 self.protectFile = protectFile
90 self.protectFeature = protectFeature
Mark Lobodzinskiff910992016-10-11 14:29:52 -060091 self.apicall = apicall
92 self.apientry = apientry
93 self.apientryp = apientryp
94 self.indentFuncProto = indentFuncProto
95 self.indentFuncPointer = indentFuncPointer
96 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -060097 self.expandEnumerants = expandEnumerants
98
Mark Lobodzinskiff910992016-10-11 14:29:52 -060099
100# ThreadOutputGenerator - subclass of OutputGenerator.
101# Generates Thread checking framework
102#
103# ---- methods ----
104# ThreadOutputGenerator(errFile, warnFile, diagFile) - args as for
105# OutputGenerator. Defines additional internal state.
106# ---- methods overriding base class ----
107# beginFile(genOpts)
108# endFile()
109# beginFeature(interface, emit)
110# endFeature()
111# genType(typeinfo,name)
112# genStruct(typeinfo,name)
113# genGroup(groupinfo,name)
114# genEnum(enuminfo, name)
115# genCmd(cmdinfo)
116class ThreadOutputGenerator(OutputGenerator):
117 """Generate specified API interfaces in a specific style, such as a C header"""
118 # This is an ordered list of sections in the header file.
119 TYPE_SECTIONS = ['include', 'define', 'basetype', 'handle', 'enum',
120 'group', 'bitmask', 'funcpointer', 'struct']
121 ALL_SECTIONS = TYPE_SECTIONS + ['command']
122 def __init__(self,
123 errFile = sys.stderr,
124 warnFile = sys.stderr,
125 diagFile = sys.stdout):
126 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
127 # Internal state - accumulators for different inner block text
128 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
129 self.intercepts = []
130
131 # Check if the parameter passed in is a pointer to an array
132 def paramIsArray(self, param):
133 return param.attrib.get('len') is not None
134
135 # Check if the parameter passed in is a pointer
136 def paramIsPointer(self, param):
137 ispointer = False
138 for elem in param:
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600139 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
140 ispointer = True
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600141 return ispointer
Mark Lobodzinski60b77b32017-02-14 09:16:56 -0700142
143 # Check if an object is a non-dispatchable handle
144 def isHandleTypeNonDispatchable(self, handletype):
145 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
146 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
147 return True
148 else:
149 return False
150
151 # Check if an object is a dispatchable handle
152 def isHandleTypeDispatchable(self, handletype):
153 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
154 if handle is not None and handle.find('type').text == 'VK_DEFINE_HANDLE':
155 return True
156 else:
157 return False
158
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600159 def makeThreadUseBlock(self, cmd, functionprefix):
160 """Generate C function pointer typedef for <command> Element"""
161 paramdecl = ''
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600162 # Find and add any parameters that are thread unsafe
163 params = cmd.findall('param')
164 for param in params:
165 paramname = param.find('name')
166 if False: # self.paramIsPointer(param):
167 paramdecl += ' // not watching use of pointer ' + paramname.text + '\n'
168 else:
169 externsync = param.attrib.get('externsync')
170 if externsync == 'true':
171 if self.paramIsArray(param):
172 paramdecl += ' for (uint32_t index=0;index<' + param.attrib.get('len') + ';index++) {\n'
173 paramdecl += ' ' + functionprefix + 'WriteObject(my_data, ' + paramname.text + '[index]);\n'
174 paramdecl += ' }\n'
175 else:
176 paramdecl += ' ' + functionprefix + 'WriteObject(my_data, ' + paramname.text + ');\n'
177 elif (param.attrib.get('externsync')):
178 if self.paramIsArray(param):
179 # Externsync can list pointers to arrays of members to synchronize
180 paramdecl += ' for (uint32_t index=0;index<' + param.attrib.get('len') + ';index++) {\n'
181 for member in externsync.split(","):
182 # Replace first empty [] in member name with index
183 element = member.replace('[]','[index]',1)
184 if '[]' in element:
185 # Replace any second empty [] in element name with
186 # inner array index based on mapping array names like
187 # "pSomeThings[]" to "someThingCount" array size.
188 # This could be more robust by mapping a param member
189 # name to a struct type and "len" attribute.
190 limit = element[0:element.find('s[]')] + 'Count'
191 dotp = limit.rfind('.p')
192 limit = limit[0:dotp+1] + limit[dotp+2:dotp+3].lower() + limit[dotp+3:]
193 paramdecl += ' for(uint32_t index2=0;index2<'+limit+';index2++)\n'
194 element = element.replace('[]','[index2]')
195 paramdecl += ' ' + functionprefix + 'WriteObject(my_data, ' + element + ');\n'
196 paramdecl += ' }\n'
197 else:
198 # externsync can list members to synchronize
199 for member in externsync.split(","):
200 member = str(member).replace("::", "->")
Mark Lobodzinski9c147802017-02-10 08:34:54 -0700201 member = str(member).replace(".", "->")
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600202 paramdecl += ' ' + functionprefix + 'WriteObject(my_data, ' + member + ');\n'
203 else:
204 paramtype = param.find('type')
205 if paramtype is not None:
206 paramtype = paramtype.text
207 else:
208 paramtype = 'None'
Mark Lobodzinski60b77b32017-02-14 09:16:56 -0700209 if (self.isHandleTypeDispatchable(paramtype) or self.isHandleTypeNonDispatchable(paramtype)) and paramtype != 'VkPhysicalDevice':
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600210 if self.paramIsArray(param) and ('pPipelines' != paramname.text):
Mark Lobodzinski9c147802017-02-10 08:34:54 -0700211 # Add pointer dereference for array counts that are pointer values
212 dereference = ''
213 for candidate in params:
214 if param.attrib.get('len') == candidate.find('name').text:
215 if self.paramIsPointer(candidate):
216 dereference = '*'
Mark Lobodzinski60b77b32017-02-14 09:16:56 -0700217 param_len = str(param.attrib.get('len')).replace("::", "->")
218 paramdecl += ' for (uint32_t index = 0; index < ' + dereference + param_len + '; index++) {\n'
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600219 paramdecl += ' ' + functionprefix + 'ReadObject(my_data, ' + paramname.text + '[index]);\n'
220 paramdecl += ' }\n'
221 elif not self.paramIsPointer(param):
222 # Pointer params are often being created.
223 # They are not being read from.
224 paramdecl += ' ' + functionprefix + 'ReadObject(my_data, ' + paramname.text + ');\n'
225 explicitexternsyncparams = cmd.findall("param[@externsync]")
226 if (explicitexternsyncparams is not None):
227 for param in explicitexternsyncparams:
228 externsyncattrib = param.attrib.get('externsync')
229 paramname = param.find('name')
230 paramdecl += ' // Host access to '
231 if externsyncattrib == 'true':
232 if self.paramIsArray(param):
233 paramdecl += 'each member of ' + paramname.text
234 elif self.paramIsPointer(param):
235 paramdecl += 'the object referenced by ' + paramname.text
236 else:
237 paramdecl += paramname.text
238 else:
239 paramdecl += externsyncattrib
240 paramdecl += ' must be externally synchronized\n'
241
242 # Find and add any "implicit" parameters that are thread unsafe
243 implicitexternsyncparams = cmd.find('implicitexternsyncparams')
244 if (implicitexternsyncparams is not None):
245 for elem in implicitexternsyncparams:
246 paramdecl += ' // '
247 paramdecl += elem.text
248 paramdecl += ' must be externally synchronized between host accesses\n'
249
250 if (paramdecl == ''):
251 return None
252 else:
253 return paramdecl
254 def beginFile(self, genOpts):
255 OutputGenerator.beginFile(self, genOpts)
256 # C-specific
257 #
258 # Multiple inclusion protection & C++ namespace.
259 if (genOpts.protectFile and self.genOpts.filename):
260 headerSym = '__' + re.sub('\.h', '_h_', os.path.basename(self.genOpts.filename))
261 write('#ifndef', headerSym, file=self.outFile)
262 write('#define', headerSym, '1', file=self.outFile)
263 self.newline()
264 write('namespace threading {', file=self.outFile)
265 self.newline()
266 #
267 # User-supplied prefix text, if any (list of strings)
268 if (genOpts.prefixText):
269 for s in genOpts.prefixText:
270 write(s, file=self.outFile)
271 def endFile(self):
272 # C-specific
273 # Finish C++ namespace and multiple inclusion protection
274 self.newline()
275 # record intercepted procedures
Mark Lobodzinskid3b439e2017-06-07 13:08:41 -0600276 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
277 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600278 write('\n'.join(self.intercepts), file=self.outFile)
279 write('};\n', file=self.outFile)
280 self.newline()
281 write('} // namespace threading', file=self.outFile)
282 if (self.genOpts.protectFile and self.genOpts.filename):
283 self.newline()
284 write('#endif', file=self.outFile)
285 # Finish processing in superclass
286 OutputGenerator.endFile(self)
287 def beginFeature(self, interface, emit):
288 #write('// starting beginFeature', file=self.outFile)
289 # Start processing in superclass
290 OutputGenerator.beginFeature(self, interface, emit)
291 # C-specific
292 # Accumulate includes, defines, types, enums, function pointer typedefs,
293 # end function prototypes separately for this feature. They're only
294 # printed in endFeature().
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600295 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600296 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
297 #write('// ending beginFeature', file=self.outFile)
298 def endFeature(self):
299 # C-specific
300 # Actually write the interface to the output file.
301 #write('// starting endFeature', file=self.outFile)
302 if (self.emit):
303 self.newline()
304 if (self.genOpts.protectFeature):
305 write('#ifndef', self.featureName, file=self.outFile)
306 # If type declarations are needed by other features based on
307 # this one, it may be necessary to suppress the ExtraProtect,
308 # or move it below the 'for section...' loop.
309 #write('// endFeature looking at self.featureExtraProtect', file=self.outFile)
310 if (self.featureExtraProtect != None):
311 write('#ifdef', self.featureExtraProtect, file=self.outFile)
312 #write('#define', self.featureName, '1', file=self.outFile)
313 for section in self.TYPE_SECTIONS:
314 #write('// endFeature writing section'+section, file=self.outFile)
315 contents = self.sections[section]
316 if contents:
317 write('\n'.join(contents), file=self.outFile)
318 self.newline()
319 #write('// endFeature looking at self.sections[command]', file=self.outFile)
320 if (self.sections['command']):
Jamie Madill24aa9742016-12-13 17:02:57 -0500321 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600322 self.newline()
323 if (self.featureExtraProtect != None):
324 write('#endif /*', self.featureExtraProtect, '*/', file=self.outFile)
325 if (self.genOpts.protectFeature):
326 write('#endif /*', self.featureName, '*/', file=self.outFile)
327 # Finish processing in superclass
328 OutputGenerator.endFeature(self)
329 #write('// ending endFeature', file=self.outFile)
330 #
331 # Append a definition to the specified section
332 def appendSection(self, section, text):
333 # self.sections[section].append('SECTION: ' + section + '\n')
334 self.sections[section].append(text)
335 #
336 # Type generation
337 def genType(self, typeinfo, name):
338 pass
339 #
340 # Struct (e.g. C "struct" type) generation.
341 # This is a special case of the <type> tag where the contents are
342 # interpreted as a set of <member> tags instead of freeform C
343 # C type declarations. The <member> tags are just like <param>
344 # tags - they are a declaration of a struct or union member.
345 # Only simple member declarations are supported (no nested
346 # structs etc.)
347 def genStruct(self, typeinfo, typeName):
348 OutputGenerator.genStruct(self, typeinfo, typeName)
349 body = 'typedef ' + typeinfo.elem.get('category') + ' ' + typeName + ' {\n'
350 # paramdecl = self.makeCParamDecl(typeinfo.elem, self.genOpts.alignFuncParam)
351 for member in typeinfo.elem.findall('.//member'):
352 body += self.makeCParamDecl(member, self.genOpts.alignFuncParam)
353 body += ';\n'
354 body += '} ' + typeName + ';\n'
355 self.appendSection('struct', body)
356 #
357 # Group (e.g. C "enum" type) generation.
358 # These are concatenated together with other types.
359 def genGroup(self, groupinfo, groupName):
360 pass
361 # Enumerant generation
362 # <enum> tags may specify their values in several ways, but are usually
363 # just integers.
364 def genEnum(self, enuminfo, name):
365 pass
366 #
367 # Command generation
368 def genCmd(self, cmdinfo, name):
369 # Commands shadowed by interface functions and are not implemented
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600370 special_functions = [
371 'vkGetDeviceProcAddr',
372 'vkGetInstanceProcAddr',
373 'vkCreateDevice',
374 'vkDestroyDevice',
375 'vkCreateInstance',
376 'vkDestroyInstance',
377 'vkAllocateCommandBuffers',
378 'vkFreeCommandBuffers',
379 'vkCreateDebugReportCallbackEXT',
380 'vkDestroyDebugReportCallbackEXT',
Mark Lobodzinski3bd82ad2017-02-16 11:45:27 -0700381 'vkAllocateDescriptorSets',
Mark Lobodzinskidf47c5a2017-02-28 15:09:31 -0700382 'vkGetSwapchainImagesKHR',
Mark Lobodzinskid3b439e2017-06-07 13:08:41 -0600383 'vkEnumerateInstanceLayerProperties',
384 'vkEnumerateInstanceExtensionProperties',
385 'vkEnumerateDeviceLayerProperties',
386 'vkEnumerateDeviceExtensionProperties',
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600387 ]
388 if name in special_functions:
389 decls = self.makeCDecls(cmdinfo.elem)
390 self.appendSection('command', '')
391 self.appendSection('command', '// declare only')
392 self.appendSection('command', decls[0])
Mark Lobodzinskid3b439e2017-06-07 13:08:41 -0600393 self.intercepts += [ ' {"%s", (void*)%s},' % (name,name[2:]) ]
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600394 return
Mark Lobodzinski9c147802017-02-10 08:34:54 -0700395 if "QueuePresentKHR" in name or ("DebugMarker" in name and "EXT" in name):
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600396 self.appendSection('command', '// TODO - not wrapping EXT function ' + name)
397 return
398 # Determine first if this function needs to be intercepted
399 startthreadsafety = self.makeThreadUseBlock(cmdinfo.elem, 'start')
400 if startthreadsafety is None:
401 return
402 finishthreadsafety = self.makeThreadUseBlock(cmdinfo.elem, 'finish')
403 # record that the function will be intercepted
404 if (self.featureExtraProtect != None):
405 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
Mark Lobodzinskid3b439e2017-06-07 13:08:41 -0600406 self.intercepts += [ ' {"%s", (void*)%s},' % (name,name[2:]) ]
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600407 if (self.featureExtraProtect != None):
408 self.intercepts += [ '#endif' ]
409
410 OutputGenerator.genCmd(self, cmdinfo, name)
411 #
412 decls = self.makeCDecls(cmdinfo.elem)
413 self.appendSection('command', '')
414 self.appendSection('command', decls[0][:-1])
415 self.appendSection('command', '{')
416 # setup common to call wrappers
417 # first parameter is always dispatchable
418 dispatchable_type = cmdinfo.elem.find('param/type').text
419 dispatchable_name = cmdinfo.elem.find('param/name').text
420 self.appendSection('command', ' dispatch_key key = get_dispatch_key('+dispatchable_name+');')
Tobin Ehlis8d6acde2017-02-08 07:40:40 -0700421 self.appendSection('command', ' layer_data *my_data = GetLayerDataPtr(key, layer_data_map);')
Mark Lobodzinskiff910992016-10-11 14:29:52 -0600422 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
423 self.appendSection('command', ' VkLayerInstanceDispatchTable *pTable = my_data->instance_dispatch_table;')
424 else:
425 self.appendSection('command', ' VkLayerDispatchTable *pTable = my_data->device_dispatch_table;')
426 # Declare result variable, if any.
427 resulttype = cmdinfo.elem.find('proto/type')
428 if (resulttype != None and resulttype.text == 'void'):
429 resulttype = None
430 if (resulttype != None):
431 self.appendSection('command', ' ' + resulttype.text + ' result;')
432 assignresult = 'result = '
433 else:
434 assignresult = ''
435
436 self.appendSection('command', ' bool threadChecks = startMultiThread();')
437 self.appendSection('command', ' if (threadChecks) {')
438 self.appendSection('command', " "+"\n ".join(str(startthreadsafety).rstrip().split("\n")))
439 self.appendSection('command', ' }')
440 params = cmdinfo.elem.findall('param/name')
441 paramstext = ','.join([str(param.text) for param in params])
442 API = cmdinfo.elem.attrib.get('name').replace('vk','pTable->',1)
443 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
444 self.appendSection('command', ' if (threadChecks) {')
445 self.appendSection('command', " "+"\n ".join(str(finishthreadsafety).rstrip().split("\n")))
446 self.appendSection('command', ' } else {')
447 self.appendSection('command', ' finishMultiThread();')
448 self.appendSection('command', ' }')
449 # Return result variable, if any.
450 if (resulttype != None):
451 self.appendSection('command', ' return result;')
452 self.appendSection('command', '}')
453 #
454 # override makeProtoName to drop the "vk" prefix
455 def makeProtoName(self, name, tail):
456 return self.genOpts.apientry + name[2:] + tail