blob: 7198b3463c6387e8c3a38cb7ab47bf10cbf20d5d [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 Lobodzinski5a1c8d22018-07-02 10:28:12 -0600178 'vkGetDescriptorSetLayoutSupport',
179 'vkGetDescriptorSetLayoutSupportKHR',
Mark Young6ba8abe2017-11-09 10:37:04 -0700180 'vkCreateDebugUtilsMessengerEXT',
181 'vkDestroyDebugUtilsMessengerEXT',
182 'vkSubmitDebugUtilsMessageEXT',
183 'vkSetDebugUtilsObjectNameEXT',
184 'vkSetDebugUtilsObjectTagEXT',
185 'vkQueueBeginDebugUtilsLabelEXT',
186 'vkQueueEndDebugUtilsLabelEXT',
187 'vkQueueInsertDebugUtilsLabelEXT',
188 'vkCmdBeginDebugUtilsLabelEXT',
189 'vkCmdEndDebugUtilsLabelEXT',
190 'vkCmdInsertDebugUtilsLabelEXT',
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600191 'vkGetDisplayModePropertiesKHR',
192 'vkGetPhysicalDeviceDisplayPropertiesKHR',
Piers Daniell16c253f2018-05-30 14:34:05 -0600193 'vkGetPhysicalDeviceDisplayProperties2KHR',
194 'vkGetDisplayPlaneSupportedDisplaysKHR',
195 'vkGetDisplayModeProperties2KHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600196 ]
197 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
198 # which is translated here into a good VU. Saves ~40 checks.
199 self.manual_vuids = dict()
200 self.manual_vuids = {
Dave Houlton57ae22f2018-05-18 16:20:52 -0600201 "fence-compatalloc": "\"VUID-vkDestroyFence-fence-01121\"",
202 "fence-nullalloc": "\"VUID-vkDestroyFence-fence-01122\"",
203 "event-compatalloc": "\"VUID-vkDestroyEvent-event-01146\"",
204 "event-nullalloc": "\"VUID-vkDestroyEvent-event-01147\"",
205 "buffer-compatalloc": "\"VUID-vkDestroyBuffer-buffer-00923\"",
206 "buffer-nullalloc": "\"VUID-vkDestroyBuffer-buffer-00924\"",
207 "image-compatalloc": "\"VUID-vkDestroyImage-image-01001\"",
208 "image-nullalloc": "\"VUID-vkDestroyImage-image-01002\"",
209 "shaderModule-compatalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01092\"",
210 "shaderModule-nullalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01093\"",
211 "pipeline-compatalloc": "\"VUID-vkDestroyPipeline-pipeline-00766\"",
212 "pipeline-nullalloc": "\"VUID-vkDestroyPipeline-pipeline-00767\"",
213 "sampler-compatalloc": "\"VUID-vkDestroySampler-sampler-01083\"",
214 "sampler-nullalloc": "\"VUID-vkDestroySampler-sampler-01084\"",
215 "renderPass-compatalloc": "\"VUID-vkDestroyRenderPass-renderPass-00874\"",
216 "renderPass-nullalloc": "\"VUID-vkDestroyRenderPass-renderPass-00875\"",
217 "descriptorUpdateTemplate-compatalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356\"",
218 "descriptorUpdateTemplate-nullalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357\"",
219 "imageView-compatalloc": "\"VUID-vkDestroyImageView-imageView-01027\"",
220 "imageView-nullalloc": "\"VUID-vkDestroyImageView-imageView-01028\"",
221 "pipelineCache-compatalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00771\"",
222 "pipelineCache-nullalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00772\"",
223 "pipelineLayout-compatalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00299\"",
224 "pipelineLayout-nullalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00300\"",
225 "descriptorSetLayout-compatalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284\"",
226 "descriptorSetLayout-nullalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285\"",
227 "semaphore-compatalloc": "\"VUID-vkDestroySemaphore-semaphore-01138\"",
228 "semaphore-nullalloc": "\"VUID-vkDestroySemaphore-semaphore-01139\"",
229 "queryPool-compatalloc": "\"VUID-vkDestroyQueryPool-queryPool-00794\"",
230 "queryPool-nullalloc": "\"VUID-vkDestroyQueryPool-queryPool-00795\"",
231 "bufferView-compatalloc": "\"VUID-vkDestroyBufferView-bufferView-00937\"",
232 "bufferView-nullalloc": "\"VUID-vkDestroyBufferView-bufferView-00938\"",
233 "surface-compatalloc": "\"VUID-vkDestroySurfaceKHR-surface-01267\"",
234 "surface-nullalloc": "\"VUID-vkDestroySurfaceKHR-surface-01268\"",
235 "framebuffer-compatalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00893\"",
236 "framebuffer-nullalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00894\"",
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600237 }
238
239 # Commands shadowed by interface functions and are not implemented
240 self.interface_functions = [
241 ]
242 self.headerVersion = None
243 # Internal state - accumulators for different inner block text
244 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
245 self.cmdMembers = []
246 self.cmd_feature_protect = [] # Save ifdef's for each command
247 self.cmd_info_data = [] # Save the cmdinfo data for validating the handles when processing is complete
248 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
249 self.extension_structs = [] # List of all structs or sister-structs containing handles
250 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
251 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
252 self.struct_member_dict = dict()
253 # Named tuples to store struct and command data
254 self.StructType = namedtuple('StructType', ['name', 'value'])
255 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
Dave Houlton57ae22f2018-05-18 16:20:52 -0600256 self.CmdMemberAlias = dict()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600257 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
258 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
259 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'isoptional', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
260 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
261 self.object_types = [] # List of all handle types
262 self.valid_vuids = set() # Set of all valid VUIDs
Dave Houlton57ae22f2018-05-18 16:20:52 -0600263 self.vuid_dict = dict() # VUID dictionary (from JSON)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600264 #
265 # Check if the parameter passed in is optional
266 def paramIsOptional(self, param):
267 # See if the handle is optional
268 isoptional = False
269 # Simple, if it's optional, return true
270 optString = param.attrib.get('optional')
271 if optString:
272 if optString == 'true':
273 isoptional = True
274 elif ',' in optString:
275 opts = []
276 for opt in optString.split(','):
277 val = opt.strip()
278 if val == 'true':
279 opts.append(True)
280 elif val == 'false':
281 opts.append(False)
282 else:
283 print('Unrecognized len attribute value',val)
284 isoptional = opts
John Zulauf9f6788c2018-04-04 14:54:11 -0600285 if not isoptional:
286 # Matching logic in parameter validation and ValidityOutputGenerator.isHandleOptional
287 optString = param.attrib.get('noautovalidity')
288 if optString and optString == 'true':
289 isoptional = True;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600290 return isoptional
291 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600292 # Get VUID identifier from implicit VUID tag
Dave Houlton57ae22f2018-05-18 16:20:52 -0600293 def GetVuid(self, parent, suffix):
294 vuid_string = 'VUID-%s-%s' % (parent, suffix)
295 vuid = "kVUIDUndefined"
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600296 if '->' in vuid_string:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600297 return vuid
298 if vuid_string in self.valid_vuids:
299 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600300 else:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600301 if parent in self.CmdMemberAlias:
302 alias_string = 'VUID-%s-%s' % (self.CmdMemberAlias[parent], suffix)
303 if alias_string in self.valid_vuids:
304 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600305 return vuid
306 #
307 # Increases indent by 4 spaces and tracks it globally
308 def incIndent(self, indent):
309 inc = ' ' * self.INDENT_SPACES
310 if indent:
311 return indent + inc
312 return inc
313 #
314 # Decreases indent by 4 spaces and tracks it globally
315 def decIndent(self, indent):
316 if indent and (len(indent) > self.INDENT_SPACES):
317 return indent[:-self.INDENT_SPACES]
318 return ''
319 #
320 # Override makeProtoName to drop the "vk" prefix
321 def makeProtoName(self, name, tail):
322 return self.genOpts.apientry + name[2:] + tail
323 #
324 # Check if the parameter passed in is a pointer to an array
325 def paramIsArray(self, param):
326 return param.attrib.get('len') is not None
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000327
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600328 #
329 # Generate the object tracker undestroyed object validation function
330 def GenReportFunc(self):
331 output_func = ''
Dave Houlton379f1422018-05-23 12:47:07 -0600332 output_func += 'void ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600333 output_func += ' DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
334 for handle in self.object_types:
335 if self.isHandleTypeNonDispatchable(handle):
336 output_func += ' DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
337 output_func += '}\n'
338 return output_func
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000339
340 #
341 # Generate the object tracker undestroyed object destruction function
342 def GenDestroyFunc(self):
343 output_func = ''
344 output_func += 'void DestroyUndestroyedObjects(VkDevice device) {\n'
345 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
346 for handle in self.object_types:
347 if self.isHandleTypeNonDispatchable(handle):
348 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
349 output_func += '}\n'
350 return output_func
351
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600352 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600353 # Walk the JSON-derived dict and find all "vuid" key values
354 def ExtractVUIDs(self, d):
355 if hasattr(d, 'items'):
356 for k, v in d.items():
357 if k == "vuid":
358 yield v
359 elif isinstance(v, dict):
360 for s in self.ExtractVUIDs(v):
361 yield s
362 elif isinstance (v, list):
363 for l in v:
364 for s in self.ExtractVUIDs(l):
365 yield s
366
367 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600368 # Called at beginning of processing as file is opened
369 def beginFile(self, genOpts):
370 OutputGenerator.beginFile(self, genOpts)
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600371
372 self.valid_usage_path = genOpts.valid_usage_path
373 vu_json_filename = os.path.join(self.valid_usage_path + os.sep, 'validusage.json')
374 if os.path.isfile(vu_json_filename):
375 json_file = open(vu_json_filename, 'r')
376 self.vuid_dict = json.load(json_file)
377 json_file.close()
378 if len(self.vuid_dict) == 0:
379 print("Error: Could not find, or error loading %s/validusage.json\n", vu_json_filename)
380 sys.exit(1)
381
Dave Houlton57ae22f2018-05-18 16:20:52 -0600382 # Build a set of all vuid text strings found in validusage.json
383 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
384 self.valid_vuids.add(json_vuid_string)
385
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600386 # File Comment
387 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
388 file_comment += '// See object_tracker_generator.py for modifications\n'
389 write(file_comment, file=self.outFile)
390 # Copyright Statement
391 copyright = ''
392 copyright += '\n'
393 copyright += '/***************************************************************************\n'
394 copyright += ' *\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600395 copyright += ' * Copyright (c) 2015-2018 The Khronos Group Inc.\n'
396 copyright += ' * Copyright (c) 2015-2018 Valve Corporation\n'
397 copyright += ' * Copyright (c) 2015-2018 LunarG, Inc.\n'
398 copyright += ' * Copyright (c) 2015-2018 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600399 copyright += ' *\n'
400 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
401 copyright += ' * you may not use this file except in compliance with the License.\n'
402 copyright += ' * You may obtain a copy of the License at\n'
403 copyright += ' *\n'
404 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
405 copyright += ' *\n'
406 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
407 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
408 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
409 copyright += ' * See the License for the specific language governing permissions and\n'
410 copyright += ' * limitations under the License.\n'
411 copyright += ' *\n'
412 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600413 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600414 copyright += ' *\n'
415 copyright += ' ****************************************************************************/\n'
416 write(copyright, file=self.outFile)
417 # Namespace
418 self.newline()
419 write('#include "object_tracker.h"', file = self.outFile)
420 self.newline()
421 write('namespace object_tracker {', file = self.outFile)
422 #
423 # Now that the data is all collected and complete, generate and output the object validation routines
424 def endFile(self):
425 self.struct_member_dict = dict(self.structMembers)
426 # Generate the list of APIs that might need to handle wrapped extension structs
427 # self.GenerateCommandWrapExtensionList()
428 self.WrapCommands()
429 # Build undestroyed objects reporting function
430 report_func = self.GenReportFunc()
431 self.newline()
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000432 # Build undestroyed objects destruction function
433 destroy_func = self.GenDestroyFunc()
434 self.newline()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600435 write('// ObjectTracker undestroyed objects validation function', file=self.outFile)
436 write('%s' % report_func, file=self.outFile)
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000437 write('%s' % destroy_func, file=self.outFile)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600438 # Actually write the interface to the output file.
439 if (self.emit):
440 self.newline()
441 if (self.featureExtraProtect != None):
442 write('#ifdef', self.featureExtraProtect, file=self.outFile)
443 # Write the object_tracker code to the file
444 if (self.sections['command']):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600445 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
446 if (self.featureExtraProtect != None):
447 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
448 else:
449 self.newline()
450
451 # Record intercepted procedures
452 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
453 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
454 write('\n'.join(self.intercepts), file=self.outFile)
455 write('};\n', file=self.outFile)
456 self.newline()
457 write('} // namespace object_tracker', file=self.outFile)
458 # Finish processing in superclass
459 OutputGenerator.endFile(self)
460 #
461 # Processing point at beginning of each extension definition
462 def beginFeature(self, interface, emit):
463 # Start processing in superclass
464 OutputGenerator.beginFeature(self, interface, emit)
465 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600466 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600467
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600468 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600469 white_list_entry = []
470 if (self.featureExtraProtect != None):
471 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
472 white_list_entry += [ '"%s"' % self.featureName ]
473 if (self.featureExtraProtect != None):
474 white_list_entry += [ '#endif' ]
475 featureType = interface.get('type')
476 if featureType == 'instance':
477 self.instance_extensions += white_list_entry
478 elif featureType == 'device':
479 self.device_extensions += white_list_entry
480 #
481 # Processing point at end of each extension definition
482 def endFeature(self):
483 # Finish processing in superclass
484 OutputGenerator.endFeature(self)
485 #
486 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700487 def genType(self, typeinfo, name, alias):
488 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600489 typeElem = typeinfo.elem
490 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
491 # Otherwise, emit the tag text.
492 category = typeElem.get('category')
493 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700494 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600495 if category == 'handle':
496 self.object_types.append(name)
497 #
498 # Append a definition to the specified section
499 def appendSection(self, section, text):
500 # self.sections[section].append('SECTION: ' + section + '\n')
501 self.sections[section].append(text)
502 #
503 # Check if the parameter passed in is a pointer
504 def paramIsPointer(self, param):
505 ispointer = False
506 for elem in param:
507 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
508 ispointer = True
509 return ispointer
510 #
511 # Get the category of a type
512 def getTypeCategory(self, typename):
513 types = self.registry.tree.findall("types/type")
514 for elem in types:
515 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
516 return elem.attrib.get('category')
517 #
518 # Check if a parent object is dispatchable or not
519 def isHandleTypeObject(self, handletype):
520 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
521 if handle is not None:
522 return True
523 else:
524 return False
525 #
526 # Check if a parent object is dispatchable or not
527 def isHandleTypeNonDispatchable(self, handletype):
528 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
529 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
530 return True
531 else:
532 return False
533 #
534 # Retrieve the type and name for a parameter
535 def getTypeNameTuple(self, param):
536 type = ''
537 name = ''
538 for elem in param:
539 if elem.tag == 'type':
540 type = noneStr(elem.text)
541 elif elem.tag == 'name':
542 name = noneStr(elem.text)
543 return (type, name)
544 #
545 # Retrieve the value of the len tag
546 def getLen(self, param):
547 result = None
548 len = param.attrib.get('len')
549 if len and len != 'null-terminated':
550 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
551 # have a null terminated array of strings. We strip the null-terminated from the
552 # 'len' field and only return the parameter specifying the string count
553 if 'null-terminated' in len:
554 result = len.split(',')[0]
555 else:
556 result = len
557 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
558 result = str(result).replace('::', '->')
559 return result
560 #
561 # Generate a VkStructureType based on a structure typename
562 def genVkStructureType(self, typename):
563 # Add underscore between lowercase then uppercase
564 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
565 # Change to uppercase
566 value = value.upper()
567 # Add STRUCTURE_TYPE_
568 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
569 #
570 # Struct parameter check generation.
571 # This is a special case of the <type> tag where the contents are interpreted as a set of
572 # <member> tags instead of freeform C type declarations. The <member> tags are just like
573 # <param> tags - they are a declaration of a struct or union member. Only simple member
574 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700575 def genStruct(self, typeinfo, typeName, alias):
576 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600577 members = typeinfo.elem.findall('.//member')
578 # Iterate over members once to get length parameters for arrays
579 lens = set()
580 for member in members:
581 len = self.getLen(member)
582 if len:
583 lens.add(len)
584 # Generate member info
585 membersInfo = []
586 for member in members:
587 # Get the member's type and name
588 info = self.getTypeNameTuple(member)
589 type = info[0]
590 name = info[1]
591 cdecl = self.makeCParamDecl(member, 0)
592 # Process VkStructureType
593 if type == 'VkStructureType':
594 # Extract the required struct type value from the comments
595 # embedded in the original text defining the 'typeinfo' element
596 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
597 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
598 if result:
599 value = result.group(0)
600 else:
601 value = self.genVkStructureType(typeName)
602 # Store the required type value
603 self.structTypes[typeName] = self.StructType(name=name, value=value)
604 # Store pointer/array/string info
605 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
606 membersInfo.append(self.CommandParam(type=type,
607 name=name,
608 ispointer=self.paramIsPointer(member),
609 isconst=True if 'const' in cdecl else False,
610 isoptional=self.paramIsOptional(member),
611 iscount=True if name in lens else False,
612 len=self.getLen(member),
613 extstructs=extstructs,
614 cdecl=cdecl,
615 islocal=False,
616 iscreate=False,
617 isdestroy=False,
618 feature_protect=self.featureExtraProtect))
619 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
620 #
621 # Insert a lock_guard line
622 def lock_guard(self, indent):
623 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
624 #
625 # Determine if a struct has an object as a member or an embedded member
626 def struct_contains_object(self, struct_item):
627 struct_member_dict = dict(self.structMembers)
628 struct_members = struct_member_dict[struct_item]
629
630 for member in struct_members:
631 if self.isHandleTypeObject(member.type):
632 return True
633 elif member.type in struct_member_dict:
634 if self.struct_contains_object(member.type) == True:
635 return True
636 return False
637 #
638 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
639 def getParmeterStructsWithObjects(self, item_list):
640 struct_list = set()
641 for item in item_list:
642 paramtype = item.find('type')
643 typecategory = self.getTypeCategory(paramtype.text)
644 if typecategory == 'struct':
645 if self.struct_contains_object(paramtype.text) == True:
646 struct_list.add(item)
647 return struct_list
648 #
649 # Return list of objects from a given list of parameters or members
650 def getObjectsInParameterList(self, item_list, create_func):
651 object_list = set()
652 if create_func == True:
653 member_list = item_list[0:-1]
654 else:
655 member_list = item_list
656 for item in member_list:
657 if self.isHandleTypeObject(paramtype.text):
658 object_list.add(item)
659 return object_list
660 #
661 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600662 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600663 def GenerateCommandWrapExtensionList(self):
664 for struct in self.structMembers:
665 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
666 found = False;
667 for item in struct.members[1].extstructs.split(','):
668 if item != '' and self.struct_contains_object(item) == True:
669 found = True
670 if found == True:
671 for item in struct.members[1].extstructs.split(','):
672 if item != '' and item not in self.extension_structs:
673 self.extension_structs.append(item)
674 #
675 # Returns True if a struct may have a pNext chain containing an object
676 def StructWithExtensions(self, struct_type):
677 if struct_type in self.struct_member_dict:
678 param_info = self.struct_member_dict[struct_type]
679 if (len(param_info) > 1) and param_info[1].extstructs is not None:
680 for item in param_info[1].extstructs.split(','):
681 if item in self.extension_structs:
682 return True
683 return False
684 #
685 # Generate VulkanObjectType from object type
686 def GetVulkanObjType(self, type):
687 return 'kVulkanObjectType%s' % type[2:]
688 #
689 # Return correct dispatch table type -- instance or device
690 def GetDispType(self, type):
691 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
692 #
693 # Generate source for creating a Vulkan object
694 def generate_create_object_code(self, indent, proto, params, cmd_info):
695 create_obj_code = ''
696 handle_type = params[-1].find('type')
697 if self.isHandleTypeObject(handle_type.text):
698 # Check for special case where multiple handles are returned
699 object_array = False
700 if cmd_info[-1].len is not None:
701 object_array = True;
702 handle_name = params[-1].find('name')
703 create_obj_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
704 indent = self.incIndent(indent)
705 create_obj_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
706 object_dest = '*%s' % handle_name.text
707 if object_array == True:
708 create_obj_code += '%sfor (uint32_t index = 0; index < %s; index++) {\n' % (indent, cmd_info[-1].len)
709 indent = self.incIndent(indent)
710 object_dest = '%s[index]' % cmd_info[-1].name
711 create_obj_code += '%sCreateObject(%s, %s, %s, pAllocator);\n' % (indent, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type))
712 if object_array == True:
713 indent = self.decIndent(indent)
714 create_obj_code += '%s}\n' % indent
715 indent = self.decIndent(indent)
716 create_obj_code += '%s}\n' % (indent)
717 return create_obj_code
718 #
719 # Generate source for destroying a non-dispatchable object
720 def generate_destroy_object_code(self, indent, proto, cmd_info):
721 destroy_obj_code = ''
722 object_array = False
723 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
724 # Check for special case where multiple handles are returned
725 if cmd_info[-1].len is not None:
726 object_array = True;
727 param = -1
728 else:
729 param = -2
730 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
731 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600732 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
733 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600734 if self.isHandleTypeObject(cmd_info[param].type) == True:
735 if object_array == True:
736 # This API is freeing an array of handles -- add loop control
737 destroy_obj_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
738 else:
739 # Call Destroy a single time
740 destroy_obj_code += '%sif (skip) return;\n' % indent
741 destroy_obj_code += '%s{\n' % indent
742 destroy_obj_code += '%s std::lock_guard<std::mutex> lock(global_lock);\n' % indent
743 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)
744 destroy_obj_code += '%s}\n' % indent
745 return object_array, destroy_obj_code
746 #
747 # Output validation for a single object (obj_count is NULL) or a counted list of objects
748 def outputObjects(self, obj_type, obj_name, obj_count, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, null_allowed, top_level):
749 decl_code = ''
750 pre_call_code = ''
751 post_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600752 param_suffix = '%s-parameter' % (obj_name)
753 parent_suffix = '%s-parent' % (obj_name)
754 param_vuid = self.GetVuid(parent_name, param_suffix)
755 parent_vuid = self.GetVuid(parent_name, parent_suffix)
756
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600757 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600758 if parent_vuid == 'kVUIDUndefined':
759 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600760 if obj_count is not None:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600761 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
762 indent = self.incIndent(indent)
763 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)
764 indent = self.decIndent(indent)
765 pre_call_code += '%s }\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600766 else:
767 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)
768 return decl_code, pre_call_code, post_call_code
769 #
770 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
771 # create_func means that this is API creates or allocates objects
772 # destroy_func indicates that this API destroys or frees objects
773 # destroy_array means that the destroy_func operated on an array of objects
774 def validate_objects(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, disp_name, parent_name, first_level_param):
775 decls = ''
776 pre_code = ''
777 post_code = ''
778 index = 'index%s' % str(array_index)
779 array_index += 1
780 # Process any objects in this structure and recurse for any sub-structs in this struct
781 for member in members:
782 # Handle objects
783 if member.iscreate and first_level_param and member == members[-1]:
784 continue
785 if self.isHandleTypeObject(member.type) == True:
786 count_name = member.len
787 if (count_name is not None):
788 count_name = '%s%s' % (prefix, member.len)
789 null_allowed = member.isoptional
790 (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)
791 decls += tmp_decl
792 pre_code += tmp_pre
793 post_code += tmp_post
794 # Handle Structs that contain objects at some level
795 elif member.type in self.struct_member_dict:
796 # Structs at first level will have an object
797 if self.struct_contains_object(member.type) == True:
798 struct_info = self.struct_member_dict[member.type]
799 # Struct Array
800 if member.len is not None:
801 # Update struct prefix
802 new_prefix = '%s%s' % (prefix, member.name)
803 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
804 indent = self.incIndent(indent)
805 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
806 indent = self.incIndent(indent)
807 local_prefix = '%s[%s].' % (new_prefix, index)
808 # Process sub-structs in this struct
809 (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)
810 decls += tmp_decl
811 pre_code += tmp_pre
812 post_code += tmp_post
813 indent = self.decIndent(indent)
814 pre_code += '%s }\n' % indent
815 indent = self.decIndent(indent)
816 pre_code += '%s }\n' % indent
817 # Single Struct
818 else:
819 # Update struct prefix
820 new_prefix = '%s%s->' % (prefix, member.name)
821 # Declare safe_VarType for struct
822 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
823 indent = self.incIndent(indent)
824 # Process sub-structs in this struct
825 (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)
826 decls += tmp_decl
827 pre_code += tmp_pre
828 post_code += tmp_post
829 indent = self.decIndent(indent)
830 pre_code += '%s }\n' % indent
831 return decls, pre_code, post_code
832 #
833 # For a particular API, generate the object handling code
834 def generate_wrapping_code(self, cmd):
835 indent = ' '
836 proto = cmd.find('proto/name')
837 params = cmd.findall('param')
838 if proto.text is not None:
839 cmd_member_dict = dict(self.cmdMembers)
840 cmd_info = cmd_member_dict[proto.text]
841 disp_name = cmd_info[0].name
842 # Handle object create operations
843 if cmd_info[0].iscreate:
844 create_obj_code = self.generate_create_object_code(indent, proto, params, cmd_info)
845 else:
846 create_obj_code = ''
847 # Handle object destroy operations
848 if cmd_info[0].isdestroy:
849 (destroy_array, destroy_object_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
850 else:
851 destroy_array = False
852 destroy_object_code = ''
853 paramdecl = ''
854 param_pre_code = ''
855 param_post_code = ''
856 create_func = True if create_obj_code else False
857 destroy_func = True if destroy_object_code else False
858 (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)
859 param_post_code += create_obj_code
860 if destroy_object_code:
861 if destroy_array == True:
862 param_post_code += destroy_object_code
863 else:
864 param_pre_code += destroy_object_code
865 if param_pre_code:
866 if (not destroy_func) or (destroy_array):
867 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
868 return paramdecl, param_pre_code, param_post_code
869 #
870 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700871 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600872
873 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700874 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600875 members = cmdinfo.elem.findall('.//param')
876 # Iterate over members once to get length parameters for arrays
877 lens = set()
878 for member in members:
879 len = self.getLen(member)
880 if len:
881 lens.add(len)
882 struct_member_dict = dict(self.structMembers)
883 # Generate member info
884 membersInfo = []
885 constains_extension_structs = False
886 for member in members:
887 # Get type and name of member
888 info = self.getTypeNameTuple(member)
889 type = info[0]
890 name = info[1]
891 cdecl = self.makeCParamDecl(member, 0)
892 # Check for parameter name in lens set
893 iscount = True if name in lens else False
894 len = self.getLen(member)
895 isconst = True if 'const' in cdecl else False
896 ispointer = self.paramIsPointer(member)
897 # Mark param as local if it is an array of objects
898 islocal = False;
899 if self.isHandleTypeObject(type) == True:
900 if (len is not None) and (isconst == True):
901 islocal = True
902 # Or if it's a struct that contains an object
903 elif type in struct_member_dict:
904 if self.struct_contains_object(type) == True:
905 islocal = True
906 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
907 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
908 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
909 membersInfo.append(self.CommandParam(type=type,
910 name=name,
911 ispointer=ispointer,
912 isconst=isconst,
913 isoptional=self.paramIsOptional(member),
914 iscount=iscount,
915 len=len,
916 extstructs=extstructs,
917 cdecl=cdecl,
918 islocal=islocal,
919 iscreate=iscreate,
920 isdestroy=isdestroy,
921 feature_protect=self.featureExtraProtect))
922 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Dave Houlton57ae22f2018-05-18 16:20:52 -0600923 if alias != None:
924 self.CmdMemberAlias[cmdname] = alias
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600925 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
926 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
927 #
928 # Create code Create, Destroy, and validate Vulkan objects
929 def WrapCommands(self):
930 cmd_member_dict = dict(self.cmdMembers)
931 cmd_info_dict = dict(self.cmd_info_data)
932 cmd_protect_dict = dict(self.cmd_feature_protect)
933 for api_call in self.cmdMembers:
934 cmdname = api_call.name
935 cmdinfo = cmd_info_dict[api_call.name]
936 if cmdname in self.interface_functions:
937 continue
938 if cmdname in self.no_autogen_list:
939 decls = self.makeCDecls(cmdinfo.elem)
940 self.appendSection('command', '')
941 self.appendSection('command', '// Declare only')
942 self.appendSection('command', decls[0])
943 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
944 continue
945 # Generate object handling code
946 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
947 # If API doesn't contain any object handles, don't fool with it
948 if not api_decls and not api_pre and not api_post:
949 continue
950 feature_extra_protect = cmd_protect_dict[api_call.name]
951 if (feature_extra_protect != None):
952 self.appendSection('command', '')
953 self.appendSection('command', '#ifdef '+ feature_extra_protect)
954 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
955 # Add intercept to procmap
956 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
957 decls = self.makeCDecls(cmdinfo.elem)
958 self.appendSection('command', '')
959 self.appendSection('command', decls[0][:-1])
960 self.appendSection('command', '{')
961 self.appendSection('command', ' bool skip = false;')
962 # Handle return values, if any
963 resulttype = cmdinfo.elem.find('proto/type')
964 if (resulttype != None and resulttype.text == 'void'):
965 resulttype = None
966 if (resulttype != None):
967 assignresult = resulttype.text + ' result = '
968 else:
969 assignresult = ''
970 # Pre-pend declarations and pre-api-call codegen
971 if api_decls:
972 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
973 if api_pre:
974 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
975 # Generate the API call itself
976 # Gather the parameter items
977 params = cmdinfo.elem.findall('param/name')
978 # Pull out the text for each of the parameters, separate them by commas in a list
979 paramstext = ', '.join([str(param.text) for param in params])
980 # Use correct dispatch table
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600981 disp_name = cmdinfo.elem.find('param/name').text
Mark Lobodzinski17de5fd2018-06-22 15:09:53 -0600982 disp_type = cmdinfo.elem.find('param/type').text
983 if disp_type in ["VkInstance", "VkPhysicalDevice"] or cmdname == 'vkCreateInstance':
984 object_type = 'instance'
985 else:
986 object_type = 'device'
987 dispatch_table = 'GetLayerDataPtr(get_dispatch_key(%s), layer_data_map)->%s_dispatch_table.' % (disp_name, object_type)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600988 API = cmdinfo.elem.attrib.get('name').replace('vk', dispatch_table, 1)
989 # Put all this together for the final down-chain call
990 if assignresult != '':
Jamie Madillfc315192017-11-08 14:11:26 -0500991 if resulttype.text == 'VkResult':
992 self.appendSection('command', ' if (skip) return VK_ERROR_VALIDATION_FAILED_EXT;')
993 elif resulttype.text == 'VkBool32':
994 self.appendSection('command', ' if (skip) return VK_FALSE;')
995 else:
996 raise Exception('Unknown result type ' + resulttype.text)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600997 else:
998 self.appendSection('command', ' if (skip) return;')
999 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
1000 # And add the post-API-call codegen
1001 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
1002 # Handle the return result variable, if any
1003 if (resulttype != None):
1004 self.appendSection('command', ' return result;')
1005 self.appendSection('command', '}')
1006 if (feature_extra_protect != None):
1007 self.appendSection('command', '#endif // '+ feature_extra_protect)
1008 self.intercepts += [ '#endif' ]