blob: c80696a489cf671309b89c062a478e7684fb0f7b [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 Lobodzinski71703a52017-03-03 08:40:16 -0700146 'vkCreateDescriptorUpdateTemplateKHR',
147 'vkDestroyDescriptorUpdateTemplateKHR',
148 'vkUpdateDescriptorSetWithTemplateKHR',
149 'vkCmdPushDescriptorSetWithTemplateKHR',
Mark Lobodzinskia096c122017-03-16 11:54:35 -0600150 'vkDebugMarkerSetObjectTagEXT',
151 'vkDebugMarkerSetObjectNameEXT',
Mark Youngabc2d6e2017-07-07 07:59:56 -0600152 'vkGetPhysicalDeviceDisplayProperties2KHR',
153 'vkGetPhysicalDeviceDisplayPlaneProperties2KHR',
154 'vkGetDisplayModeProperties2KHR',
Petr Krause91f7a12017-12-14 20:57:36 +0100155 'vkCreateRenderPass',
156 'vkDestroyRenderPass',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600157 ]
158 # Commands shadowed by interface functions and are not implemented
159 self.interface_functions = [
160 'vkGetPhysicalDeviceDisplayPropertiesKHR',
161 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
162 'vkGetDisplayPlaneSupportedDisplaysKHR',
163 'vkGetDisplayModePropertiesKHR',
Norbert Nopper1dec9a52016-11-25 07:55:13 +0100164 'vkGetDisplayPlaneCapabilitiesKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600165 # DebugReport APIs are hooked, but handled separately in the source file
166 'vkCreateDebugReportCallbackEXT',
167 'vkDestroyDebugReportCallbackEXT',
168 'vkDebugReportMessageEXT',
169 ]
170 self.headerVersion = None
171 # Internal state - accumulators for different inner block text
172 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600173
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600174 self.cmdMembers = []
175 self.cmd_feature_protect = [] # Save ifdef's for each command
Mark Lobodzinski85904632017-04-06 10:07:42 -0600176 self.cmd_info_data = [] # Save the cmdinfo data for wrapping the handles when processing is complete
177 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
178 self.extension_structs = [] # List of all structs or sister-structs containing handles
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600179 # A sister-struct may contain no handles but shares a structextends attribute with one that does
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600180 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
181 self.struct_member_dict = dict()
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600182 # Named tuples to store struct and command data
Mark Lobodzinski85904632017-04-06 10:07:42 -0600183 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600184 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
185 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
186 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600187
188 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600189 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
190 #
191 def incIndent(self, indent):
192 inc = ' ' * self.INDENT_SPACES
193 if indent:
194 return indent + inc
195 return inc
196 #
197 def decIndent(self, indent):
198 if indent and (len(indent) > self.INDENT_SPACES):
199 return indent[:-self.INDENT_SPACES]
200 return ''
201 #
202 # Override makeProtoName to drop the "vk" prefix
203 def makeProtoName(self, name, tail):
204 return self.genOpts.apientry + name[2:] + tail
205 #
206 # Check if the parameter passed in is a pointer to an array
207 def paramIsArray(self, param):
208 return param.attrib.get('len') is not None
209 #
210 def beginFile(self, genOpts):
211 OutputGenerator.beginFile(self, genOpts)
212 # User-supplied prefix text, if any (list of strings)
213 if (genOpts.prefixText):
214 for s in genOpts.prefixText:
215 write(s, file=self.outFile)
216 # Namespace
217 self.newline()
218 write('namespace unique_objects {', file = self.outFile)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600219 # Now that the data is all collected and complete, generate and output the wrapping/unwrapping routines
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600220 def endFile(self):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600221
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600222 self.struct_member_dict = dict(self.structMembers)
223
224 # Generate the list of APIs that might need to handle wrapped extension structs
225 self.GenerateCommandWrapExtensionList()
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600226 # Write out wrapping/unwrapping functions
227 self.WrapCommands()
Mark Lobodzinski85904632017-04-06 10:07:42 -0600228 # Build and write out pNext processing function
229 extension_proc = self.build_extension_processing_func()
230 self.newline()
231 write('// Unique Objects pNext extension handling function', file=self.outFile)
232 write('%s' % extension_proc, file=self.outFile)
233
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600234 # Actually write the interface to the output file.
235 if (self.emit):
236 self.newline()
237 if (self.featureExtraProtect != None):
238 write('#ifdef', self.featureExtraProtect, file=self.outFile)
239 # Write the unique_objects code to the file
240 if (self.sections['command']):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600241 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
242 if (self.featureExtraProtect != None):
243 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
244 else:
245 self.newline()
246
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600247 # Record intercepted procedures
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600248 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
249 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600250 write('\n'.join(self.intercepts), file=self.outFile)
251 write('};\n', file=self.outFile)
252 self.newline()
253 write('} // namespace unique_objects', file=self.outFile)
254 # Finish processing in superclass
255 OutputGenerator.endFile(self)
256 #
257 def beginFeature(self, interface, emit):
258 # Start processing in superclass
259 OutputGenerator.beginFeature(self, interface, emit)
260 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600261 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600262 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700263 white_list_entry = []
264 if (self.featureExtraProtect != None):
265 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
266 white_list_entry += [ '"%s"' % self.featureName ]
267 if (self.featureExtraProtect != None):
268 white_list_entry += [ '#endif' ]
269 featureType = interface.get('type')
270 if featureType == 'instance':
271 self.instance_extensions += white_list_entry
272 elif featureType == 'device':
273 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600274 #
275 def endFeature(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600276 # Finish processing in superclass
277 OutputGenerator.endFeature(self)
278 #
279 def genType(self, typeinfo, name):
280 OutputGenerator.genType(self, typeinfo, name)
281 typeElem = typeinfo.elem
282 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
283 # Otherwise, emit the tag text.
284 category = typeElem.get('category')
285 if (category == 'struct' or category == 'union'):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600286 self.genStruct(typeinfo, name)
287 #
288 # Append a definition to the specified section
289 def appendSection(self, section, text):
290 # self.sections[section].append('SECTION: ' + section + '\n')
291 self.sections[section].append(text)
292 #
293 # Check if the parameter passed in is a pointer
294 def paramIsPointer(self, param):
295 ispointer = False
296 for elem in param:
297 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
298 ispointer = True
299 return ispointer
300 #
301 # Get the category of a type
302 def getTypeCategory(self, typename):
303 types = self.registry.tree.findall("types/type")
304 for elem in types:
305 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
306 return elem.attrib.get('category')
307 #
308 # Check if a parent object is dispatchable or not
309 def isHandleTypeNonDispatchable(self, handletype):
310 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
311 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
312 return True
313 else:
314 return False
315 #
316 # Retrieve the type and name for a parameter
317 def getTypeNameTuple(self, param):
318 type = ''
319 name = ''
320 for elem in param:
321 if elem.tag == 'type':
322 type = noneStr(elem.text)
323 elif elem.tag == 'name':
324 name = noneStr(elem.text)
325 return (type, name)
326 #
327 # Retrieve the value of the len tag
328 def getLen(self, param):
329 result = None
330 len = param.attrib.get('len')
331 if len and len != 'null-terminated':
332 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
333 # have a null terminated array of strings. We strip the null-terminated from the
334 # 'len' field and only return the parameter specifying the string count
335 if 'null-terminated' in len:
336 result = len.split(',')[0]
337 else:
338 result = len
339 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
340 result = str(result).replace('::', '->')
341 return result
342 #
343 # Generate a VkStructureType based on a structure typename
344 def genVkStructureType(self, typename):
345 # Add underscore between lowercase then uppercase
346 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
347 # Change to uppercase
348 value = value.upper()
349 # Add STRUCTURE_TYPE_
350 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
351 #
352 # Struct parameter check generation.
353 # This is a special case of the <type> tag where the contents are interpreted as a set of
354 # <member> tags instead of freeform C type declarations. The <member> tags are just like
355 # <param> tags - they are a declaration of a struct or union member. Only simple member
356 # declarations are supported (no nested structs etc.)
357 def genStruct(self, typeinfo, typeName):
358 OutputGenerator.genStruct(self, typeinfo, typeName)
359 members = typeinfo.elem.findall('.//member')
360 # Iterate over members once to get length parameters for arrays
361 lens = set()
362 for member in members:
363 len = self.getLen(member)
364 if len:
365 lens.add(len)
366 # Generate member info
367 membersInfo = []
368 for member in members:
369 # Get the member's type and name
370 info = self.getTypeNameTuple(member)
371 type = info[0]
372 name = info[1]
373 cdecl = self.makeCParamDecl(member, 0)
374 # Process VkStructureType
375 if type == 'VkStructureType':
376 # Extract the required struct type value from the comments
377 # embedded in the original text defining the 'typeinfo' element
378 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
379 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
380 if result:
381 value = result.group(0)
382 else:
383 value = self.genVkStructureType(typeName)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600384 # Store the required type value
385 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600386 # Store pointer/array/string info
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600387 extstructs = self.registry.validextensionstructs[typeName] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600388 membersInfo.append(self.CommandParam(type=type,
389 name=name,
390 ispointer=self.paramIsPointer(member),
391 isconst=True if 'const' in cdecl else False,
392 iscount=True if name in lens else False,
393 len=self.getLen(member),
Mark Lobodzinski85904632017-04-06 10:07:42 -0600394 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600395 cdecl=cdecl,
396 islocal=False,
397 iscreate=False,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600398 isdestroy=False,
399 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600400 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
Mark Lobodzinski85904632017-04-06 10:07:42 -0600401
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600402 #
403 # Insert a lock_guard line
404 def lock_guard(self, indent):
405 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
406 #
407 # Determine if a struct has an NDO as a member or an embedded member
408 def struct_contains_ndo(self, struct_item):
409 struct_member_dict = dict(self.structMembers)
410 struct_members = struct_member_dict[struct_item]
411
412 for member in struct_members:
413 if self.isHandleTypeNonDispatchable(member.type):
414 return True
415 elif member.type in struct_member_dict:
416 if self.struct_contains_ndo(member.type) == True:
417 return True
418 return False
419 #
420 # Return list of struct members which contain, or which sub-structures contain
421 # an NDO in a given list of parameters or members
422 def getParmeterStructsWithNdos(self, item_list):
423 struct_list = set()
424 for item in item_list:
425 paramtype = item.find('type')
426 typecategory = self.getTypeCategory(paramtype.text)
427 if typecategory == 'struct':
428 if self.struct_contains_ndo(paramtype.text) == True:
429 struct_list.add(item)
430 return struct_list
431 #
432 # Return list of non-dispatchable objects from a given list of parameters or members
433 def getNdosInParameterList(self, item_list, create_func):
434 ndo_list = set()
435 if create_func == True:
436 member_list = item_list[0:-1]
437 else:
438 member_list = item_list
439 for item in member_list:
440 if self.isHandleTypeNonDispatchable(paramtype.text):
441 ndo_list.add(item)
442 return ndo_list
443 #
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600444 # Construct list of extension structs containing handles, or extension structs that share a structextends attribute
445 # 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 -0600446 # TODO: make this recursive -- structs buried three or more levels deep are not searched for extensions
447 def GenerateCommandWrapExtensionList(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600448 for struct in self.structMembers:
449 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
450 found = False;
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600451 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600452 if item != '' and self.struct_contains_ndo(item) == True:
453 found = True
454 if found == True:
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 item not in self.extension_structs:
457 self.extension_structs.append(item)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600458 #
459 # Returns True if a struct may have a pNext chain containing an NDO
460 def StructWithExtensions(self, struct_type):
461 if struct_type in self.struct_member_dict:
462 param_info = self.struct_member_dict[struct_type]
463 if (len(param_info) > 1) and param_info[1].extstructs is not None:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600464 for item in param_info[1].extstructs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600465 if item in self.extension_structs:
466 return True
467 return False
468 #
469 # Generate pNext handling function
470 def build_extension_processing_func(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600471 # Construct helper functions to build and free pNext extension chains
472 pnext_proc = ''
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700473 pnext_proc += 'void *CreateUnwrappedExtensionStructs(const void *pNext) {\n'
Mark Lobodzinski85904632017-04-06 10:07:42 -0600474 pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
475 pnext_proc += ' void *head_pnext = NULL;\n'
476 pnext_proc += ' void *prev_ext_struct = NULL;\n'
477 pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
478 pnext_proc += ' while (cur_pnext != NULL) {\n'
479 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(cur_pnext);\n\n'
480 pnext_proc += ' switch (header->sType) {\n'
481 for item in self.extension_structs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600482 struct_info = self.struct_member_dict[item]
Mark Lobodzinski85904632017-04-06 10:07:42 -0600483 if struct_info[0].feature_protect is not None:
484 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
485 pnext_proc += ' case %s: {\n' % self.structTypes[item].value
Chris Forbes0f86c402017-05-02 18:36:39 -0700486 pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600487 pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
488 # Generate code to unwrap the handles
489 indent = ' '
490 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, 'safe_struct->', 0, False, False, False, False)
491 pnext_proc += tmp_pre
492 pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
493 pnext_proc += ' } break;\n'
494 if struct_info[0].feature_protect is not None:
495 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
496 pnext_proc += '\n'
497 pnext_proc += ' default:\n'
498 pnext_proc += ' break;\n'
499 pnext_proc += ' }\n\n'
500 pnext_proc += ' // Save pointer to the first structure in the pNext chain\n'
501 pnext_proc += ' head_pnext = (head_pnext ? head_pnext : cur_ext_struct);\n\n'
502 pnext_proc += ' // For any extension structure but the first, link the last struct\'s pNext to the current ext struct\n'
503 pnext_proc += ' if (prev_ext_struct) {\n'
504 pnext_proc += ' (reinterpret_cast<GenericHeader *>(prev_ext_struct))->pNext = cur_ext_struct;\n'
505 pnext_proc += ' }\n'
506 pnext_proc += ' prev_ext_struct = cur_ext_struct;\n\n'
507 pnext_proc += ' // Process the next structure in the chain\n'
508 pnext_proc += ' cur_pnext = const_cast<void *>(header->pNext);\n'
509 pnext_proc += ' }\n'
510 pnext_proc += ' return head_pnext;\n'
511 pnext_proc += '}\n\n'
512 pnext_proc += '// Free a pNext extension chain\n'
513 pnext_proc += 'void FreeUnwrappedExtensionStructs(void *head) {\n'
514 pnext_proc += ' void * curr_ptr = head;\n'
515 pnext_proc += ' while (curr_ptr) {\n'
516 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(curr_ptr);\n'
517 pnext_proc += ' void *temp = curr_ptr;\n'
518 pnext_proc += ' curr_ptr = header->pNext;\n'
519 pnext_proc += ' free(temp);\n'
520 pnext_proc += ' }\n'
521 pnext_proc += '}\n'
522 return pnext_proc
523
524 #
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600525 # Generate source for creating a non-dispatchable object
526 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
527 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700528 handle_type = params[-1].find('type')
529 if self.isHandleTypeNonDispatchable(handle_type.text):
530 # Check for special case where multiple handles are returned
531 ndo_array = False
532 if cmd_info[-1].len is not None:
533 ndo_array = True;
534 handle_name = params[-1].find('name')
535 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
536 indent = self.incIndent(indent)
537 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
538 ndo_dest = '*%s' % handle_name.text
539 if ndo_array == True:
540 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600541 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700542 ndo_dest = '%s[index0]' % cmd_info[-1].name
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700543 create_ndo_code += '%s%s = WrapNew(%s);\n' % (indent, ndo_dest, ndo_dest)
Mark Young39389872017-01-19 21:10:49 -0700544 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600545 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700546 create_ndo_code += '%s}\n' % indent
547 indent = self.decIndent(indent)
548 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600549 return create_ndo_code
550 #
551 # Generate source for destroying a non-dispatchable object
552 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
553 destroy_ndo_code = ''
554 ndo_array = False
555 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
556 # Check for special case where multiple handles are returned
557 if cmd_info[-1].len is not None:
558 ndo_array = True;
559 param = -1
560 else:
561 param = -2
562 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
563 if ndo_array == True:
564 # This API is freeing an array of handles. Remove them from the unique_id map.
565 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
566 indent = self.incIndent(indent)
567 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
568 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
569 indent = self.incIndent(indent)
570 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
571 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700572 destroy_ndo_code += '%sunique_id_mapping.erase(unique_id);\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600573 indent = self.decIndent(indent);
574 destroy_ndo_code += '%s}\n' % indent
575 indent = self.decIndent(indent);
576 destroy_ndo_code += '%s}\n' % indent
577 else:
578 # Remove a single handle from the map
579 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
580 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 -0700581 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)
582 destroy_ndo_code += '%sunique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600583 destroy_ndo_code += '%slock.unlock();\n' % (indent)
584 return ndo_array, destroy_ndo_code
585
586 #
587 # Clean up local declarations
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600588 def cleanUpLocalDeclarations(self, indent, prefix, name, len, index, process_pnext):
Mark Young26095c42017-05-09 13:19:04 -0600589 cleanup = '%sif (local_%s%s) {\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600590 if len is not None:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600591 if process_pnext:
592 cleanup += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, len, index)
593 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s[%s].pNext));\n' % (indent, prefix, name, index)
594 cleanup += '%s }\n' % indent
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600595 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
596 else:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600597 if process_pnext:
598 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s->pNext));\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600599 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
Mark Young26095c42017-05-09 13:19:04 -0600600 cleanup += "%s}\n" % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600601 return cleanup
602 #
603 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
604 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
605 decl_code = ''
606 pre_call_code = ''
607 post_call_code = ''
608 if ndo_count is not None:
609 if top_level == True:
610 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
611 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
612 indent = self.incIndent(indent)
613 if top_level == True:
614 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
615 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
616 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700617 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 -0600618 else:
619 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
620 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700621 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 -0600622 indent = self.decIndent(indent)
623 pre_call_code += '%s }\n' % indent
624 indent = self.decIndent(indent)
625 pre_call_code += '%s }\n' % indent
626 if top_level == True:
627 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
628 indent = self.incIndent(indent)
629 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
630 else:
631 if top_level == True:
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600632 if (destroy_func == False) or (destroy_array == True):
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700633 pre_call_code += '%s %s = Unwrap(%s);\n' % (indent, ndo_name, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600634 else:
635 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
636 # as part of the string and explicitly print it
637 fix = str(prefix).strip('local_');
638 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
639 indent = self.incIndent(indent)
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700640 pre_call_code += '%s %s%s = Unwrap(%s%s);\n' % (indent, prefix, ndo_name, fix, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600641 indent = self.decIndent(indent)
642 pre_call_code += '%s }\n' % indent
643 return decl_code, pre_call_code, post_call_code
644 #
645 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
646 # create_func means that this is API creates or allocates NDOs
647 # destroy_func indicates that this API destroys or frees NDOs
648 # destroy_array means that the destroy_func operated on an array of NDOs
649 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
650 decls = ''
651 pre_code = ''
652 post_code = ''
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600653 index = 'index%s' % str(array_index)
654 array_index += 1
655 # Process any NDOs in this structure and recurse for any sub-structs in this struct
656 for member in members:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600657 process_pnext = self.StructWithExtensions(member.type)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600658 # Handle NDOs
659 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500660 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600661 if (count_name is not None):
662 if first_level_param == False:
663 count_name = '%s%s' % (prefix, member.len)
664
665 if (first_level_param == False) or (create_func == False):
666 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
667 decls += tmp_decl
668 pre_code += tmp_pre
669 post_code += tmp_post
670 # Handle Structs that contain NDOs at some level
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600671 elif member.type in self.struct_member_dict:
672 # Structs at first level will have an NDO, OR, we need a safe_struct for the pnext chain
673 if self.struct_contains_ndo(member.type) == True or process_pnext:
674 struct_info = self.struct_member_dict[member.type]
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600675 # Struct Array
676 if member.len is not None:
677 # Update struct prefix
678 if first_level_param == True:
679 new_prefix = 'local_%s' % member.name
680 # Declare safe_VarType for struct
681 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
682 else:
683 new_prefix = '%s%s' % (prefix, member.name)
684 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
685 indent = self.incIndent(indent)
686 if first_level_param == True:
687 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
688 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
689 indent = self.incIndent(indent)
690 if first_level_param == True:
691 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600692 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700693 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 -0600694 local_prefix = '%s[%s].' % (new_prefix, index)
695 # Process sub-structs in this struct
696 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
697 decls += tmp_decl
698 pre_code += tmp_pre
699 post_code += tmp_post
700 indent = self.decIndent(indent)
701 pre_code += '%s }\n' % indent
702 indent = self.decIndent(indent)
703 pre_code += '%s }\n' % indent
704 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600705 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600706 # Single Struct
707 else:
708 # Update struct prefix
709 if first_level_param == True:
710 new_prefix = 'local_%s->' % member.name
711 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
712 else:
713 new_prefix = '%s%s->' % (prefix, member.name)
714 # Declare safe_VarType for struct
715 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
716 indent = self.incIndent(indent)
717 if first_level_param == True:
718 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
719 # Process sub-structs in this struct
720 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
721 decls += tmp_decl
722 pre_code += tmp_pre
723 post_code += tmp_post
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600724 if process_pnext:
Mark Lobodzinskic7eda922018-02-28 13:38:45 -0700725 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 -0600726 indent = self.decIndent(indent)
727 pre_code += '%s }\n' % indent
728 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600729 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600730 return decls, pre_code, post_code
731 #
732 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
733 def generate_wrapping_code(self, cmd):
734 indent = ' '
735 proto = cmd.find('proto/name')
736 params = cmd.findall('param')
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600737
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600738 if proto.text is not None:
739 cmd_member_dict = dict(self.cmdMembers)
740 cmd_info = cmd_member_dict[proto.text]
741 # Handle ndo create/allocate operations
742 if cmd_info[0].iscreate:
743 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
744 else:
745 create_ndo_code = ''
746 # Handle ndo destroy/free operations
747 if cmd_info[0].isdestroy:
748 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
749 else:
750 destroy_array = False
751 destroy_ndo_code = ''
752 paramdecl = ''
753 param_pre_code = ''
754 param_post_code = ''
755 create_func = True if create_ndo_code else False
756 destroy_func = True if destroy_ndo_code else False
757 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
758 param_post_code += create_ndo_code
759 if destroy_ndo_code:
760 if destroy_array == True:
761 param_post_code += destroy_ndo_code
762 else:
763 param_pre_code += destroy_ndo_code
764 if param_pre_code:
765 if (not destroy_func) or (destroy_array):
766 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
767 return paramdecl, param_pre_code, param_post_code
768 #
769 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
770 def genCmd(self, cmdinfo, cmdname):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600771
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600772 # Add struct-member type information to command parameter information
773 OutputGenerator.genCmd(self, cmdinfo, cmdname)
774 members = cmdinfo.elem.findall('.//param')
775 # Iterate over members once to get length parameters for arrays
776 lens = set()
777 for member in members:
778 len = self.getLen(member)
779 if len:
780 lens.add(len)
781 struct_member_dict = dict(self.structMembers)
782 # Generate member info
783 membersInfo = []
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600784 constains_extension_structs = False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600785 for member in members:
786 # Get type and name of member
787 info = self.getTypeNameTuple(member)
788 type = info[0]
789 name = info[1]
790 cdecl = self.makeCParamDecl(member, 0)
791 # Check for parameter name in lens set
792 iscount = True if name in lens else False
793 len = self.getLen(member)
794 isconst = True if 'const' in cdecl else False
795 ispointer = self.paramIsPointer(member)
796 # Mark param as local if it is an array of NDOs
797 islocal = False;
798 if self.isHandleTypeNonDispatchable(type) == True:
799 if (len is not None) and (isconst == True):
800 islocal = True
801 # Or if it's a struct that contains an NDO
802 elif type in struct_member_dict:
803 if self.struct_contains_ndo(type) == True:
804 islocal = True
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600805 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700806 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 -0600807 extstructs = self.registry.validextensionstructs[type] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600808 membersInfo.append(self.CommandParam(type=type,
809 name=name,
810 ispointer=ispointer,
811 isconst=isconst,
812 iscount=iscount,
813 len=len,
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600814 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600815 cdecl=cdecl,
816 islocal=islocal,
817 iscreate=iscreate,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600818 isdestroy=isdestroy,
819 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600820 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600821 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
822 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
823 #
824 # Create code to wrap NDOs as well as handling some boilerplate code
825 def WrapCommands(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600826 cmd_member_dict = dict(self.cmdMembers)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600827 cmd_info_dict = dict(self.cmd_info_data)
828 cmd_protect_dict = dict(self.cmd_feature_protect)
829
830 for api_call in self.cmdMembers:
831 cmdname = api_call.name
832 cmdinfo = cmd_info_dict[api_call.name]
833 if cmdname in self.interface_functions:
834 continue
835 if cmdname in self.no_autogen_list:
836 decls = self.makeCDecls(cmdinfo.elem)
837 self.appendSection('command', '')
838 self.appendSection('command', '// Declare only')
839 self.appendSection('command', decls[0])
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600840 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600841 continue
842 # Generate NDO wrapping/unwrapping code for all parameters
843 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
844 # If API doesn't contain an NDO's, don't fool with it
845 if not api_decls and not api_pre and not api_post:
846 continue
847 feature_extra_protect = cmd_protect_dict[api_call.name]
848 if (feature_extra_protect != None):
849 self.appendSection('command', '')
850 self.appendSection('command', '#ifdef '+ feature_extra_protect)
851 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
852 # Add intercept to procmap
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600853 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600854 decls = self.makeCDecls(cmdinfo.elem)
855 self.appendSection('command', '')
856 self.appendSection('command', decls[0][:-1])
857 self.appendSection('command', '{')
858 # Setup common to call wrappers, first parameter is always dispatchable
859 dispatchable_type = cmdinfo.elem.find('param/type').text
860 dispatchable_name = cmdinfo.elem.find('param/name').text
861 # Generate local instance/pdev/device data lookup
Chris Forbes5279a8c2017-05-02 16:26:23 -0700862 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
863 self.appendSection('command', ' instance_layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), instance_layer_data_map);')
864 else:
865 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600866 # Handle return values, if any
867 resulttype = cmdinfo.elem.find('proto/type')
868 if (resulttype != None and resulttype.text == 'void'):
869 resulttype = None
870 if (resulttype != None):
871 assignresult = resulttype.text + ' result = '
872 else:
873 assignresult = ''
874 # Pre-pend declarations and pre-api-call codegen
875 if api_decls:
876 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
877 if api_pre:
878 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
879 # Generate the API call itself
880 # Gather the parameter items
881 params = cmdinfo.elem.findall('param/name')
882 # Pull out the text for each of the parameters, separate them by commas in a list
883 paramstext = ', '.join([str(param.text) for param in params])
884 # If any of these paramters has been replaced by a local var, fix up the list
885 params = cmd_member_dict[cmdname]
886 for param in params:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600887 if param.islocal == True or self.StructWithExtensions(param.type):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600888 if param.ispointer == True:
889 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
890 else:
891 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
892 # Use correct dispatch table
Chris Forbes44c05302017-05-02 16:42:55 -0700893 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->dispatch_table.',1)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600894 # Put all this together for the final down-chain call
895 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
896 # And add the post-API-call codegen
897 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
898 # Handle the return result variable, if any
899 if (resulttype != None):
900 self.appendSection('command', ' return result;')
901 self.appendSection('command', '}')
902 if (feature_extra_protect != None):
903 self.appendSection('command', '#endif // '+ feature_extra_protect)
904 self.intercepts += [ '#endif' ]