blob: 3588c28052b00a4af490f701dfe386e000f7ce59 [file] [log] [blame]
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001#!/usr/bin/python3 -i
2#
Dave Houlton57ae22f2018-05-18 16:20:52 -06003# Copyright (c) 2015-2018 The Khronos Group Inc.
4# Copyright (c) 2015-2018 Valve Corporation
5# Copyright (c) 2015-2018 LunarG, Inc.
6# Copyright (c) 2015-2018 Google Inc.
Mark Lobodzinskid1461482017-07-18 13:56:09 -06007#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Mark Lobodzinski <mark@lunarg.com>
Dave Houlton57ae22f2018-05-18 16:20:52 -060021# Author: Dave Houlton <daveh@lunarg.com>
Mark Lobodzinskid1461482017-07-18 13:56:09 -060022
Dave Houlton57ae22f2018-05-18 16:20:52 -060023import os,re,sys,string,json
Mark Lobodzinskid1461482017-07-18 13:56:09 -060024import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski62f71562017-10-24 13:41:18 -060027from common_codegen import *
Mark Lobodzinskid1461482017-07-18 13:56:09 -060028
Jamie Madill8d4cda22017-11-08 13:40:09 -050029# This is a workaround to use a Python 2.7 and 3.x compatible syntax.
30from io import open
31
Mark Lobodzinskid1461482017-07-18 13:56:09 -060032# ObjectTrackerGeneratorOptions - subclass of GeneratorOptions.
33#
34# Adds options used by ObjectTrackerOutputGenerator objects during
35# object_tracker layer generation.
36#
37# Additional members
38# prefixText - list of strings to prefix generated header with
39# (usually a copyright statement + calling convention macros).
40# protectFile - True if multiple inclusion protection should be
41# generated (based on the filename) around the entire header.
42# protectFeature - True if #ifndef..#endif protection should be
43# generated around a feature interface in the header file.
44# genFuncPointers - True if function pointer typedefs should be
45# generated
46# protectProto - If conditional protection should be generated
47# around prototype declarations, set to either '#ifdef'
48# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
49# to require opt-out (#ifndef protectProtoStr). Otherwise
50# set to None.
51# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
52# declarations, if protectProto is set
53# apicall - string to use for the function declaration prefix,
54# such as APICALL on Windows.
55# apientry - string to use for the calling convention macro,
56# in typedefs, such as APIENTRY.
57# apientryp - string to use for the calling convention macro
58# in function pointer typedefs, such as APIENTRYP.
59# indentFuncProto - True if prototype declarations should put each
60# parameter on a separate line
61# indentFuncPointer - True if typedefed function pointers should put each
62# parameter on a separate line
63# alignFuncParam - if nonzero and parameters are being put on a
64# separate line, align parameter names at the specified column
65class ObjectTrackerGeneratorOptions(GeneratorOptions):
66 def __init__(self,
67 filename = None,
68 directory = '.',
69 apiname = None,
70 profile = None,
71 versions = '.*',
72 emitversions = '.*',
73 defaultExtensions = None,
74 addExtensions = None,
75 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060076 emitExtensions = None,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060077 sortProcedure = regSortFeatures,
78 prefixText = "",
79 genFuncPointers = True,
80 protectFile = True,
81 protectFeature = True,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060082 apicall = '',
83 apientry = '',
84 apientryp = '',
85 indentFuncProto = True,
86 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060087 alignFuncParam = 0,
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -060088 expandEnumerants = True,
89 valid_usage_path = ''):
Mark Lobodzinskid1461482017-07-18 13:56:09 -060090 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
91 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060092 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskid1461482017-07-18 13:56:09 -060093 self.prefixText = prefixText
94 self.genFuncPointers = genFuncPointers
95 self.protectFile = protectFile
96 self.protectFeature = protectFeature
Mark Lobodzinskid1461482017-07-18 13:56:09 -060097 self.apicall = apicall
98 self.apientry = apientry
99 self.apientryp = apientryp
100 self.indentFuncProto = indentFuncProto
101 self.indentFuncPointer = indentFuncPointer
102 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600103 self.expandEnumerants = expandEnumerants
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600104 self.valid_usage_path = valid_usage_path
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600105
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600106
107# ObjectTrackerOutputGenerator - subclass of OutputGenerator.
108# Generates object_tracker layer object validation code
109#
110# ---- methods ----
111# ObjectTrackerOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
112# ---- methods overriding base class ----
113# beginFile(genOpts)
114# endFile()
115# beginFeature(interface, emit)
116# endFeature()
117# genCmd(cmdinfo)
118# genStruct()
119# genType()
120class ObjectTrackerOutputGenerator(OutputGenerator):
121 """Generate ObjectTracker code based on XML element attributes"""
122 # This is an ordered list of sections in the header file.
123 ALL_SECTIONS = ['command']
124 def __init__(self,
125 errFile = sys.stderr,
126 warnFile = sys.stderr,
127 diagFile = sys.stdout):
128 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
129 self.INDENT_SPACES = 4
130 self.intercepts = []
131 self.instance_extensions = []
132 self.device_extensions = []
133 # Commands which are not autogenerated but still intercepted
134 self.no_autogen_list = [
135 'vkDestroyInstance',
136 'vkDestroyDevice',
137 'vkUpdateDescriptorSets',
138 'vkDestroyDebugReportCallbackEXT',
139 'vkDebugReportMessageEXT',
140 'vkGetPhysicalDeviceQueueFamilyProperties',
141 'vkFreeCommandBuffers',
142 'vkDestroySwapchainKHR',
143 'vkDestroyDescriptorPool',
144 'vkDestroyCommandPool',
Mark Lobodzinski14ddc192017-10-25 16:57:04 -0600145 'vkGetPhysicalDeviceQueueFamilyProperties2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600146 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
147 'vkResetDescriptorPool',
148 'vkBeginCommandBuffer',
149 'vkCreateDebugReportCallbackEXT',
150 'vkEnumerateInstanceLayerProperties',
151 'vkEnumerateDeviceLayerProperties',
152 'vkEnumerateInstanceExtensionProperties',
153 'vkEnumerateDeviceExtensionProperties',
154 'vkCreateDevice',
155 'vkCreateInstance',
156 'vkEnumeratePhysicalDevices',
157 'vkAllocateCommandBuffers',
158 'vkAllocateDescriptorSets',
159 'vkFreeDescriptorSets',
Tony Barbour2fd0c2c2017-08-08 12:51:33 -0600160 'vkCmdPushDescriptorSetKHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600161 'vkDebugMarkerSetObjectNameEXT',
162 'vkGetPhysicalDeviceProcAddr',
163 'vkGetDeviceProcAddr',
164 'vkGetInstanceProcAddr',
165 'vkEnumerateInstanceExtensionProperties',
166 'vkEnumerateInstanceLayerProperties',
167 'vkEnumerateDeviceLayerProperties',
168 'vkGetDeviceProcAddr',
169 'vkGetInstanceProcAddr',
170 'vkEnumerateDeviceExtensionProperties',
171 'vk_layerGetPhysicalDeviceProcAddr',
172 'vkNegotiateLoaderLayerInterfaceVersion',
173 'vkCreateComputePipelines',
174 'vkGetDeviceQueue',
Yiwei Zhang991d88d2018-02-14 14:39:46 -0800175 'vkGetDeviceQueue2',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600176 'vkGetSwapchainImagesKHR',
Petr Kraus42f6f8d2017-12-17 17:37:33 +0100177 'vkCreateDescriptorSetLayout',
Mark Lobodzinski5a1c8d22018-07-02 10:28:12 -0600178 'vkGetDescriptorSetLayoutSupport',
179 'vkGetDescriptorSetLayoutSupportKHR',
Mark Young6ba8abe2017-11-09 10:37:04 -0700180 'vkCreateDebugUtilsMessengerEXT',
181 'vkDestroyDebugUtilsMessengerEXT',
182 'vkSubmitDebugUtilsMessageEXT',
183 'vkSetDebugUtilsObjectNameEXT',
184 'vkSetDebugUtilsObjectTagEXT',
185 'vkQueueBeginDebugUtilsLabelEXT',
186 'vkQueueEndDebugUtilsLabelEXT',
187 'vkQueueInsertDebugUtilsLabelEXT',
188 'vkCmdBeginDebugUtilsLabelEXT',
189 'vkCmdEndDebugUtilsLabelEXT',
190 'vkCmdInsertDebugUtilsLabelEXT',
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600191 'vkGetDisplayModePropertiesKHR',
192 'vkGetPhysicalDeviceDisplayPropertiesKHR',
Piers Daniell16c253f2018-05-30 14:34:05 -0600193 'vkGetPhysicalDeviceDisplayProperties2KHR',
194 'vkGetDisplayPlaneSupportedDisplaysKHR',
195 'vkGetDisplayModeProperties2KHR',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600196 ]
197 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
198 # which is translated here into a good VU. Saves ~40 checks.
199 self.manual_vuids = dict()
200 self.manual_vuids = {
Dave Houlton57ae22f2018-05-18 16:20:52 -0600201 "fence-compatalloc": "\"VUID-vkDestroyFence-fence-01121\"",
202 "fence-nullalloc": "\"VUID-vkDestroyFence-fence-01122\"",
203 "event-compatalloc": "\"VUID-vkDestroyEvent-event-01146\"",
204 "event-nullalloc": "\"VUID-vkDestroyEvent-event-01147\"",
205 "buffer-compatalloc": "\"VUID-vkDestroyBuffer-buffer-00923\"",
206 "buffer-nullalloc": "\"VUID-vkDestroyBuffer-buffer-00924\"",
207 "image-compatalloc": "\"VUID-vkDestroyImage-image-01001\"",
208 "image-nullalloc": "\"VUID-vkDestroyImage-image-01002\"",
209 "shaderModule-compatalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01092\"",
210 "shaderModule-nullalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01093\"",
211 "pipeline-compatalloc": "\"VUID-vkDestroyPipeline-pipeline-00766\"",
212 "pipeline-nullalloc": "\"VUID-vkDestroyPipeline-pipeline-00767\"",
213 "sampler-compatalloc": "\"VUID-vkDestroySampler-sampler-01083\"",
214 "sampler-nullalloc": "\"VUID-vkDestroySampler-sampler-01084\"",
215 "renderPass-compatalloc": "\"VUID-vkDestroyRenderPass-renderPass-00874\"",
216 "renderPass-nullalloc": "\"VUID-vkDestroyRenderPass-renderPass-00875\"",
217 "descriptorUpdateTemplate-compatalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356\"",
218 "descriptorUpdateTemplate-nullalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357\"",
219 "imageView-compatalloc": "\"VUID-vkDestroyImageView-imageView-01027\"",
220 "imageView-nullalloc": "\"VUID-vkDestroyImageView-imageView-01028\"",
221 "pipelineCache-compatalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00771\"",
222 "pipelineCache-nullalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00772\"",
223 "pipelineLayout-compatalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00299\"",
224 "pipelineLayout-nullalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00300\"",
225 "descriptorSetLayout-compatalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284\"",
226 "descriptorSetLayout-nullalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285\"",
227 "semaphore-compatalloc": "\"VUID-vkDestroySemaphore-semaphore-01138\"",
228 "semaphore-nullalloc": "\"VUID-vkDestroySemaphore-semaphore-01139\"",
229 "queryPool-compatalloc": "\"VUID-vkDestroyQueryPool-queryPool-00794\"",
230 "queryPool-nullalloc": "\"VUID-vkDestroyQueryPool-queryPool-00795\"",
231 "bufferView-compatalloc": "\"VUID-vkDestroyBufferView-bufferView-00937\"",
232 "bufferView-nullalloc": "\"VUID-vkDestroyBufferView-bufferView-00938\"",
233 "surface-compatalloc": "\"VUID-vkDestroySurfaceKHR-surface-01267\"",
234 "surface-nullalloc": "\"VUID-vkDestroySurfaceKHR-surface-01268\"",
235 "framebuffer-compatalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00893\"",
236 "framebuffer-nullalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00894\"",
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600237 }
238
239 # Commands shadowed by interface functions and are not implemented
240 self.interface_functions = [
241 ]
242 self.headerVersion = None
243 # Internal state - accumulators for different inner block text
244 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600245 self.cmd_list = [] # list of commands processed to maintain ordering
246 self.cmd_info_dict = {} # Per entry-point data for code generation and validation
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600247 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
248 self.extension_structs = [] # List of all structs or sister-structs containing handles
249 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
250 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
251 self.struct_member_dict = dict()
252 # Named tuples to store struct and command data
253 self.StructType = namedtuple('StructType', ['name', 'value'])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600254 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo', 'members', 'extra_protect', 'alias', 'iscreate', 'isdestroy', 'allocator'])
255 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'isconst', 'isoptional', 'iscount', 'iscreate', 'len', 'extstructs', 'cdecl', 'islocal'])
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600256 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
257 self.object_types = [] # List of all handle types
258 self.valid_vuids = set() # Set of all valid VUIDs
Dave Houlton57ae22f2018-05-18 16:20:52 -0600259 self.vuid_dict = dict() # VUID dictionary (from JSON)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600260 #
261 # Check if the parameter passed in is optional
262 def paramIsOptional(self, param):
263 # See if the handle is optional
264 isoptional = False
265 # Simple, if it's optional, return true
266 optString = param.attrib.get('optional')
267 if optString:
268 if optString == 'true':
269 isoptional = True
270 elif ',' in optString:
271 opts = []
272 for opt in optString.split(','):
273 val = opt.strip()
274 if val == 'true':
275 opts.append(True)
276 elif val == 'false':
277 opts.append(False)
278 else:
279 print('Unrecognized len attribute value',val)
280 isoptional = opts
John Zulauf9f6788c2018-04-04 14:54:11 -0600281 if not isoptional:
282 # Matching logic in parameter validation and ValidityOutputGenerator.isHandleOptional
283 optString = param.attrib.get('noautovalidity')
284 if optString and optString == 'true':
285 isoptional = True;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600286 return isoptional
287 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600288 # Get VUID identifier from implicit VUID tag
Dave Houlton57ae22f2018-05-18 16:20:52 -0600289 def GetVuid(self, parent, suffix):
290 vuid_string = 'VUID-%s-%s' % (parent, suffix)
291 vuid = "kVUIDUndefined"
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600292 if '->' in vuid_string:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600293 return vuid
294 if vuid_string in self.valid_vuids:
295 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600296 else:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600297 alias = self.cmd_info_dict[parent].alias if parent in self.cmd_info_dict else None
298 if alias:
299 alias_string = 'VUID-%s-%s' % (alias, suffix)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600300 if alias_string in self.valid_vuids:
301 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600302 return vuid
303 #
304 # Increases indent by 4 spaces and tracks it globally
305 def incIndent(self, indent):
306 inc = ' ' * self.INDENT_SPACES
307 if indent:
308 return indent + inc
309 return inc
310 #
311 # Decreases indent by 4 spaces and tracks it globally
312 def decIndent(self, indent):
313 if indent and (len(indent) > self.INDENT_SPACES):
314 return indent[:-self.INDENT_SPACES]
315 return ''
316 #
317 # Override makeProtoName to drop the "vk" prefix
318 def makeProtoName(self, name, tail):
319 return self.genOpts.apientry + name[2:] + tail
320 #
321 # Check if the parameter passed in is a pointer to an array
322 def paramIsArray(self, param):
323 return param.attrib.get('len') is not None
GabrĂ­el ArthĂșr PĂ©turssonfdcb5402018-03-20 21:52:06 +0000324
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600325 #
326 # Generate the object tracker undestroyed object validation function
327 def GenReportFunc(self):
328 output_func = ''
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600329 output_func += 'bool ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
330 output_func += ' bool skip = false;\n'
331 output_func += ' skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600332 for handle in self.object_types:
333 if self.isHandleTypeNonDispatchable(handle):
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600334 output_func += ' skip |= DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
335 output_func += ' return skip;\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600336 output_func += '}\n'
337 return output_func
GabrĂ­el ArthĂșr PĂ©turssonfdcb5402018-03-20 21:52:06 +0000338
339 #
340 # Generate the object tracker undestroyed object destruction function
341 def GenDestroyFunc(self):
342 output_func = ''
343 output_func += 'void DestroyUndestroyedObjects(VkDevice device) {\n'
344 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
345 for handle in self.object_types:
346 if self.isHandleTypeNonDispatchable(handle):
347 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
348 output_func += '}\n'
349 return output_func
350
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600351 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600352 # Walk the JSON-derived dict and find all "vuid" key values
353 def ExtractVUIDs(self, d):
354 if hasattr(d, 'items'):
355 for k, v in d.items():
356 if k == "vuid":
357 yield v
358 elif isinstance(v, dict):
359 for s in self.ExtractVUIDs(v):
360 yield s
361 elif isinstance (v, list):
362 for l in v:
363 for s in self.ExtractVUIDs(l):
364 yield s
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600365 #
366 # Separate content for validation (utils) and core files
367 def otwrite(self, dest, formatstring):
368 if 'core' in self.genOpts.filename and (dest == 'core' or dest == 'both'):
369 write(formatstring, file=self.outFile)
370 elif 'utils' in self.genOpts.filename and (dest == 'util' or dest == 'both'):
371 write(formatstring, file=self.outFile)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600372
373 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600374 # Called at beginning of processing as file is opened
375 def beginFile(self, genOpts):
376 OutputGenerator.beginFile(self, genOpts)
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600377
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600378 core_file = (genOpts.filename == 'object_tracker_utils_auto.cpp')
379 utils_file = (genOpts.filename == 'object_tracker_core_auto.cpp')
380
381 if not core_file and not utils_file:
382 print("Error: Output Filenames have changed, update generator source.\n")
383 sys.exit(1)
384
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600385 self.valid_usage_path = genOpts.valid_usage_path
386 vu_json_filename = os.path.join(self.valid_usage_path + os.sep, 'validusage.json')
387 if os.path.isfile(vu_json_filename):
388 json_file = open(vu_json_filename, 'r')
389 self.vuid_dict = json.load(json_file)
390 json_file.close()
391 if len(self.vuid_dict) == 0:
392 print("Error: Could not find, or error loading %s/validusage.json\n", vu_json_filename)
393 sys.exit(1)
394
Dave Houlton57ae22f2018-05-18 16:20:52 -0600395 # Build a set of all vuid text strings found in validusage.json
396 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
397 self.valid_vuids.add(json_vuid_string)
398
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600399 # File Comment
400 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
401 file_comment += '// See object_tracker_generator.py for modifications\n'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600402 self.otwrite('both', file_comment)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600403 # Copyright Statement
404 copyright = ''
405 copyright += '\n'
406 copyright += '/***************************************************************************\n'
407 copyright += ' *\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600408 copyright += ' * Copyright (c) 2015-2018 The Khronos Group Inc.\n'
409 copyright += ' * Copyright (c) 2015-2018 Valve Corporation\n'
410 copyright += ' * Copyright (c) 2015-2018 LunarG, Inc.\n'
411 copyright += ' * Copyright (c) 2015-2018 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600412 copyright += ' *\n'
413 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
414 copyright += ' * you may not use this file except in compliance with the License.\n'
415 copyright += ' * You may obtain a copy of the License at\n'
416 copyright += ' *\n'
417 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
418 copyright += ' *\n'
419 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
420 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
421 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
422 copyright += ' * See the License for the specific language governing permissions and\n'
423 copyright += ' * limitations under the License.\n'
424 copyright += ' *\n'
425 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600426 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600427 copyright += ' *\n'
428 copyright += ' ****************************************************************************/\n'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600429 self.otwrite('both', copyright)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600430 # Namespace
431 self.newline()
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600432 self.otwrite('both', '#include "object_tracker.h"')
433 self.otwrite('both', '#include "object_lifetime_validation.h"')
434 self.otwrite('both', '\n')
435 self.otwrite('both', 'namespace object_tracker {')
436 self.otwrite('core', '#include "precall.h"')
437 self.otwrite('core', '#include "postcall.h"')
438 self.otwrite('core', '\n')
439
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600440 #
441 # Now that the data is all collected and complete, generate and output the object validation routines
442 def endFile(self):
443 self.struct_member_dict = dict(self.structMembers)
444 # Generate the list of APIs that might need to handle wrapped extension structs
445 # self.GenerateCommandWrapExtensionList()
446 self.WrapCommands()
447 # Build undestroyed objects reporting function
448 report_func = self.GenReportFunc()
449 self.newline()
GabrĂ­el ArthĂșr PĂ©turssonfdcb5402018-03-20 21:52:06 +0000450 # Build undestroyed objects destruction function
451 destroy_func = self.GenDestroyFunc()
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600452 self.otwrite('util', '\n')
453 self.otwrite('util', '// ObjectTracker undestroyed objects validation function')
454 self.otwrite('util', '%s' % report_func)
455 self.otwrite('util', '%s' % destroy_func)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600456 # Actually write the interface to the output file.
457 if (self.emit):
458 self.newline()
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600459 if self.featureExtraProtect is not None:
460 prot = '#ifdef %s' % self.featureExtraProtect
461 self.otwrite('both', '%s' % prot)
462 # Write the object_tracker code to the file
463 if self.sections['command']:
464 source = ('\n'.join(self.sections['command']))
465 self.otwrite('both', '%s' % source)
MichaƂ Janiszewski3c3ce9e2018-10-30 23:25:21 +0100466 if (self.featureExtraProtect is not None):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600467 prot = '\n#endif // %s', self.featureExtraProtect
468 self.otwrite('both', prot)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600469 else:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600470 self.otwrite('both', '\n')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600471
472 # Record intercepted procedures
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600473 self.otwrite('core', '// Map of all APIs to be intercepted by this layer')
474 self.otwrite('core', 'const std::unordered_map<std::string, void*> name_to_funcptr_map = {')
475 intercepts = '\n'.join(self.intercepts)
476 self.otwrite('core', '%s' % intercepts)
477 self.otwrite('core', '};\n\n')
478 self.otwrite('both', '} // namespace object_tracker')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600479 # Finish processing in superclass
480 OutputGenerator.endFile(self)
481 #
482 # Processing point at beginning of each extension definition
483 def beginFeature(self, interface, emit):
484 # Start processing in superclass
485 OutputGenerator.beginFeature(self, interface, emit)
486 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600487 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600488
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600489 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600490 white_list_entry = []
MichaƂ Janiszewski3c3ce9e2018-10-30 23:25:21 +0100491 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600492 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
493 white_list_entry += [ '"%s"' % self.featureName ]
MichaƂ Janiszewski3c3ce9e2018-10-30 23:25:21 +0100494 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600495 white_list_entry += [ '#endif' ]
496 featureType = interface.get('type')
497 if featureType == 'instance':
498 self.instance_extensions += white_list_entry
499 elif featureType == 'device':
500 self.device_extensions += white_list_entry
501 #
502 # Processing point at end of each extension definition
503 def endFeature(self):
504 # Finish processing in superclass
505 OutputGenerator.endFeature(self)
506 #
507 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700508 def genType(self, typeinfo, name, alias):
509 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600510 typeElem = typeinfo.elem
511 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
512 # Otherwise, emit the tag text.
513 category = typeElem.get('category')
514 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700515 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600516 if category == 'handle':
517 self.object_types.append(name)
518 #
519 # Append a definition to the specified section
520 def appendSection(self, section, text):
521 # self.sections[section].append('SECTION: ' + section + '\n')
522 self.sections[section].append(text)
523 #
524 # Check if the parameter passed in is a pointer
525 def paramIsPointer(self, param):
526 ispointer = False
527 for elem in param:
528 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
529 ispointer = True
530 return ispointer
531 #
532 # Get the category of a type
533 def getTypeCategory(self, typename):
534 types = self.registry.tree.findall("types/type")
535 for elem in types:
536 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
537 return elem.attrib.get('category')
538 #
539 # Check if a parent object is dispatchable or not
540 def isHandleTypeObject(self, handletype):
541 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
542 if handle is not None:
543 return True
544 else:
545 return False
546 #
547 # Check if a parent object is dispatchable or not
548 def isHandleTypeNonDispatchable(self, handletype):
549 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
550 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
551 return True
552 else:
553 return False
554 #
555 # Retrieve the type and name for a parameter
556 def getTypeNameTuple(self, param):
557 type = ''
558 name = ''
559 for elem in param:
560 if elem.tag == 'type':
561 type = noneStr(elem.text)
562 elif elem.tag == 'name':
563 name = noneStr(elem.text)
564 return (type, name)
565 #
566 # Retrieve the value of the len tag
567 def getLen(self, param):
568 result = None
569 len = param.attrib.get('len')
570 if len and len != 'null-terminated':
571 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
572 # have a null terminated array of strings. We strip the null-terminated from the
573 # 'len' field and only return the parameter specifying the string count
574 if 'null-terminated' in len:
575 result = len.split(',')[0]
576 else:
577 result = len
578 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
579 result = str(result).replace('::', '->')
580 return result
581 #
582 # Generate a VkStructureType based on a structure typename
583 def genVkStructureType(self, typename):
584 # Add underscore between lowercase then uppercase
585 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
586 # Change to uppercase
587 value = value.upper()
588 # Add STRUCTURE_TYPE_
589 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
590 #
591 # Struct parameter check generation.
592 # This is a special case of the <type> tag where the contents are interpreted as a set of
593 # <member> tags instead of freeform C type declarations. The <member> tags are just like
594 # <param> tags - they are a declaration of a struct or union member. Only simple member
595 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700596 def genStruct(self, typeinfo, typeName, alias):
597 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600598 members = typeinfo.elem.findall('.//member')
599 # Iterate over members once to get length parameters for arrays
600 lens = set()
601 for member in members:
602 len = self.getLen(member)
603 if len:
604 lens.add(len)
605 # Generate member info
606 membersInfo = []
607 for member in members:
608 # Get the member's type and name
609 info = self.getTypeNameTuple(member)
610 type = info[0]
611 name = info[1]
612 cdecl = self.makeCParamDecl(member, 0)
613 # Process VkStructureType
614 if type == 'VkStructureType':
615 # Extract the required struct type value from the comments
616 # embedded in the original text defining the 'typeinfo' element
617 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
618 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
619 if result:
620 value = result.group(0)
621 else:
622 value = self.genVkStructureType(typeName)
623 # Store the required type value
624 self.structTypes[typeName] = self.StructType(name=name, value=value)
625 # Store pointer/array/string info
626 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
627 membersInfo.append(self.CommandParam(type=type,
628 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600629 isconst=True if 'const' in cdecl else False,
630 isoptional=self.paramIsOptional(member),
631 iscount=True if name in lens else False,
632 len=self.getLen(member),
633 extstructs=extstructs,
634 cdecl=cdecl,
635 islocal=False,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600636 iscreate=False))
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600637 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
638 #
639 # Insert a lock_guard line
640 def lock_guard(self, indent):
641 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
642 #
643 # Determine if a struct has an object as a member or an embedded member
644 def struct_contains_object(self, struct_item):
645 struct_member_dict = dict(self.structMembers)
646 struct_members = struct_member_dict[struct_item]
647
648 for member in struct_members:
649 if self.isHandleTypeObject(member.type):
650 return True
Mike Schuchardtcf2eda02018-08-11 20:34:07 -0700651 # recurse for member structs, guard against infinite recursion
652 elif member.type in struct_member_dict and member.type != struct_item:
653 if self.struct_contains_object(member.type):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600654 return True
655 return False
656 #
657 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
658 def getParmeterStructsWithObjects(self, item_list):
659 struct_list = set()
660 for item in item_list:
661 paramtype = item.find('type')
662 typecategory = self.getTypeCategory(paramtype.text)
663 if typecategory == 'struct':
664 if self.struct_contains_object(paramtype.text) == True:
665 struct_list.add(item)
666 return struct_list
667 #
668 # Return list of objects from a given list of parameters or members
669 def getObjectsInParameterList(self, item_list, create_func):
670 object_list = set()
671 if create_func == True:
672 member_list = item_list[0:-1]
673 else:
674 member_list = item_list
675 for item in member_list:
676 if self.isHandleTypeObject(paramtype.text):
677 object_list.add(item)
678 return object_list
679 #
680 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600681 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600682 def GenerateCommandWrapExtensionList(self):
683 for struct in self.structMembers:
684 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
685 found = False;
686 for item in struct.members[1].extstructs.split(','):
687 if item != '' and self.struct_contains_object(item) == True:
688 found = True
689 if found == True:
690 for item in struct.members[1].extstructs.split(','):
691 if item != '' and item not in self.extension_structs:
692 self.extension_structs.append(item)
693 #
694 # Returns True if a struct may have a pNext chain containing an object
695 def StructWithExtensions(self, struct_type):
696 if struct_type in self.struct_member_dict:
697 param_info = self.struct_member_dict[struct_type]
698 if (len(param_info) > 1) and param_info[1].extstructs is not None:
699 for item in param_info[1].extstructs.split(','):
700 if item in self.extension_structs:
701 return True
702 return False
703 #
704 # Generate VulkanObjectType from object type
705 def GetVulkanObjType(self, type):
706 return 'kVulkanObjectType%s' % type[2:]
707 #
708 # Return correct dispatch table type -- instance or device
709 def GetDispType(self, type):
710 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
711 #
712 # Generate source for creating a Vulkan object
John Zulaufbb6e5e42018-08-06 16:00:07 -0600713 def generate_create_object_code(self, indent, proto, params, cmd_info, allocator):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600714 create_obj_code = ''
715 handle_type = params[-1].find('type')
716 if self.isHandleTypeObject(handle_type.text):
717 # Check for special case where multiple handles are returned
718 object_array = False
719 if cmd_info[-1].len is not None:
720 object_array = True;
721 handle_name = params[-1].find('name')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600722 object_dest = '*%s' % handle_name.text
723 if object_array == True:
724 create_obj_code += '%sfor (uint32_t index = 0; index < %s; index++) {\n' % (indent, cmd_info[-1].len)
725 indent = self.incIndent(indent)
726 object_dest = '%s[index]' % cmd_info[-1].name
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600727
728 dispobj = params[0].find('type').text
729 calltype = 'Device'
730 if dispobj == 'VkInstance' or dispobj == 'VkPhysicalDevice':
731 calltype = 'Instance'
732
733 create_obj_code += '%s%sCreateObject(%s, %s, %s, %s);\n' % (indent, calltype, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type), allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600734 if object_array == True:
735 indent = self.decIndent(indent)
736 create_obj_code += '%s}\n' % indent
737 indent = self.decIndent(indent)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600738 return create_obj_code
739 #
740 # Generate source for destroying a non-dispatchable object
741 def generate_destroy_object_code(self, indent, proto, cmd_info):
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600742 validate_code = ''
743 record_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600744 object_array = False
745 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
746 # Check for special case where multiple handles are returned
747 if cmd_info[-1].len is not None:
748 object_array = True;
749 param = -1
750 else:
751 param = -2
752 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
753 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600754 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
755 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600756 if self.isHandleTypeObject(cmd_info[param].type) == True:
757 if object_array == True:
758 # This API is freeing an array of handles -- add loop control
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600759 validate_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600760 else:
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600761 dispobj = cmd_info[0].type
762 calltype = 'Device'
763 if dispobj == 'VkInstance' or dispobj == 'VkPhysicalDevice':
764 calltype = 'Instance'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600765 # Call Destroy a single time
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600766 validate_code += '%sskip |= %sValidateDestroyObject(%s, %s, %s, pAllocator, %s, %s);\n' % (indent, calltype, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type), compatalloc_vuid, nullalloc_vuid)
767 record_code += '%s%sRecordDestroyObject(%s, %s, %s);\n' % (indent, calltype, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type))
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600768 return object_array, validate_code, record_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600769 #
770 # Output validation for a single object (obj_count is NULL) or a counted list of objects
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600771 def outputObjects(self, obj_type, obj_name, obj_count, prefix, index, indent, disp_name, parent_name, null_allowed, top_level):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600772 pre_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600773 param_suffix = '%s-parameter' % (obj_name)
774 parent_suffix = '%s-parent' % (obj_name)
775 param_vuid = self.GetVuid(parent_name, param_suffix)
776 parent_vuid = self.GetVuid(parent_name, parent_suffix)
777
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600778 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600779 if parent_vuid == 'kVUIDUndefined':
780 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600781 calltype = 'Device'
782 if disp_name == 'instance' or disp_name == 'physicalDevice':
783 calltype = 'Instance'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600784 if obj_count is not None:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600785 pre_call_code += '%sfor (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, obj_count, index)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600786 indent = self.incIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600787 pre_call_code += '%sskip |= %sValidateObject(%s, %s%s[%s], %s, %s, %s, %s);\n' % (indent, calltype, disp_name, prefix, obj_name, index, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600788 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600789 pre_call_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600790 else:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600791 pre_call_code += '%sskip |= %sValidateObject(%s, %s%s, %s, %s, %s, %s);\n' % (indent, calltype, disp_name, prefix, obj_name, self.GetVulkanObjType(obj_type), null_allowed, param_vuid, parent_vuid)
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600792 return pre_call_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600793 #
794 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600795 def validate_objects(self, members, indent, prefix, array_index, disp_name, parent_name, first_level_param):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600796 pre_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600797 index = 'index%s' % str(array_index)
798 array_index += 1
799 # Process any objects in this structure and recurse for any sub-structs in this struct
800 for member in members:
801 # Handle objects
802 if member.iscreate and first_level_param and member == members[-1]:
803 continue
804 if self.isHandleTypeObject(member.type) == True:
805 count_name = member.len
806 if (count_name is not None):
807 count_name = '%s%s' % (prefix, member.len)
808 null_allowed = member.isoptional
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600809 tmp_pre = self.outputObjects(member.type, member.name, count_name, prefix, index, indent, disp_name, parent_name, str(null_allowed).lower(), first_level_param)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600810 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600811 # Handle Structs that contain objects at some level
812 elif member.type in self.struct_member_dict:
813 # Structs at first level will have an object
814 if self.struct_contains_object(member.type) == True:
815 struct_info = self.struct_member_dict[member.type]
Jeff Bolz38b3ce72018-09-19 12:53:38 -0500816 # TODO (jbolz): Can this use paramIsPointer?
Jeff Bolzba74d972018-09-12 15:54:57 -0500817 ispointer = '*' in member.cdecl;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600818 # Struct Array
819 if member.len is not None:
820 # Update struct prefix
821 new_prefix = '%s%s' % (prefix, member.name)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600822 pre_code += '%sif (%s%s) {\n' % (indent, prefix, member.name)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600823 indent = self.incIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600824 pre_code += '%sfor (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600825 indent = self.incIndent(indent)
826 local_prefix = '%s[%s].' % (new_prefix, index)
827 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600828 tmp_pre = self.validate_objects(struct_info, indent, local_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600829 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600830 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600831 pre_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600832 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600833 pre_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600834 # Single Struct
Jeff Bolzba74d972018-09-12 15:54:57 -0500835 elif ispointer:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600836 # Update struct prefix
837 new_prefix = '%s%s->' % (prefix, member.name)
838 # Declare safe_VarType for struct
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600839 pre_code += '%sif (%s%s) {\n' % (indent, prefix, member.name)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600840 indent = self.incIndent(indent)
841 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600842 tmp_pre = self.validate_objects(struct_info, indent, new_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600843 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600844 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600845 pre_code += '%s}\n' % indent
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600846 return pre_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600847 #
848 # For a particular API, generate the object handling code
849 def generate_wrapping_code(self, cmd):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600850 indent = ' '
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600851 pre_call_validate = ''
852 pre_call_record = ''
853 post_call_record = ''
854
855 destroy_array = False
856 validate_destroy_code = ''
857 record_destroy_code = ''
858
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600859 proto = cmd.find('proto/name')
860 params = cmd.findall('param')
861 if proto.text is not None:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600862 cmddata = self.cmd_info_dict[proto.text]
863 cmd_info = cmddata.members
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600864 disp_name = cmd_info[0].name
John Zulaufbb6e5e42018-08-06 16:00:07 -0600865 # Handle object create operations if last parameter is created by this call
866 if cmddata.iscreate:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600867 post_call_record += self.generate_create_object_code(indent, proto, params, cmd_info, cmddata.allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600868 # Handle object destroy operations
John Zulaufbb6e5e42018-08-06 16:00:07 -0600869 if cmddata.isdestroy:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600870 (destroy_array, validate_destroy_code, record_destroy_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
Mark Lobodzinski2a51e802018-09-12 16:07:01 -0600871
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600872 pre_call_record += record_destroy_code
873 pre_call_validate += self.validate_objects(cmd_info, indent, '', 0, disp_name, proto.text, True)
874 pre_call_validate += validate_destroy_code
875
876 return pre_call_validate, pre_call_record, post_call_record
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600877 #
878 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700879 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600880
881 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700882 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600883 members = cmdinfo.elem.findall('.//param')
884 # Iterate over members once to get length parameters for arrays
885 lens = set()
886 for member in members:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600887 length = self.getLen(member)
888 if length:
889 lens.add(length)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600890 struct_member_dict = dict(self.structMembers)
John Zulaufbb6e5e42018-08-06 16:00:07 -0600891
892 # Set command invariant information needed at a per member level in validate...
893 is_create_command = any(filter(lambda pat: pat in cmdname, ('Create', 'Allocate', 'Enumerate', 'RegisterDeviceEvent', 'RegisterDisplayEvent')))
894 last_member_is_pointer = len(members) and self.paramIsPointer(members[-1])
895 iscreate = is_create_command or ('vkGet' in cmdname and last_member_is_pointer)
896 isdestroy = any([destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']])
897
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600898 # Generate member info
899 membersInfo = []
900 constains_extension_structs = False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600901 allocator = 'nullptr'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600902 for member in members:
903 # Get type and name of member
904 info = self.getTypeNameTuple(member)
905 type = info[0]
906 name = info[1]
907 cdecl = self.makeCParamDecl(member, 0)
908 # Check for parameter name in lens set
909 iscount = True if name in lens else False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600910 length = self.getLen(member)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600911 isconst = True if 'const' in cdecl else False
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600912 # Mark param as local if it is an array of objects
913 islocal = False;
914 if self.isHandleTypeObject(type) == True:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600915 if (length is not None) and (isconst == True):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600916 islocal = True
917 # Or if it's a struct that contains an object
918 elif type in struct_member_dict:
919 if self.struct_contains_object(type) == True:
920 islocal = True
John Zulaufbb6e5e42018-08-06 16:00:07 -0600921 if type == 'VkAllocationCallbacks':
922 allocator = name
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600923 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
924 membersInfo.append(self.CommandParam(type=type,
925 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600926 isconst=isconst,
927 isoptional=self.paramIsOptional(member),
928 iscount=iscount,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600929 len=length,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600930 extstructs=extstructs,
931 cdecl=cdecl,
932 islocal=islocal,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600933 iscreate=iscreate))
934
935 self.cmd_list.append(cmdname)
936 self.cmd_info_dict[cmdname] =self.CmdInfoData(name=cmdname, cmdinfo=cmdinfo, members=membersInfo, iscreate=iscreate, isdestroy=isdestroy, allocator=allocator, extra_protect=self.featureExtraProtect, alias=alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600937 #
938 # Create code Create, Destroy, and validate Vulkan objects
939 def WrapCommands(self):
John Zulaufbb6e5e42018-08-06 16:00:07 -0600940 for cmdname in self.cmd_list:
941 cmddata = self.cmd_info_dict[cmdname]
942 cmdinfo = cmddata.cmdinfo
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600943 if cmdname in self.interface_functions:
944 continue
945 if cmdname in self.no_autogen_list:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600946 if 'core' in self.genOpts.filename:
947 decls = self.makeCDecls(cmdinfo.elem)
948 self.appendSection('command', '')
949 self.appendSection('command', '// Declare only')
950 self.appendSection('command', decls[0])
951 self.intercepts += [ ' {"%s", (void *)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600952 continue
953 # Generate object handling code
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600954 (pre_call_validate, pre_call_record, post_call_record) = self.generate_wrapping_code(cmdinfo.elem)
955
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600956 # If API doesn't contain any object handles, don't fool with it
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600957 if not pre_call_validate and not pre_call_record and not post_call_record:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600958 continue
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600959
John Zulaufbb6e5e42018-08-06 16:00:07 -0600960 feature_extra_protect = cmddata.extra_protect
MichaƂ Janiszewski3c3ce9e2018-10-30 23:25:21 +0100961 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600962 self.appendSection('command', '')
963 self.appendSection('command', '#ifdef '+ feature_extra_protect)
964 self.intercepts += [ '#ifdef %s' % feature_extra_protect ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600965
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600966 # Add intercept to procmap
967 self.intercepts += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600968
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600969 decls = self.makeCDecls(cmdinfo.elem)
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600970
971 # Gather the parameter items
972 params = cmdinfo.elem.findall('param/name')
973 # Pull out the text for each of the parameters, separate them by commas in a list
974 paramstext = ', '.join([str(param.text) for param in params])
975 # Generate the API call template
976 fcn_call = cmdinfo.elem.attrib.get('name').replace('vk', 'TOKEN', 1) + '(' + paramstext + ');'
977
978 func_decl_template = decls[0][:-1].split('VKAPI_CALL ')
979 func_decl_template = func_decl_template[1] + ' {'
980
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600981 if 'utils' in self.genOpts.filename:
982 # Output PreCallValidateAPI function if necessary
983 if pre_call_validate:
984 pre_cv_func_decl = 'bool PreCallValidate' + func_decl_template
985 self.appendSection('command', '')
986 self.appendSection('command', pre_cv_func_decl)
987 self.appendSection('command', ' bool skip = false;')
988 self.appendSection('command', pre_call_validate)
989 self.appendSection('command', ' return skip;')
990 self.appendSection('command', '}')
991
992 # Output PreCallRecordAPI function if necessary
993 if pre_call_record:
994 pre_cr_func_decl = 'void PreCallRecord' + func_decl_template
995 self.appendSection('command', '')
996 self.appendSection('command', pre_cr_func_decl)
997 self.appendSection('command', pre_call_record)
998 self.appendSection('command', '}')
999
1000 # Output PosCallRecordAPI function if necessary
1001 if post_call_record:
1002 post_cr_func_decl = 'void PostCallRecord' + func_decl_template
1003 self.appendSection('command', '')
1004 self.appendSection('command', post_cr_func_decl)
1005 self.appendSection('command', post_call_record)
1006 self.appendSection('command', '}')
1007
1008 if 'core' in self.genOpts.filename:
1009 # Output API function:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001010 self.appendSection('command', '')
Mark Lobodzinski63902f02018-09-21 10:36:44 -06001011 self.appendSection('command', decls[0][:-1])
1012 self.appendSection('command', '{')
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001013
Mark Lobodzinski63902f02018-09-21 10:36:44 -06001014 # Handle return values, if any
1015 resulttype = cmdinfo.elem.find('proto/type')
1016 if (resulttype is not None and resulttype.text == 'void'):
1017 resulttype = None
1018 if (resulttype is not None):
1019 assignresult = resulttype.text + ' result = '
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001020 else:
Mark Lobodzinski63902f02018-09-21 10:36:44 -06001021 assignresult = ''
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001022
Mark Lobodzinski63902f02018-09-21 10:36:44 -06001023 # Output all pre-API-call source
1024 if pre_call_validate:
1025 self.appendSection('command', ' bool skip = false;')
1026 if pre_call_validate or pre_call_record:
1027 self.appendSection('command', ' {')
1028 self.appendSection('command', ' std::lock_guard<std::mutex> lock(global_lock);')
1029 # If necessary, add call to PreCallValidateApi(...);
1030 if pre_call_validate:
1031 pcv_call = fcn_call.replace('TOKEN', ' skip |= PreCallValidate', 1)
1032 self.appendSection('command', pcv_call)
1033 if assignresult != '':
1034 if resulttype.text == 'VkResult':
1035 self.appendSection('command', ' if (skip) return VK_ERROR_VALIDATION_FAILED_EXT;')
1036 elif resulttype.text == 'VkBool32':
1037 self.appendSection('command', ' if (skip) return VK_FALSE;')
1038 else:
1039 raise Exception('Unknown result type ' + resulttype.text)
1040 else:
1041 self.appendSection('command', ' if (skip) return;')
1042 # If necessary, add call to PreCallRecordApi(...);
1043 if pre_call_record:
1044 pre_cr_call = fcn_call.replace('TOKEN', ' PreCallRecord', 1)
1045 self.appendSection('command', pre_cr_call)
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001046
Mark Lobodzinski63902f02018-09-21 10:36:44 -06001047 if pre_call_validate or pre_call_record:
1048 self.appendSection('command', ' }')
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001049
Mark Lobodzinski63902f02018-09-21 10:36:44 -06001050 # Build down-chain call strings and output source
1051 # Use correct dispatch table
1052 disp_name = cmdinfo.elem.find('param/name').text
1053 disp_type = cmdinfo.elem.find('param/type').text
1054 map_type = ''
1055 if disp_type in ["VkInstance", "VkPhysicalDevice"] or cmdname == 'vkCreateInstance':
1056 object_type = 'instance'
1057 map_type = 'instance_'
1058 else:
1059 object_type = 'device'
1060 dispatch_table = 'GetLayerDataPtr(get_dispatch_key(%s), %slayer_data_map)->%s_dispatch_table.' % (disp_name, map_type, object_type)
1061 down_chain_call = fcn_call.replace('TOKEN', dispatch_table, 1)
1062 self.appendSection('command', ' ' + assignresult + down_chain_call)
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -06001063
Mark Lobodzinski63902f02018-09-21 10:36:44 -06001064 # If necessary, add call to PostCallRecordApi(...);
1065 if post_call_record:
1066 if assignresult:
1067 if resulttype.text == 'VkResult':
1068 self.appendSection('command', ' if (VK_SUCCESS == result) {')
1069 elif resulttype.text == 'VkBool32':
1070 self.appendSection('command', ' if (VK_TRUE == result) {')
1071 self.appendSection('command', ' std::lock_guard<std::mutex> lock(global_lock);')
1072 post_cr_call = fcn_call.replace('TOKEN', ' PostCallRecord', 1)
1073 self.appendSection('command', post_cr_call)
1074 self.appendSection('command', ' }')
1075
1076 # Handle the return result variable, if any
1077 if (resulttype is not None):
1078 self.appendSection('command', ' return result;')
1079 self.appendSection('command', '}')
MichaƂ Janiszewski3c3ce9e2018-10-30 23:25:21 +01001080 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001081 self.appendSection('command', '#endif // '+ feature_extra_protect)
1082 self.intercepts += [ '#endif' ]