blob: 9fd63280c7c9837390944945c483d1dd14b76f5b [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',
Tony-LunarGf2e1c3f2018-09-06 13:57:26 -0600156 'vkCreateRenderPass2KHR',
Petr Krause91f7a12017-12-14 20:57:36 +0100157 'vkDestroyRenderPass',
Mark Young6ba8abe2017-11-09 10:37:04 -0700158 'vkSetDebugUtilsObjectNameEXT',
159 'vkSetDebugUtilsObjectTagEXT',
Mike Schuchardt3b093d72018-06-06 11:58:06 -0600160 'vkGetPhysicalDeviceDisplayPropertiesKHR',
161 'vkGetPhysicalDeviceDisplayProperties2KHR',
162 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
163 'vkGetPhysicalDeviceDisplayPlaneProperties2KHR',
164 'vkGetDisplayPlaneSupportedDisplaysKHR',
165 'vkGetDisplayModePropertiesKHR',
166 'vkGetDisplayModeProperties2KHR',
Mark Young6ba8abe2017-11-09 10:37:04 -0700167 'vkCreateDebugUtilsMessengerEXT',
168 'vkDestroyDebugUtilsMessengerEXT',
169 'vkSubmitDebugUtilsMessageEXT',
Tobin Ehlis7cbe99b2018-06-21 14:22:01 -0600170 'vkCreateDebugReportCallbackEXT',
171 'vkDestroyDebugReportCallbackEXT',
172 'vkDebugReportMessageEXT',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600173 ]
174 self.headerVersion = None
175 # Internal state - accumulators for different inner block text
176 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600177
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600178 self.cmdMembers = []
179 self.cmd_feature_protect = [] # Save ifdef's for each command
Mark Lobodzinski85904632017-04-06 10:07:42 -0600180 self.cmd_info_data = [] # Save the cmdinfo data for wrapping the handles when processing is complete
181 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
182 self.extension_structs = [] # List of all structs or sister-structs containing handles
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600183 # A sister-struct may contain no handles but shares a structextends attribute with one that does
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600184 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
185 self.struct_member_dict = dict()
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600186 # Named tuples to store struct and command data
Mark Lobodzinski85904632017-04-06 10:07:42 -0600187 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600188 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
189 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
190 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600191
192 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600193 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
194 #
195 def incIndent(self, indent):
196 inc = ' ' * self.INDENT_SPACES
197 if indent:
198 return indent + inc
199 return inc
200 #
201 def decIndent(self, indent):
202 if indent and (len(indent) > self.INDENT_SPACES):
203 return indent[:-self.INDENT_SPACES]
204 return ''
205 #
206 # Override makeProtoName to drop the "vk" prefix
207 def makeProtoName(self, name, tail):
208 return self.genOpts.apientry + name[2:] + tail
209 #
210 # Check if the parameter passed in is a pointer to an array
211 def paramIsArray(self, param):
212 return param.attrib.get('len') is not None
213 #
214 def beginFile(self, genOpts):
215 OutputGenerator.beginFile(self, genOpts)
216 # User-supplied prefix text, if any (list of strings)
217 if (genOpts.prefixText):
218 for s in genOpts.prefixText:
219 write(s, file=self.outFile)
220 # Namespace
221 self.newline()
222 write('namespace unique_objects {', file = self.outFile)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600223 # Now that the data is all collected and complete, generate and output the wrapping/unwrapping routines
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600224 def endFile(self):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600225
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600226 self.struct_member_dict = dict(self.structMembers)
227
228 # Generate the list of APIs that might need to handle wrapped extension structs
229 self.GenerateCommandWrapExtensionList()
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600230 # Write out wrapping/unwrapping functions
231 self.WrapCommands()
Mark Lobodzinski85904632017-04-06 10:07:42 -0600232 # Build and write out pNext processing function
233 extension_proc = self.build_extension_processing_func()
234 self.newline()
235 write('// Unique Objects pNext extension handling function', file=self.outFile)
236 write('%s' % extension_proc, file=self.outFile)
237
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600238 # Actually write the interface to the output file.
239 if (self.emit):
240 self.newline()
241 if (self.featureExtraProtect != None):
242 write('#ifdef', self.featureExtraProtect, file=self.outFile)
243 # Write the unique_objects code to the file
244 if (self.sections['command']):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600245 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
246 if (self.featureExtraProtect != None):
247 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
248 else:
249 self.newline()
250
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600251 # Record intercepted procedures
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600252 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
John Zulauf9b777302018-10-08 11:15:51 -0600253 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600254 write('\n'.join(self.intercepts), file=self.outFile)
255 write('};\n', file=self.outFile)
256 self.newline()
257 write('} // namespace unique_objects', file=self.outFile)
258 # Finish processing in superclass
259 OutputGenerator.endFile(self)
260 #
261 def beginFeature(self, interface, emit):
262 # Start processing in superclass
263 OutputGenerator.beginFeature(self, interface, emit)
264 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600265 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600266 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700267 white_list_entry = []
268 if (self.featureExtraProtect != None):
269 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
270 white_list_entry += [ '"%s"' % self.featureName ]
271 if (self.featureExtraProtect != None):
272 white_list_entry += [ '#endif' ]
273 featureType = interface.get('type')
274 if featureType == 'instance':
275 self.instance_extensions += white_list_entry
276 elif featureType == 'device':
277 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600278 #
279 def endFeature(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600280 # Finish processing in superclass
281 OutputGenerator.endFeature(self)
282 #
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700283 def genType(self, typeinfo, name, alias):
284 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600285 typeElem = typeinfo.elem
286 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
287 # Otherwise, emit the tag text.
288 category = typeElem.get('category')
289 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700290 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600291 #
292 # Append a definition to the specified section
293 def appendSection(self, section, text):
294 # self.sections[section].append('SECTION: ' + section + '\n')
295 self.sections[section].append(text)
296 #
297 # Check if the parameter passed in is a pointer
298 def paramIsPointer(self, param):
299 ispointer = False
300 for elem in param:
301 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
302 ispointer = True
303 return ispointer
304 #
305 # Get the category of a type
306 def getTypeCategory(self, typename):
307 types = self.registry.tree.findall("types/type")
308 for elem in types:
309 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
310 return elem.attrib.get('category')
311 #
312 # Check if a parent object is dispatchable or not
313 def isHandleTypeNonDispatchable(self, handletype):
314 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
315 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
316 return True
317 else:
318 return False
319 #
320 # Retrieve the type and name for a parameter
321 def getTypeNameTuple(self, param):
322 type = ''
323 name = ''
324 for elem in param:
325 if elem.tag == 'type':
326 type = noneStr(elem.text)
327 elif elem.tag == 'name':
328 name = noneStr(elem.text)
329 return (type, name)
330 #
331 # Retrieve the value of the len tag
332 def getLen(self, param):
333 result = None
334 len = param.attrib.get('len')
335 if len and len != 'null-terminated':
336 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
337 # have a null terminated array of strings. We strip the null-terminated from the
338 # 'len' field and only return the parameter specifying the string count
339 if 'null-terminated' in len:
340 result = len.split(',')[0]
341 else:
342 result = len
343 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
344 result = str(result).replace('::', '->')
345 return result
346 #
347 # Generate a VkStructureType based on a structure typename
348 def genVkStructureType(self, typename):
349 # Add underscore between lowercase then uppercase
350 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
351 # Change to uppercase
352 value = value.upper()
353 # Add STRUCTURE_TYPE_
354 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
355 #
356 # Struct parameter check generation.
357 # This is a special case of the <type> tag where the contents are interpreted as a set of
358 # <member> tags instead of freeform C type declarations. The <member> tags are just like
359 # <param> tags - they are a declaration of a struct or union member. Only simple member
360 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700361 def genStruct(self, typeinfo, typeName, alias):
362 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600363 members = typeinfo.elem.findall('.//member')
364 # Iterate over members once to get length parameters for arrays
365 lens = set()
366 for member in members:
367 len = self.getLen(member)
368 if len:
369 lens.add(len)
370 # Generate member info
371 membersInfo = []
372 for member in members:
373 # Get the member's type and name
374 info = self.getTypeNameTuple(member)
375 type = info[0]
376 name = info[1]
377 cdecl = self.makeCParamDecl(member, 0)
378 # Process VkStructureType
379 if type == 'VkStructureType':
380 # Extract the required struct type value from the comments
381 # embedded in the original text defining the 'typeinfo' element
382 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
383 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
384 if result:
385 value = result.group(0)
386 else:
387 value = self.genVkStructureType(typeName)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600388 # Store the required type value
389 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600390 # Store pointer/array/string info
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600391 extstructs = self.registry.validextensionstructs[typeName] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600392 membersInfo.append(self.CommandParam(type=type,
393 name=name,
394 ispointer=self.paramIsPointer(member),
395 isconst=True if 'const' in cdecl else False,
396 iscount=True if name in lens else False,
397 len=self.getLen(member),
Mark Lobodzinski85904632017-04-06 10:07:42 -0600398 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600399 cdecl=cdecl,
400 islocal=False,
401 iscreate=False,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600402 isdestroy=False,
403 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600404 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
Mark Lobodzinski85904632017-04-06 10:07:42 -0600405
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600406 #
407 # Insert a lock_guard line
408 def lock_guard(self, indent):
409 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
410 #
411 # Determine if a struct has an NDO as a member or an embedded member
412 def struct_contains_ndo(self, struct_item):
413 struct_member_dict = dict(self.structMembers)
414 struct_members = struct_member_dict[struct_item]
415
416 for member in struct_members:
417 if self.isHandleTypeNonDispatchable(member.type):
418 return True
419 elif member.type in struct_member_dict:
420 if self.struct_contains_ndo(member.type) == True:
421 return True
422 return False
423 #
424 # Return list of struct members which contain, or which sub-structures contain
425 # an NDO in a given list of parameters or members
426 def getParmeterStructsWithNdos(self, item_list):
427 struct_list = set()
428 for item in item_list:
429 paramtype = item.find('type')
430 typecategory = self.getTypeCategory(paramtype.text)
431 if typecategory == 'struct':
432 if self.struct_contains_ndo(paramtype.text) == True:
433 struct_list.add(item)
434 return struct_list
435 #
436 # Return list of non-dispatchable objects from a given list of parameters or members
437 def getNdosInParameterList(self, item_list, create_func):
438 ndo_list = set()
439 if create_func == True:
440 member_list = item_list[0:-1]
441 else:
442 member_list = item_list
443 for item in member_list:
444 if self.isHandleTypeNonDispatchable(paramtype.text):
445 ndo_list.add(item)
446 return ndo_list
447 #
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600448 # Construct list of extension structs containing handles, or extension structs that share a structextends attribute
449 # 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 -0600450 # TODO: make this recursive -- structs buried three or more levels deep are not searched for extensions
451 def GenerateCommandWrapExtensionList(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600452 for struct in self.structMembers:
453 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
454 found = False;
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600455 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600456 if item != '' and self.struct_contains_ndo(item) == True:
457 found = True
458 if found == True:
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 item not in self.extension_structs:
461 self.extension_structs.append(item)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600462 #
463 # Returns True if a struct may have a pNext chain containing an NDO
464 def StructWithExtensions(self, struct_type):
465 if struct_type in self.struct_member_dict:
466 param_info = self.struct_member_dict[struct_type]
467 if (len(param_info) > 1) and param_info[1].extstructs is not None:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600468 for item in param_info[1].extstructs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600469 if item in self.extension_structs:
470 return True
471 return False
472 #
473 # Generate pNext handling function
474 def build_extension_processing_func(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600475 # Construct helper functions to build and free pNext extension chains
476 pnext_proc = ''
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700477 pnext_proc += 'void *CreateUnwrappedExtensionStructs(const void *pNext) {\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600478 pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
479 pnext_proc += ' void *head_pnext = NULL;\n'
480 pnext_proc += ' void *prev_ext_struct = NULL;\n'
481 pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
482 pnext_proc += ' while (cur_pnext != NULL) {\n'
483 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(cur_pnext);\n\n'
484 pnext_proc += ' switch (header->sType) {\n'
485 for item in self.extension_structs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600486 struct_info = self.struct_member_dict[item]
Mark Lobodzinski85904632017-04-06 10:07:42 -0600487 if struct_info[0].feature_protect is not None:
488 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
489 pnext_proc += ' case %s: {\n' % self.structTypes[item].value
Chris Forbes0f86c402017-05-02 18:36:39 -0700490 pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600491 pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
492 # Generate code to unwrap the handles
493 indent = ' '
494 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, 'safe_struct->', 0, False, False, False, False)
495 pnext_proc += tmp_pre
496 pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
497 pnext_proc += ' } break;\n'
498 if struct_info[0].feature_protect is not None:
499 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
500 pnext_proc += '\n'
501 pnext_proc += ' default:\n'
502 pnext_proc += ' break;\n'
503 pnext_proc += ' }\n\n'
504 pnext_proc += ' // Save pointer to the first structure in the pNext chain\n'
505 pnext_proc += ' head_pnext = (head_pnext ? head_pnext : cur_ext_struct);\n\n'
506 pnext_proc += ' // For any extension structure but the first, link the last struct\'s pNext to the current ext struct\n'
507 pnext_proc += ' if (prev_ext_struct) {\n'
508 pnext_proc += ' (reinterpret_cast<GenericHeader *>(prev_ext_struct))->pNext = cur_ext_struct;\n'
509 pnext_proc += ' }\n'
510 pnext_proc += ' prev_ext_struct = cur_ext_struct;\n\n'
511 pnext_proc += ' // Process the next structure in the chain\n'
512 pnext_proc += ' cur_pnext = const_cast<void *>(header->pNext);\n'
513 pnext_proc += ' }\n'
514 pnext_proc += ' return head_pnext;\n'
515 pnext_proc += '}\n\n'
516 pnext_proc += '// Free a pNext extension chain\n'
517 pnext_proc += 'void FreeUnwrappedExtensionStructs(void *head) {\n'
Gabríel Arthúr Péturssoneecaa4d2018-03-18 20:21:11 +0000518 pnext_proc += ' GenericHeader *curr_ptr = reinterpret_cast<GenericHeader *>(head);\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600519 pnext_proc += ' while (curr_ptr) {\n'
Gabríel Arthúr Péturssoneecaa4d2018-03-18 20:21:11 +0000520 pnext_proc += ' GenericHeader *header = curr_ptr;\n'
521 pnext_proc += ' curr_ptr = reinterpret_cast<GenericHeader *>(header->pNext);\n\n'
522 pnext_proc += ' switch (header->sType) {\n';
523 for item in self.extension_structs:
524 struct_info = self.struct_member_dict[item]
525 if struct_info[0].feature_protect is not None:
526 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
527 pnext_proc += ' case %s:\n' % self.structTypes[item].value
528 pnext_proc += ' delete reinterpret_cast<safe_%s *>(header);\n' % item
529 pnext_proc += ' break;\n'
530 if struct_info[0].feature_protect is not None:
531 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
532 pnext_proc += '\n'
533 pnext_proc += ' default:\n'
534 pnext_proc += ' assert(0);\n'
535 pnext_proc += ' }\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600536 pnext_proc += ' }\n'
537 pnext_proc += '}\n'
538 return pnext_proc
539
540 #
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600541 # Generate source for creating a non-dispatchable object
542 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
543 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700544 handle_type = params[-1].find('type')
545 if self.isHandleTypeNonDispatchable(handle_type.text):
546 # Check for special case where multiple handles are returned
547 ndo_array = False
548 if cmd_info[-1].len is not None:
549 ndo_array = True;
550 handle_name = params[-1].find('name')
551 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
552 indent = self.incIndent(indent)
553 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
554 ndo_dest = '*%s' % handle_name.text
555 if ndo_array == True:
556 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600557 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700558 ndo_dest = '%s[index0]' % cmd_info[-1].name
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700559 create_ndo_code += '%s%s = WrapNew(%s);\n' % (indent, ndo_dest, ndo_dest)
Mark Young39389872017-01-19 21:10:49 -0700560 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600561 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700562 create_ndo_code += '%s}\n' % indent
563 indent = self.decIndent(indent)
564 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600565 return create_ndo_code
566 #
567 # Generate source for destroying a non-dispatchable object
568 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
569 destroy_ndo_code = ''
570 ndo_array = False
571 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
572 # Check for special case where multiple handles are returned
573 if cmd_info[-1].len is not None:
574 ndo_array = True;
575 param = -1
576 else:
577 param = -2
578 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
579 if ndo_array == True:
580 # This API is freeing an array of handles. Remove them from the unique_id map.
581 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
582 indent = self.incIndent(indent)
583 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
584 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
585 indent = self.incIndent(indent)
586 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
587 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700588 destroy_ndo_code += '%sunique_id_mapping.erase(unique_id);\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600589 indent = self.decIndent(indent);
590 destroy_ndo_code += '%s}\n' % indent
591 indent = self.decIndent(indent);
592 destroy_ndo_code += '%s}\n' % indent
593 else:
594 # Remove a single handle from the map
595 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
596 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 -0700597 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)
598 destroy_ndo_code += '%sunique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600599 destroy_ndo_code += '%slock.unlock();\n' % (indent)
600 return ndo_array, destroy_ndo_code
601
602 #
603 # Clean up local declarations
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600604 def cleanUpLocalDeclarations(self, indent, prefix, name, len, index, process_pnext):
Mark Young26095c42017-05-09 13:19:04 -0600605 cleanup = '%sif (local_%s%s) {\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600606 if len is not None:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600607 if process_pnext:
608 cleanup += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, len, index)
609 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s[%s].pNext));\n' % (indent, prefix, name, index)
610 cleanup += '%s }\n' % indent
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600611 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
612 else:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600613 if process_pnext:
614 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s->pNext));\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600615 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
Mark Young26095c42017-05-09 13:19:04 -0600616 cleanup += "%s}\n" % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600617 return cleanup
618 #
619 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
620 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
621 decl_code = ''
622 pre_call_code = ''
623 post_call_code = ''
624 if ndo_count is not None:
625 if top_level == True:
626 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
627 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
628 indent = self.incIndent(indent)
629 if top_level == True:
630 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
631 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
632 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700633 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 -0600634 else:
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 %s%s[%s] = Unwrap(%s%s[%s]);\n' % (indent, prefix, ndo_name, index, prefix, ndo_name, index)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600638 indent = self.decIndent(indent)
639 pre_call_code += '%s }\n' % indent
640 indent = self.decIndent(indent)
641 pre_call_code += '%s }\n' % indent
642 if top_level == True:
643 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
644 indent = self.incIndent(indent)
645 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
646 else:
647 if top_level == True:
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600648 if (destroy_func == False) or (destroy_array == True):
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700649 pre_call_code += '%s %s = Unwrap(%s);\n' % (indent, ndo_name, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600650 else:
651 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
652 # as part of the string and explicitly print it
653 fix = str(prefix).strip('local_');
654 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
655 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700656 pre_call_code += '%s %s%s = Unwrap(%s%s);\n' % (indent, prefix, ndo_name, fix, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600657 indent = self.decIndent(indent)
658 pre_call_code += '%s }\n' % indent
659 return decl_code, pre_call_code, post_call_code
660 #
661 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
662 # create_func means that this is API creates or allocates NDOs
663 # destroy_func indicates that this API destroys or frees NDOs
664 # destroy_array means that the destroy_func operated on an array of NDOs
665 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
666 decls = ''
667 pre_code = ''
668 post_code = ''
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600669 index = 'index%s' % str(array_index)
670 array_index += 1
671 # Process any NDOs in this structure and recurse for any sub-structs in this struct
672 for member in members:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600673 process_pnext = self.StructWithExtensions(member.type)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600674 # Handle NDOs
675 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500676 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600677 if (count_name is not None):
678 if first_level_param == False:
679 count_name = '%s%s' % (prefix, member.len)
680
681 if (first_level_param == False) or (create_func == False):
682 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
683 decls += tmp_decl
684 pre_code += tmp_pre
685 post_code += tmp_post
686 # Handle Structs that contain NDOs at some level
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600687 elif member.type in self.struct_member_dict:
688 # Structs at first level will have an NDO, OR, we need a safe_struct for the pnext chain
689 if self.struct_contains_ndo(member.type) == True or process_pnext:
690 struct_info = self.struct_member_dict[member.type]
Jeff Bolz38b3ce72018-09-19 12:53:38 -0500691 # TODO (jbolz): Can this use paramIsPointer?
Jeff Bolzba74d972018-09-12 15:54:57 -0500692 ispointer = '*' in member.cdecl;
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
Jeff Bolzba74d972018-09-12 15:54:57 -0500725 elif ispointer:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600726 # 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)
Jeff Bolzba74d972018-09-12 15:54:57 -0500748 else:
749 # Update struct prefix
750 if first_level_param == True:
Jeff Bolz97eba1d2018-09-19 02:41:29 -0500751 sys.exit(1)
Jeff Bolzba74d972018-09-12 15:54:57 -0500752 else:
753 new_prefix = '%s%s.' % (prefix, member.name)
Jeff Bolzba74d972018-09-12 15:54:57 -0500754 # Process sub-structs in this struct
755 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
756 decls += tmp_decl
757 pre_code += tmp_pre
758 post_code += tmp_post
759 if process_pnext:
760 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 -0600761 return decls, pre_code, post_code
762 #
763 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
764 def generate_wrapping_code(self, cmd):
765 indent = ' '
766 proto = cmd.find('proto/name')
767 params = cmd.findall('param')
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600768
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600769 if proto.text is not None:
770 cmd_member_dict = dict(self.cmdMembers)
771 cmd_info = cmd_member_dict[proto.text]
772 # Handle ndo create/allocate operations
773 if cmd_info[0].iscreate:
774 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
775 else:
776 create_ndo_code = ''
777 # Handle ndo destroy/free operations
778 if cmd_info[0].isdestroy:
779 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
780 else:
781 destroy_array = False
782 destroy_ndo_code = ''
783 paramdecl = ''
784 param_pre_code = ''
785 param_post_code = ''
786 create_func = True if create_ndo_code else False
787 destroy_func = True if destroy_ndo_code else False
788 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
789 param_post_code += create_ndo_code
790 if destroy_ndo_code:
791 if destroy_array == True:
792 param_post_code += destroy_ndo_code
793 else:
794 param_pre_code += destroy_ndo_code
795 if param_pre_code:
796 if (not destroy_func) or (destroy_array):
797 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
798 return paramdecl, param_pre_code, param_post_code
799 #
800 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700801 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600802
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600803 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700804 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600805 members = cmdinfo.elem.findall('.//param')
806 # Iterate over members once to get length parameters for arrays
807 lens = set()
808 for member in members:
809 len = self.getLen(member)
810 if len:
811 lens.add(len)
812 struct_member_dict = dict(self.structMembers)
813 # Generate member info
814 membersInfo = []
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600815 constains_extension_structs = False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600816 for member in members:
817 # Get type and name of member
818 info = self.getTypeNameTuple(member)
819 type = info[0]
820 name = info[1]
821 cdecl = self.makeCParamDecl(member, 0)
822 # Check for parameter name in lens set
823 iscount = True if name in lens else False
824 len = self.getLen(member)
825 isconst = True if 'const' in cdecl else False
826 ispointer = self.paramIsPointer(member)
827 # Mark param as local if it is an array of NDOs
828 islocal = False;
829 if self.isHandleTypeNonDispatchable(type) == True:
830 if (len is not None) and (isconst == True):
831 islocal = True
832 # Or if it's a struct that contains an NDO
833 elif type in struct_member_dict:
834 if self.struct_contains_ndo(type) == True:
835 islocal = True
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600836 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700837 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 -0600838 extstructs = self.registry.validextensionstructs[type] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600839 membersInfo.append(self.CommandParam(type=type,
840 name=name,
841 ispointer=ispointer,
842 isconst=isconst,
843 iscount=iscount,
844 len=len,
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600845 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600846 cdecl=cdecl,
847 islocal=islocal,
848 iscreate=iscreate,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600849 isdestroy=isdestroy,
850 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600851 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600852 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
853 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
854 #
855 # Create code to wrap NDOs as well as handling some boilerplate code
856 def WrapCommands(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600857 cmd_member_dict = dict(self.cmdMembers)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600858 cmd_info_dict = dict(self.cmd_info_data)
859 cmd_protect_dict = dict(self.cmd_feature_protect)
860
861 for api_call in self.cmdMembers:
862 cmdname = api_call.name
863 cmdinfo = cmd_info_dict[api_call.name]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600864 if cmdname in self.no_autogen_list:
865 decls = self.makeCDecls(cmdinfo.elem)
866 self.appendSection('command', '')
867 self.appendSection('command', '// Declare only')
868 self.appendSection('command', decls[0])
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600869 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600870 continue
871 # Generate NDO wrapping/unwrapping code for all parameters
872 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
873 # If API doesn't contain an NDO's, don't fool with it
874 if not api_decls and not api_pre and not api_post:
875 continue
876 feature_extra_protect = cmd_protect_dict[api_call.name]
877 if (feature_extra_protect != None):
878 self.appendSection('command', '')
879 self.appendSection('command', '#ifdef '+ feature_extra_protect)
880 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
881 # Add intercept to procmap
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600882 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600883 decls = self.makeCDecls(cmdinfo.elem)
884 self.appendSection('command', '')
885 self.appendSection('command', decls[0][:-1])
886 self.appendSection('command', '{')
887 # Setup common to call wrappers, first parameter is always dispatchable
888 dispatchable_type = cmdinfo.elem.find('param/type').text
889 dispatchable_name = cmdinfo.elem.find('param/name').text
890 # Generate local instance/pdev/device data lookup
Chris Forbes5279a8c2017-05-02 16:26:23 -0700891 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
892 self.appendSection('command', ' instance_layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), instance_layer_data_map);')
893 else:
894 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600895 # Handle return values, if any
896 resulttype = cmdinfo.elem.find('proto/type')
897 if (resulttype != None and resulttype.text == 'void'):
898 resulttype = None
899 if (resulttype != None):
900 assignresult = resulttype.text + ' result = '
901 else:
902 assignresult = ''
903 # Pre-pend declarations and pre-api-call codegen
904 if api_decls:
905 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
906 if api_pre:
907 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
908 # Generate the API call itself
909 # Gather the parameter items
910 params = cmdinfo.elem.findall('param/name')
911 # Pull out the text for each of the parameters, separate them by commas in a list
912 paramstext = ', '.join([str(param.text) for param in params])
913 # If any of these paramters has been replaced by a local var, fix up the list
914 params = cmd_member_dict[cmdname]
915 for param in params:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600916 if param.islocal == True or self.StructWithExtensions(param.type):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600917 if param.ispointer == True:
918 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
919 else:
920 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
921 # Use correct dispatch table
Chris Forbes44c05302017-05-02 16:42:55 -0700922 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->dispatch_table.',1)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600923 # Put all this together for the final down-chain call
924 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
925 # And add the post-API-call codegen
926 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
927 # Handle the return result variable, if any
928 if (resulttype != None):
929 self.appendSection('command', ' return result;')
930 self.appendSection('command', '}')
931 if (feature_extra_protect != None):
932 self.appendSection('command', '#endif // '+ feature_extra_protect)
933 self.intercepts += [ '#endif' ]