blob: 8d4b68af08dc0909bd733a7196fe60484dc804f2 [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,
88 expandEnumerants = True):
Mark Lobodzinskid1461482017-07-18 13:56:09 -060089 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
90 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060091 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskid1461482017-07-18 13:56:09 -060092 self.prefixText = prefixText
93 self.genFuncPointers = genFuncPointers
94 self.protectFile = protectFile
95 self.protectFeature = protectFeature
Mark Lobodzinskid1461482017-07-18 13:56:09 -060096 self.apicall = apicall
97 self.apientry = apientry
98 self.apientryp = apientryp
99 self.indentFuncProto = indentFuncProto
100 self.indentFuncPointer = indentFuncPointer
101 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600102 self.expandEnumerants = expandEnumerants
103
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600104
105# ObjectTrackerOutputGenerator - subclass of OutputGenerator.
106# Generates object_tracker layer object validation code
107#
108# ---- methods ----
109# ObjectTrackerOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
110# ---- methods overriding base class ----
111# beginFile(genOpts)
112# endFile()
113# beginFeature(interface, emit)
114# endFeature()
115# genCmd(cmdinfo)
116# genStruct()
117# genType()
118class ObjectTrackerOutputGenerator(OutputGenerator):
119 """Generate ObjectTracker code based on XML element attributes"""
120 # This is an ordered list of sections in the header file.
121 ALL_SECTIONS = ['command']
122 def __init__(self,
123 errFile = sys.stderr,
124 warnFile = sys.stderr,
125 diagFile = sys.stdout):
126 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
127 self.INDENT_SPACES = 4
128 self.intercepts = []
129 self.instance_extensions = []
130 self.device_extensions = []
131 # Commands which are not autogenerated but still intercepted
132 self.no_autogen_list = [
133 'vkDestroyInstance',
134 'vkDestroyDevice',
135 'vkUpdateDescriptorSets',
136 'vkDestroyDebugReportCallbackEXT',
137 'vkDebugReportMessageEXT',
138 'vkGetPhysicalDeviceQueueFamilyProperties',
139 'vkFreeCommandBuffers',
140 'vkDestroySwapchainKHR',
141 'vkDestroyDescriptorPool',
142 'vkDestroyCommandPool',
Mark Lobodzinski14ddc192017-10-25 16:57:04 -0600143 'vkGetPhysicalDeviceQueueFamilyProperties2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600144 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
145 'vkResetDescriptorPool',
146 'vkBeginCommandBuffer',
147 'vkCreateDebugReportCallbackEXT',
148 'vkEnumerateInstanceLayerProperties',
149 'vkEnumerateDeviceLayerProperties',
150 'vkEnumerateInstanceExtensionProperties',
151 'vkEnumerateDeviceExtensionProperties',
152 'vkCreateDevice',
153 'vkCreateInstance',
154 'vkEnumeratePhysicalDevices',
155 'vkAllocateCommandBuffers',
156 'vkAllocateDescriptorSets',
157 'vkFreeDescriptorSets',
Tony Barbour2fd0c2c2017-08-08 12:51:33 -0600158 'vkCmdPushDescriptorSetKHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600159 'vkDebugMarkerSetObjectNameEXT',
160 'vkGetPhysicalDeviceProcAddr',
161 'vkGetDeviceProcAddr',
162 'vkGetInstanceProcAddr',
163 'vkEnumerateInstanceExtensionProperties',
164 'vkEnumerateInstanceLayerProperties',
165 'vkEnumerateDeviceLayerProperties',
166 'vkGetDeviceProcAddr',
167 'vkGetInstanceProcAddr',
168 'vkEnumerateDeviceExtensionProperties',
169 'vk_layerGetPhysicalDeviceProcAddr',
170 'vkNegotiateLoaderLayerInterfaceVersion',
171 'vkCreateComputePipelines',
172 'vkGetDeviceQueue',
Yiwei Zhang991d88d2018-02-14 14:39:46 -0800173 'vkGetDeviceQueue2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600174 'vkGetSwapchainImagesKHR',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100175 'vkCreateDescriptorSetLayout',
Mark Young6ba8abe2017-11-09 10:37:04 -0700176 'vkCreateDebugUtilsMessengerEXT',
177 'vkDestroyDebugUtilsMessengerEXT',
178 'vkSubmitDebugUtilsMessageEXT',
179 'vkSetDebugUtilsObjectNameEXT',
180 'vkSetDebugUtilsObjectTagEXT',
181 'vkQueueBeginDebugUtilsLabelEXT',
182 'vkQueueEndDebugUtilsLabelEXT',
183 'vkQueueInsertDebugUtilsLabelEXT',
184 'vkCmdBeginDebugUtilsLabelEXT',
185 'vkCmdEndDebugUtilsLabelEXT',
186 'vkCmdInsertDebugUtilsLabelEXT',
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600187 'vkGetDisplayModePropertiesKHR',
188 'vkGetPhysicalDeviceDisplayPropertiesKHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600189 ]
190 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
191 # which is translated here into a good VU. Saves ~40 checks.
192 self.manual_vuids = dict()
193 self.manual_vuids = {
Dave Houlton57ae22f2018-05-18 16:20:52 -0600194 "fence-compatalloc": "\"VUID-vkDestroyFence-fence-01121\"",
195 "fence-nullalloc": "\"VUID-vkDestroyFence-fence-01122\"",
196 "event-compatalloc": "\"VUID-vkDestroyEvent-event-01146\"",
197 "event-nullalloc": "\"VUID-vkDestroyEvent-event-01147\"",
198 "buffer-compatalloc": "\"VUID-vkDestroyBuffer-buffer-00923\"",
199 "buffer-nullalloc": "\"VUID-vkDestroyBuffer-buffer-00924\"",
200 "image-compatalloc": "\"VUID-vkDestroyImage-image-01001\"",
201 "image-nullalloc": "\"VUID-vkDestroyImage-image-01002\"",
202 "shaderModule-compatalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01092\"",
203 "shaderModule-nullalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01093\"",
204 "pipeline-compatalloc": "\"VUID-vkDestroyPipeline-pipeline-00766\"",
205 "pipeline-nullalloc": "\"VUID-vkDestroyPipeline-pipeline-00767\"",
206 "sampler-compatalloc": "\"VUID-vkDestroySampler-sampler-01083\"",
207 "sampler-nullalloc": "\"VUID-vkDestroySampler-sampler-01084\"",
208 "renderPass-compatalloc": "\"VUID-vkDestroyRenderPass-renderPass-00874\"",
209 "renderPass-nullalloc": "\"VUID-vkDestroyRenderPass-renderPass-00875\"",
210 "descriptorUpdateTemplate-compatalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356\"",
211 "descriptorUpdateTemplate-nullalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357\"",
212 "imageView-compatalloc": "\"VUID-vkDestroyImageView-imageView-01027\"",
213 "imageView-nullalloc": "\"VUID-vkDestroyImageView-imageView-01028\"",
214 "pipelineCache-compatalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00771\"",
215 "pipelineCache-nullalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00772\"",
216 "pipelineLayout-compatalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00299\"",
217 "pipelineLayout-nullalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00300\"",
218 "descriptorSetLayout-compatalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284\"",
219 "descriptorSetLayout-nullalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285\"",
220 "semaphore-compatalloc": "\"VUID-vkDestroySemaphore-semaphore-01138\"",
221 "semaphore-nullalloc": "\"VUID-vkDestroySemaphore-semaphore-01139\"",
222 "queryPool-compatalloc": "\"VUID-vkDestroyQueryPool-queryPool-00794\"",
223 "queryPool-nullalloc": "\"VUID-vkDestroyQueryPool-queryPool-00795\"",
224 "bufferView-compatalloc": "\"VUID-vkDestroyBufferView-bufferView-00937\"",
225 "bufferView-nullalloc": "\"VUID-vkDestroyBufferView-bufferView-00938\"",
226 "surface-compatalloc": "\"VUID-vkDestroySurfaceKHR-surface-01267\"",
227 "surface-nullalloc": "\"VUID-vkDestroySurfaceKHR-surface-01268\"",
228 "framebuffer-compatalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00893\"",
229 "framebuffer-nullalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00894\"",
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600230 }
231
232 # Commands shadowed by interface functions and are not implemented
233 self.interface_functions = [
234 ]
235 self.headerVersion = None
236 # Internal state - accumulators for different inner block text
237 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
238 self.cmdMembers = []
239 self.cmd_feature_protect = [] # Save ifdef's for each command
240 self.cmd_info_data = [] # Save the cmdinfo data for validating the handles when processing is complete
241 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
242 self.extension_structs = [] # List of all structs or sister-structs containing handles
243 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
244 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
245 self.struct_member_dict = dict()
246 # Named tuples to store struct and command data
247 self.StructType = namedtuple('StructType', ['name', 'value'])
248 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
Dave Houlton57ae22f2018-05-18 16:20:52 -0600249 self.CmdMemberAlias = dict()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600250 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo'])
251 self.CmdExtraProtect = namedtuple('CmdExtraProtect', ['name', 'extra_protect'])
252 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'isoptional', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy', 'feature_protect'])
253 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
254 self.object_types = [] # List of all handle types
255 self.valid_vuids = set() # Set of all valid VUIDs
Dave Houlton57ae22f2018-05-18 16:20:52 -0600256 self.vuid_dict = dict() # VUID dictionary (from JSON)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600257 # Cover cases where file is built from scripts directory, Lin/Win, or Android build structure
Jamie Madillc47ddf92017-12-20 14:45:11 -0500258 # Set cwd to the script directory to more easily locate the header.
259 previous_dir = os.getcwd()
260 os.chdir(os.path.dirname(sys.argv[0]))
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600261 vuid_filename_locations = [
Dave Houlton57ae22f2018-05-18 16:20:52 -0600262 './Vulkan-Headers/registry/validusage.json',
263 '../Vulkan-Headers/registry/validusage.json',
264 '../../Vulkan-Headers/registry/validusage.json',
265 '../../../Vulkan-Headers/registry/validusage.json'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600266 ]
267 for vuid_filename in vuid_filename_locations:
268 if os.path.isfile(vuid_filename):
Dave Houlton57ae22f2018-05-18 16:20:52 -0600269 json_file = open(vuid_filename, 'r')
270 self.vuid_dict = json.load(json_file)
271 json_file.close()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600272 break
Dave Houlton57ae22f2018-05-18 16:20:52 -0600273 if len(self.vuid_dict) == 0:
274 print("Error: Could not find, or error loading validusage.json")
Jamie Madill3935f7c2017-11-08 13:50:14 -0500275 sys.exit(1)
Jamie Madillc47ddf92017-12-20 14:45:11 -0500276 os.chdir(previous_dir)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600277 #
278 # Check if the parameter passed in is optional
279 def paramIsOptional(self, param):
280 # See if the handle is optional
281 isoptional = False
282 # Simple, if it's optional, return true
283 optString = param.attrib.get('optional')
284 if optString:
285 if optString == 'true':
286 isoptional = True
287 elif ',' in optString:
288 opts = []
289 for opt in optString.split(','):
290 val = opt.strip()
291 if val == 'true':
292 opts.append(True)
293 elif val == 'false':
294 opts.append(False)
295 else:
296 print('Unrecognized len attribute value',val)
297 isoptional = opts
John Zulauf9f6788c2018-04-04 14:54:11 -0600298 if not isoptional:
299 # Matching logic in parameter validation and ValidityOutputGenerator.isHandleOptional
300 optString = param.attrib.get('noautovalidity')
301 if optString and optString == 'true':
302 isoptional = True;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600303 return isoptional
304 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600305 # Get VUID identifier from implicit VUID tag
Dave Houlton57ae22f2018-05-18 16:20:52 -0600306 def GetVuid(self, parent, suffix):
307 vuid_string = 'VUID-%s-%s' % (parent, suffix)
308 vuid = "kVUIDUndefined"
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600309 if '->' in vuid_string:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600310 return vuid
311 if vuid_string in self.valid_vuids:
312 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600313 else:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600314 if parent in self.CmdMemberAlias:
315 alias_string = 'VUID-%s-%s' % (self.CmdMemberAlias[parent], suffix)
316 if alias_string in self.valid_vuids:
317 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600318 return vuid
319 #
320 # Increases indent by 4 spaces and tracks it globally
321 def incIndent(self, indent):
322 inc = ' ' * self.INDENT_SPACES
323 if indent:
324 return indent + inc
325 return inc
326 #
327 # Decreases indent by 4 spaces and tracks it globally
328 def decIndent(self, indent):
329 if indent and (len(indent) > self.INDENT_SPACES):
330 return indent[:-self.INDENT_SPACES]
331 return ''
332 #
333 # Override makeProtoName to drop the "vk" prefix
334 def makeProtoName(self, name, tail):
335 return self.genOpts.apientry + name[2:] + tail
336 #
337 # Check if the parameter passed in is a pointer to an array
338 def paramIsArray(self, param):
339 return param.attrib.get('len') is not None
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000340
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600341 #
342 # Generate the object tracker undestroyed object validation function
343 def GenReportFunc(self):
344 output_func = ''
Dave Houlton379f1422018-05-23 12:47:07 -0600345 output_func += 'void ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600346 output_func += ' DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
347 for handle in self.object_types:
348 if self.isHandleTypeNonDispatchable(handle):
349 output_func += ' DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
350 output_func += '}\n'
351 return output_func
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000352
353 #
354 # Generate the object tracker undestroyed object destruction function
355 def GenDestroyFunc(self):
356 output_func = ''
357 output_func += 'void DestroyUndestroyedObjects(VkDevice device) {\n'
358 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
359 for handle in self.object_types:
360 if self.isHandleTypeNonDispatchable(handle):
361 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
362 output_func += '}\n'
363 return output_func
364
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600365 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600366 # Walk the JSON-derived dict and find all "vuid" key values
367 def ExtractVUIDs(self, d):
368 if hasattr(d, 'items'):
369 for k, v in d.items():
370 if k == "vuid":
371 yield v
372 elif isinstance(v, dict):
373 for s in self.ExtractVUIDs(v):
374 yield s
375 elif isinstance (v, list):
376 for l in v:
377 for s in self.ExtractVUIDs(l):
378 yield s
379
380 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600381 # Called at beginning of processing as file is opened
382 def beginFile(self, genOpts):
383 OutputGenerator.beginFile(self, genOpts)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600384 # Build a set of all vuid text strings found in validusage.json
385 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
386 self.valid_vuids.add(json_vuid_string)
387
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600388 # File Comment
389 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
390 file_comment += '// See object_tracker_generator.py for modifications\n'
391 write(file_comment, file=self.outFile)
392 # Copyright Statement
393 copyright = ''
394 copyright += '\n'
395 copyright += '/***************************************************************************\n'
396 copyright += ' *\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600397 copyright += ' * Copyright (c) 2015-2018 The Khronos Group Inc.\n'
398 copyright += ' * Copyright (c) 2015-2018 Valve Corporation\n'
399 copyright += ' * Copyright (c) 2015-2018 LunarG, Inc.\n'
400 copyright += ' * Copyright (c) 2015-2018 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600401 copyright += ' *\n'
402 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
403 copyright += ' * you may not use this file except in compliance with the License.\n'
404 copyright += ' * You may obtain a copy of the License at\n'
405 copyright += ' *\n'
406 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
407 copyright += ' *\n'
408 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
409 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
410 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
411 copyright += ' * See the License for the specific language governing permissions and\n'
412 copyright += ' * limitations under the License.\n'
413 copyright += ' *\n'
414 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600415 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600416 copyright += ' *\n'
417 copyright += ' ****************************************************************************/\n'
418 write(copyright, file=self.outFile)
419 # Namespace
420 self.newline()
421 write('#include "object_tracker.h"', file = self.outFile)
422 self.newline()
423 write('namespace object_tracker {', file = self.outFile)
424 #
425 # Now that the data is all collected and complete, generate and output the object validation routines
426 def endFile(self):
427 self.struct_member_dict = dict(self.structMembers)
428 # Generate the list of APIs that might need to handle wrapped extension structs
429 # self.GenerateCommandWrapExtensionList()
430 self.WrapCommands()
431 # Build undestroyed objects reporting function
432 report_func = self.GenReportFunc()
433 self.newline()
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000434 # Build undestroyed objects destruction function
435 destroy_func = self.GenDestroyFunc()
436 self.newline()
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600437 write('// ObjectTracker undestroyed objects validation function', file=self.outFile)
438 write('%s' % report_func, file=self.outFile)
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000439 write('%s' % destroy_func, file=self.outFile)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600440 # Actually write the interface to the output file.
441 if (self.emit):
442 self.newline()
443 if (self.featureExtraProtect != None):
444 write('#ifdef', self.featureExtraProtect, file=self.outFile)
445 # Write the object_tracker code to the file
446 if (self.sections['command']):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600447 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
448 if (self.featureExtraProtect != None):
449 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
450 else:
451 self.newline()
452
453 # Record intercepted procedures
454 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
455 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
456 write('\n'.join(self.intercepts), file=self.outFile)
457 write('};\n', file=self.outFile)
458 self.newline()
459 write('} // namespace object_tracker', file=self.outFile)
460 # Finish processing in superclass
461 OutputGenerator.endFile(self)
462 #
463 # Processing point at beginning of each extension definition
464 def beginFeature(self, interface, emit):
465 # Start processing in superclass
466 OutputGenerator.beginFeature(self, interface, emit)
467 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600468 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600469
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600470 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600471 white_list_entry = []
472 if (self.featureExtraProtect != None):
473 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
474 white_list_entry += [ '"%s"' % self.featureName ]
475 if (self.featureExtraProtect != None):
476 white_list_entry += [ '#endif' ]
477 featureType = interface.get('type')
478 if featureType == 'instance':
479 self.instance_extensions += white_list_entry
480 elif featureType == 'device':
481 self.device_extensions += white_list_entry
482 #
483 # Processing point at end of each extension definition
484 def endFeature(self):
485 # Finish processing in superclass
486 OutputGenerator.endFeature(self)
487 #
488 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700489 def genType(self, typeinfo, name, alias):
490 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600491 typeElem = typeinfo.elem
492 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
493 # Otherwise, emit the tag text.
494 category = typeElem.get('category')
495 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700496 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600497 if category == 'handle':
498 self.object_types.append(name)
499 #
500 # Append a definition to the specified section
501 def appendSection(self, section, text):
502 # self.sections[section].append('SECTION: ' + section + '\n')
503 self.sections[section].append(text)
504 #
505 # Check if the parameter passed in is a pointer
506 def paramIsPointer(self, param):
507 ispointer = False
508 for elem in param:
509 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
510 ispointer = True
511 return ispointer
512 #
513 # Get the category of a type
514 def getTypeCategory(self, typename):
515 types = self.registry.tree.findall("types/type")
516 for elem in types:
517 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
518 return elem.attrib.get('category')
519 #
520 # Check if a parent object is dispatchable or not
521 def isHandleTypeObject(self, handletype):
522 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
523 if handle is not None:
524 return True
525 else:
526 return False
527 #
528 # Check if a parent object is dispatchable or not
529 def isHandleTypeNonDispatchable(self, handletype):
530 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
531 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
532 return True
533 else:
534 return False
535 #
536 # Retrieve the type and name for a parameter
537 def getTypeNameTuple(self, param):
538 type = ''
539 name = ''
540 for elem in param:
541 if elem.tag == 'type':
542 type = noneStr(elem.text)
543 elif elem.tag == 'name':
544 name = noneStr(elem.text)
545 return (type, name)
546 #
547 # Retrieve the value of the len tag
548 def getLen(self, param):
549 result = None
550 len = param.attrib.get('len')
551 if len and len != 'null-terminated':
552 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
553 # have a null terminated array of strings. We strip the null-terminated from the
554 # 'len' field and only return the parameter specifying the string count
555 if 'null-terminated' in len:
556 result = len.split(',')[0]
557 else:
558 result = len
559 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
560 result = str(result).replace('::', '->')
561 return result
562 #
563 # Generate a VkStructureType based on a structure typename
564 def genVkStructureType(self, typename):
565 # Add underscore between lowercase then uppercase
566 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
567 # Change to uppercase
568 value = value.upper()
569 # Add STRUCTURE_TYPE_
570 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
571 #
572 # Struct parameter check generation.
573 # This is a special case of the <type> tag where the contents are interpreted as a set of
574 # <member> tags instead of freeform C type declarations. The <member> tags are just like
575 # <param> tags - they are a declaration of a struct or union member. Only simple member
576 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700577 def genStruct(self, typeinfo, typeName, alias):
578 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600579 members = typeinfo.elem.findall('.//member')
580 # Iterate over members once to get length parameters for arrays
581 lens = set()
582 for member in members:
583 len = self.getLen(member)
584 if len:
585 lens.add(len)
586 # Generate member info
587 membersInfo = []
588 for member in members:
589 # Get the member's type and name
590 info = self.getTypeNameTuple(member)
591 type = info[0]
592 name = info[1]
593 cdecl = self.makeCParamDecl(member, 0)
594 # Process VkStructureType
595 if type == 'VkStructureType':
596 # Extract the required struct type value from the comments
597 # embedded in the original text defining the 'typeinfo' element
598 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
599 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
600 if result:
601 value = result.group(0)
602 else:
603 value = self.genVkStructureType(typeName)
604 # Store the required type value
605 self.structTypes[typeName] = self.StructType(name=name, value=value)
606 # Store pointer/array/string info
607 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
608 membersInfo.append(self.CommandParam(type=type,
609 name=name,
610 ispointer=self.paramIsPointer(member),
611 isconst=True if 'const' in cdecl else False,
612 isoptional=self.paramIsOptional(member),
613 iscount=True if name in lens else False,
614 len=self.getLen(member),
615 extstructs=extstructs,
616 cdecl=cdecl,
617 islocal=False,
618 iscreate=False,
619 isdestroy=False,
620 feature_protect=self.featureExtraProtect))
621 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
622 #
623 # Insert a lock_guard line
624 def lock_guard(self, indent):
625 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
626 #
627 # Determine if a struct has an object as a member or an embedded member
628 def struct_contains_object(self, struct_item):
629 struct_member_dict = dict(self.structMembers)
630 struct_members = struct_member_dict[struct_item]
631
632 for member in struct_members:
633 if self.isHandleTypeObject(member.type):
634 return True
635 elif member.type in struct_member_dict:
636 if self.struct_contains_object(member.type) == True:
637 return True
638 return False
639 #
640 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
641 def getParmeterStructsWithObjects(self, item_list):
642 struct_list = set()
643 for item in item_list:
644 paramtype = item.find('type')
645 typecategory = self.getTypeCategory(paramtype.text)
646 if typecategory == 'struct':
647 if self.struct_contains_object(paramtype.text) == True:
648 struct_list.add(item)
649 return struct_list
650 #
651 # Return list of objects from a given list of parameters or members
652 def getObjectsInParameterList(self, item_list, create_func):
653 object_list = set()
654 if create_func == True:
655 member_list = item_list[0:-1]
656 else:
657 member_list = item_list
658 for item in member_list:
659 if self.isHandleTypeObject(paramtype.text):
660 object_list.add(item)
661 return object_list
662 #
663 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600664 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600665 def GenerateCommandWrapExtensionList(self):
666 for struct in self.structMembers:
667 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
668 found = False;
669 for item in struct.members[1].extstructs.split(','):
670 if item != '' and self.struct_contains_object(item) == True:
671 found = True
672 if found == True:
673 for item in struct.members[1].extstructs.split(','):
674 if item != '' and item not in self.extension_structs:
675 self.extension_structs.append(item)
676 #
677 # Returns True if a struct may have a pNext chain containing an object
678 def StructWithExtensions(self, struct_type):
679 if struct_type in self.struct_member_dict:
680 param_info = self.struct_member_dict[struct_type]
681 if (len(param_info) > 1) and param_info[1].extstructs is not None:
682 for item in param_info[1].extstructs.split(','):
683 if item in self.extension_structs:
684 return True
685 return False
686 #
687 # Generate VulkanObjectType from object type
688 def GetVulkanObjType(self, type):
689 return 'kVulkanObjectType%s' % type[2:]
690 #
691 # Return correct dispatch table type -- instance or device
692 def GetDispType(self, type):
693 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
694 #
695 # Generate source for creating a Vulkan object
696 def generate_create_object_code(self, indent, proto, params, cmd_info):
697 create_obj_code = ''
698 handle_type = params[-1].find('type')
699 if self.isHandleTypeObject(handle_type.text):
700 # Check for special case where multiple handles are returned
701 object_array = False
702 if cmd_info[-1].len is not None:
703 object_array = True;
704 handle_name = params[-1].find('name')
705 create_obj_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
706 indent = self.incIndent(indent)
707 create_obj_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
708 object_dest = '*%s' % handle_name.text
709 if object_array == True:
710 create_obj_code += '%sfor (uint32_t index = 0; index < %s; index++) {\n' % (indent, cmd_info[-1].len)
711 indent = self.incIndent(indent)
712 object_dest = '%s[index]' % cmd_info[-1].name
713 create_obj_code += '%sCreateObject(%s, %s, %s, pAllocator);\n' % (indent, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type))
714 if object_array == True:
715 indent = self.decIndent(indent)
716 create_obj_code += '%s}\n' % indent
717 indent = self.decIndent(indent)
718 create_obj_code += '%s}\n' % (indent)
719 return create_obj_code
720 #
721 # Generate source for destroying a non-dispatchable object
722 def generate_destroy_object_code(self, indent, proto, cmd_info):
723 destroy_obj_code = ''
724 object_array = False
725 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
726 # Check for special case where multiple handles are returned
727 if cmd_info[-1].len is not None:
728 object_array = True;
729 param = -1
730 else:
731 param = -2
732 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
733 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600734 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
735 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600736 if self.isHandleTypeObject(cmd_info[param].type) == True:
737 if object_array == True:
738 # This API is freeing an array of handles -- add loop control
739 destroy_obj_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
740 else:
741 # Call Destroy a single time
742 destroy_obj_code += '%sif (skip) return;\n' % indent
743 destroy_obj_code += '%s{\n' % indent
744 destroy_obj_code += '%s std::lock_guard<std::mutex> lock(global_lock);\n' % indent
745 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)
746 destroy_obj_code += '%s}\n' % indent
747 return object_array, destroy_obj_code
748 #
749 # Output validation for a single object (obj_count is NULL) or a counted list of objects
750 def outputObjects(self, obj_type, obj_name, obj_count, prefix, index, indent, destroy_func, destroy_array, disp_name, parent_name, null_allowed, top_level):
751 decl_code = ''
752 pre_call_code = ''
753 post_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600754 param_suffix = '%s-parameter' % (obj_name)
755 parent_suffix = '%s-parent' % (obj_name)
756 param_vuid = self.GetVuid(parent_name, param_suffix)
757 parent_vuid = self.GetVuid(parent_name, parent_suffix)
758
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600759 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600760 if parent_vuid == 'kVUIDUndefined':
761 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600762 if obj_count is not None:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600763 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
764 indent = self.incIndent(indent)
765 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)
766 indent = self.decIndent(indent)
767 pre_call_code += '%s }\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600768 else:
769 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)
770 return decl_code, pre_call_code, post_call_code
771 #
772 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
773 # create_func means that this is API creates or allocates objects
774 # destroy_func indicates that this API destroys or frees objects
775 # destroy_array means that the destroy_func operated on an array of objects
776 def validate_objects(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, disp_name, parent_name, first_level_param):
777 decls = ''
778 pre_code = ''
779 post_code = ''
780 index = 'index%s' % str(array_index)
781 array_index += 1
782 # Process any objects in this structure and recurse for any sub-structs in this struct
783 for member in members:
784 # Handle objects
785 if member.iscreate and first_level_param and member == members[-1]:
786 continue
787 if self.isHandleTypeObject(member.type) == True:
788 count_name = member.len
789 if (count_name is not None):
790 count_name = '%s%s' % (prefix, member.len)
791 null_allowed = member.isoptional
792 (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)
793 decls += tmp_decl
794 pre_code += tmp_pre
795 post_code += tmp_post
796 # Handle Structs that contain objects at some level
797 elif member.type in self.struct_member_dict:
798 # Structs at first level will have an object
799 if self.struct_contains_object(member.type) == True:
800 struct_info = self.struct_member_dict[member.type]
801 # Struct Array
802 if member.len is not None:
803 # Update struct prefix
804 new_prefix = '%s%s' % (prefix, member.name)
805 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
806 indent = self.incIndent(indent)
807 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
808 indent = self.incIndent(indent)
809 local_prefix = '%s[%s].' % (new_prefix, index)
810 # Process sub-structs in this struct
811 (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)
812 decls += tmp_decl
813 pre_code += tmp_pre
814 post_code += tmp_post
815 indent = self.decIndent(indent)
816 pre_code += '%s }\n' % indent
817 indent = self.decIndent(indent)
818 pre_code += '%s }\n' % indent
819 # Single Struct
820 else:
821 # Update struct prefix
822 new_prefix = '%s%s->' % (prefix, member.name)
823 # Declare safe_VarType for struct
824 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
825 indent = self.incIndent(indent)
826 # Process sub-structs in this struct
827 (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)
828 decls += tmp_decl
829 pre_code += tmp_pre
830 post_code += tmp_post
831 indent = self.decIndent(indent)
832 pre_code += '%s }\n' % indent
833 return decls, pre_code, post_code
834 #
835 # For a particular API, generate the object handling code
836 def generate_wrapping_code(self, cmd):
837 indent = ' '
838 proto = cmd.find('proto/name')
839 params = cmd.findall('param')
840 if proto.text is not None:
841 cmd_member_dict = dict(self.cmdMembers)
842 cmd_info = cmd_member_dict[proto.text]
843 disp_name = cmd_info[0].name
844 # Handle object create operations
845 if cmd_info[0].iscreate:
846 create_obj_code = self.generate_create_object_code(indent, proto, params, cmd_info)
847 else:
848 create_obj_code = ''
849 # Handle object destroy operations
850 if cmd_info[0].isdestroy:
851 (destroy_array, destroy_object_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
852 else:
853 destroy_array = False
854 destroy_object_code = ''
855 paramdecl = ''
856 param_pre_code = ''
857 param_post_code = ''
858 create_func = True if create_obj_code else False
859 destroy_func = True if destroy_object_code else False
860 (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)
861 param_post_code += create_obj_code
862 if destroy_object_code:
863 if destroy_array == True:
864 param_post_code += destroy_object_code
865 else:
866 param_pre_code += destroy_object_code
867 if param_pre_code:
868 if (not destroy_func) or (destroy_array):
869 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
870 return paramdecl, param_pre_code, param_post_code
871 #
872 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700873 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600874
875 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700876 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600877 members = cmdinfo.elem.findall('.//param')
878 # Iterate over members once to get length parameters for arrays
879 lens = set()
880 for member in members:
881 len = self.getLen(member)
882 if len:
883 lens.add(len)
884 struct_member_dict = dict(self.structMembers)
885 # Generate member info
886 membersInfo = []
887 constains_extension_structs = False
888 for member in members:
889 # Get type and name of member
890 info = self.getTypeNameTuple(member)
891 type = info[0]
892 name = info[1]
893 cdecl = self.makeCParamDecl(member, 0)
894 # Check for parameter name in lens set
895 iscount = True if name in lens else False
896 len = self.getLen(member)
897 isconst = True if 'const' in cdecl else False
898 ispointer = self.paramIsPointer(member)
899 # Mark param as local if it is an array of objects
900 islocal = False;
901 if self.isHandleTypeObject(type) == True:
902 if (len is not None) and (isconst == True):
903 islocal = True
904 # Or if it's a struct that contains an object
905 elif type in struct_member_dict:
906 if self.struct_contains_object(type) == True:
907 islocal = True
908 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
909 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
910 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
911 membersInfo.append(self.CommandParam(type=type,
912 name=name,
913 ispointer=ispointer,
914 isconst=isconst,
915 isoptional=self.paramIsOptional(member),
916 iscount=iscount,
917 len=len,
918 extstructs=extstructs,
919 cdecl=cdecl,
920 islocal=islocal,
921 iscreate=iscreate,
922 isdestroy=isdestroy,
923 feature_protect=self.featureExtraProtect))
924 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
Dave Houlton57ae22f2018-05-18 16:20:52 -0600925 if alias != None:
926 self.CmdMemberAlias[cmdname] = alias
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600927 self.cmd_info_data.append(self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo))
928 self.cmd_feature_protect.append(self.CmdExtraProtect(name=cmdname, extra_protect=self.featureExtraProtect))
929 #
930 # Create code Create, Destroy, and validate Vulkan objects
931 def WrapCommands(self):
932 cmd_member_dict = dict(self.cmdMembers)
933 cmd_info_dict = dict(self.cmd_info_data)
934 cmd_protect_dict = dict(self.cmd_feature_protect)
935 for api_call in self.cmdMembers:
936 cmdname = api_call.name
937 cmdinfo = cmd_info_dict[api_call.name]
938 if cmdname in self.interface_functions:
939 continue
940 if cmdname in self.no_autogen_list:
941 decls = self.makeCDecls(cmdinfo.elem)
942 self.appendSection('command', '')
943 self.appendSection('command', '// Declare only')
944 self.appendSection('command', decls[0])
945 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
946 continue
947 # Generate object handling code
948 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
949 # If API doesn't contain any object handles, don't fool with it
950 if not api_decls and not api_pre and not api_post:
951 continue
952 feature_extra_protect = cmd_protect_dict[api_call.name]
953 if (feature_extra_protect != None):
954 self.appendSection('command', '')
955 self.appendSection('command', '#ifdef '+ feature_extra_protect)
956 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
957 # Add intercept to procmap
958 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
959 decls = self.makeCDecls(cmdinfo.elem)
960 self.appendSection('command', '')
961 self.appendSection('command', decls[0][:-1])
962 self.appendSection('command', '{')
963 self.appendSection('command', ' bool skip = false;')
964 # Handle return values, if any
965 resulttype = cmdinfo.elem.find('proto/type')
966 if (resulttype != None and resulttype.text == 'void'):
967 resulttype = None
968 if (resulttype != None):
969 assignresult = resulttype.text + ' result = '
970 else:
971 assignresult = ''
972 # Pre-pend declarations and pre-api-call codegen
973 if api_decls:
974 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
975 if api_pre:
976 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
977 # Generate the API call itself
978 # Gather the parameter items
979 params = cmdinfo.elem.findall('param/name')
980 # Pull out the text for each of the parameters, separate them by commas in a list
981 paramstext = ', '.join([str(param.text) for param in params])
982 # Use correct dispatch table
983 disp_type = cmdinfo.elem.find('param/type').text
984 disp_name = cmdinfo.elem.find('param/name').text
985 dispatch_table = 'get_dispatch_table(ot_%s_table_map, %s)->' % (self.GetDispType(disp_type), disp_name)
986 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' ]