blob: 6bcfbcb66cb08017dc4fe8a89e48d93ac9357149 [file] [log] [blame]
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001#!/usr/bin/python3 -i
2#
Dave Houlton57ae22f2018-05-18 16:20:52 -06003# Copyright (c) 2015-2018 The Khronos Group Inc.
4# Copyright (c) 2015-2018 Valve Corporation
5# Copyright (c) 2015-2018 LunarG, Inc.
6# Copyright (c) 2015-2018 Google Inc.
Mark Lobodzinskid1461482017-07-18 13:56:09 -06007#
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: Mark Lobodzinski <mark@lunarg.com>
Dave Houlton57ae22f2018-05-18 16:20:52 -060021# Author: Dave Houlton <daveh@lunarg.com>
Mark Lobodzinskid1461482017-07-18 13:56:09 -060022
Dave Houlton57ae22f2018-05-18 16:20:52 -060023import os,re,sys,string,json
Mark Lobodzinskid1461482017-07-18 13:56:09 -060024import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060027from common_codegen import *
Mark Lobodzinskid1461482017-07-18 13:56:09 -060028
Jamie Madill8d4cda22017-11-08 13:40:09 -050029# This is a workaround to use a Python 2.7 and 3.x compatible syntax.
30from io import open
31
Mark Lobodzinskid1461482017-07-18 13:56:09 -060032# ObjectTrackerGeneratorOptions - subclass of GeneratorOptions.
33#
34# Adds options used by ObjectTrackerOutputGenerator objects during
35# object_tracker layer generation.
36#
37# Additional members
38# prefixText - list of strings to prefix generated header with
39# (usually a copyright statement + calling convention macros).
40# protectFile - True if multiple inclusion protection should be
41# generated (based on the filename) around the entire header.
42# protectFeature - True if #ifndef..#endif protection should be
43# generated around a feature interface in the header file.
44# genFuncPointers - True if function pointer typedefs should be
45# generated
46# protectProto - If conditional protection should be generated
47# around prototype declarations, set to either '#ifdef'
48# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
49# to require opt-out (#ifndef protectProtoStr). Otherwise
50# set to None.
51# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
52# declarations, if protectProto is set
53# apicall - string to use for the function declaration prefix,
54# such as APICALL on Windows.
55# apientry - string to use for the calling convention macro,
56# in typedefs, such as APIENTRY.
57# apientryp - string to use for the calling convention macro
58# in function pointer typedefs, such as APIENTRYP.
59# indentFuncProto - True if prototype declarations should put each
60# parameter on a separate line
61# indentFuncPointer - True if typedefed function pointers should put each
62# parameter on a separate line
63# alignFuncParam - if nonzero and parameters are being put on a
64# separate line, align parameter names at the specified column
65class ObjectTrackerGeneratorOptions(GeneratorOptions):
66 def __init__(self,
67 filename = None,
68 directory = '.',
69 apiname = None,
70 profile = None,
71 versions = '.*',
72 emitversions = '.*',
73 defaultExtensions = None,
74 addExtensions = None,
75 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060076 emitExtensions = None,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060077 sortProcedure = regSortFeatures,
78 prefixText = "",
79 genFuncPointers = True,
80 protectFile = True,
81 protectFeature = True,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060082 apicall = '',
83 apientry = '',
84 apientryp = '',
85 indentFuncProto = True,
86 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060087 alignFuncParam = 0,
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -060088 expandEnumerants = True,
89 valid_usage_path = ''):
Mark Lobodzinskid1461482017-07-18 13:56:09 -060090 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
91 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060092 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskid1461482017-07-18 13:56:09 -060093 self.prefixText = prefixText
94 self.genFuncPointers = genFuncPointers
95 self.protectFile = protectFile
96 self.protectFeature = protectFeature
Mark Lobodzinskid1461482017-07-18 13:56:09 -060097 self.apicall = apicall
98 self.apientry = apientry
99 self.apientryp = apientryp
100 self.indentFuncProto = indentFuncProto
101 self.indentFuncPointer = indentFuncPointer
102 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600103 self.expandEnumerants = expandEnumerants
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600104 self.valid_usage_path = valid_usage_path
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600105
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600106
107# ObjectTrackerOutputGenerator - subclass of OutputGenerator.
108# Generates object_tracker layer object validation code
109#
110# ---- methods ----
111# ObjectTrackerOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
112# ---- methods overriding base class ----
113# beginFile(genOpts)
114# endFile()
115# beginFeature(interface, emit)
116# endFeature()
117# genCmd(cmdinfo)
118# genStruct()
119# genType()
120class ObjectTrackerOutputGenerator(OutputGenerator):
121 """Generate ObjectTracker code based on XML element attributes"""
122 # This is an ordered list of sections in the header file.
123 ALL_SECTIONS = ['command']
124 def __init__(self,
125 errFile = sys.stderr,
126 warnFile = sys.stderr,
127 diagFile = sys.stdout):
128 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
129 self.INDENT_SPACES = 4
130 self.intercepts = []
131 self.instance_extensions = []
132 self.device_extensions = []
133 # Commands which are not autogenerated but still intercepted
134 self.no_autogen_list = [
135 'vkDestroyInstance',
136 'vkDestroyDevice',
137 'vkUpdateDescriptorSets',
138 'vkDestroyDebugReportCallbackEXT',
139 'vkDebugReportMessageEXT',
140 'vkGetPhysicalDeviceQueueFamilyProperties',
141 'vkFreeCommandBuffers',
142 'vkDestroySwapchainKHR',
143 'vkDestroyDescriptorPool',
144 'vkDestroyCommandPool',
Mark Lobodzinski14ddc192017-10-25 16:57:04 -0600145 'vkGetPhysicalDeviceQueueFamilyProperties2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600146 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
147 'vkResetDescriptorPool',
148 'vkBeginCommandBuffer',
149 'vkCreateDebugReportCallbackEXT',
150 'vkEnumerateInstanceLayerProperties',
151 'vkEnumerateDeviceLayerProperties',
152 'vkEnumerateInstanceExtensionProperties',
153 'vkEnumerateDeviceExtensionProperties',
154 'vkCreateDevice',
155 'vkCreateInstance',
156 'vkEnumeratePhysicalDevices',
157 'vkAllocateCommandBuffers',
158 'vkAllocateDescriptorSets',
159 'vkFreeDescriptorSets',
Tony Barbour2fd0c2c2017-08-08 12:51:33 -0600160 'vkCmdPushDescriptorSetKHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600161 'vkDebugMarkerSetObjectNameEXT',
162 'vkGetPhysicalDeviceProcAddr',
163 'vkGetDeviceProcAddr',
164 'vkGetInstanceProcAddr',
165 'vkEnumerateInstanceExtensionProperties',
166 'vkEnumerateInstanceLayerProperties',
167 'vkEnumerateDeviceLayerProperties',
168 'vkGetDeviceProcAddr',
169 'vkGetInstanceProcAddr',
170 'vkEnumerateDeviceExtensionProperties',
171 'vk_layerGetPhysicalDeviceProcAddr',
172 'vkNegotiateLoaderLayerInterfaceVersion',
173 'vkCreateComputePipelines',
174 'vkGetDeviceQueue',
Yiwei Zhang991d88d2018-02-14 14:39:46 -0800175 'vkGetDeviceQueue2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600176 'vkGetSwapchainImagesKHR',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100177 'vkCreateDescriptorSetLayout',
Mark Young6ba8abe2017-11-09 10:37:04 -0700178 'vkCreateDebugUtilsMessengerEXT',
179 'vkDestroyDebugUtilsMessengerEXT',
180 'vkSubmitDebugUtilsMessageEXT',
181 'vkSetDebugUtilsObjectNameEXT',
182 'vkSetDebugUtilsObjectTagEXT',
183 'vkQueueBeginDebugUtilsLabelEXT',
184 'vkQueueEndDebugUtilsLabelEXT',
185 'vkQueueInsertDebugUtilsLabelEXT',
186 'vkCmdBeginDebugUtilsLabelEXT',
187 'vkCmdEndDebugUtilsLabelEXT',
188 'vkCmdInsertDebugUtilsLabelEXT',
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600189 'vkGetDisplayModePropertiesKHR',
190 'vkGetPhysicalDeviceDisplayPropertiesKHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600191 ]
192 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
193 # which is translated here into a good VU. Saves ~40 checks.
194 self.manual_vuids = dict()
195 self.manual_vuids = {
Dave Houlton57ae22f2018-05-18 16:20:52 -0600196 "fence-compatalloc": "\"VUID-vkDestroyFence-fence-01121\"",
197 "fence-nullalloc": "\"VUID-vkDestroyFence-fence-01122\"",
198 "event-compatalloc": "\"VUID-vkDestroyEvent-event-01146\"",
199 "event-nullalloc": "\"VUID-vkDestroyEvent-event-01147\"",
200 "buffer-compatalloc": "\"VUID-vkDestroyBuffer-buffer-00923\"",
201 "buffer-nullalloc": "\"VUID-vkDestroyBuffer-buffer-00924\"",
202 "image-compatalloc": "\"VUID-vkDestroyImage-image-01001\"",
203 "image-nullalloc": "\"VUID-vkDestroyImage-image-01002\"",
204 "shaderModule-compatalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01092\"",
205 "shaderModule-nullalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01093\"",
206 "pipeline-compatalloc": "\"VUID-vkDestroyPipeline-pipeline-00766\"",
207 "pipeline-nullalloc": "\"VUID-vkDestroyPipeline-pipeline-00767\"",
208 "sampler-compatalloc": "\"VUID-vkDestroySampler-sampler-01083\"",
209 "sampler-nullalloc": "\"VUID-vkDestroySampler-sampler-01084\"",
210 "renderPass-compatalloc": "\"VUID-vkDestroyRenderPass-renderPass-00874\"",
211 "renderPass-nullalloc": "\"VUID-vkDestroyRenderPass-renderPass-00875\"",
212 "descriptorUpdateTemplate-compatalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356\"",
213 "descriptorUpdateTemplate-nullalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357\"",
214 "imageView-compatalloc": "\"VUID-vkDestroyImageView-imageView-01027\"",
215 "imageView-nullalloc": "\"VUID-vkDestroyImageView-imageView-01028\"",
216 "pipelineCache-compatalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00771\"",
217 "pipelineCache-nullalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00772\"",
218 "pipelineLayout-compatalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00299\"",
219 "pipelineLayout-nullalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00300\"",
220 "descriptorSetLayout-compatalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284\"",
221 "descriptorSetLayout-nullalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285\"",
222 "semaphore-compatalloc": "\"VUID-vkDestroySemaphore-semaphore-01138\"",
223 "semaphore-nullalloc": "\"VUID-vkDestroySemaphore-semaphore-01139\"",
224 "queryPool-compatalloc": "\"VUID-vkDestroyQueryPool-queryPool-00794\"",
225 "queryPool-nullalloc": "\"VUID-vkDestroyQueryPool-queryPool-00795\"",
226 "bufferView-compatalloc": "\"VUID-vkDestroyBufferView-bufferView-00937\"",
227 "bufferView-nullalloc": "\"VUID-vkDestroyBufferView-bufferView-00938\"",
228 "surface-compatalloc": "\"VUID-vkDestroySurfaceKHR-surface-01267\"",
229 "surface-nullalloc": "\"VUID-vkDestroySurfaceKHR-surface-01268\"",
230 "framebuffer-compatalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00893\"",
231 "framebuffer-nullalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00894\"",
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600232 }
233
234 # Commands shadowed by interface functions and are not implemented
235 self.interface_functions = [
236 ]
237 self.headerVersion = None
238 # Internal state - accumulators for different inner block text
239 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
240 self.cmdMembers = []
241 self.cmd_feature_protect = [] # Save ifdef's for each command
242 self.cmd_info_data = [] # Save the cmdinfo data for validating the handles when processing is complete
243 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
244 self.extension_structs = [] # List of all structs or sister-structs containing handles
245 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
246 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
247 self.struct_member_dict = dict()
248 # Named tuples to store struct and command data
249 self.StructType = namedtuple('StructType', ['name', 'value'])
250 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
Dave Houlton57ae22f2018-05-18 16:20:52 -0600251 self.CmdMemberAlias = dict()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600252 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
253 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
254 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'isoptional', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
255 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
256 self.object_types = [] # List of all handle types
257 self.valid_vuids = set() # Set of all valid VUIDs
Dave Houlton57ae22f2018-05-18 16:20:52 -0600258 self.vuid_dict = dict() # VUID dictionary (from JSON)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600259 #
260 # Check if the parameter passed in is optional
261 def paramIsOptional(self, param):
262 # See if the handle is optional
263 isoptional = False
264 # Simple, if it's optional, return true
265 optString = param.attrib.get('optional')
266 if optString:
267 if optString == 'true':
268 isoptional = True
269 elif ',' in optString:
270 opts = []
271 for opt in optString.split(','):
272 val = opt.strip()
273 if val == 'true':
274 opts.append(True)
275 elif val == 'false':
276 opts.append(False)
277 else:
278 print('Unrecognized len attribute value',val)
279 isoptional = opts
John Zulauf9f6788c2018-04-04 14:54:11 -0600280 if not isoptional:
281 # Matching logic in parameter validation and ValidityOutputGenerator.isHandleOptional
282 optString = param.attrib.get('noautovalidity')
283 if optString and optString == 'true':
284 isoptional = True;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600285 return isoptional
286 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600287 # Get VUID identifier from implicit VUID tag
Dave Houlton57ae22f2018-05-18 16:20:52 -0600288 def GetVuid(self, parent, suffix):
289 vuid_string = 'VUID-%s-%s' % (parent, suffix)
290 vuid = "kVUIDUndefined"
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600291 if '->' in vuid_string:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600292 return vuid
293 if vuid_string in self.valid_vuids:
294 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600295 else:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600296 if parent in self.CmdMemberAlias:
297 alias_string = 'VUID-%s-%s' % (self.CmdMemberAlias[parent], suffix)
298 if alias_string in self.valid_vuids:
299 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600300 return vuid
301 #
302 # Increases indent by 4 spaces and tracks it globally
303 def incIndent(self, indent):
304 inc = ' ' * self.INDENT_SPACES
305 if indent:
306 return indent + inc
307 return inc
308 #
309 # Decreases indent by 4 spaces and tracks it globally
310 def decIndent(self, indent):
311 if indent and (len(indent) > self.INDENT_SPACES):
312 return indent[:-self.INDENT_SPACES]
313 return ''
314 #
315 # Override makeProtoName to drop the "vk" prefix
316 def makeProtoName(self, name, tail):
317 return self.genOpts.apientry + name[2:] + tail
318 #
319 # Check if the parameter passed in is a pointer to an array
320 def paramIsArray(self, param):
321 return param.attrib.get('len') is not None
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000322
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600323 #
324 # Generate the object tracker undestroyed object validation function
325 def GenReportFunc(self):
326 output_func = ''
Dave Houlton379f1422018-05-23 12:47:07 -0600327 output_func += 'void ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600328 output_func += ' DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
329 for handle in self.object_types:
330 if self.isHandleTypeNonDispatchable(handle):
331 output_func += ' DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
332 output_func += '}\n'
333 return output_func
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000334
335 #
336 # Generate the object tracker undestroyed object destruction function
337 def GenDestroyFunc(self):
338 output_func = ''
339 output_func += 'void DestroyUndestroyedObjects(VkDevice device) {\n'
340 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
341 for handle in self.object_types:
342 if self.isHandleTypeNonDispatchable(handle):
343 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
344 output_func += '}\n'
345 return output_func
346
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600347 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600348 # Walk the JSON-derived dict and find all "vuid" key values
349 def ExtractVUIDs(self, d):
350 if hasattr(d, 'items'):
351 for k, v in d.items():
352 if k == "vuid":
353 yield v
354 elif isinstance(v, dict):
355 for s in self.ExtractVUIDs(v):
356 yield s
357 elif isinstance (v, list):
358 for l in v:
359 for s in self.ExtractVUIDs(l):
360 yield s
361
362 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600363 # Called at beginning of processing as file is opened
364 def beginFile(self, genOpts):
365 OutputGenerator.beginFile(self, genOpts)
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600366
367 self.valid_usage_path = genOpts.valid_usage_path
368 vu_json_filename = os.path.join(self.valid_usage_path + os.sep, 'validusage.json')
369 if os.path.isfile(vu_json_filename):
370 json_file = open(vu_json_filename, 'r')
371 self.vuid_dict = json.load(json_file)
372 json_file.close()
373 if len(self.vuid_dict) == 0:
374 print("Error: Could not find, or error loading %s/validusage.json\n", vu_json_filename)
375 sys.exit(1)
376
Dave Houlton57ae22f2018-05-18 16:20:52 -0600377 # Build a set of all vuid text strings found in validusage.json
378 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
379 self.valid_vuids.add(json_vuid_string)
380
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600381 # File Comment
382 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
383 file_comment += '// See object_tracker_generator.py for modifications\n'
384 write(file_comment, file=self.outFile)
385 # Copyright Statement
386 copyright = ''
387 copyright += '\n'
388 copyright += '/***************************************************************************\n'
389 copyright += ' *\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600390 copyright += ' * Copyright (c) 2015-2018 The Khronos Group Inc.\n'
391 copyright += ' * Copyright (c) 2015-2018 Valve Corporation\n'
392 copyright += ' * Copyright (c) 2015-2018 LunarG, Inc.\n'
393 copyright += ' * Copyright (c) 2015-2018 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600394 copyright += ' *\n'
395 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
396 copyright += ' * you may not use this file except in compliance with the License.\n'
397 copyright += ' * You may obtain a copy of the License at\n'
398 copyright += ' *\n'
399 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
400 copyright += ' *\n'
401 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
402 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
403 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
404 copyright += ' * See the License for the specific language governing permissions and\n'
405 copyright += ' * limitations under the License.\n'
406 copyright += ' *\n'
407 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600408 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600409 copyright += ' *\n'
410 copyright += ' ****************************************************************************/\n'
411 write(copyright, file=self.outFile)
412 # Namespace
413 self.newline()
414 write('#include "object_tracker.h"', file = self.outFile)
415 self.newline()
416 write('namespace object_tracker {', file = self.outFile)
417 #
418 # Now that the data is all collected and complete, generate and output the object validation routines
419 def endFile(self):
420 self.struct_member_dict = dict(self.structMembers)
421 # Generate the list of APIs that might need to handle wrapped extension structs
422 # self.GenerateCommandWrapExtensionList()
423 self.WrapCommands()
424 # Build undestroyed objects reporting function
425 report_func = self.GenReportFunc()
426 self.newline()
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000427 # Build undestroyed objects destruction function
428 destroy_func = self.GenDestroyFunc()
429 self.newline()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600430 write('// ObjectTracker undestroyed objects validation function', file=self.outFile)
431 write('%s' % report_func, file=self.outFile)
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000432 write('%s' % destroy_func, file=self.outFile)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600433 # Actually write the interface to the output file.
434 if (self.emit):
435 self.newline()
436 if (self.featureExtraProtect != None):
437 write('#ifdef', self.featureExtraProtect, file=self.outFile)
438 # Write the object_tracker code to the file
439 if (self.sections['command']):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600440 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
441 if (self.featureExtraProtect != None):
442 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
443 else:
444 self.newline()
445
446 # Record intercepted procedures
447 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
448 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
449 write('\n'.join(self.intercepts), file=self.outFile)
450 write('};\n', file=self.outFile)
451 self.newline()
452 write('} // namespace object_tracker', file=self.outFile)
453 # Finish processing in superclass
454 OutputGenerator.endFile(self)
455 #
456 # Processing point at beginning of each extension definition
457 def beginFeature(self, interface, emit):
458 # Start processing in superclass
459 OutputGenerator.beginFeature(self, interface, emit)
460 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600461 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600462
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600463 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600464 white_list_entry = []
465 if (self.featureExtraProtect != None):
466 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
467 white_list_entry += [ '"%s"' % self.featureName ]
468 if (self.featureExtraProtect != None):
469 white_list_entry += [ '#endif' ]
470 featureType = interface.get('type')
471 if featureType == 'instance':
472 self.instance_extensions += white_list_entry
473 elif featureType == 'device':
474 self.device_extensions += white_list_entry
475 #
476 # Processing point at end of each extension definition
477 def endFeature(self):
478 # Finish processing in superclass
479 OutputGenerator.endFeature(self)
480 #
481 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700482 def genType(self, typeinfo, name, alias):
483 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600484 typeElem = typeinfo.elem
485 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
486 # Otherwise, emit the tag text.
487 category = typeElem.get('category')
488 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700489 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600490 if category == 'handle':
491 self.object_types.append(name)
492 #
493 # Append a definition to the specified section
494 def appendSection(self, section, text):
495 # self.sections[section].append('SECTION: ' + section + '\n')
496 self.sections[section].append(text)
497 #
498 # Check if the parameter passed in is a pointer
499 def paramIsPointer(self, param):
500 ispointer = False
501 for elem in param:
502 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
503 ispointer = True
504 return ispointer
505 #
506 # Get the category of a type
507 def getTypeCategory(self, typename):
508 types = self.registry.tree.findall("types/type")
509 for elem in types:
510 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
511 return elem.attrib.get('category')
512 #
513 # Check if a parent object is dispatchable or not
514 def isHandleTypeObject(self, handletype):
515 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
516 if handle is not None:
517 return True
518 else:
519 return False
520 #
521 # Check if a parent object is dispatchable or not
522 def isHandleTypeNonDispatchable(self, handletype):
523 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
524 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
525 return True
526 else:
527 return False
528 #
529 # Retrieve the type and name for a parameter
530 def getTypeNameTuple(self, param):
531 type = ''
532 name = ''
533 for elem in param:
534 if elem.tag == 'type':
535 type = noneStr(elem.text)
536 elif elem.tag == 'name':
537 name = noneStr(elem.text)
538 return (type, name)
539 #
540 # Retrieve the value of the len tag
541 def getLen(self, param):
542 result = None
543 len = param.attrib.get('len')
544 if len and len != 'null-terminated':
545 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
546 # have a null terminated array of strings. We strip the null-terminated from the
547 # 'len' field and only return the parameter specifying the string count
548 if 'null-terminated' in len:
549 result = len.split(',')[0]
550 else:
551 result = len
552 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
553 result = str(result).replace('::', '->')
554 return result
555 #
556 # Generate a VkStructureType based on a structure typename
557 def genVkStructureType(self, typename):
558 # Add underscore between lowercase then uppercase
559 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
560 # Change to uppercase
561 value = value.upper()
562 # Add STRUCTURE_TYPE_
563 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
564 #
565 # Struct parameter check generation.
566 # This is a special case of the <type> tag where the contents are interpreted as a set of
567 # <member> tags instead of freeform C type declarations. The <member> tags are just like
568 # <param> tags - they are a declaration of a struct or union member. Only simple member
569 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700570 def genStruct(self, typeinfo, typeName, alias):
571 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600572 members = typeinfo.elem.findall('.//member')
573 # Iterate over members once to get length parameters for arrays
574 lens = set()
575 for member in members:
576 len = self.getLen(member)
577 if len:
578 lens.add(len)
579 # Generate member info
580 membersInfo = []
581 for member in members:
582 # Get the member's type and name
583 info = self.getTypeNameTuple(member)
584 type = info[0]
585 name = info[1]
586 cdecl = self.makeCParamDecl(member, 0)
587 # Process VkStructureType
588 if type == 'VkStructureType':
589 # Extract the required struct type value from the comments
590 # embedded in the original text defining the 'typeinfo' element
591 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
592 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
593 if result:
594 value = result.group(0)
595 else:
596 value = self.genVkStructureType(typeName)
597 # Store the required type value
598 self.structTypes[typeName] = self.StructType(name=name, value=value)
599 # Store pointer/array/string info
600 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
601 membersInfo.append(self.CommandParam(type=type,
602 name=name,
603 ispointer=self.paramIsPointer(member),
604 isconst=True if 'const' in cdecl else False,
605 isoptional=self.paramIsOptional(member),
606 iscount=True if name in lens else False,
607 len=self.getLen(member),
608 extstructs=extstructs,
609 cdecl=cdecl,
610 islocal=False,
611 iscreate=False,
612 isdestroy=False,
613 feature_protect=self.featureExtraProtect))
614 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
615 #
616 # Insert a lock_guard line
617 def lock_guard(self, indent):
618 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
619 #
620 # Determine if a struct has an object as a member or an embedded member
621 def struct_contains_object(self, struct_item):
622 struct_member_dict = dict(self.structMembers)
623 struct_members = struct_member_dict[struct_item]
624
625 for member in struct_members:
626 if self.isHandleTypeObject(member.type):
627 return True
628 elif member.type in struct_member_dict:
629 if self.struct_contains_object(member.type) == True:
630 return True
631 return False
632 #
633 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
634 def getParmeterStructsWithObjects(self, item_list):
635 struct_list = set()
636 for item in item_list:
637 paramtype = item.find('type')
638 typecategory = self.getTypeCategory(paramtype.text)
639 if typecategory == 'struct':
640 if self.struct_contains_object(paramtype.text) == True:
641 struct_list.add(item)
642 return struct_list
643 #
644 # Return list of objects from a given list of parameters or members
645 def getObjectsInParameterList(self, item_list, create_func):
646 object_list = set()
647 if create_func == True:
648 member_list = item_list[0:-1]
649 else:
650 member_list = item_list
651 for item in member_list:
652 if self.isHandleTypeObject(paramtype.text):
653 object_list.add(item)
654 return object_list
655 #
656 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600657 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600658 def GenerateCommandWrapExtensionList(self):
659 for struct in self.structMembers:
660 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
661 found = False;
662 for item in struct.members[1].extstructs.split(','):
663 if item != '' and self.struct_contains_object(item) == True:
664 found = True
665 if found == True:
666 for item in struct.members[1].extstructs.split(','):
667 if item != '' and item not in self.extension_structs:
668 self.extension_structs.append(item)
669 #
670 # Returns True if a struct may have a pNext chain containing an object
671 def StructWithExtensions(self, struct_type):
672 if struct_type in self.struct_member_dict:
673 param_info = self.struct_member_dict[struct_type]
674 if (len(param_info) > 1) and param_info[1].extstructs is not None:
675 for item in param_info[1].extstructs.split(','):
676 if item in self.extension_structs:
677 return True
678 return False
679 #
680 # Generate VulkanObjectType from object type
681 def GetVulkanObjType(self, type):
682 return 'kVulkanObjectType%s' % type[2:]
683 #
684 # Return correct dispatch table type -- instance or device
685 def GetDispType(self, type):
686 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
687 #
688 # Generate source for creating a Vulkan object
689 def generate_create_object_code(self, indent, proto, params, cmd_info):
690 create_obj_code = ''
691 handle_type = params[-1].find('type')
692 if self.isHandleTypeObject(handle_type.text):
693 # Check for special case where multiple handles are returned
694 object_array = False
695 if cmd_info[-1].len is not None:
696 object_array = True;
697 handle_name = params[-1].find('name')
698 create_obj_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
699 indent = self.incIndent(indent)
700 create_obj_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
701 object_dest = '*%s' % handle_name.text
702 if object_array == True:
703 create_obj_code += '%sfor (uint32_t index = 0; index < %s; index++) {\n' % (indent, cmd_info[-1].len)
704 indent = self.incIndent(indent)
705 object_dest = '%s[index]' % cmd_info[-1].name
706 create_obj_code += '%sCreateObject(%s, %s, %s, pAllocator);\n' % (indent, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type))
707 if object_array == True:
708 indent = self.decIndent(indent)
709 create_obj_code += '%s}\n' % indent
710 indent = self.decIndent(indent)
711 create_obj_code += '%s}\n' % (indent)
712 return create_obj_code
713 #
714 # Generate source for destroying a non-dispatchable object
715 def generate_destroy_object_code(self, indent, proto, cmd_info):
716 destroy_obj_code = ''
717 object_array = False
718 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
719 # Check for special case where multiple handles are returned
720 if cmd_info[-1].len is not None:
721 object_array = True;
722 param = -1
723 else:
724 param = -2
725 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
726 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600727 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
728 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600729 if self.isHandleTypeObject(cmd_info[param].type) == True:
730 if object_array == True:
731 # This API is freeing an array of handles -- add loop control
732 destroy_obj_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
733 else:
734 # Call Destroy a single time
735 destroy_obj_code += '%sif (skip) return;\n' % indent
736 destroy_obj_code += '%s{\n' % indent
737 destroy_obj_code += '%s std::lock_guard<std::mutex> lock(global_lock);\n' % indent
738 destroy_obj_code += '%s DestroyObject(%s, %s, %s, pAllocator, %s, %s);\n' % (indent, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type), compatalloc_vuid, nullalloc_vuid)
739 destroy_obj_code += '%s}\n' % indent
740 return object_array, destroy_obj_code
741 #
742 # Output validation for a single object (obj_count is NULL) or a counted list of objects
743 def outputObjects(self, obj_type, obj_name, obj_count, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, null_allowed, top_level):
744 decl_code = ''
745 pre_call_code = ''
746 post_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600747 param_suffix = '%s-parameter' % (obj_name)
748 parent_suffix = '%s-parent' % (obj_name)
749 param_vuid = self.GetVuid(parent_name, param_suffix)
750 parent_vuid = self.GetVuid(parent_name, parent_suffix)
751
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600752 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600753 if parent_vuid == 'kVUIDUndefined':
754 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600755 if obj_count is not None:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600756 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
757 indent = self.incIndent(indent)
758 pre_call_code += '%s skip |= ValidateObject(%s, %s%s[%s], %s, %s, %s, %s);\n' % (indent, disp_name, prefix, obj_name, index, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
759 indent = self.decIndent(indent)
760 pre_call_code += '%s }\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600761 else:
762 pre_call_code += '%s skip |= ValidateObject(%s, %s%s, %s, %s, %s, %s);\n' % (indent, disp_name, prefix, obj_name, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
763 return decl_code, pre_call_code, post_call_code
764 #
765 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
766 # create_func means that this is API creates or allocates objects
767 # destroy_func indicates that this API destroys or frees objects
768 # destroy_array means that the destroy_func operated on an array of objects
769 def validate_objects(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, disp_name, parent_name, first_level_param):
770 decls = ''
771 pre_code = ''
772 post_code = ''
773 index = 'index%s' % str(array_index)
774 array_index += 1
775 # Process any objects in this structure and recurse for any sub-structs in this struct
776 for member in members:
777 # Handle objects
778 if member.iscreate and first_level_param and member == members[-1]:
779 continue
780 if self.isHandleTypeObject(member.type) == True:
781 count_name = member.len
782 if (count_name is not None):
783 count_name = '%s%s' % (prefix, member.len)
784 null_allowed = member.isoptional
785 (tmp_decl, tmp_pre, tmp_post) = self.outputObjects(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, str(null_allowed).lower(), first_level_param)
786 decls += tmp_decl
787 pre_code += tmp_pre
788 post_code += tmp_post
789 # Handle Structs that contain objects at some level
790 elif member.type in self.struct_member_dict:
791 # Structs at first level will have an object
792 if self.struct_contains_object(member.type) == True:
793 struct_info = self.struct_member_dict[member.type]
794 # Struct Array
795 if member.len is not None:
796 # Update struct prefix
797 new_prefix = '%s%s' % (prefix, member.name)
798 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
799 indent = self.incIndent(indent)
800 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
801 indent = self.incIndent(indent)
802 local_prefix = '%s[%s].' % (new_prefix, index)
803 # Process sub-structs in this struct
804 (tmp_decl, tmp_pre, tmp_post) = self.validate_objects(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, disp_name, member.type, False)
805 decls += tmp_decl
806 pre_code += tmp_pre
807 post_code += tmp_post
808 indent = self.decIndent(indent)
809 pre_code += '%s }\n' % indent
810 indent = self.decIndent(indent)
811 pre_code += '%s }\n' % indent
812 # Single Struct
813 else:
814 # Update struct prefix
815 new_prefix = '%s%s->' % (prefix, member.name)
816 # Declare safe_VarType for struct
817 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
818 indent = self.incIndent(indent)
819 # Process sub-structs in this struct
820 (tmp_decl, tmp_pre, tmp_post) = self.validate_objects(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, disp_name, member.type, False)
821 decls += tmp_decl
822 pre_code += tmp_pre
823 post_code += tmp_post
824 indent = self.decIndent(indent)
825 pre_code += '%s }\n' % indent
826 return decls, pre_code, post_code
827 #
828 # For a particular API, generate the object handling code
829 def generate_wrapping_code(self, cmd):
830 indent = ' '
831 proto = cmd.find('proto/name')
832 params = cmd.findall('param')
833 if proto.text is not None:
834 cmd_member_dict = dict(self.cmdMembers)
835 cmd_info = cmd_member_dict[proto.text]
836 disp_name = cmd_info[0].name
837 # Handle object create operations
838 if cmd_info[0].iscreate:
839 create_obj_code = self.generate_create_object_code(indent, proto, params, cmd_info)
840 else:
841 create_obj_code = ''
842 # Handle object destroy operations
843 if cmd_info[0].isdestroy:
844 (destroy_array, destroy_object_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
845 else:
846 destroy_array = False
847 destroy_object_code = ''
848 paramdecl = ''
849 param_pre_code = ''
850 param_post_code = ''
851 create_func = True if create_obj_code else False
852 destroy_func = True if destroy_object_code else False
853 (paramdecl, param_pre_code, param_post_code) = self.validate_objects(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, disp_name, proto.text, True)
854 param_post_code += create_obj_code
855 if destroy_object_code:
856 if destroy_array == True:
857 param_post_code += destroy_object_code
858 else:
859 param_pre_code += destroy_object_code
860 if param_pre_code:
861 if (not destroy_func) or (destroy_array):
862 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
863 return paramdecl, param_pre_code, param_post_code
864 #
865 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700866 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600867
868 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700869 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600870 members = cmdinfo.elem.findall('.//param')
871 # Iterate over members once to get length parameters for arrays
872 lens = set()
873 for member in members:
874 len = self.getLen(member)
875 if len:
876 lens.add(len)
877 struct_member_dict = dict(self.structMembers)
878 # Generate member info
879 membersInfo = []
880 constains_extension_structs = False
881 for member in members:
882 # Get type and name of member
883 info = self.getTypeNameTuple(member)
884 type = info[0]
885 name = info[1]
886 cdecl = self.makeCParamDecl(member, 0)
887 # Check for parameter name in lens set
888 iscount = True if name in lens else False
889 len = self.getLen(member)
890 isconst = True if 'const' in cdecl else False
891 ispointer = self.paramIsPointer(member)
892 # Mark param as local if it is an array of objects
893 islocal = False;
894 if self.isHandleTypeObject(type) == True:
895 if (len is not None) and (isconst == True):
896 islocal = True
897 # Or if it's a struct that contains an object
898 elif type in struct_member_dict:
899 if self.struct_contains_object(type) == True:
900 islocal = True
901 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
902 iscreate = True if True in [create_txt in cmdname for create_txt in ['Create', 'Allocate', 'Enumerate', 'RegisterDeviceEvent', 'RegisterDisplayEvent']] or ('vkGet' in cmdname and member == members[-1] and ispointer == True) else False
903 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
904 membersInfo.append(self.CommandParam(type=type,
905 name=name,
906 ispointer=ispointer,
907 isconst=isconst,
908 isoptional=self.paramIsOptional(member),
909 iscount=iscount,
910 len=len,
911 extstructs=extstructs,
912 cdecl=cdecl,
913 islocal=islocal,
914 iscreate=iscreate,
915 isdestroy=isdestroy,
916 feature_protect=self.featureExtraProtect))
917 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Dave Houlton57ae22f2018-05-18 16:20:52 -0600918 if alias != None:
919 self.CmdMemberAlias[cmdname] = alias
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600920 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
921 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
922 #
923 # Create code Create, Destroy, and validate Vulkan objects
924 def WrapCommands(self):
925 cmd_member_dict = dict(self.cmdMembers)
926 cmd_info_dict = dict(self.cmd_info_data)
927 cmd_protect_dict = dict(self.cmd_feature_protect)
928 for api_call in self.cmdMembers:
929 cmdname = api_call.name
930 cmdinfo = cmd_info_dict[api_call.name]
931 if cmdname in self.interface_functions:
932 continue
933 if cmdname in self.no_autogen_list:
934 decls = self.makeCDecls(cmdinfo.elem)
935 self.appendSection('command', '')
936 self.appendSection('command', '// Declare only')
937 self.appendSection('command', decls[0])
938 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
939 continue
940 # Generate object handling code
941 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
942 # If API doesn't contain any object handles, don't fool with it
943 if not api_decls and not api_pre and not api_post:
944 continue
945 feature_extra_protect = cmd_protect_dict[api_call.name]
946 if (feature_extra_protect != None):
947 self.appendSection('command', '')
948 self.appendSection('command', '#ifdef '+ feature_extra_protect)
949 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
950 # Add intercept to procmap
951 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
952 decls = self.makeCDecls(cmdinfo.elem)
953 self.appendSection('command', '')
954 self.appendSection('command', decls[0][:-1])
955 self.appendSection('command', '{')
956 self.appendSection('command', ' bool skip = false;')
957 # Handle return values, if any
958 resulttype = cmdinfo.elem.find('proto/type')
959 if (resulttype != None and resulttype.text == 'void'):
960 resulttype = None
961 if (resulttype != None):
962 assignresult = resulttype.text + ' result = '
963 else:
964 assignresult = ''
965 # Pre-pend declarations and pre-api-call codegen
966 if api_decls:
967 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
968 if api_pre:
969 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
970 # Generate the API call itself
971 # Gather the parameter items
972 params = cmdinfo.elem.findall('param/name')
973 # Pull out the text for each of the parameters, separate them by commas in a list
974 paramstext = ', '.join([str(param.text) for param in params])
975 # Use correct dispatch table
976 disp_type = cmdinfo.elem.find('param/type').text
977 disp_name = cmdinfo.elem.find('param/name').text
978 dispatch_table = 'get_dispatch_table(ot_%s_table_map, %s)->' % (self.GetDispType(disp_type), disp_name)
979 API = cmdinfo.elem.attrib.get('name').replace('vk', dispatch_table, 1)
980 # Put all this together for the final down-chain call
981 if assignresult != '':
Jamie Madillfc315192017-11-08 14:11:26 -0500982 if resulttype.text == 'VkResult':
983 self.appendSection('command', ' if (skip) return VK_ERROR_VALIDATION_FAILED_EXT;')
984 elif resulttype.text == 'VkBool32':
985 self.appendSection('command', ' if (skip) return VK_FALSE;')
986 else:
987 raise Exception('Unknown result type ' + resulttype.text)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600988 else:
989 self.appendSection('command', ' if (skip) return;')
990 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
991 # And add the post-API-call codegen
992 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
993 # Handle the return result variable, if any
994 if (resulttype != None):
995 self.appendSection('command', ' return result;')
996 self.appendSection('command', '}')
997 if (feature_extra_protect != None):
998 self.appendSection('command', '#endif // '+ feature_extra_protect)
999 self.intercepts += [ '#endif' ]