blob: abe8df4baf01e8e89fcf7693f2f1ce6799c5e08a [file] [log] [blame]
Mark Lobodzinskia509c292016-10-11 14:33:07 -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: Tobin Ehlis <tobine@google.com>
21# Author: Mark Lobodzinski <mark@lunarg.com>
22
23import os,re,sys
24import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060027from common_codegen import *
Mark Lobodzinskia509c292016-10-11 14:33:07 -060028
29# UniqueObjectsGeneratorOptions - subclass of GeneratorOptions.
30#
31# Adds options used by UniqueObjectsOutputGenerator objects during
32# unique objects layer generation.
33#
34# Additional members
35# prefixText - list of strings to prefix generated header with
36# (usually a copyright statement + calling convention macros).
37# protectFile - True if multiple inclusion protection should be
38# generated (based on the filename) around the entire header.
39# protectFeature - True if #ifndef..#endif protection should be
40# generated around a feature interface in the header file.
41# genFuncPointers - True if function pointer typedefs should be
42# generated
43# protectProto - If conditional protection should be generated
44# around prototype declarations, set to either '#ifdef'
45# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
46# to require opt-out (#ifndef protectProtoStr). Otherwise
47# set to None.
48# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
49# declarations, if protectProto is set
50# apicall - string to use for the function declaration prefix,
51# such as APICALL on Windows.
52# apientry - string to use for the calling convention macro,
53# in typedefs, such as APIENTRY.
54# apientryp - string to use for the calling convention macro
55# in function pointer typedefs, such as APIENTRYP.
56# indentFuncProto - True if prototype declarations should put each
57# parameter on a separate line
58# indentFuncPointer - True if typedefed function pointers should put each
59# parameter on a separate line
60# alignFuncParam - if nonzero and parameters are being put on a
61# separate line, align parameter names at the specified column
62class UniqueObjectsGeneratorOptions(GeneratorOptions):
63 def __init__(self,
64 filename = None,
65 directory = '.',
66 apiname = None,
67 profile = None,
68 versions = '.*',
69 emitversions = '.*',
70 defaultExtensions = None,
71 addExtensions = None,
72 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060073 emitExtensions = None,
Mark Lobodzinskia509c292016-10-11 14:33:07 -060074 sortProcedure = regSortFeatures,
75 prefixText = "",
76 genFuncPointers = True,
77 protectFile = True,
78 protectFeature = True,
Mark Lobodzinskia509c292016-10-11 14:33:07 -060079 apicall = '',
80 apientry = '',
81 apientryp = '',
82 indentFuncProto = True,
83 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060084 alignFuncParam = 0,
85 expandEnumerants = True):
Mark Lobodzinskia509c292016-10-11 14:33:07 -060086 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
87 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060088 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskia509c292016-10-11 14:33:07 -060089 self.prefixText = prefixText
90 self.genFuncPointers = genFuncPointers
91 self.protectFile = protectFile
92 self.protectFeature = protectFeature
Mark Lobodzinskia509c292016-10-11 14:33:07 -060093 self.apicall = apicall
94 self.apientry = apientry
95 self.apientryp = apientryp
96 self.indentFuncProto = indentFuncProto
97 self.indentFuncPointer = indentFuncPointer
Mark Lobodzinski62f71562017-10-24 13:41:18 -060098 self.alignFuncParam = alignFuncParam
99 self.expandEnumerants = expandEnumerants
100
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600101
102# UniqueObjectsOutputGenerator - subclass of OutputGenerator.
103# Generates unique objects layer non-dispatchable handle-wrapping code.
104#
105# ---- methods ----
106# UniqueObjectsOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
107# ---- methods overriding base class ----
108# beginFile(genOpts)
109# endFile()
110# beginFeature(interface, emit)
111# endFeature()
112# genCmd(cmdinfo)
113# genStruct()
114# genType()
115class UniqueObjectsOutputGenerator(OutputGenerator):
116 """Generate UniqueObjects code based on XML element attributes"""
117 # This is an ordered list of sections in the header file.
118 ALL_SECTIONS = ['command']
119 def __init__(self,
120 errFile = sys.stderr,
121 warnFile = sys.stderr,
122 diagFile = sys.stdout):
123 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
124 self.INDENT_SPACES = 4
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600125 self.intercepts = []
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700126 self.instance_extensions = []
127 self.device_extensions = []
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600128 # Commands which are not autogenerated but still intercepted
129 self.no_autogen_list = [
Jamie Madill24aa9742016-12-13 17:02:57 -0500130 'vkGetDeviceProcAddr',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600131 'vkGetInstanceProcAddr',
132 'vkCreateInstance',
133 'vkDestroyInstance',
134 'vkCreateDevice',
135 'vkDestroyDevice',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600136 'vkCreateComputePipelines',
137 'vkCreateGraphicsPipelines',
138 'vkCreateSwapchainKHR',
Dustin Graves9a6eb052017-03-28 14:18:54 -0600139 'vkCreateSharedSwapchainsKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600140 'vkGetSwapchainImagesKHR',
Mark Lobodzinski1ce83f42018-02-16 09:58:07 -0700141 'vkDestroySwapchainKHR',
Chris Forbes0f507f22017-04-16 13:13:17 +1200142 'vkQueuePresentKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600143 'vkEnumerateInstanceLayerProperties',
144 'vkEnumerateDeviceLayerProperties',
145 'vkEnumerateInstanceExtensionProperties',
Mark Lobodzinskiab9a8752017-10-25 16:56:42 -0600146 'vkCreateDescriptorUpdateTemplate',
Mark Lobodzinski71703a52017-03-03 08:40:16 -0700147 'vkCreateDescriptorUpdateTemplateKHR',
Mark Lobodzinskiab9a8752017-10-25 16:56:42 -0600148 'vkDestroyDescriptorUpdateTemplate',
Mark Lobodzinski71703a52017-03-03 08:40:16 -0700149 'vkDestroyDescriptorUpdateTemplateKHR',
Mark Lobodzinskiab9a8752017-10-25 16:56:42 -0600150 'vkUpdateDescriptorSetWithTemplate',
Mark Lobodzinski71703a52017-03-03 08:40:16 -0700151 'vkUpdateDescriptorSetWithTemplateKHR',
152 'vkCmdPushDescriptorSetWithTemplateKHR',
Mark Lobodzinskia096c122017-03-16 11:54:35 -0600153 'vkDebugMarkerSetObjectTagEXT',
154 'vkDebugMarkerSetObjectNameEXT',
Petr Krause91f7a12017-12-14 20:57:36 +0100155 'vkCreateRenderPass',
156 'vkDestroyRenderPass',
Mark Young6ba8abe2017-11-09 10:37:04 -0700157 'vkSetDebugUtilsObjectNameEXT',
158 'vkSetDebugUtilsObjectTagEXT',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600159 ]
160 # Commands shadowed by interface functions and are not implemented
161 self.interface_functions = [
162 'vkGetPhysicalDeviceDisplayPropertiesKHR',
163 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
164 'vkGetDisplayPlaneSupportedDisplaysKHR',
165 'vkGetDisplayModePropertiesKHR',
Norbert Nopper1dec9a52016-11-25 07:55:13 +0100166 'vkGetDisplayPlaneCapabilitiesKHR',
Mark Young6ba8abe2017-11-09 10:37:04 -0700167 # VK_EXT_debug_report APIs are hooked, but handled separately in the source file
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600168 'vkCreateDebugReportCallbackEXT',
169 'vkDestroyDebugReportCallbackEXT',
170 'vkDebugReportMessageEXT',
Mark Young6ba8abe2017-11-09 10:37:04 -0700171 # VK_EXT_debug_utils APIs are hooked, but handled separately in the source file
172 'vkCreateDebugUtilsMessengerEXT',
173 'vkDestroyDebugUtilsMessengerEXT',
174 'vkSubmitDebugUtilsMessageEXT',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600175 ]
176 self.headerVersion = None
177 # Internal state - accumulators for different inner block text
178 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600179
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600180 self.cmdMembers = []
181 self.cmd_feature_protect = [] # Save ifdef's for each command
Mark Lobodzinski85904632017-04-06 10:07:42 -0600182 self.cmd_info_data = [] # Save the cmdinfo data for wrapping the handles when processing is complete
183 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
184 self.extension_structs = [] # List of all structs or sister-structs containing handles
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600185 # A sister-struct may contain no handles but shares a structextends attribute with one that does
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600186 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
187 self.struct_member_dict = dict()
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600188 # Named tuples to store struct and command data
Mark Lobodzinski85904632017-04-06 10:07:42 -0600189 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600190 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
191 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
192 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600193
194 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600195 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
196 #
197 def incIndent(self, indent):
198 inc = ' ' * self.INDENT_SPACES
199 if indent:
200 return indent + inc
201 return inc
202 #
203 def decIndent(self, indent):
204 if indent and (len(indent) > self.INDENT_SPACES):
205 return indent[:-self.INDENT_SPACES]
206 return ''
207 #
208 # Override makeProtoName to drop the "vk" prefix
209 def makeProtoName(self, name, tail):
210 return self.genOpts.apientry + name[2:] + tail
211 #
212 # Check if the parameter passed in is a pointer to an array
213 def paramIsArray(self, param):
214 return param.attrib.get('len') is not None
215 #
216 def beginFile(self, genOpts):
217 OutputGenerator.beginFile(self, genOpts)
218 # User-supplied prefix text, if any (list of strings)
219 if (genOpts.prefixText):
220 for s in genOpts.prefixText:
221 write(s, file=self.outFile)
222 # Namespace
223 self.newline()
224 write('namespace unique_objects {', file = self.outFile)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600225 # Now that the data is all collected and complete, generate and output the wrapping/unwrapping routines
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600226 def endFile(self):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600227
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600228 self.struct_member_dict = dict(self.structMembers)
229
230 # Generate the list of APIs that might need to handle wrapped extension structs
231 self.GenerateCommandWrapExtensionList()
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600232 # Write out wrapping/unwrapping functions
233 self.WrapCommands()
Mark Lobodzinski85904632017-04-06 10:07:42 -0600234 # Build and write out pNext processing function
235 extension_proc = self.build_extension_processing_func()
236 self.newline()
237 write('// Unique Objects pNext extension handling function', file=self.outFile)
238 write('%s' % extension_proc, file=self.outFile)
239
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600240 # Actually write the interface to the output file.
241 if (self.emit):
242 self.newline()
243 if (self.featureExtraProtect != None):
244 write('#ifdef', self.featureExtraProtect, file=self.outFile)
245 # Write the unique_objects code to the file
246 if (self.sections['command']):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600247 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
248 if (self.featureExtraProtect != None):
249 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
250 else:
251 self.newline()
252
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600253 # Record intercepted procedures
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600254 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
255 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600256 write('\n'.join(self.intercepts), file=self.outFile)
257 write('};\n', file=self.outFile)
258 self.newline()
259 write('} // namespace unique_objects', file=self.outFile)
260 # Finish processing in superclass
261 OutputGenerator.endFile(self)
262 #
263 def beginFeature(self, interface, emit):
264 # Start processing in superclass
265 OutputGenerator.beginFeature(self, interface, emit)
266 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600267 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600268 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700269 white_list_entry = []
270 if (self.featureExtraProtect != None):
271 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
272 white_list_entry += [ '"%s"' % self.featureName ]
273 if (self.featureExtraProtect != None):
274 white_list_entry += [ '#endif' ]
275 featureType = interface.get('type')
276 if featureType == 'instance':
277 self.instance_extensions += white_list_entry
278 elif featureType == 'device':
279 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600280 #
281 def endFeature(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600282 # Finish processing in superclass
283 OutputGenerator.endFeature(self)
284 #
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700285 def genType(self, typeinfo, name, alias):
286 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600287 typeElem = typeinfo.elem
288 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
289 # Otherwise, emit the tag text.
290 category = typeElem.get('category')
291 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700292 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600293 #
294 # Append a definition to the specified section
295 def appendSection(self, section, text):
296 # self.sections[section].append('SECTION: ' + section + '\n')
297 self.sections[section].append(text)
298 #
299 # Check if the parameter passed in is a pointer
300 def paramIsPointer(self, param):
301 ispointer = False
302 for elem in param:
303 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
304 ispointer = True
305 return ispointer
306 #
307 # Get the category of a type
308 def getTypeCategory(self, typename):
309 types = self.registry.tree.findall("types/type")
310 for elem in types:
311 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
312 return elem.attrib.get('category')
313 #
314 # Check if a parent object is dispatchable or not
315 def isHandleTypeNonDispatchable(self, handletype):
316 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
317 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
318 return True
319 else:
320 return False
321 #
322 # Retrieve the type and name for a parameter
323 def getTypeNameTuple(self, param):
324 type = ''
325 name = ''
326 for elem in param:
327 if elem.tag == 'type':
328 type = noneStr(elem.text)
329 elif elem.tag == 'name':
330 name = noneStr(elem.text)
331 return (type, name)
332 #
333 # Retrieve the value of the len tag
334 def getLen(self, param):
335 result = None
336 len = param.attrib.get('len')
337 if len and len != 'null-terminated':
338 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
339 # have a null terminated array of strings. We strip the null-terminated from the
340 # 'len' field and only return the parameter specifying the string count
341 if 'null-terminated' in len:
342 result = len.split(',')[0]
343 else:
344 result = len
345 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
346 result = str(result).replace('::', '->')
347 return result
348 #
349 # Generate a VkStructureType based on a structure typename
350 def genVkStructureType(self, typename):
351 # Add underscore between lowercase then uppercase
352 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
353 # Change to uppercase
354 value = value.upper()
355 # Add STRUCTURE_TYPE_
356 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
357 #
358 # Struct parameter check generation.
359 # This is a special case of the <type> tag where the contents are interpreted as a set of
360 # <member> tags instead of freeform C type declarations. The <member> tags are just like
361 # <param> tags - they are a declaration of a struct or union member. Only simple member
362 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700363 def genStruct(self, typeinfo, typeName, alias):
364 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600365 members = typeinfo.elem.findall('.//member')
366 # Iterate over members once to get length parameters for arrays
367 lens = set()
368 for member in members:
369 len = self.getLen(member)
370 if len:
371 lens.add(len)
372 # Generate member info
373 membersInfo = []
374 for member in members:
375 # Get the member's type and name
376 info = self.getTypeNameTuple(member)
377 type = info[0]
378 name = info[1]
379 cdecl = self.makeCParamDecl(member, 0)
380 # Process VkStructureType
381 if type == 'VkStructureType':
382 # Extract the required struct type value from the comments
383 # embedded in the original text defining the 'typeinfo' element
384 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
385 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
386 if result:
387 value = result.group(0)
388 else:
389 value = self.genVkStructureType(typeName)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600390 # Store the required type value
391 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600392 # Store pointer/array/string info
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600393 extstructs = self.registry.validextensionstructs[typeName] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600394 membersInfo.append(self.CommandParam(type=type,
395 name=name,
396 ispointer=self.paramIsPointer(member),
397 isconst=True if 'const' in cdecl else False,
398 iscount=True if name in lens else False,
399 len=self.getLen(member),
Mark Lobodzinski85904632017-04-06 10:07:42 -0600400 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600401 cdecl=cdecl,
402 islocal=False,
403 iscreate=False,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600404 isdestroy=False,
405 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600406 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
Mark Lobodzinski85904632017-04-06 10:07:42 -0600407
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600408 #
409 # Insert a lock_guard line
410 def lock_guard(self, indent):
411 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
412 #
413 # Determine if a struct has an NDO as a member or an embedded member
414 def struct_contains_ndo(self, struct_item):
415 struct_member_dict = dict(self.structMembers)
416 struct_members = struct_member_dict[struct_item]
417
418 for member in struct_members:
419 if self.isHandleTypeNonDispatchable(member.type):
420 return True
421 elif member.type in struct_member_dict:
422 if self.struct_contains_ndo(member.type) == True:
423 return True
424 return False
425 #
426 # Return list of struct members which contain, or which sub-structures contain
427 # an NDO in a given list of parameters or members
428 def getParmeterStructsWithNdos(self, item_list):
429 struct_list = set()
430 for item in item_list:
431 paramtype = item.find('type')
432 typecategory = self.getTypeCategory(paramtype.text)
433 if typecategory == 'struct':
434 if self.struct_contains_ndo(paramtype.text) == True:
435 struct_list.add(item)
436 return struct_list
437 #
438 # Return list of non-dispatchable objects from a given list of parameters or members
439 def getNdosInParameterList(self, item_list, create_func):
440 ndo_list = set()
441 if create_func == True:
442 member_list = item_list[0:-1]
443 else:
444 member_list = item_list
445 for item in member_list:
446 if self.isHandleTypeNonDispatchable(paramtype.text):
447 ndo_list.add(item)
448 return ndo_list
449 #
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600450 # Construct list of extension structs containing handles, or extension structs that share a structextends attribute
451 # WITH an extension struct containing handles. All extension structs in any pNext chain will have to be copied.
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600452 # TODO: make this recursive -- structs buried three or more levels deep are not searched for extensions
453 def GenerateCommandWrapExtensionList(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600454 for struct in self.structMembers:
455 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
456 found = False;
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600457 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600458 if item != '' and self.struct_contains_ndo(item) == True:
459 found = True
460 if found == True:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600461 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600462 if item != '' and item not in self.extension_structs:
463 self.extension_structs.append(item)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600464 #
465 # Returns True if a struct may have a pNext chain containing an NDO
466 def StructWithExtensions(self, struct_type):
467 if struct_type in self.struct_member_dict:
468 param_info = self.struct_member_dict[struct_type]
469 if (len(param_info) > 1) and param_info[1].extstructs is not None:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600470 for item in param_info[1].extstructs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600471 if item in self.extension_structs:
472 return True
473 return False
474 #
475 # Generate pNext handling function
476 def build_extension_processing_func(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600477 # Construct helper functions to build and free pNext extension chains
478 pnext_proc = ''
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700479 pnext_proc += 'void *CreateUnwrappedExtensionStructs(const void *pNext) {\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600480 pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
481 pnext_proc += ' void *head_pnext = NULL;\n'
482 pnext_proc += ' void *prev_ext_struct = NULL;\n'
483 pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
484 pnext_proc += ' while (cur_pnext != NULL) {\n'
485 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(cur_pnext);\n\n'
486 pnext_proc += ' switch (header->sType) {\n'
487 for item in self.extension_structs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600488 struct_info = self.struct_member_dict[item]
Mark Lobodzinski85904632017-04-06 10:07:42 -0600489 if struct_info[0].feature_protect is not None:
490 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
491 pnext_proc += ' case %s: {\n' % self.structTypes[item].value
Chris Forbes0f86c402017-05-02 18:36:39 -0700492 pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600493 pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
494 # Generate code to unwrap the handles
495 indent = ' '
496 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, 'safe_struct->', 0, False, False, False, False)
497 pnext_proc += tmp_pre
498 pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
499 pnext_proc += ' } break;\n'
500 if struct_info[0].feature_protect is not None:
501 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
502 pnext_proc += '\n'
503 pnext_proc += ' default:\n'
504 pnext_proc += ' break;\n'
505 pnext_proc += ' }\n\n'
506 pnext_proc += ' // Save pointer to the first structure in the pNext chain\n'
507 pnext_proc += ' head_pnext = (head_pnext ? head_pnext : cur_ext_struct);\n\n'
508 pnext_proc += ' // For any extension structure but the first, link the last struct\'s pNext to the current ext struct\n'
509 pnext_proc += ' if (prev_ext_struct) {\n'
510 pnext_proc += ' (reinterpret_cast<GenericHeader *>(prev_ext_struct))->pNext = cur_ext_struct;\n'
511 pnext_proc += ' }\n'
512 pnext_proc += ' prev_ext_struct = cur_ext_struct;\n\n'
513 pnext_proc += ' // Process the next structure in the chain\n'
514 pnext_proc += ' cur_pnext = const_cast<void *>(header->pNext);\n'
515 pnext_proc += ' }\n'
516 pnext_proc += ' return head_pnext;\n'
517 pnext_proc += '}\n\n'
518 pnext_proc += '// Free a pNext extension chain\n'
519 pnext_proc += 'void FreeUnwrappedExtensionStructs(void *head) {\n'
Gabríel Arthúr Péturssoneecaa4d2018-03-18 20:21:11 +0000520 pnext_proc += ' GenericHeader *curr_ptr = reinterpret_cast<GenericHeader *>(head);\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600521 pnext_proc += ' while (curr_ptr) {\n'
Gabríel Arthúr Péturssoneecaa4d2018-03-18 20:21:11 +0000522 pnext_proc += ' GenericHeader *header = curr_ptr;\n'
523 pnext_proc += ' curr_ptr = reinterpret_cast<GenericHeader *>(header->pNext);\n\n'
524 pnext_proc += ' switch (header->sType) {\n';
525 for item in self.extension_structs:
526 struct_info = self.struct_member_dict[item]
527 if struct_info[0].feature_protect is not None:
528 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
529 pnext_proc += ' case %s:\n' % self.structTypes[item].value
530 pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
531 pnext_proc += ' break;\n'
532 if struct_info[0].feature_protect is not None:
533 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
534 pnext_proc += '\n'
535 pnext_proc += ' default:\n'
536 pnext_proc += ' assert(0);\n'
537 pnext_proc += ' }\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600538 pnext_proc += ' }\n'
539 pnext_proc += '}\n'
540 return pnext_proc
541
542 #
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600543 # Generate source for creating a non-dispatchable object
544 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
545 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700546 handle_type = params[-1].find('type')
547 if self.isHandleTypeNonDispatchable(handle_type.text):
548 # Check for special case where multiple handles are returned
549 ndo_array = False
550 if cmd_info[-1].len is not None:
551 ndo_array = True;
552 handle_name = params[-1].find('name')
553 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
554 indent = self.incIndent(indent)
555 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
556 ndo_dest = '*%s' % handle_name.text
557 if ndo_array == True:
558 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600559 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700560 ndo_dest = '%s[index0]' % cmd_info[-1].name
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700561 create_ndo_code += '%s%s = WrapNew(%s);\n' % (indent, ndo_dest, ndo_dest)
Mark Young39389872017-01-19 21:10:49 -0700562 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600563 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700564 create_ndo_code += '%s}\n' % indent
565 indent = self.decIndent(indent)
566 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600567 return create_ndo_code
568 #
569 # Generate source for destroying a non-dispatchable object
570 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
571 destroy_ndo_code = ''
572 ndo_array = False
573 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
574 # Check for special case where multiple handles are returned
575 if cmd_info[-1].len is not None:
576 ndo_array = True;
577 param = -1
578 else:
579 param = -2
580 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
581 if ndo_array == True:
582 # This API is freeing an array of handles. Remove them from the unique_id map.
583 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
584 indent = self.incIndent(indent)
585 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
586 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
587 indent = self.incIndent(indent)
588 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
589 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700590 destroy_ndo_code += '%sunique_id_mapping.erase(unique_id);\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600591 indent = self.decIndent(indent);
592 destroy_ndo_code += '%s}\n' % indent
593 indent = self.decIndent(indent);
594 destroy_ndo_code += '%s}\n' % indent
595 else:
596 # Remove a single handle from the map
597 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
598 destroy_ndo_code += '%suint64_t %s_id = reinterpret_cast<uint64_t &>(%s);\n' % (indent, cmd_info[param].name, cmd_info[param].name)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700599 destroy_ndo_code += '%s%s = (%s)unique_id_mapping[%s_id];\n' % (indent, cmd_info[param].name, cmd_info[param].type, cmd_info[param].name)
600 destroy_ndo_code += '%sunique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600601 destroy_ndo_code += '%slock.unlock();\n' % (indent)
602 return ndo_array, destroy_ndo_code
603
604 #
605 # Clean up local declarations
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600606 def cleanUpLocalDeclarations(self, indent, prefix, name, len, index, process_pnext):
Mark Young26095c42017-05-09 13:19:04 -0600607 cleanup = '%sif (local_%s%s) {\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600608 if len is not None:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600609 if process_pnext:
610 cleanup += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, len, index)
611 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s[%s].pNext));\n' % (indent, prefix, name, index)
612 cleanup += '%s }\n' % indent
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600613 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
614 else:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600615 if process_pnext:
616 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s->pNext));\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600617 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
Mark Young26095c42017-05-09 13:19:04 -0600618 cleanup += "%s}\n" % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600619 return cleanup
620 #
621 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
622 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
623 decl_code = ''
624 pre_call_code = ''
625 post_call_code = ''
626 if ndo_count is not None:
627 if top_level == True:
628 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
629 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
630 indent = self.incIndent(indent)
631 if top_level == True:
632 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
633 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
634 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700635 pre_call_code += '%s local_%s%s[%s] = Unwrap(%s[%s]);\n' % (indent, prefix, ndo_name, index, ndo_name, index)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600636 else:
637 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
638 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700639 pre_call_code += '%s %s%s[%s] = Unwrap(%s%s[%s]);\n' % (indent, prefix, ndo_name, index, prefix, ndo_name, index)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600640 indent = self.decIndent(indent)
641 pre_call_code += '%s }\n' % indent
642 indent = self.decIndent(indent)
643 pre_call_code += '%s }\n' % indent
644 if top_level == True:
645 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
646 indent = self.incIndent(indent)
647 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
648 else:
649 if top_level == True:
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600650 if (destroy_func == False) or (destroy_array == True):
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700651 pre_call_code += '%s %s = Unwrap(%s);\n' % (indent, ndo_name, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600652 else:
653 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
654 # as part of the string and explicitly print it
655 fix = str(prefix).strip('local_');
656 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
657 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700658 pre_call_code += '%s %s%s = Unwrap(%s%s);\n' % (indent, prefix, ndo_name, fix, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600659 indent = self.decIndent(indent)
660 pre_call_code += '%s }\n' % indent
661 return decl_code, pre_call_code, post_call_code
662 #
663 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
664 # create_func means that this is API creates or allocates NDOs
665 # destroy_func indicates that this API destroys or frees NDOs
666 # destroy_array means that the destroy_func operated on an array of NDOs
667 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
668 decls = ''
669 pre_code = ''
670 post_code = ''
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600671 index = 'index%s' % str(array_index)
672 array_index += 1
673 # Process any NDOs in this structure and recurse for any sub-structs in this struct
674 for member in members:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600675 process_pnext = self.StructWithExtensions(member.type)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600676 # Handle NDOs
677 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500678 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600679 if (count_name is not None):
680 if first_level_param == False:
681 count_name = '%s%s' % (prefix, member.len)
682
683 if (first_level_param == False) or (create_func == False):
684 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
685 decls += tmp_decl
686 pre_code += tmp_pre
687 post_code += tmp_post
688 # Handle Structs that contain NDOs at some level
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600689 elif member.type in self.struct_member_dict:
690 # Structs at first level will have an NDO, OR, we need a safe_struct for the pnext chain
691 if self.struct_contains_ndo(member.type) == True or process_pnext:
692 struct_info = self.struct_member_dict[member.type]
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600693 # Struct Array
694 if member.len is not None:
695 # Update struct prefix
696 if first_level_param == True:
697 new_prefix = 'local_%s' % member.name
698 # Declare safe_VarType for struct
699 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
700 else:
701 new_prefix = '%s%s' % (prefix, member.name)
702 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
703 indent = self.incIndent(indent)
704 if first_level_param == True:
705 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
706 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
707 indent = self.incIndent(indent)
708 if first_level_param == True:
709 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600710 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700711 pre_code += '%s %s[%s].pNext = CreateUnwrappedExtensionStructs(%s[%s].pNext);\n' % (indent, new_prefix, index, new_prefix, index)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600712 local_prefix = '%s[%s].' % (new_prefix, index)
713 # Process sub-structs in this struct
714 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
715 decls += tmp_decl
716 pre_code += tmp_pre
717 post_code += tmp_post
718 indent = self.decIndent(indent)
719 pre_code += '%s }\n' % indent
720 indent = self.decIndent(indent)
721 pre_code += '%s }\n' % indent
722 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600723 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600724 # Single Struct
725 else:
726 # Update struct prefix
727 if first_level_param == True:
728 new_prefix = 'local_%s->' % member.name
729 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
730 else:
731 new_prefix = '%s%s->' % (prefix, member.name)
732 # Declare safe_VarType for struct
733 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
734 indent = self.incIndent(indent)
735 if first_level_param == True:
736 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
737 # Process sub-structs in this struct
738 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
739 decls += tmp_decl
740 pre_code += tmp_pre
741 post_code += tmp_post
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600742 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700743 pre_code += '%s local_%s%s->pNext = CreateUnwrappedExtensionStructs(local_%s%s->pNext);\n' % (indent, prefix, member.name, prefix, member.name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600744 indent = self.decIndent(indent)
745 pre_code += '%s }\n' % indent
746 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600747 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600748 return decls, pre_code, post_code
749 #
750 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
751 def generate_wrapping_code(self, cmd):
752 indent = ' '
753 proto = cmd.find('proto/name')
754 params = cmd.findall('param')
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600755
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600756 if proto.text is not None:
757 cmd_member_dict = dict(self.cmdMembers)
758 cmd_info = cmd_member_dict[proto.text]
759 # Handle ndo create/allocate operations
760 if cmd_info[0].iscreate:
761 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
762 else:
763 create_ndo_code = ''
764 # Handle ndo destroy/free operations
765 if cmd_info[0].isdestroy:
766 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
767 else:
768 destroy_array = False
769 destroy_ndo_code = ''
770 paramdecl = ''
771 param_pre_code = ''
772 param_post_code = ''
773 create_func = True if create_ndo_code else False
774 destroy_func = True if destroy_ndo_code else False
775 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
776 param_post_code += create_ndo_code
777 if destroy_ndo_code:
778 if destroy_array == True:
779 param_post_code += destroy_ndo_code
780 else:
781 param_pre_code += destroy_ndo_code
782 if param_pre_code:
783 if (not destroy_func) or (destroy_array):
784 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
785 return paramdecl, param_pre_code, param_post_code
786 #
787 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700788 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600789
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600790 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700791 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600792 members = cmdinfo.elem.findall('.//param')
793 # Iterate over members once to get length parameters for arrays
794 lens = set()
795 for member in members:
796 len = self.getLen(member)
797 if len:
798 lens.add(len)
799 struct_member_dict = dict(self.structMembers)
800 # Generate member info
801 membersInfo = []
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600802 constains_extension_structs = False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600803 for member in members:
804 # Get type and name of member
805 info = self.getTypeNameTuple(member)
806 type = info[0]
807 name = info[1]
808 cdecl = self.makeCParamDecl(member, 0)
809 # Check for parameter name in lens set
810 iscount = True if name in lens else False
811 len = self.getLen(member)
812 isconst = True if 'const' in cdecl else False
813 ispointer = self.paramIsPointer(member)
814 # Mark param as local if it is an array of NDOs
815 islocal = False;
816 if self.isHandleTypeNonDispatchable(type) == True:
817 if (len is not None) and (isconst == True):
818 islocal = True
819 # Or if it's a struct that contains an NDO
820 elif type in struct_member_dict:
821 if self.struct_contains_ndo(type) == True:
822 islocal = True
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600823 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700824 iscreate = True if True in [create_txt in cmdname for create_txt in ['Create', 'Allocate', 'GetRandROutputDisplayEXT', 'RegisterDeviceEvent', 'RegisterDisplayEvent']] else False
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600825 extstructs = self.registry.validextensionstructs[type] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600826 membersInfo.append(self.CommandParam(type=type,
827 name=name,
828 ispointer=ispointer,
829 isconst=isconst,
830 iscount=iscount,
831 len=len,
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600832 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600833 cdecl=cdecl,
834 islocal=islocal,
835 iscreate=iscreate,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600836 isdestroy=isdestroy,
837 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600838 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600839 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
840 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
841 #
842 # Create code to wrap NDOs as well as handling some boilerplate code
843 def WrapCommands(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600844 cmd_member_dict = dict(self.cmdMembers)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600845 cmd_info_dict = dict(self.cmd_info_data)
846 cmd_protect_dict = dict(self.cmd_feature_protect)
847
848 for api_call in self.cmdMembers:
849 cmdname = api_call.name
850 cmdinfo = cmd_info_dict[api_call.name]
851 if cmdname in self.interface_functions:
852 continue
853 if cmdname in self.no_autogen_list:
854 decls = self.makeCDecls(cmdinfo.elem)
855 self.appendSection('command', '')
856 self.appendSection('command', '// Declare only')
857 self.appendSection('command', decls[0])
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600858 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600859 continue
860 # Generate NDO wrapping/unwrapping code for all parameters
861 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
862 # If API doesn't contain an NDO's, don't fool with it
863 if not api_decls and not api_pre and not api_post:
864 continue
865 feature_extra_protect = cmd_protect_dict[api_call.name]
866 if (feature_extra_protect != None):
867 self.appendSection('command', '')
868 self.appendSection('command', '#ifdef '+ feature_extra_protect)
869 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
870 # Add intercept to procmap
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600871 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600872 decls = self.makeCDecls(cmdinfo.elem)
873 self.appendSection('command', '')
874 self.appendSection('command', decls[0][:-1])
875 self.appendSection('command', '{')
876 # Setup common to call wrappers, first parameter is always dispatchable
877 dispatchable_type = cmdinfo.elem.find('param/type').text
878 dispatchable_name = cmdinfo.elem.find('param/name').text
879 # Generate local instance/pdev/device data lookup
Chris Forbes5279a8c2017-05-02 16:26:23 -0700880 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
881 self.appendSection('command', ' instance_layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), instance_layer_data_map);')
882 else:
883 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600884 # Handle return values, if any
885 resulttype = cmdinfo.elem.find('proto/type')
886 if (resulttype != None and resulttype.text == 'void'):
887 resulttype = None
888 if (resulttype != None):
889 assignresult = resulttype.text + ' result = '
890 else:
891 assignresult = ''
892 # Pre-pend declarations and pre-api-call codegen
893 if api_decls:
894 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
895 if api_pre:
896 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
897 # Generate the API call itself
898 # Gather the parameter items
899 params = cmdinfo.elem.findall('param/name')
900 # Pull out the text for each of the parameters, separate them by commas in a list
901 paramstext = ', '.join([str(param.text) for param in params])
902 # If any of these paramters has been replaced by a local var, fix up the list
903 params = cmd_member_dict[cmdname]
904 for param in params:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600905 if param.islocal == True or self.StructWithExtensions(param.type):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600906 if param.ispointer == True:
907 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
908 else:
909 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
910 # Use correct dispatch table
Chris Forbes44c05302017-05-02 16:42:55 -0700911 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->dispatch_table.',1)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600912 # Put all this together for the final down-chain call
913 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
914 # And add the post-API-call codegen
915 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
916 # Handle the return result variable, if any
917 if (resulttype != None):
918 self.appendSection('command', ' return result;')
919 self.appendSection('command', '}')
920 if (feature_extra_protect != None):
921 self.appendSection('command', '#endif // '+ feature_extra_protect)
922 self.intercepts += [ '#endif' ]