blob: 6550ff38b922632bd6c92b489c06dea467a8ba2f [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',
Mike Schuchardt3b093d72018-06-06 11:58:06 -0600159 'vkGetPhysicalDeviceDisplayPropertiesKHR',
160 'vkGetPhysicalDeviceDisplayProperties2KHR',
161 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
162 'vkGetPhysicalDeviceDisplayPlaneProperties2KHR',
163 'vkGetDisplayPlaneSupportedDisplaysKHR',
164 'vkGetDisplayModePropertiesKHR',
165 'vkGetDisplayModeProperties2KHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600166 ]
167 # Commands shadowed by interface functions and are not implemented
168 self.interface_functions = [
Mark Young6ba8abe2017-11-09 10:37:04 -0700169 # VK_EXT_debug_report APIs are hooked, but handled separately in the source file
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600170 'vkCreateDebugReportCallbackEXT',
171 'vkDestroyDebugReportCallbackEXT',
172 'vkDebugReportMessageEXT',
Mark Young6ba8abe2017-11-09 10:37:04 -0700173 # VK_EXT_debug_utils APIs are hooked, but handled separately in the source file
174 'vkCreateDebugUtilsMessengerEXT',
175 'vkDestroyDebugUtilsMessengerEXT',
176 'vkSubmitDebugUtilsMessageEXT',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600177 ]
178 self.headerVersion = None
179 # Internal state - accumulators for different inner block text
180 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600181
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600182 self.cmdMembers = []
183 self.cmd_feature_protect = [] # Save ifdef's for each command
Mark Lobodzinski85904632017-04-06 10:07:42 -0600184 self.cmd_info_data = [] # Save the cmdinfo data for wrapping the handles when processing is complete
185 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
186 self.extension_structs = [] # List of all structs or sister-structs containing handles
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600187 # A sister-struct may contain no handles but shares a structextends attribute with one that does
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600188 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
189 self.struct_member_dict = dict()
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600190 # Named tuples to store struct and command data
Mark Lobodzinski85904632017-04-06 10:07:42 -0600191 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600192 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
193 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
194 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600195
196 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600197 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
198 #
199 def incIndent(self, indent):
200 inc = ' ' * self.INDENT_SPACES
201 if indent:
202 return indent + inc
203 return inc
204 #
205 def decIndent(self, indent):
206 if indent and (len(indent) > self.INDENT_SPACES):
207 return indent[:-self.INDENT_SPACES]
208 return ''
209 #
210 # Override makeProtoName to drop the "vk" prefix
211 def makeProtoName(self, name, tail):
212 return self.genOpts.apientry + name[2:] + tail
213 #
214 # Check if the parameter passed in is a pointer to an array
215 def paramIsArray(self, param):
216 return param.attrib.get('len') is not None
217 #
218 def beginFile(self, genOpts):
219 OutputGenerator.beginFile(self, genOpts)
220 # User-supplied prefix text, if any (list of strings)
221 if (genOpts.prefixText):
222 for s in genOpts.prefixText:
223 write(s, file=self.outFile)
224 # Namespace
225 self.newline()
226 write('namespace unique_objects {', file = self.outFile)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600227 # Now that the data is all collected and complete, generate and output the wrapping/unwrapping routines
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600228 def endFile(self):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600229
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600230 self.struct_member_dict = dict(self.structMembers)
231
232 # Generate the list of APIs that might need to handle wrapped extension structs
233 self.GenerateCommandWrapExtensionList()
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600234 # Write out wrapping/unwrapping functions
235 self.WrapCommands()
Mark Lobodzinski85904632017-04-06 10:07:42 -0600236 # Build and write out pNext processing function
237 extension_proc = self.build_extension_processing_func()
238 self.newline()
239 write('// Unique Objects pNext extension handling function', file=self.outFile)
240 write('%s' % extension_proc, file=self.outFile)
241
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600242 # Actually write the interface to the output file.
243 if (self.emit):
244 self.newline()
245 if (self.featureExtraProtect != None):
246 write('#ifdef', self.featureExtraProtect, file=self.outFile)
247 # Write the unique_objects code to the file
248 if (self.sections['command']):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600249 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
250 if (self.featureExtraProtect != None):
251 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
252 else:
253 self.newline()
254
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600255 # Record intercepted procedures
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600256 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
257 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600258 write('\n'.join(self.intercepts), file=self.outFile)
259 write('};\n', file=self.outFile)
260 self.newline()
261 write('} // namespace unique_objects', file=self.outFile)
262 # Finish processing in superclass
263 OutputGenerator.endFile(self)
264 #
265 def beginFeature(self, interface, emit):
266 # Start processing in superclass
267 OutputGenerator.beginFeature(self, interface, emit)
268 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600269 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600270 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700271 white_list_entry = []
272 if (self.featureExtraProtect != None):
273 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
274 white_list_entry += [ '"%s"' % self.featureName ]
275 if (self.featureExtraProtect != None):
276 white_list_entry += [ '#endif' ]
277 featureType = interface.get('type')
278 if featureType == 'instance':
279 self.instance_extensions += white_list_entry
280 elif featureType == 'device':
281 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600282 #
283 def endFeature(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600284 # Finish processing in superclass
285 OutputGenerator.endFeature(self)
286 #
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700287 def genType(self, typeinfo, name, alias):
288 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600289 typeElem = typeinfo.elem
290 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
291 # Otherwise, emit the tag text.
292 category = typeElem.get('category')
293 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700294 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600295 #
296 # Append a definition to the specified section
297 def appendSection(self, section, text):
298 # self.sections[section].append('SECTION: ' + section + '\n')
299 self.sections[section].append(text)
300 #
301 # Check if the parameter passed in is a pointer
302 def paramIsPointer(self, param):
303 ispointer = False
304 for elem in param:
305 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
306 ispointer = True
307 return ispointer
308 #
309 # Get the category of a type
310 def getTypeCategory(self, typename):
311 types = self.registry.tree.findall("types/type")
312 for elem in types:
313 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
314 return elem.attrib.get('category')
315 #
316 # Check if a parent object is dispatchable or not
317 def isHandleTypeNonDispatchable(self, handletype):
318 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
319 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
320 return True
321 else:
322 return False
323 #
324 # Retrieve the type and name for a parameter
325 def getTypeNameTuple(self, param):
326 type = ''
327 name = ''
328 for elem in param:
329 if elem.tag == 'type':
330 type = noneStr(elem.text)
331 elif elem.tag == 'name':
332 name = noneStr(elem.text)
333 return (type, name)
334 #
335 # Retrieve the value of the len tag
336 def getLen(self, param):
337 result = None
338 len = param.attrib.get('len')
339 if len and len != 'null-terminated':
340 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
341 # have a null terminated array of strings. We strip the null-terminated from the
342 # 'len' field and only return the parameter specifying the string count
343 if 'null-terminated' in len:
344 result = len.split(',')[0]
345 else:
346 result = len
347 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
348 result = str(result).replace('::', '->')
349 return result
350 #
351 # Generate a VkStructureType based on a structure typename
352 def genVkStructureType(self, typename):
353 # Add underscore between lowercase then uppercase
354 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
355 # Change to uppercase
356 value = value.upper()
357 # Add STRUCTURE_TYPE_
358 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
359 #
360 # Struct parameter check generation.
361 # This is a special case of the <type> tag where the contents are interpreted as a set of
362 # <member> tags instead of freeform C type declarations. The <member> tags are just like
363 # <param> tags - they are a declaration of a struct or union member. Only simple member
364 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700365 def genStruct(self, typeinfo, typeName, alias):
366 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600367 members = typeinfo.elem.findall('.//member')
368 # Iterate over members once to get length parameters for arrays
369 lens = set()
370 for member in members:
371 len = self.getLen(member)
372 if len:
373 lens.add(len)
374 # Generate member info
375 membersInfo = []
376 for member in members:
377 # Get the member's type and name
378 info = self.getTypeNameTuple(member)
379 type = info[0]
380 name = info[1]
381 cdecl = self.makeCParamDecl(member, 0)
382 # Process VkStructureType
383 if type == 'VkStructureType':
384 # Extract the required struct type value from the comments
385 # embedded in the original text defining the 'typeinfo' element
386 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
387 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
388 if result:
389 value = result.group(0)
390 else:
391 value = self.genVkStructureType(typeName)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600392 # Store the required type value
393 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600394 # Store pointer/array/string info
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600395 extstructs = self.registry.validextensionstructs[typeName] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600396 membersInfo.append(self.CommandParam(type=type,
397 name=name,
398 ispointer=self.paramIsPointer(member),
399 isconst=True if 'const' in cdecl else False,
400 iscount=True if name in lens else False,
401 len=self.getLen(member),
Mark Lobodzinski85904632017-04-06 10:07:42 -0600402 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600403 cdecl=cdecl,
404 islocal=False,
405 iscreate=False,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600406 isdestroy=False,
407 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600408 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
Mark Lobodzinski85904632017-04-06 10:07:42 -0600409
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600410 #
411 # Insert a lock_guard line
412 def lock_guard(self, indent):
413 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
414 #
415 # Determine if a struct has an NDO as a member or an embedded member
416 def struct_contains_ndo(self, struct_item):
417 struct_member_dict = dict(self.structMembers)
418 struct_members = struct_member_dict[struct_item]
419
420 for member in struct_members:
421 if self.isHandleTypeNonDispatchable(member.type):
422 return True
423 elif member.type in struct_member_dict:
424 if self.struct_contains_ndo(member.type) == True:
425 return True
426 return False
427 #
428 # Return list of struct members which contain, or which sub-structures contain
429 # an NDO in a given list of parameters or members
430 def getParmeterStructsWithNdos(self, item_list):
431 struct_list = set()
432 for item in item_list:
433 paramtype = item.find('type')
434 typecategory = self.getTypeCategory(paramtype.text)
435 if typecategory == 'struct':
436 if self.struct_contains_ndo(paramtype.text) == True:
437 struct_list.add(item)
438 return struct_list
439 #
440 # Return list of non-dispatchable objects from a given list of parameters or members
441 def getNdosInParameterList(self, item_list, create_func):
442 ndo_list = set()
443 if create_func == True:
444 member_list = item_list[0:-1]
445 else:
446 member_list = item_list
447 for item in member_list:
448 if self.isHandleTypeNonDispatchable(paramtype.text):
449 ndo_list.add(item)
450 return ndo_list
451 #
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600452 # Construct list of extension structs containing handles, or extension structs that share a structextends attribute
453 # 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 -0600454 # TODO: make this recursive -- structs buried three or more levels deep are not searched for extensions
455 def GenerateCommandWrapExtensionList(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600456 for struct in self.structMembers:
457 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
458 found = False;
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600459 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600460 if item != '' and self.struct_contains_ndo(item) == True:
461 found = True
462 if found == True:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600463 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600464 if item != '' and item not in self.extension_structs:
465 self.extension_structs.append(item)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600466 #
467 # Returns True if a struct may have a pNext chain containing an NDO
468 def StructWithExtensions(self, struct_type):
469 if struct_type in self.struct_member_dict:
470 param_info = self.struct_member_dict[struct_type]
471 if (len(param_info) > 1) and param_info[1].extstructs is not None:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600472 for item in param_info[1].extstructs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600473 if item in self.extension_structs:
474 return True
475 return False
476 #
477 # Generate pNext handling function
478 def build_extension_processing_func(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600479 # Construct helper functions to build and free pNext extension chains
480 pnext_proc = ''
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700481 pnext_proc += 'void *CreateUnwrappedExtensionStructs(const void *pNext) {\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600482 pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
483 pnext_proc += ' void *head_pnext = NULL;\n'
484 pnext_proc += ' void *prev_ext_struct = NULL;\n'
485 pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
486 pnext_proc += ' while (cur_pnext != NULL) {\n'
487 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(cur_pnext);\n\n'
488 pnext_proc += ' switch (header->sType) {\n'
489 for item in self.extension_structs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600490 struct_info = self.struct_member_dict[item]
Mark Lobodzinski85904632017-04-06 10:07:42 -0600491 if struct_info[0].feature_protect is not None:
492 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
493 pnext_proc += ' case %s: {\n' % self.structTypes[item].value
Chris Forbes0f86c402017-05-02 18:36:39 -0700494 pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600495 pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
496 # Generate code to unwrap the handles
497 indent = ' '
498 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, 'safe_struct->', 0, False, False, False, False)
499 pnext_proc += tmp_pre
500 pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
501 pnext_proc += ' } break;\n'
502 if struct_info[0].feature_protect is not None:
503 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
504 pnext_proc += '\n'
505 pnext_proc += ' default:\n'
506 pnext_proc += ' break;\n'
507 pnext_proc += ' }\n\n'
508 pnext_proc += ' // Save pointer to the first structure in the pNext chain\n'
509 pnext_proc += ' head_pnext = (head_pnext ? head_pnext : cur_ext_struct);\n\n'
510 pnext_proc += ' // For any extension structure but the first, link the last struct\'s pNext to the current ext struct\n'
511 pnext_proc += ' if (prev_ext_struct) {\n'
512 pnext_proc += ' (reinterpret_cast<GenericHeader *>(prev_ext_struct))->pNext = cur_ext_struct;\n'
513 pnext_proc += ' }\n'
514 pnext_proc += ' prev_ext_struct = cur_ext_struct;\n\n'
515 pnext_proc += ' // Process the next structure in the chain\n'
516 pnext_proc += ' cur_pnext = const_cast<void *>(header->pNext);\n'
517 pnext_proc += ' }\n'
518 pnext_proc += ' return head_pnext;\n'
519 pnext_proc += '}\n\n'
520 pnext_proc += '// Free a pNext extension chain\n'
521 pnext_proc += 'void FreeUnwrappedExtensionStructs(void *head) {\n'
Gabríel Arthúr Péturssoneecaa4d2018-03-18 20:21:11 +0000522 pnext_proc += ' GenericHeader *curr_ptr = reinterpret_cast<GenericHeader *>(head);\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600523 pnext_proc += ' while (curr_ptr) {\n'
Gabríel Arthúr Péturssoneecaa4d2018-03-18 20:21:11 +0000524 pnext_proc += ' GenericHeader *header = curr_ptr;\n'
525 pnext_proc += ' curr_ptr = reinterpret_cast<GenericHeader *>(header->pNext);\n\n'
526 pnext_proc += ' switch (header->sType) {\n';
527 for item in self.extension_structs:
528 struct_info = self.struct_member_dict[item]
529 if struct_info[0].feature_protect is not None:
530 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
531 pnext_proc += ' case %s:\n' % self.structTypes[item].value
532 pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
533 pnext_proc += ' break;\n'
534 if struct_info[0].feature_protect is not None:
535 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
536 pnext_proc += '\n'
537 pnext_proc += ' default:\n'
538 pnext_proc += ' assert(0);\n'
539 pnext_proc += ' }\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600540 pnext_proc += ' }\n'
541 pnext_proc += '}\n'
542 return pnext_proc
543
544 #
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600545 # Generate source for creating a non-dispatchable object
546 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
547 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700548 handle_type = params[-1].find('type')
549 if self.isHandleTypeNonDispatchable(handle_type.text):
550 # Check for special case where multiple handles are returned
551 ndo_array = False
552 if cmd_info[-1].len is not None:
553 ndo_array = True;
554 handle_name = params[-1].find('name')
555 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
556 indent = self.incIndent(indent)
557 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
558 ndo_dest = '*%s' % handle_name.text
559 if ndo_array == True:
560 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600561 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700562 ndo_dest = '%s[index0]' % cmd_info[-1].name
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700563 create_ndo_code += '%s%s = WrapNew(%s);\n' % (indent, ndo_dest, ndo_dest)
Mark Young39389872017-01-19 21:10:49 -0700564 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600565 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700566 create_ndo_code += '%s}\n' % indent
567 indent = self.decIndent(indent)
568 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600569 return create_ndo_code
570 #
571 # Generate source for destroying a non-dispatchable object
572 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
573 destroy_ndo_code = ''
574 ndo_array = False
575 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
576 # Check for special case where multiple handles are returned
577 if cmd_info[-1].len is not None:
578 ndo_array = True;
579 param = -1
580 else:
581 param = -2
582 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
583 if ndo_array == True:
584 # This API is freeing an array of handles. Remove them from the unique_id map.
585 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
586 indent = self.incIndent(indent)
587 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
588 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
589 indent = self.incIndent(indent)
590 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
591 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700592 destroy_ndo_code += '%sunique_id_mapping.erase(unique_id);\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600593 indent = self.decIndent(indent);
594 destroy_ndo_code += '%s}\n' % indent
595 indent = self.decIndent(indent);
596 destroy_ndo_code += '%s}\n' % indent
597 else:
598 # Remove a single handle from the map
599 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
600 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 -0700601 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)
602 destroy_ndo_code += '%sunique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600603 destroy_ndo_code += '%slock.unlock();\n' % (indent)
604 return ndo_array, destroy_ndo_code
605
606 #
607 # Clean up local declarations
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600608 def cleanUpLocalDeclarations(self, indent, prefix, name, len, index, process_pnext):
Mark Young26095c42017-05-09 13:19:04 -0600609 cleanup = '%sif (local_%s%s) {\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600610 if len is not None:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600611 if process_pnext:
612 cleanup += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, len, index)
613 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s[%s].pNext));\n' % (indent, prefix, name, index)
614 cleanup += '%s }\n' % indent
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600615 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
616 else:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600617 if process_pnext:
618 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s->pNext));\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600619 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
Mark Young26095c42017-05-09 13:19:04 -0600620 cleanup += "%s}\n" % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600621 return cleanup
622 #
623 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
624 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
625 decl_code = ''
626 pre_call_code = ''
627 post_call_code = ''
628 if ndo_count is not None:
629 if top_level == True:
630 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
631 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
632 indent = self.incIndent(indent)
633 if top_level == True:
634 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
635 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
636 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700637 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 -0600638 else:
639 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
640 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700641 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 -0600642 indent = self.decIndent(indent)
643 pre_call_code += '%s }\n' % indent
644 indent = self.decIndent(indent)
645 pre_call_code += '%s }\n' % indent
646 if top_level == True:
647 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
648 indent = self.incIndent(indent)
649 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
650 else:
651 if top_level == True:
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600652 if (destroy_func == False) or (destroy_array == True):
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700653 pre_call_code += '%s %s = Unwrap(%s);\n' % (indent, ndo_name, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600654 else:
655 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
656 # as part of the string and explicitly print it
657 fix = str(prefix).strip('local_');
658 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
659 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700660 pre_call_code += '%s %s%s = Unwrap(%s%s);\n' % (indent, prefix, ndo_name, fix, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600661 indent = self.decIndent(indent)
662 pre_call_code += '%s }\n' % indent
663 return decl_code, pre_call_code, post_call_code
664 #
665 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
666 # create_func means that this is API creates or allocates NDOs
667 # destroy_func indicates that this API destroys or frees NDOs
668 # destroy_array means that the destroy_func operated on an array of NDOs
669 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
670 decls = ''
671 pre_code = ''
672 post_code = ''
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600673 index = 'index%s' % str(array_index)
674 array_index += 1
675 # Process any NDOs in this structure and recurse for any sub-structs in this struct
676 for member in members:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600677 process_pnext = self.StructWithExtensions(member.type)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600678 # Handle NDOs
679 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500680 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600681 if (count_name is not None):
682 if first_level_param == False:
683 count_name = '%s%s' % (prefix, member.len)
684
685 if (first_level_param == False) or (create_func == False):
686 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
687 decls += tmp_decl
688 pre_code += tmp_pre
689 post_code += tmp_post
690 # Handle Structs that contain NDOs at some level
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600691 elif member.type in self.struct_member_dict:
692 # Structs at first level will have an NDO, OR, we need a safe_struct for the pnext chain
693 if self.struct_contains_ndo(member.type) == True or process_pnext:
694 struct_info = self.struct_member_dict[member.type]
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600695 # Struct Array
696 if member.len is not None:
697 # Update struct prefix
698 if first_level_param == True:
699 new_prefix = 'local_%s' % member.name
700 # Declare safe_VarType for struct
701 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
702 else:
703 new_prefix = '%s%s' % (prefix, member.name)
704 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
705 indent = self.incIndent(indent)
706 if first_level_param == True:
707 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
708 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
709 indent = self.incIndent(indent)
710 if first_level_param == True:
711 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600712 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700713 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 -0600714 local_prefix = '%s[%s].' % (new_prefix, index)
715 # Process sub-structs in this struct
716 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
717 decls += tmp_decl
718 pre_code += tmp_pre
719 post_code += tmp_post
720 indent = self.decIndent(indent)
721 pre_code += '%s }\n' % indent
722 indent = self.decIndent(indent)
723 pre_code += '%s }\n' % indent
724 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600725 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600726 # Single Struct
727 else:
728 # Update struct prefix
729 if first_level_param == True:
730 new_prefix = 'local_%s->' % member.name
731 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
732 else:
733 new_prefix = '%s%s->' % (prefix, member.name)
734 # Declare safe_VarType for struct
735 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
736 indent = self.incIndent(indent)
737 if first_level_param == True:
738 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
739 # Process sub-structs in this struct
740 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
741 decls += tmp_decl
742 pre_code += tmp_pre
743 post_code += tmp_post
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600744 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700745 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 -0600746 indent = self.decIndent(indent)
747 pre_code += '%s }\n' % indent
748 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600749 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600750 return decls, pre_code, post_code
751 #
752 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
753 def generate_wrapping_code(self, cmd):
754 indent = ' '
755 proto = cmd.find('proto/name')
756 params = cmd.findall('param')
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600757
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600758 if proto.text is not None:
759 cmd_member_dict = dict(self.cmdMembers)
760 cmd_info = cmd_member_dict[proto.text]
761 # Handle ndo create/allocate operations
762 if cmd_info[0].iscreate:
763 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
764 else:
765 create_ndo_code = ''
766 # Handle ndo destroy/free operations
767 if cmd_info[0].isdestroy:
768 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
769 else:
770 destroy_array = False
771 destroy_ndo_code = ''
772 paramdecl = ''
773 param_pre_code = ''
774 param_post_code = ''
775 create_func = True if create_ndo_code else False
776 destroy_func = True if destroy_ndo_code else False
777 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
778 param_post_code += create_ndo_code
779 if destroy_ndo_code:
780 if destroy_array == True:
781 param_post_code += destroy_ndo_code
782 else:
783 param_pre_code += destroy_ndo_code
784 if param_pre_code:
785 if (not destroy_func) or (destroy_array):
786 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
787 return paramdecl, param_pre_code, param_post_code
788 #
789 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700790 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600791
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600792 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700793 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600794 members = cmdinfo.elem.findall('.//param')
795 # Iterate over members once to get length parameters for arrays
796 lens = set()
797 for member in members:
798 len = self.getLen(member)
799 if len:
800 lens.add(len)
801 struct_member_dict = dict(self.structMembers)
802 # Generate member info
803 membersInfo = []
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600804 constains_extension_structs = False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600805 for member in members:
806 # Get type and name of member
807 info = self.getTypeNameTuple(member)
808 type = info[0]
809 name = info[1]
810 cdecl = self.makeCParamDecl(member, 0)
811 # Check for parameter name in lens set
812 iscount = True if name in lens else False
813 len = self.getLen(member)
814 isconst = True if 'const' in cdecl else False
815 ispointer = self.paramIsPointer(member)
816 # Mark param as local if it is an array of NDOs
817 islocal = False;
818 if self.isHandleTypeNonDispatchable(type) == True:
819 if (len is not None) and (isconst == True):
820 islocal = True
821 # Or if it's a struct that contains an NDO
822 elif type in struct_member_dict:
823 if self.struct_contains_ndo(type) == True:
824 islocal = True
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600825 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700826 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 -0600827 extstructs = self.registry.validextensionstructs[type] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600828 membersInfo.append(self.CommandParam(type=type,
829 name=name,
830 ispointer=ispointer,
831 isconst=isconst,
832 iscount=iscount,
833 len=len,
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600834 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600835 cdecl=cdecl,
836 islocal=islocal,
837 iscreate=iscreate,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600838 isdestroy=isdestroy,
839 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600840 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600841 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
842 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
843 #
844 # Create code to wrap NDOs as well as handling some boilerplate code
845 def WrapCommands(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600846 cmd_member_dict = dict(self.cmdMembers)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600847 cmd_info_dict = dict(self.cmd_info_data)
848 cmd_protect_dict = dict(self.cmd_feature_protect)
849
850 for api_call in self.cmdMembers:
851 cmdname = api_call.name
852 cmdinfo = cmd_info_dict[api_call.name]
853 if cmdname in self.interface_functions:
854 continue
855 if cmdname in self.no_autogen_list:
856 decls = self.makeCDecls(cmdinfo.elem)
857 self.appendSection('command', '')
858 self.appendSection('command', '// Declare only')
859 self.appendSection('command', decls[0])
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600860 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600861 continue
862 # Generate NDO wrapping/unwrapping code for all parameters
863 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
864 # If API doesn't contain an NDO's, don't fool with it
865 if not api_decls and not api_pre and not api_post:
866 continue
867 feature_extra_protect = cmd_protect_dict[api_call.name]
868 if (feature_extra_protect != None):
869 self.appendSection('command', '')
870 self.appendSection('command', '#ifdef '+ feature_extra_protect)
871 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
872 # Add intercept to procmap
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600873 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600874 decls = self.makeCDecls(cmdinfo.elem)
875 self.appendSection('command', '')
876 self.appendSection('command', decls[0][:-1])
877 self.appendSection('command', '{')
878 # Setup common to call wrappers, first parameter is always dispatchable
879 dispatchable_type = cmdinfo.elem.find('param/type').text
880 dispatchable_name = cmdinfo.elem.find('param/name').text
881 # Generate local instance/pdev/device data lookup
Chris Forbes5279a8c2017-05-02 16:26:23 -0700882 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
883 self.appendSection('command', ' instance_layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), instance_layer_data_map);')
884 else:
885 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600886 # Handle return values, if any
887 resulttype = cmdinfo.elem.find('proto/type')
888 if (resulttype != None and resulttype.text == 'void'):
889 resulttype = None
890 if (resulttype != None):
891 assignresult = resulttype.text + ' result = '
892 else:
893 assignresult = ''
894 # Pre-pend declarations and pre-api-call codegen
895 if api_decls:
896 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
897 if api_pre:
898 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
899 # Generate the API call itself
900 # Gather the parameter items
901 params = cmdinfo.elem.findall('param/name')
902 # Pull out the text for each of the parameters, separate them by commas in a list
903 paramstext = ', '.join([str(param.text) for param in params])
904 # If any of these paramters has been replaced by a local var, fix up the list
905 params = cmd_member_dict[cmdname]
906 for param in params:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600907 if param.islocal == True or self.StructWithExtensions(param.type):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600908 if param.ispointer == True:
909 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
910 else:
911 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
912 # Use correct dispatch table
Chris Forbes44c05302017-05-02 16:42:55 -0700913 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->dispatch_table.',1)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600914 # Put all this together for the final down-chain call
915 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
916 # And add the post-API-call codegen
917 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
918 # Handle the return result variable, if any
919 if (resulttype != None):
920 self.appendSection('command', ' return result;')
921 self.appendSection('command', '}')
922 if (feature_extra_protect != None):
923 self.appendSection('command', '#endif // '+ feature_extra_protect)
924 self.intercepts += [ '#endif' ]