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