blob: 78526a3eae44e9aaf6a8d99ce90501e34fd06b85 [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',
Mark Youngabc2d6e2017-07-07 07:59:56 -0600155 'vkGetPhysicalDeviceDisplayProperties2KHR',
156 'vkGetPhysicalDeviceDisplayPlaneProperties2KHR',
157 'vkGetDisplayModeProperties2KHR',
Petr Krause91f7a12017-12-14 20:57:36 +0100158 'vkCreateRenderPass',
159 'vkDestroyRenderPass',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600160 ]
161 # Commands shadowed by interface functions and are not implemented
162 self.interface_functions = [
163 'vkGetPhysicalDeviceDisplayPropertiesKHR',
164 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
165 'vkGetDisplayPlaneSupportedDisplaysKHR',
166 'vkGetDisplayModePropertiesKHR',
Norbert Nopper1dec9a52016-11-25 07:55:13 +0100167 'vkGetDisplayPlaneCapabilitiesKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600168 # DebugReport APIs are hooked, but handled separately in the source file
169 'vkCreateDebugReportCallbackEXT',
170 'vkDestroyDebugReportCallbackEXT',
171 'vkDebugReportMessageEXT',
172 ]
173 self.headerVersion = None
174 # Internal state - accumulators for different inner block text
175 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600176
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600177 self.cmdMembers = []
178 self.cmd_feature_protect = [] # Save ifdef's for each command
Mark Lobodzinski85904632017-04-06 10:07:42 -0600179 self.cmd_info_data = [] # Save the cmdinfo data for wrapping the handles when processing is complete
180 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
181 self.extension_structs = [] # List of all structs or sister-structs containing handles
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600182 # A sister-struct may contain no handles but shares a structextends attribute with one that does
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600183 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
184 self.struct_member_dict = dict()
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600185 # Named tuples to store struct and command data
Mark Lobodzinski85904632017-04-06 10:07:42 -0600186 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600187 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
188 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
189 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600190
191 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600192 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
193 #
194 def incIndent(self, indent):
195 inc = ' ' * self.INDENT_SPACES
196 if indent:
197 return indent + inc
198 return inc
199 #
200 def decIndent(self, indent):
201 if indent and (len(indent) > self.INDENT_SPACES):
202 return indent[:-self.INDENT_SPACES]
203 return ''
204 #
205 # Override makeProtoName to drop the "vk" prefix
206 def makeProtoName(self, name, tail):
207 return self.genOpts.apientry + name[2:] + tail
208 #
209 # Check if the parameter passed in is a pointer to an array
210 def paramIsArray(self, param):
211 return param.attrib.get('len') is not None
212 #
213 def beginFile(self, genOpts):
214 OutputGenerator.beginFile(self, genOpts)
215 # User-supplied prefix text, if any (list of strings)
216 if (genOpts.prefixText):
217 for s in genOpts.prefixText:
218 write(s, file=self.outFile)
219 # Namespace
220 self.newline()
221 write('namespace unique_objects {', file = self.outFile)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600222 # Now that the data is all collected and complete, generate and output the wrapping/unwrapping routines
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600223 def endFile(self):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600224
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600225 self.struct_member_dict = dict(self.structMembers)
226
227 # Generate the list of APIs that might need to handle wrapped extension structs
228 self.GenerateCommandWrapExtensionList()
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600229 # Write out wrapping/unwrapping functions
230 self.WrapCommands()
Mark Lobodzinski85904632017-04-06 10:07:42 -0600231 # Build and write out pNext processing function
232 extension_proc = self.build_extension_processing_func()
233 self.newline()
234 write('// Unique Objects pNext extension handling function', file=self.outFile)
235 write('%s' % extension_proc, file=self.outFile)
236
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600237 # Actually write the interface to the output file.
238 if (self.emit):
239 self.newline()
240 if (self.featureExtraProtect != None):
241 write('#ifdef', self.featureExtraProtect, file=self.outFile)
242 # Write the unique_objects code to the file
243 if (self.sections['command']):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600244 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
245 if (self.featureExtraProtect != None):
246 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
247 else:
248 self.newline()
249
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600250 # Record intercepted procedures
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600251 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
252 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600253 write('\n'.join(self.intercepts), file=self.outFile)
254 write('};\n', file=self.outFile)
255 self.newline()
256 write('} // namespace unique_objects', file=self.outFile)
257 # Finish processing in superclass
258 OutputGenerator.endFile(self)
259 #
260 def beginFeature(self, interface, emit):
261 # Start processing in superclass
262 OutputGenerator.beginFeature(self, interface, emit)
263 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600264 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600265 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700266 white_list_entry = []
267 if (self.featureExtraProtect != None):
268 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
269 white_list_entry += [ '"%s"' % self.featureName ]
270 if (self.featureExtraProtect != None):
271 white_list_entry += [ '#endif' ]
272 featureType = interface.get('type')
273 if featureType == 'instance':
274 self.instance_extensions += white_list_entry
275 elif featureType == 'device':
276 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600277 #
278 def endFeature(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600279 # Finish processing in superclass
280 OutputGenerator.endFeature(self)
281 #
282 def genType(self, typeinfo, name):
283 OutputGenerator.genType(self, typeinfo, name)
284 typeElem = typeinfo.elem
285 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
286 # Otherwise, emit the tag text.
287 category = typeElem.get('category')
288 if (category == 'struct' or category == 'union'):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600289 self.genStruct(typeinfo, name)
290 #
291 # Append a definition to the specified section
292 def appendSection(self, section, text):
293 # self.sections[section].append('SECTION: ' + section + '\n')
294 self.sections[section].append(text)
295 #
296 # Check if the parameter passed in is a pointer
297 def paramIsPointer(self, param):
298 ispointer = False
299 for elem in param:
300 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
301 ispointer = True
302 return ispointer
303 #
304 # Get the category of a type
305 def getTypeCategory(self, typename):
306 types = self.registry.tree.findall("types/type")
307 for elem in types:
308 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
309 return elem.attrib.get('category')
310 #
311 # Check if a parent object is dispatchable or not
312 def isHandleTypeNonDispatchable(self, handletype):
313 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
314 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
315 return True
316 else:
317 return False
318 #
319 # Retrieve the type and name for a parameter
320 def getTypeNameTuple(self, param):
321 type = ''
322 name = ''
323 for elem in param:
324 if elem.tag == 'type':
325 type = noneStr(elem.text)
326 elif elem.tag == 'name':
327 name = noneStr(elem.text)
328 return (type, name)
329 #
330 # Retrieve the value of the len tag
331 def getLen(self, param):
332 result = None
333 len = param.attrib.get('len')
334 if len and len != 'null-terminated':
335 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
336 # have a null terminated array of strings. We strip the null-terminated from the
337 # 'len' field and only return the parameter specifying the string count
338 if 'null-terminated' in len:
339 result = len.split(',')[0]
340 else:
341 result = len
342 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
343 result = str(result).replace('::', '->')
344 return result
345 #
346 # Generate a VkStructureType based on a structure typename
347 def genVkStructureType(self, typename):
348 # Add underscore between lowercase then uppercase
349 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
350 # Change to uppercase
351 value = value.upper()
352 # Add STRUCTURE_TYPE_
353 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
354 #
355 # Struct parameter check generation.
356 # This is a special case of the <type> tag where the contents are interpreted as a set of
357 # <member> tags instead of freeform C type declarations. The <member> tags are just like
358 # <param> tags - they are a declaration of a struct or union member. Only simple member
359 # declarations are supported (no nested structs etc.)
360 def genStruct(self, typeinfo, typeName):
361 OutputGenerator.genStruct(self, typeinfo, typeName)
362 members = typeinfo.elem.findall('.//member')
363 # Iterate over members once to get length parameters for arrays
364 lens = set()
365 for member in members:
366 len = self.getLen(member)
367 if len:
368 lens.add(len)
369 # Generate member info
370 membersInfo = []
371 for member in members:
372 # Get the member's type and name
373 info = self.getTypeNameTuple(member)
374 type = info[0]
375 name = info[1]
376 cdecl = self.makeCParamDecl(member, 0)
377 # Process VkStructureType
378 if type == 'VkStructureType':
379 # Extract the required struct type value from the comments
380 # embedded in the original text defining the 'typeinfo' element
381 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
382 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
383 if result:
384 value = result.group(0)
385 else:
386 value = self.genVkStructureType(typeName)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600387 # Store the required type value
388 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600389 # Store pointer/array/string info
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600390 extstructs = self.registry.validextensionstructs[typeName] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600391 membersInfo.append(self.CommandParam(type=type,
392 name=name,
393 ispointer=self.paramIsPointer(member),
394 isconst=True if 'const' in cdecl else False,
395 iscount=True if name in lens else False,
396 len=self.getLen(member),
Mark Lobodzinski85904632017-04-06 10:07:42 -0600397 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600398 cdecl=cdecl,
399 islocal=False,
400 iscreate=False,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600401 isdestroy=False,
402 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600403 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
Mark Lobodzinski85904632017-04-06 10:07:42 -0600404
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600405 #
406 # Insert a lock_guard line
407 def lock_guard(self, indent):
408 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
409 #
410 # Determine if a struct has an NDO as a member or an embedded member
411 def struct_contains_ndo(self, struct_item):
412 struct_member_dict = dict(self.structMembers)
413 struct_members = struct_member_dict[struct_item]
414
415 for member in struct_members:
416 if self.isHandleTypeNonDispatchable(member.type):
417 return True
418 elif member.type in struct_member_dict:
419 if self.struct_contains_ndo(member.type) == True:
420 return True
421 return False
422 #
423 # Return list of struct members which contain, or which sub-structures contain
424 # an NDO in a given list of parameters or members
425 def getParmeterStructsWithNdos(self, item_list):
426 struct_list = set()
427 for item in item_list:
428 paramtype = item.find('type')
429 typecategory = self.getTypeCategory(paramtype.text)
430 if typecategory == 'struct':
431 if self.struct_contains_ndo(paramtype.text) == True:
432 struct_list.add(item)
433 return struct_list
434 #
435 # Return list of non-dispatchable objects from a given list of parameters or members
436 def getNdosInParameterList(self, item_list, create_func):
437 ndo_list = set()
438 if create_func == True:
439 member_list = item_list[0:-1]
440 else:
441 member_list = item_list
442 for item in member_list:
443 if self.isHandleTypeNonDispatchable(paramtype.text):
444 ndo_list.add(item)
445 return ndo_list
446 #
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600447 # Construct list of extension structs containing handles, or extension structs that share a structextends attribute
448 # 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 -0600449 # TODO: make this recursive -- structs buried three or more levels deep are not searched for extensions
450 def GenerateCommandWrapExtensionList(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600451 for struct in self.structMembers:
452 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
453 found = False;
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600454 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600455 if item != '' and self.struct_contains_ndo(item) == True:
456 found = True
457 if found == True:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600458 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600459 if item != '' and item not in self.extension_structs:
460 self.extension_structs.append(item)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600461 #
462 # Returns True if a struct may have a pNext chain containing an NDO
463 def StructWithExtensions(self, struct_type):
464 if struct_type in self.struct_member_dict:
465 param_info = self.struct_member_dict[struct_type]
466 if (len(param_info) > 1) and param_info[1].extstructs is not None:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600467 for item in param_info[1].extstructs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600468 if item in self.extension_structs:
469 return True
470 return False
471 #
472 # Generate pNext handling function
473 def build_extension_processing_func(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600474 # Construct helper functions to build and free pNext extension chains
475 pnext_proc = ''
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700476 pnext_proc += 'void *CreateUnwrappedExtensionStructs(const void *pNext) {\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600477 pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
478 pnext_proc += ' void *head_pnext = NULL;\n'
479 pnext_proc += ' void *prev_ext_struct = NULL;\n'
480 pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
481 pnext_proc += ' while (cur_pnext != NULL) {\n'
482 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(cur_pnext);\n\n'
483 pnext_proc += ' switch (header->sType) {\n'
484 for item in self.extension_structs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600485 struct_info = self.struct_member_dict[item]
Mark Lobodzinski85904632017-04-06 10:07:42 -0600486 if struct_info[0].feature_protect is not None:
487 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
488 pnext_proc += ' case %s: {\n' % self.structTypes[item].value
Chris Forbes0f86c402017-05-02 18:36:39 -0700489 pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600490 pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
491 # Generate code to unwrap the handles
492 indent = ' '
493 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, 'safe_struct->', 0, False, False, False, False)
494 pnext_proc += tmp_pre
495 pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
496 pnext_proc += ' } break;\n'
497 if struct_info[0].feature_protect is not None:
498 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
499 pnext_proc += '\n'
500 pnext_proc += ' default:\n'
501 pnext_proc += ' break;\n'
502 pnext_proc += ' }\n\n'
503 pnext_proc += ' // Save pointer to the first structure in the pNext chain\n'
504 pnext_proc += ' head_pnext = (head_pnext ? head_pnext : cur_ext_struct);\n\n'
505 pnext_proc += ' // For any extension structure but the first, link the last struct\'s pNext to the current ext struct\n'
506 pnext_proc += ' if (prev_ext_struct) {\n'
507 pnext_proc += ' (reinterpret_cast<GenericHeader *>(prev_ext_struct))->pNext = cur_ext_struct;\n'
508 pnext_proc += ' }\n'
509 pnext_proc += ' prev_ext_struct = cur_ext_struct;\n\n'
510 pnext_proc += ' // Process the next structure in the chain\n'
511 pnext_proc += ' cur_pnext = const_cast<void *>(header->pNext);\n'
512 pnext_proc += ' }\n'
513 pnext_proc += ' return head_pnext;\n'
514 pnext_proc += '}\n\n'
515 pnext_proc += '// Free a pNext extension chain\n'
516 pnext_proc += 'void FreeUnwrappedExtensionStructs(void *head) {\n'
517 pnext_proc += ' void * curr_ptr = head;\n'
518 pnext_proc += ' while (curr_ptr) {\n'
519 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(curr_ptr);\n'
520 pnext_proc += ' void *temp = curr_ptr;\n'
521 pnext_proc += ' curr_ptr = header->pNext;\n'
522 pnext_proc += ' free(temp);\n'
523 pnext_proc += ' }\n'
524 pnext_proc += '}\n'
525 return pnext_proc
526
527 #
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600528 # Generate source for creating a non-dispatchable object
529 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
530 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700531 handle_type = params[-1].find('type')
532 if self.isHandleTypeNonDispatchable(handle_type.text):
533 # Check for special case where multiple handles are returned
534 ndo_array = False
535 if cmd_info[-1].len is not None:
536 ndo_array = True;
537 handle_name = params[-1].find('name')
538 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
539 indent = self.incIndent(indent)
540 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
541 ndo_dest = '*%s' % handle_name.text
542 if ndo_array == True:
543 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600544 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700545 ndo_dest = '%s[index0]' % cmd_info[-1].name
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700546 create_ndo_code += '%s%s = WrapNew(%s);\n' % (indent, ndo_dest, ndo_dest)
Mark Young39389872017-01-19 21:10:49 -0700547 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600548 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700549 create_ndo_code += '%s}\n' % indent
550 indent = self.decIndent(indent)
551 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600552 return create_ndo_code
553 #
554 # Generate source for destroying a non-dispatchable object
555 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
556 destroy_ndo_code = ''
557 ndo_array = False
558 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
559 # Check for special case where multiple handles are returned
560 if cmd_info[-1].len is not None:
561 ndo_array = True;
562 param = -1
563 else:
564 param = -2
565 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
566 if ndo_array == True:
567 # This API is freeing an array of handles. Remove them from the unique_id map.
568 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
569 indent = self.incIndent(indent)
570 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
571 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
572 indent = self.incIndent(indent)
573 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
574 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700575 destroy_ndo_code += '%sunique_id_mapping.erase(unique_id);\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600576 indent = self.decIndent(indent);
577 destroy_ndo_code += '%s}\n' % indent
578 indent = self.decIndent(indent);
579 destroy_ndo_code += '%s}\n' % indent
580 else:
581 # Remove a single handle from the map
582 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
583 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 -0700584 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)
585 destroy_ndo_code += '%sunique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600586 destroy_ndo_code += '%slock.unlock();\n' % (indent)
587 return ndo_array, destroy_ndo_code
588
589 #
590 # Clean up local declarations
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600591 def cleanUpLocalDeclarations(self, indent, prefix, name, len, index, process_pnext):
Mark Young26095c42017-05-09 13:19:04 -0600592 cleanup = '%sif (local_%s%s) {\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600593 if len is not None:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600594 if process_pnext:
595 cleanup += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, len, index)
596 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s[%s].pNext));\n' % (indent, prefix, name, index)
597 cleanup += '%s }\n' % indent
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600598 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
599 else:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600600 if process_pnext:
601 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s->pNext));\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600602 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
Mark Young26095c42017-05-09 13:19:04 -0600603 cleanup += "%s}\n" % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600604 return cleanup
605 #
606 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
607 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
608 decl_code = ''
609 pre_call_code = ''
610 post_call_code = ''
611 if ndo_count is not None:
612 if top_level == True:
613 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
614 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
615 indent = self.incIndent(indent)
616 if top_level == True:
617 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
618 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
619 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700620 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 -0600621 else:
622 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
623 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700624 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 -0600625 indent = self.decIndent(indent)
626 pre_call_code += '%s }\n' % indent
627 indent = self.decIndent(indent)
628 pre_call_code += '%s }\n' % indent
629 if top_level == True:
630 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
631 indent = self.incIndent(indent)
632 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
633 else:
634 if top_level == True:
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600635 if (destroy_func == False) or (destroy_array == True):
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700636 pre_call_code += '%s %s = Unwrap(%s);\n' % (indent, ndo_name, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600637 else:
638 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
639 # as part of the string and explicitly print it
640 fix = str(prefix).strip('local_');
641 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
642 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700643 pre_call_code += '%s %s%s = Unwrap(%s%s);\n' % (indent, prefix, ndo_name, fix, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600644 indent = self.decIndent(indent)
645 pre_call_code += '%s }\n' % indent
646 return decl_code, pre_call_code, post_call_code
647 #
648 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
649 # create_func means that this is API creates or allocates NDOs
650 # destroy_func indicates that this API destroys or frees NDOs
651 # destroy_array means that the destroy_func operated on an array of NDOs
652 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
653 decls = ''
654 pre_code = ''
655 post_code = ''
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600656 index = 'index%s' % str(array_index)
657 array_index += 1
658 # Process any NDOs in this structure and recurse for any sub-structs in this struct
659 for member in members:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600660 process_pnext = self.StructWithExtensions(member.type)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600661 # Handle NDOs
662 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500663 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600664 if (count_name is not None):
665 if first_level_param == False:
666 count_name = '%s%s' % (prefix, member.len)
667
668 if (first_level_param == False) or (create_func == False):
669 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
670 decls += tmp_decl
671 pre_code += tmp_pre
672 post_code += tmp_post
673 # Handle Structs that contain NDOs at some level
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600674 elif member.type in self.struct_member_dict:
675 # Structs at first level will have an NDO, OR, we need a safe_struct for the pnext chain
676 if self.struct_contains_ndo(member.type) == True or process_pnext:
677 struct_info = self.struct_member_dict[member.type]
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600678 # Struct Array
679 if member.len is not None:
680 # Update struct prefix
681 if first_level_param == True:
682 new_prefix = 'local_%s' % member.name
683 # Declare safe_VarType for struct
684 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
685 else:
686 new_prefix = '%s%s' % (prefix, member.name)
687 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
688 indent = self.incIndent(indent)
689 if first_level_param == True:
690 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
691 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
692 indent = self.incIndent(indent)
693 if first_level_param == True:
694 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600695 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700696 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 -0600697 local_prefix = '%s[%s].' % (new_prefix, index)
698 # Process sub-structs in this struct
699 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
700 decls += tmp_decl
701 pre_code += tmp_pre
702 post_code += tmp_post
703 indent = self.decIndent(indent)
704 pre_code += '%s }\n' % indent
705 indent = self.decIndent(indent)
706 pre_code += '%s }\n' % indent
707 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600708 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600709 # Single Struct
710 else:
711 # Update struct prefix
712 if first_level_param == True:
713 new_prefix = 'local_%s->' % member.name
714 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
715 else:
716 new_prefix = '%s%s->' % (prefix, member.name)
717 # Declare safe_VarType for struct
718 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
719 indent = self.incIndent(indent)
720 if first_level_param == True:
721 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
722 # Process sub-structs in this struct
723 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
724 decls += tmp_decl
725 pre_code += tmp_pre
726 post_code += tmp_post
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600727 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700728 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 -0600729 indent = self.decIndent(indent)
730 pre_code += '%s }\n' % indent
731 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600732 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600733 return decls, pre_code, post_code
734 #
735 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
736 def generate_wrapping_code(self, cmd):
737 indent = ' '
738 proto = cmd.find('proto/name')
739 params = cmd.findall('param')
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600740
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600741 if proto.text is not None:
742 cmd_member_dict = dict(self.cmdMembers)
743 cmd_info = cmd_member_dict[proto.text]
744 # Handle ndo create/allocate operations
745 if cmd_info[0].iscreate:
746 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
747 else:
748 create_ndo_code = ''
749 # Handle ndo destroy/free operations
750 if cmd_info[0].isdestroy:
751 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
752 else:
753 destroy_array = False
754 destroy_ndo_code = ''
755 paramdecl = ''
756 param_pre_code = ''
757 param_post_code = ''
758 create_func = True if create_ndo_code else False
759 destroy_func = True if destroy_ndo_code else False
760 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
761 param_post_code += create_ndo_code
762 if destroy_ndo_code:
763 if destroy_array == True:
764 param_post_code += destroy_ndo_code
765 else:
766 param_pre_code += destroy_ndo_code
767 if param_pre_code:
768 if (not destroy_func) or (destroy_array):
769 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
770 return paramdecl, param_pre_code, param_post_code
771 #
772 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
773 def genCmd(self, cmdinfo, cmdname):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600774
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600775 # Add struct-member type information to command parameter information
776 OutputGenerator.genCmd(self, cmdinfo, cmdname)
777 members = cmdinfo.elem.findall('.//param')
778 # Iterate over members once to get length parameters for arrays
779 lens = set()
780 for member in members:
781 len = self.getLen(member)
782 if len:
783 lens.add(len)
784 struct_member_dict = dict(self.structMembers)
785 # Generate member info
786 membersInfo = []
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600787 constains_extension_structs = False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600788 for member in members:
789 # Get type and name of member
790 info = self.getTypeNameTuple(member)
791 type = info[0]
792 name = info[1]
793 cdecl = self.makeCParamDecl(member, 0)
794 # Check for parameter name in lens set
795 iscount = True if name in lens else False
796 len = self.getLen(member)
797 isconst = True if 'const' in cdecl else False
798 ispointer = self.paramIsPointer(member)
799 # Mark param as local if it is an array of NDOs
800 islocal = False;
801 if self.isHandleTypeNonDispatchable(type) == True:
802 if (len is not None) and (isconst == True):
803 islocal = True
804 # Or if it's a struct that contains an NDO
805 elif type in struct_member_dict:
806 if self.struct_contains_ndo(type) == True:
807 islocal = True
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600808 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700809 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 -0600810 extstructs = self.registry.validextensionstructs[type] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600811 membersInfo.append(self.CommandParam(type=type,
812 name=name,
813 ispointer=ispointer,
814 isconst=isconst,
815 iscount=iscount,
816 len=len,
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600817 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600818 cdecl=cdecl,
819 islocal=islocal,
820 iscreate=iscreate,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600821 isdestroy=isdestroy,
822 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600823 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600824 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
825 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
826 #
827 # Create code to wrap NDOs as well as handling some boilerplate code
828 def WrapCommands(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600829 cmd_member_dict = dict(self.cmdMembers)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600830 cmd_info_dict = dict(self.cmd_info_data)
831 cmd_protect_dict = dict(self.cmd_feature_protect)
832
833 for api_call in self.cmdMembers:
834 cmdname = api_call.name
835 cmdinfo = cmd_info_dict[api_call.name]
836 if cmdname in self.interface_functions:
837 continue
838 if cmdname in self.no_autogen_list:
839 decls = self.makeCDecls(cmdinfo.elem)
840 self.appendSection('command', '')
841 self.appendSection('command', '// Declare only')
842 self.appendSection('command', decls[0])
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600843 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600844 continue
845 # Generate NDO wrapping/unwrapping code for all parameters
846 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
847 # If API doesn't contain an NDO's, don't fool with it
848 if not api_decls and not api_pre and not api_post:
849 continue
850 feature_extra_protect = cmd_protect_dict[api_call.name]
851 if (feature_extra_protect != None):
852 self.appendSection('command', '')
853 self.appendSection('command', '#ifdef '+ feature_extra_protect)
854 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
855 # Add intercept to procmap
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600856 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600857 decls = self.makeCDecls(cmdinfo.elem)
858 self.appendSection('command', '')
859 self.appendSection('command', decls[0][:-1])
860 self.appendSection('command', '{')
861 # Setup common to call wrappers, first parameter is always dispatchable
862 dispatchable_type = cmdinfo.elem.find('param/type').text
863 dispatchable_name = cmdinfo.elem.find('param/name').text
864 # Generate local instance/pdev/device data lookup
Chris Forbes5279a8c2017-05-02 16:26:23 -0700865 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
866 self.appendSection('command', ' instance_layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), instance_layer_data_map);')
867 else:
868 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600869 # Handle return values, if any
870 resulttype = cmdinfo.elem.find('proto/type')
871 if (resulttype != None and resulttype.text == 'void'):
872 resulttype = None
873 if (resulttype != None):
874 assignresult = resulttype.text + ' result = '
875 else:
876 assignresult = ''
877 # Pre-pend declarations and pre-api-call codegen
878 if api_decls:
879 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
880 if api_pre:
881 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
882 # Generate the API call itself
883 # Gather the parameter items
884 params = cmdinfo.elem.findall('param/name')
885 # Pull out the text for each of the parameters, separate them by commas in a list
886 paramstext = ', '.join([str(param.text) for param in params])
887 # If any of these paramters has been replaced by a local var, fix up the list
888 params = cmd_member_dict[cmdname]
889 for param in params:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600890 if param.islocal == True or self.StructWithExtensions(param.type):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600891 if param.ispointer == True:
892 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
893 else:
894 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
895 # Use correct dispatch table
Chris Forbes44c05302017-05-02 16:42:55 -0700896 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->dispatch_table.',1)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600897 # Put all this together for the final down-chain call
898 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
899 # And add the post-API-call codegen
900 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
901 # Handle the return result variable, if any
902 if (resulttype != None):
903 self.appendSection('command', ' return result;')
904 self.appendSection('command', '}')
905 if (feature_extra_protect != None):
906 self.appendSection('command', '#endif // '+ feature_extra_protect)
907 self.intercepts += [ '#endif' ]