blob: 9cfa9546db220d202222fc47b94159d33b54b83c [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
27
28# UniqueObjectsGeneratorOptions - subclass of GeneratorOptions.
29#
30# Adds options used by UniqueObjectsOutputGenerator objects during
31# unique objects layer generation.
32#
33# Additional members
34# prefixText - list of strings to prefix generated header with
35# (usually a copyright statement + calling convention macros).
36# protectFile - True if multiple inclusion protection should be
37# generated (based on the filename) around the entire header.
38# protectFeature - True if #ifndef..#endif protection should be
39# generated around a feature interface in the header file.
40# genFuncPointers - True if function pointer typedefs should be
41# generated
42# protectProto - If conditional protection should be generated
43# around prototype declarations, set to either '#ifdef'
44# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
45# to require opt-out (#ifndef protectProtoStr). Otherwise
46# set to None.
47# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
48# declarations, if protectProto is set
49# apicall - string to use for the function declaration prefix,
50# such as APICALL on Windows.
51# apientry - string to use for the calling convention macro,
52# in typedefs, such as APIENTRY.
53# apientryp - string to use for the calling convention macro
54# in function pointer typedefs, such as APIENTRYP.
55# indentFuncProto - True if prototype declarations should put each
56# parameter on a separate line
57# indentFuncPointer - True if typedefed function pointers should put each
58# parameter on a separate line
59# alignFuncParam - if nonzero and parameters are being put on a
60# separate line, align parameter names at the specified column
61class UniqueObjectsGeneratorOptions(GeneratorOptions):
62 def __init__(self,
63 filename = None,
64 directory = '.',
65 apiname = None,
66 profile = None,
67 versions = '.*',
68 emitversions = '.*',
69 defaultExtensions = None,
70 addExtensions = None,
71 removeExtensions = None,
72 sortProcedure = regSortFeatures,
73 prefixText = "",
74 genFuncPointers = True,
75 protectFile = True,
76 protectFeature = True,
77 protectProto = None,
78 protectProtoStr = None,
79 apicall = '',
80 apientry = '',
81 apientryp = '',
82 indentFuncProto = True,
83 indentFuncPointer = False,
84 alignFuncParam = 0):
85 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
86 versions, emitversions, defaultExtensions,
87 addExtensions, removeExtensions, sortProcedure)
88 self.prefixText = prefixText
89 self.genFuncPointers = genFuncPointers
90 self.protectFile = protectFile
91 self.protectFeature = protectFeature
92 self.protectProto = protectProto
93 self.protectProtoStr = protectProtoStr
94 self.apicall = apicall
95 self.apientry = apientry
96 self.apientryp = apientryp
97 self.indentFuncProto = indentFuncProto
98 self.indentFuncPointer = indentFuncPointer
99 self.alignFuncParam = alignFuncParam
100
101# UniqueObjectsOutputGenerator - subclass of OutputGenerator.
102# Generates unique objects layer non-dispatchable handle-wrapping code.
103#
104# ---- methods ----
105# UniqueObjectsOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
106# ---- methods overriding base class ----
107# beginFile(genOpts)
108# endFile()
109# beginFeature(interface, emit)
110# endFeature()
111# genCmd(cmdinfo)
112# genStruct()
113# genType()
114class UniqueObjectsOutputGenerator(OutputGenerator):
115 """Generate UniqueObjects code based on XML element attributes"""
116 # This is an ordered list of sections in the header file.
117 ALL_SECTIONS = ['command']
118 def __init__(self,
119 errFile = sys.stderr,
120 warnFile = sys.stderr,
121 diagFile = sys.stdout):
122 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
123 self.INDENT_SPACES = 4
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600124 self.intercepts = []
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700125 self.instance_extensions = []
126 self.device_extensions = []
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600127 # Commands which are not autogenerated but still intercepted
128 self.no_autogen_list = [
Jamie Madill24aa9742016-12-13 17:02:57 -0500129 'vkGetDeviceProcAddr',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600130 'vkGetInstanceProcAddr',
131 'vkCreateInstance',
132 'vkDestroyInstance',
133 'vkCreateDevice',
134 'vkDestroyDevice',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600135 'vkCreateComputePipelines',
136 'vkCreateGraphicsPipelines',
137 'vkCreateSwapchainKHR',
Dustin Graves9a6eb052017-03-28 14:18:54 -0600138 'vkCreateSharedSwapchainsKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600139 'vkGetSwapchainImagesKHR',
Chris Forbes0f507f22017-04-16 13:13:17 +1200140 'vkQueuePresentKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600141 'vkEnumerateInstanceLayerProperties',
142 'vkEnumerateDeviceLayerProperties',
143 'vkEnumerateInstanceExtensionProperties',
Mark Lobodzinski71703a52017-03-03 08:40:16 -0700144 'vkCreateDescriptorUpdateTemplateKHR',
145 'vkDestroyDescriptorUpdateTemplateKHR',
146 'vkUpdateDescriptorSetWithTemplateKHR',
147 'vkCmdPushDescriptorSetWithTemplateKHR',
Mark Lobodzinskia096c122017-03-16 11:54:35 -0600148 'vkDebugMarkerSetObjectTagEXT',
149 'vkDebugMarkerSetObjectNameEXT',
Mark Youngabc2d6e2017-07-07 07:59:56 -0600150 'vkGetPhysicalDeviceDisplayProperties2KHR',
151 'vkGetPhysicalDeviceDisplayPlaneProperties2KHR',
152 'vkGetDisplayModeProperties2KHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600153 ]
154 # Commands shadowed by interface functions and are not implemented
155 self.interface_functions = [
156 'vkGetPhysicalDeviceDisplayPropertiesKHR',
157 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
158 'vkGetDisplayPlaneSupportedDisplaysKHR',
159 'vkGetDisplayModePropertiesKHR',
Norbert Nopper1dec9a52016-11-25 07:55:13 +0100160 'vkGetDisplayPlaneCapabilitiesKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600161 # DebugReport APIs are hooked, but handled separately in the source file
162 'vkCreateDebugReportCallbackEXT',
163 'vkDestroyDebugReportCallbackEXT',
164 'vkDebugReportMessageEXT',
165 ]
166 self.headerVersion = None
167 # Internal state - accumulators for different inner block text
168 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600169
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600170 self.cmdMembers = []
171 self.cmd_feature_protect = [] # Save ifdef's for each command
Mark Lobodzinski85904632017-04-06 10:07:42 -0600172 self.cmd_info_data = [] # Save the cmdinfo data for wrapping the handles when processing is complete
173 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
174 self.extension_structs = [] # List of all structs or sister-structs containing handles
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600175 # A sister-struct may contain no handles but shares a structextends attribute with one that does
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600176 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
177 self.struct_member_dict = dict()
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600178 # Named tuples to store struct and command data
Mark Lobodzinski85904632017-04-06 10:07:42 -0600179 self.StructType = namedtuple('StructType', ['name', 'value'])
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600180 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
181 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
182 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
Mark Lobodzinski85904632017-04-06 10:07:42 -0600183
184 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600185 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
186 #
187 def incIndent(self, indent):
188 inc = ' ' * self.INDENT_SPACES
189 if indent:
190 return indent + inc
191 return inc
192 #
193 def decIndent(self, indent):
194 if indent and (len(indent) > self.INDENT_SPACES):
195 return indent[:-self.INDENT_SPACES]
196 return ''
197 #
198 # Override makeProtoName to drop the "vk" prefix
199 def makeProtoName(self, name, tail):
200 return self.genOpts.apientry + name[2:] + tail
201 #
202 # Check if the parameter passed in is a pointer to an array
203 def paramIsArray(self, param):
204 return param.attrib.get('len') is not None
205 #
206 def beginFile(self, genOpts):
207 OutputGenerator.beginFile(self, genOpts)
208 # User-supplied prefix text, if any (list of strings)
209 if (genOpts.prefixText):
210 for s in genOpts.prefixText:
211 write(s, file=self.outFile)
212 # Namespace
213 self.newline()
214 write('namespace unique_objects {', file = self.outFile)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600215 # Now that the data is all collected and complete, generate and output the wrapping/unwrapping routines
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600216 def endFile(self):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600217
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600218 self.struct_member_dict = dict(self.structMembers)
219
220 # Generate the list of APIs that might need to handle wrapped extension structs
221 self.GenerateCommandWrapExtensionList()
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600222 # Write out wrapping/unwrapping functions
223 self.WrapCommands()
Mark Lobodzinski85904632017-04-06 10:07:42 -0600224 # Build and write out pNext processing function
225 extension_proc = self.build_extension_processing_func()
226 self.newline()
227 write('// Unique Objects pNext extension handling function', file=self.outFile)
228 write('%s' % extension_proc, file=self.outFile)
229
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600230 # Actually write the interface to the output file.
231 if (self.emit):
232 self.newline()
233 if (self.featureExtraProtect != None):
234 write('#ifdef', self.featureExtraProtect, file=self.outFile)
235 # Write the unique_objects code to the file
236 if (self.sections['command']):
237 if (self.genOpts.protectProto):
238 write(self.genOpts.protectProto,
239 self.genOpts.protectProtoStr, file=self.outFile)
240 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
241 if (self.featureExtraProtect != None):
242 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
243 else:
244 self.newline()
245
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700246 # Write out device extension white list
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600247 self.newline()
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700248 write('// Layer Device Extension Whitelist', file=self.outFile)
249 write('static const char *kUniqueObjectsSupportedDeviceExtensions =', file=self.outFile)
250 for line in self.device_extensions:
251 write('%s' % line, file=self.outFile)
252 write(';\n', file=self.outFile)
253
254 # Write out instance extension white list
255 self.newline()
256 write('// Layer Instance Extension Whitelist', file=self.outFile)
257 write('static const char *kUniqueObjectsSupportedInstanceExtensions =', file=self.outFile)
258 for line in self.instance_extensions:
259 write('%s' % line, file=self.outFile)
260 write(';\n', file=self.outFile)
261 self.newline()
262
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600263 # Record intercepted procedures
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600264 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
265 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600266 write('\n'.join(self.intercepts), file=self.outFile)
267 write('};\n', file=self.outFile)
268 self.newline()
269 write('} // namespace unique_objects', file=self.outFile)
270 # Finish processing in superclass
271 OutputGenerator.endFile(self)
272 #
273 def beginFeature(self, interface, emit):
274 # Start processing in superclass
275 OutputGenerator.beginFeature(self, interface, emit)
276 self.headerVersion = None
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600277
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700278 if self.featureName != 'VK_VERSION_1_0':
279 white_list_entry = []
280 if (self.featureExtraProtect != None):
281 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
282 white_list_entry += [ '"%s"' % self.featureName ]
283 if (self.featureExtraProtect != None):
284 white_list_entry += [ '#endif' ]
285 featureType = interface.get('type')
286 if featureType == 'instance':
287 self.instance_extensions += white_list_entry
288 elif featureType == 'device':
289 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600290 #
291 def endFeature(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600292 # Finish processing in superclass
293 OutputGenerator.endFeature(self)
294 #
295 def genType(self, typeinfo, name):
296 OutputGenerator.genType(self, typeinfo, name)
297 typeElem = typeinfo.elem
298 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
299 # Otherwise, emit the tag text.
300 category = typeElem.get('category')
301 if (category == 'struct' or category == 'union'):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600302 self.genStruct(typeinfo, name)
303 #
304 # Append a definition to the specified section
305 def appendSection(self, section, text):
306 # self.sections[section].append('SECTION: ' + section + '\n')
307 self.sections[section].append(text)
308 #
309 # Check if the parameter passed in is a pointer
310 def paramIsPointer(self, param):
311 ispointer = False
312 for elem in param:
313 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
314 ispointer = True
315 return ispointer
316 #
317 # Get the category of a type
318 def getTypeCategory(self, typename):
319 types = self.registry.tree.findall("types/type")
320 for elem in types:
321 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
322 return elem.attrib.get('category')
323 #
324 # Check if a parent object is dispatchable or not
325 def isHandleTypeNonDispatchable(self, handletype):
326 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
327 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
328 return True
329 else:
330 return False
331 #
332 # Retrieve the type and name for a parameter
333 def getTypeNameTuple(self, param):
334 type = ''
335 name = ''
336 for elem in param:
337 if elem.tag == 'type':
338 type = noneStr(elem.text)
339 elif elem.tag == 'name':
340 name = noneStr(elem.text)
341 return (type, name)
342 #
343 # Retrieve the value of the len tag
344 def getLen(self, param):
345 result = None
346 len = param.attrib.get('len')
347 if len and len != 'null-terminated':
348 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
349 # have a null terminated array of strings. We strip the null-terminated from the
350 # 'len' field and only return the parameter specifying the string count
351 if 'null-terminated' in len:
352 result = len.split(',')[0]
353 else:
354 result = len
355 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
356 result = str(result).replace('::', '->')
357 return result
358 #
359 # Generate a VkStructureType based on a structure typename
360 def genVkStructureType(self, typename):
361 # Add underscore between lowercase then uppercase
362 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
363 # Change to uppercase
364 value = value.upper()
365 # Add STRUCTURE_TYPE_
366 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
367 #
368 # Struct parameter check generation.
369 # This is a special case of the <type> tag where the contents are interpreted as a set of
370 # <member> tags instead of freeform C type declarations. The <member> tags are just like
371 # <param> tags - they are a declaration of a struct or union member. Only simple member
372 # declarations are supported (no nested structs etc.)
373 def genStruct(self, typeinfo, typeName):
374 OutputGenerator.genStruct(self, typeinfo, typeName)
375 members = typeinfo.elem.findall('.//member')
376 # Iterate over members once to get length parameters for arrays
377 lens = set()
378 for member in members:
379 len = self.getLen(member)
380 if len:
381 lens.add(len)
382 # Generate member info
383 membersInfo = []
384 for member in members:
385 # Get the member's type and name
386 info = self.getTypeNameTuple(member)
387 type = info[0]
388 name = info[1]
389 cdecl = self.makeCParamDecl(member, 0)
390 # Process VkStructureType
391 if type == 'VkStructureType':
392 # Extract the required struct type value from the comments
393 # embedded in the original text defining the 'typeinfo' element
394 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
395 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
396 if result:
397 value = result.group(0)
398 else:
399 value = self.genVkStructureType(typeName)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600400 # Store the required type value
401 self.structTypes[typeName] = self.StructType(name=name, value=value)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600402 # Store pointer/array/string info
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600403 extstructs = self.registry.validextensionstructs[typeName] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600404 membersInfo.append(self.CommandParam(type=type,
405 name=name,
406 ispointer=self.paramIsPointer(member),
407 isconst=True if 'const' in cdecl else False,
408 iscount=True if name in lens else False,
409 len=self.getLen(member),
Mark Lobodzinski85904632017-04-06 10:07:42 -0600410 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600411 cdecl=cdecl,
412 islocal=False,
413 iscreate=False,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600414 isdestroy=False,
415 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600416 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
Mark Lobodzinski85904632017-04-06 10:07:42 -0600417
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600418 #
419 # Insert a lock_guard line
420 def lock_guard(self, indent):
421 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
422 #
423 # Determine if a struct has an NDO as a member or an embedded member
424 def struct_contains_ndo(self, struct_item):
425 struct_member_dict = dict(self.structMembers)
426 struct_members = struct_member_dict[struct_item]
427
428 for member in struct_members:
429 if self.isHandleTypeNonDispatchable(member.type):
430 return True
431 elif member.type in struct_member_dict:
432 if self.struct_contains_ndo(member.type) == True:
433 return True
434 return False
435 #
436 # Return list of struct members which contain, or which sub-structures contain
437 # an NDO in a given list of parameters or members
438 def getParmeterStructsWithNdos(self, item_list):
439 struct_list = set()
440 for item in item_list:
441 paramtype = item.find('type')
442 typecategory = self.getTypeCategory(paramtype.text)
443 if typecategory == 'struct':
444 if self.struct_contains_ndo(paramtype.text) == True:
445 struct_list.add(item)
446 return struct_list
447 #
448 # Return list of non-dispatchable objects from a given list of parameters or members
449 def getNdosInParameterList(self, item_list, create_func):
450 ndo_list = set()
451 if create_func == True:
452 member_list = item_list[0:-1]
453 else:
454 member_list = item_list
455 for item in member_list:
456 if self.isHandleTypeNonDispatchable(paramtype.text):
457 ndo_list.add(item)
458 return ndo_list
459 #
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600460 # Construct list of extension structs containing handles, or extension structs that share a structextends attribute
461 # 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 -0600462 # TODO: make this recursive -- structs buried three or more levels deep are not searched for extensions
463 def GenerateCommandWrapExtensionList(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600464 for struct in self.structMembers:
465 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
466 found = False;
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600467 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600468 if item != '' and self.struct_contains_ndo(item) == True:
469 found = True
470 if found == True:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600471 for item in struct.members[1].extstructs:
Mark Lobodzinski85904632017-04-06 10:07:42 -0600472 if item != '' and item not in self.extension_structs:
473 self.extension_structs.append(item)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600474 #
475 # Returns True if a struct may have a pNext chain containing an NDO
476 def StructWithExtensions(self, struct_type):
477 if struct_type in self.struct_member_dict:
478 param_info = self.struct_member_dict[struct_type]
479 if (len(param_info) > 1) and param_info[1].extstructs is not None:
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600480 for item in param_info[1].extstructs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600481 if item in self.extension_structs:
482 return True
483 return False
484 #
485 # Generate pNext handling function
486 def build_extension_processing_func(self):
Mark Lobodzinski85904632017-04-06 10:07:42 -0600487 # Construct helper functions to build and free pNext extension chains
488 pnext_proc = ''
489 pnext_proc += 'void *CreateUnwrappedExtensionStructs(layer_data *dev_data, const void *pNext) {\n'
490 pnext_proc += ' void *cur_pnext = const_cast<void *>(pNext);\n'
491 pnext_proc += ' void *head_pnext = NULL;\n'
492 pnext_proc += ' void *prev_ext_struct = NULL;\n'
493 pnext_proc += ' void *cur_ext_struct = NULL;\n\n'
494 pnext_proc += ' while (cur_pnext != NULL) {\n'
495 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(cur_pnext);\n\n'
496 pnext_proc += ' switch (header->sType) {\n'
497 for item in self.extension_structs:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600498 struct_info = self.struct_member_dict[item]
Mark Lobodzinski85904632017-04-06 10:07:42 -0600499 if struct_info[0].feature_protect is not None:
500 pnext_proc += '#ifdef %s \n' % struct_info[0].feature_protect
501 pnext_proc += ' case %s: {\n' % self.structTypes[item].value
Chris Forbes0f86c402017-05-02 18:36:39 -0700502 pnext_proc += ' safe_%s *safe_struct = new safe_%s;\n' % (item, item)
Mark Lobodzinski85904632017-04-06 10:07:42 -0600503 pnext_proc += ' safe_struct->initialize(reinterpret_cast<const %s *>(cur_pnext));\n' % item
504 # Generate code to unwrap the handles
505 indent = ' '
506 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, 'safe_struct->', 0, False, False, False, False)
507 pnext_proc += tmp_pre
508 pnext_proc += ' cur_ext_struct = reinterpret_cast<void *>(safe_struct);\n'
509 pnext_proc += ' } break;\n'
510 if struct_info[0].feature_protect is not None:
511 pnext_proc += '#endif // %s \n' % struct_info[0].feature_protect
512 pnext_proc += '\n'
513 pnext_proc += ' default:\n'
514 pnext_proc += ' break;\n'
515 pnext_proc += ' }\n\n'
516 pnext_proc += ' // Save pointer to the first structure in the pNext chain\n'
517 pnext_proc += ' head_pnext = (head_pnext ? head_pnext : cur_ext_struct);\n\n'
518 pnext_proc += ' // For any extension structure but the first, link the last struct\'s pNext to the current ext struct\n'
519 pnext_proc += ' if (prev_ext_struct) {\n'
520 pnext_proc += ' (reinterpret_cast<GenericHeader *>(prev_ext_struct))->pNext = cur_ext_struct;\n'
521 pnext_proc += ' }\n'
522 pnext_proc += ' prev_ext_struct = cur_ext_struct;\n\n'
523 pnext_proc += ' // Process the next structure in the chain\n'
524 pnext_proc += ' cur_pnext = const_cast<void *>(header->pNext);\n'
525 pnext_proc += ' }\n'
526 pnext_proc += ' return head_pnext;\n'
527 pnext_proc += '}\n\n'
528 pnext_proc += '// Free a pNext extension chain\n'
529 pnext_proc += 'void FreeUnwrappedExtensionStructs(void *head) {\n'
530 pnext_proc += ' void * curr_ptr = head;\n'
531 pnext_proc += ' while (curr_ptr) {\n'
532 pnext_proc += ' GenericHeader *header = reinterpret_cast<GenericHeader *>(curr_ptr);\n'
533 pnext_proc += ' void *temp = curr_ptr;\n'
534 pnext_proc += ' curr_ptr = header->pNext;\n'
535 pnext_proc += ' free(temp);\n'
536 pnext_proc += ' }\n'
537 pnext_proc += '}\n'
538 return pnext_proc
539
540 #
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600541 # Generate source for creating a non-dispatchable object
542 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
543 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700544 handle_type = params[-1].find('type')
545 if self.isHandleTypeNonDispatchable(handle_type.text):
546 # Check for special case where multiple handles are returned
547 ndo_array = False
548 if cmd_info[-1].len is not None:
549 ndo_array = True;
550 handle_name = params[-1].find('name')
551 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
552 indent = self.incIndent(indent)
553 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
554 ndo_dest = '*%s' % handle_name.text
555 if ndo_array == True:
556 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600557 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700558 ndo_dest = '%s[index0]' % cmd_info[-1].name
Chris Forbesd73a1a02017-05-02 18:25:30 -0700559 create_ndo_code += '%s%s = WrapNew(dev_data, %s);\n' % (indent, ndo_dest, ndo_dest)
Mark Young39389872017-01-19 21:10:49 -0700560 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600561 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700562 create_ndo_code += '%s}\n' % indent
563 indent = self.decIndent(indent)
564 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600565 return create_ndo_code
566 #
567 # Generate source for destroying a non-dispatchable object
568 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
569 destroy_ndo_code = ''
570 ndo_array = False
571 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
572 # Check for special case where multiple handles are returned
573 if cmd_info[-1].len is not None:
574 ndo_array = True;
575 param = -1
576 else:
577 param = -2
578 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
579 if ndo_array == True:
580 # This API is freeing an array of handles. Remove them from the unique_id map.
581 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
582 indent = self.incIndent(indent)
583 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
584 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
585 indent = self.incIndent(indent)
586 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
587 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
588 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(unique_id);\n' % (indent)
589 indent = self.decIndent(indent);
590 destroy_ndo_code += '%s}\n' % indent
591 indent = self.decIndent(indent);
592 destroy_ndo_code += '%s}\n' % indent
593 else:
594 # Remove a single handle from the map
595 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
596 destroy_ndo_code += '%suint64_t %s_id = reinterpret_cast<uint64_t &>(%s);\n' % (indent, cmd_info[param].name, cmd_info[param].name)
597 destroy_ndo_code += '%s%s = (%s)dev_data->unique_id_mapping[%s_id];\n' % (indent, cmd_info[param].name, cmd_info[param].type, cmd_info[param].name)
598 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
599 destroy_ndo_code += '%slock.unlock();\n' % (indent)
600 return ndo_array, destroy_ndo_code
601
602 #
603 # Clean up local declarations
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600604 def cleanUpLocalDeclarations(self, indent, prefix, name, len, index, process_pnext):
Mark Young26095c42017-05-09 13:19:04 -0600605 cleanup = '%sif (local_%s%s) {\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600606 if len is not None:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600607 if process_pnext:
608 cleanup += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, len, index)
609 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s[%s].pNext));\n' % (indent, prefix, name, index)
610 cleanup += '%s }\n' % indent
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600611 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
612 else:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600613 if process_pnext:
614 cleanup += '%s FreeUnwrappedExtensionStructs(const_cast<void *>(local_%s%s->pNext));\n' % (indent, prefix, name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600615 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
Mark Young26095c42017-05-09 13:19:04 -0600616 cleanup += "%s}\n" % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600617 return cleanup
618 #
619 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
620 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
621 decl_code = ''
622 pre_call_code = ''
623 post_call_code = ''
624 if ndo_count is not None:
625 if top_level == True:
626 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
627 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
628 indent = self.incIndent(indent)
629 if top_level == True:
630 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
631 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
632 indent = self.incIndent(indent)
Chris Forbesb9889702017-05-02 18:35:12 -0700633 pre_call_code += '%s local_%s%s[%s] = Unwrap(dev_data, %s[%s]);\n' % (indent, prefix, ndo_name, index, ndo_name, index)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600634 else:
635 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
636 indent = self.incIndent(indent)
Chris Forbesb9889702017-05-02 18:35:12 -0700637 pre_call_code += '%s %s%s[%s] = Unwrap(dev_data, %s%s[%s]);\n' % (indent, prefix, ndo_name, index, prefix, ndo_name, index)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600638 indent = self.decIndent(indent)
639 pre_call_code += '%s }\n' % indent
640 indent = self.decIndent(indent)
641 pre_call_code += '%s }\n' % indent
642 if top_level == True:
643 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
644 indent = self.incIndent(indent)
645 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
646 else:
647 if top_level == True:
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600648 if (destroy_func == False) or (destroy_array == True):
Chris Forbesb9889702017-05-02 18:35:12 -0700649 pre_call_code += '%s %s = Unwrap(dev_data, %s);\n' % (indent, ndo_name, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600650 else:
651 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
652 # as part of the string and explicitly print it
653 fix = str(prefix).strip('local_');
654 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
655 indent = self.incIndent(indent)
Chris Forbesb9889702017-05-02 18:35:12 -0700656 pre_call_code += '%s %s%s = Unwrap(dev_data, %s%s);\n' % (indent, prefix, ndo_name, fix, ndo_name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600657 indent = self.decIndent(indent)
658 pre_call_code += '%s }\n' % indent
659 return decl_code, pre_call_code, post_call_code
660 #
661 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
662 # create_func means that this is API creates or allocates NDOs
663 # destroy_func indicates that this API destroys or frees NDOs
664 # destroy_array means that the destroy_func operated on an array of NDOs
665 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
666 decls = ''
667 pre_code = ''
668 post_code = ''
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600669 index = 'index%s' % str(array_index)
670 array_index += 1
671 # Process any NDOs in this structure and recurse for any sub-structs in this struct
672 for member in members:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600673 process_pnext = self.StructWithExtensions(member.type)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600674 # Handle NDOs
675 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500676 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600677 if (count_name is not None):
678 if first_level_param == False:
679 count_name = '%s%s' % (prefix, member.len)
680
681 if (first_level_param == False) or (create_func == False):
682 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
683 decls += tmp_decl
684 pre_code += tmp_pre
685 post_code += tmp_post
686 # Handle Structs that contain NDOs at some level
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600687 elif member.type in self.struct_member_dict:
688 # Structs at first level will have an NDO, OR, we need a safe_struct for the pnext chain
689 if self.struct_contains_ndo(member.type) == True or process_pnext:
690 struct_info = self.struct_member_dict[member.type]
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600691 # Struct Array
692 if member.len is not None:
693 # Update struct prefix
694 if first_level_param == True:
695 new_prefix = 'local_%s' % member.name
696 # Declare safe_VarType for struct
697 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
698 else:
699 new_prefix = '%s%s' % (prefix, member.name)
700 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
701 indent = self.incIndent(indent)
702 if first_level_param == True:
703 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
704 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
705 indent = self.incIndent(indent)
706 if first_level_param == True:
707 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600708 if process_pnext:
709 pre_code += '%s %s[%s].pNext = CreateUnwrappedExtensionStructs(dev_data, %s[%s].pNext);\n' % (indent, new_prefix, index, new_prefix, index)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600710 local_prefix = '%s[%s].' % (new_prefix, index)
711 # Process sub-structs in this struct
712 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
713 decls += tmp_decl
714 pre_code += tmp_pre
715 post_code += tmp_post
716 indent = self.decIndent(indent)
717 pre_code += '%s }\n' % indent
718 indent = self.decIndent(indent)
719 pre_code += '%s }\n' % indent
720 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600721 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600722 # Single Struct
723 else:
724 # Update struct prefix
725 if first_level_param == True:
726 new_prefix = 'local_%s->' % member.name
727 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
728 else:
729 new_prefix = '%s%s->' % (prefix, member.name)
730 # Declare safe_VarType for struct
731 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
732 indent = self.incIndent(indent)
733 if first_level_param == True:
734 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
735 # Process sub-structs in this struct
736 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
737 decls += tmp_decl
738 pre_code += tmp_pre
739 post_code += tmp_post
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600740 if process_pnext:
741 pre_code += '%s local_%s%s->pNext = CreateUnwrappedExtensionStructs(dev_data, local_%s%s->pNext);\n' % (indent, prefix, member.name, prefix, member.name)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600742 indent = self.decIndent(indent)
743 pre_code += '%s }\n' % indent
744 if first_level_param == True:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600745 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len, index, process_pnext)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600746 return decls, pre_code, post_code
747 #
748 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
749 def generate_wrapping_code(self, cmd):
750 indent = ' '
751 proto = cmd.find('proto/name')
752 params = cmd.findall('param')
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600753
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600754 if proto.text is not None:
755 cmd_member_dict = dict(self.cmdMembers)
756 cmd_info = cmd_member_dict[proto.text]
757 # Handle ndo create/allocate operations
758 if cmd_info[0].iscreate:
759 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
760 else:
761 create_ndo_code = ''
762 # Handle ndo destroy/free operations
763 if cmd_info[0].isdestroy:
764 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
765 else:
766 destroy_array = False
767 destroy_ndo_code = ''
768 paramdecl = ''
769 param_pre_code = ''
770 param_post_code = ''
771 create_func = True if create_ndo_code else False
772 destroy_func = True if destroy_ndo_code else False
773 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
774 param_post_code += create_ndo_code
775 if destroy_ndo_code:
776 if destroy_array == True:
777 param_post_code += destroy_ndo_code
778 else:
779 param_pre_code += destroy_ndo_code
780 if param_pre_code:
781 if (not destroy_func) or (destroy_array):
782 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
783 return paramdecl, param_pre_code, param_post_code
784 #
785 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
786 def genCmd(self, cmdinfo, cmdname):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600787
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600788 # Add struct-member type information to command parameter information
789 OutputGenerator.genCmd(self, cmdinfo, cmdname)
790 members = cmdinfo.elem.findall('.//param')
791 # Iterate over members once to get length parameters for arrays
792 lens = set()
793 for member in members:
794 len = self.getLen(member)
795 if len:
796 lens.add(len)
797 struct_member_dict = dict(self.structMembers)
798 # Generate member info
799 membersInfo = []
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600800 constains_extension_structs = False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600801 for member in members:
802 # Get type and name of member
803 info = self.getTypeNameTuple(member)
804 type = info[0]
805 name = info[1]
806 cdecl = self.makeCParamDecl(member, 0)
807 # Check for parameter name in lens set
808 iscount = True if name in lens else False
809 len = self.getLen(member)
810 isconst = True if 'const' in cdecl else False
811 ispointer = self.paramIsPointer(member)
812 # Mark param as local if it is an array of NDOs
813 islocal = False;
814 if self.isHandleTypeNonDispatchable(type) == True:
815 if (len is not None) and (isconst == True):
816 islocal = True
817 # Or if it's a struct that contains an NDO
818 elif type in struct_member_dict:
819 if self.struct_contains_ndo(type) == True:
820 islocal = True
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600821 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700822 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 -0600823 extstructs = self.registry.validextensionstructs[type] if name == 'pNext' else None
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600824 membersInfo.append(self.CommandParam(type=type,
825 name=name,
826 ispointer=ispointer,
827 isconst=isconst,
828 iscount=iscount,
829 len=len,
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600830 extstructs=extstructs,
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600831 cdecl=cdecl,
832 islocal=islocal,
833 iscreate=iscreate,
Mark Lobodzinski85904632017-04-06 10:07:42 -0600834 isdestroy=isdestroy,
835 feature_protect=self.featureExtraProtect))
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600836 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600837 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
838 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
839 #
840 # Create code to wrap NDOs as well as handling some boilerplate code
841 def WrapCommands(self):
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600842 cmd_member_dict = dict(self.cmdMembers)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600843 cmd_info_dict = dict(self.cmd_info_data)
844 cmd_protect_dict = dict(self.cmd_feature_protect)
845
846 for api_call in self.cmdMembers:
847 cmdname = api_call.name
848 cmdinfo = cmd_info_dict[api_call.name]
849 if cmdname in self.interface_functions:
850 continue
851 if cmdname in self.no_autogen_list:
852 decls = self.makeCDecls(cmdinfo.elem)
853 self.appendSection('command', '')
854 self.appendSection('command', '// Declare only')
855 self.appendSection('command', decls[0])
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600856 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600857 continue
858 # Generate NDO wrapping/unwrapping code for all parameters
859 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
860 # If API doesn't contain an NDO's, don't fool with it
861 if not api_decls and not api_pre and not api_post:
862 continue
863 feature_extra_protect = cmd_protect_dict[api_call.name]
864 if (feature_extra_protect != None):
865 self.appendSection('command', '')
866 self.appendSection('command', '#ifdef '+ feature_extra_protect)
867 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
868 # Add intercept to procmap
Mark Lobodzinski38686e92017-06-07 16:04:50 -0600869 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600870 decls = self.makeCDecls(cmdinfo.elem)
871 self.appendSection('command', '')
872 self.appendSection('command', decls[0][:-1])
873 self.appendSection('command', '{')
874 # Setup common to call wrappers, first parameter is always dispatchable
875 dispatchable_type = cmdinfo.elem.find('param/type').text
876 dispatchable_name = cmdinfo.elem.find('param/name').text
877 # Generate local instance/pdev/device data lookup
Chris Forbes5279a8c2017-05-02 16:26:23 -0700878 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
879 self.appendSection('command', ' instance_layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), instance_layer_data_map);')
880 else:
881 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600882 # Handle return values, if any
883 resulttype = cmdinfo.elem.find('proto/type')
884 if (resulttype != None and resulttype.text == 'void'):
885 resulttype = None
886 if (resulttype != None):
887 assignresult = resulttype.text + ' result = '
888 else:
889 assignresult = ''
890 # Pre-pend declarations and pre-api-call codegen
891 if api_decls:
892 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
893 if api_pre:
894 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
895 # Generate the API call itself
896 # Gather the parameter items
897 params = cmdinfo.elem.findall('param/name')
898 # Pull out the text for each of the parameters, separate them by commas in a list
899 paramstext = ', '.join([str(param.text) for param in params])
900 # If any of these paramters has been replaced by a local var, fix up the list
901 params = cmd_member_dict[cmdname]
902 for param in params:
Mark Lobodzinskifbd4d182017-04-07 15:31:35 -0600903 if param.islocal == True or self.StructWithExtensions(param.type):
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600904 if param.ispointer == True:
905 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
906 else:
907 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
908 # Use correct dispatch table
Chris Forbes44c05302017-05-02 16:42:55 -0700909 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->dispatch_table.',1)
Mark Lobodzinski65c6cfa2017-04-06 15:22:07 -0600910 # Put all this together for the final down-chain call
911 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
912 # And add the post-API-call codegen
913 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
914 # Handle the return result variable, if any
915 if (resulttype != None):
916 self.appendSection('command', ' return result;')
917 self.appendSection('command', '}')
918 if (feature_extra_protect != None):
919 self.appendSection('command', '#endif // '+ feature_extra_protect)
920 self.intercepts += [ '#endif' ]