blob: e0a2afa12d2e2402b0db73d9c3fa39616cd73848 [file] [log] [blame]
Mark Lobodzinskid1461482017-07-18 13:56:09 -06001#!/usr/bin/python3 -i
2#
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -07003# Copyright (c) 2015-2019 The Khronos Group Inc.
4# Copyright (c) 2015-2019 Valve Corporation
5# Copyright (c) 2015-2019 LunarG, Inc.
6# Copyright (c) 2015-2019 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,
Mike Schuchardt21638df2019-03-16 10:52:02 -070067 conventions = None,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060068 filename = None,
69 directory = '.',
70 apiname = None,
71 profile = None,
72 versions = '.*',
73 emitversions = '.*',
74 defaultExtensions = None,
75 addExtensions = None,
76 removeExtensions = None,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060077 emitExtensions = None,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060078 sortProcedure = regSortFeatures,
79 prefixText = "",
80 genFuncPointers = True,
81 protectFile = True,
82 protectFeature = True,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060083 apicall = '',
84 apientry = '',
85 apientryp = '',
86 indentFuncProto = True,
87 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060088 alignFuncParam = 0,
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -060089 expandEnumerants = True,
90 valid_usage_path = ''):
Mike Schuchardt21638df2019-03-16 10:52:02 -070091 GeneratorOptions.__init__(self, conventions, filename, directory, apiname, profile,
Mark Lobodzinskid1461482017-07-18 13:56:09 -060092 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060093 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinskid1461482017-07-18 13:56:09 -060094 self.prefixText = prefixText
95 self.genFuncPointers = genFuncPointers
96 self.protectFile = protectFile
97 self.protectFeature = protectFeature
Mark Lobodzinskid1461482017-07-18 13:56:09 -060098 self.apicall = apicall
99 self.apientry = apientry
100 self.apientryp = apientryp
101 self.indentFuncProto = indentFuncProto
102 self.indentFuncPointer = indentFuncPointer
103 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600104 self.expandEnumerants = expandEnumerants
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600105 self.valid_usage_path = valid_usage_path
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600106
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600107
108# ObjectTrackerOutputGenerator - subclass of OutputGenerator.
109# Generates object_tracker layer object validation code
110#
111# ---- methods ----
112# ObjectTrackerOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
113# ---- methods overriding base class ----
114# beginFile(genOpts)
115# endFile()
116# beginFeature(interface, emit)
117# endFeature()
118# genCmd(cmdinfo)
119# genStruct()
120# genType()
121class ObjectTrackerOutputGenerator(OutputGenerator):
122 """Generate ObjectTracker code based on XML element attributes"""
123 # This is an ordered list of sections in the header file.
124 ALL_SECTIONS = ['command']
125 def __init__(self,
126 errFile = sys.stderr,
127 warnFile = sys.stderr,
128 diagFile = sys.stdout):
129 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
130 self.INDENT_SPACES = 4
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600131 self.prototypes = []
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600132 self.instance_extensions = []
133 self.device_extensions = []
134 # Commands which are not autogenerated but still intercepted
135 self.no_autogen_list = [
136 'vkDestroyInstance',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600137 'vkCreateInstance',
138 'vkEnumeratePhysicalDevices',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600139 'vkGetPhysicalDeviceQueueFamilyProperties',
140 'vkGetPhysicalDeviceQueueFamilyProperties2',
141 'vkGetPhysicalDeviceQueueFamilyProperties2KHR',
142 'vkGetDeviceQueue',
143 'vkGetDeviceQueue2',
144 'vkCreateDescriptorSetLayout',
145 'vkDestroyDescriptorPool',
146 'vkDestroyCommandPool',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600147 'vkAllocateCommandBuffers',
148 'vkAllocateDescriptorSets',
149 'vkFreeDescriptorSets',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600150 'vkFreeCommandBuffers',
151 'vkUpdateDescriptorSets',
152 'vkBeginCommandBuffer',
Mark Lobodzinski5a1c8d22018-07-02 10:28:12 -0600153 'vkGetDescriptorSetLayoutSupport',
154 'vkGetDescriptorSetLayoutSupportKHR',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600155 'vkDestroySwapchainKHR',
156 'vkGetSwapchainImagesKHR',
157 'vkCmdPushDescriptorSetKHR',
158 'vkDestroyDevice',
159 'vkResetDescriptorPool',
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600160 'vkGetPhysicalDeviceDisplayPropertiesKHR',
Piers Daniell16c253f2018-05-30 14:34:05 -0600161 'vkGetPhysicalDeviceDisplayProperties2KHR',
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600162 'vkGetDisplayModePropertiesKHR',
Piers Daniell16c253f2018-05-30 14:34:05 -0600163 'vkGetDisplayModeProperties2KHR',
Shannon McPhersonf7d9cf62019-06-26 09:23:57 -0600164 'vkAcquirePerformanceConfigurationINTEL',
165 'vkReleasePerformanceConfigurationINTEL',
166 'vkQueueSetPerformanceConfigurationINTEL',
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600167 ]
168 # These VUIDS are not implicit, but are best handled in this layer. Codegen for vkDestroy calls will generate a key
169 # which is translated here into a good VU. Saves ~40 checks.
170 self.manual_vuids = dict()
171 self.manual_vuids = {
Dave Houlton57ae22f2018-05-18 16:20:52 -0600172 "fence-compatalloc": "\"VUID-vkDestroyFence-fence-01121\"",
173 "fence-nullalloc": "\"VUID-vkDestroyFence-fence-01122\"",
174 "event-compatalloc": "\"VUID-vkDestroyEvent-event-01146\"",
175 "event-nullalloc": "\"VUID-vkDestroyEvent-event-01147\"",
176 "buffer-compatalloc": "\"VUID-vkDestroyBuffer-buffer-00923\"",
177 "buffer-nullalloc": "\"VUID-vkDestroyBuffer-buffer-00924\"",
178 "image-compatalloc": "\"VUID-vkDestroyImage-image-01001\"",
179 "image-nullalloc": "\"VUID-vkDestroyImage-image-01002\"",
180 "shaderModule-compatalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01092\"",
181 "shaderModule-nullalloc": "\"VUID-vkDestroyShaderModule-shaderModule-01093\"",
182 "pipeline-compatalloc": "\"VUID-vkDestroyPipeline-pipeline-00766\"",
183 "pipeline-nullalloc": "\"VUID-vkDestroyPipeline-pipeline-00767\"",
184 "sampler-compatalloc": "\"VUID-vkDestroySampler-sampler-01083\"",
185 "sampler-nullalloc": "\"VUID-vkDestroySampler-sampler-01084\"",
186 "renderPass-compatalloc": "\"VUID-vkDestroyRenderPass-renderPass-00874\"",
187 "renderPass-nullalloc": "\"VUID-vkDestroyRenderPass-renderPass-00875\"",
188 "descriptorUpdateTemplate-compatalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00356\"",
189 "descriptorUpdateTemplate-nullalloc": "\"VUID-vkDestroyDescriptorUpdateTemplate-descriptorSetLayout-00357\"",
190 "imageView-compatalloc": "\"VUID-vkDestroyImageView-imageView-01027\"",
191 "imageView-nullalloc": "\"VUID-vkDestroyImageView-imageView-01028\"",
192 "pipelineCache-compatalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00771\"",
193 "pipelineCache-nullalloc": "\"VUID-vkDestroyPipelineCache-pipelineCache-00772\"",
194 "pipelineLayout-compatalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00299\"",
195 "pipelineLayout-nullalloc": "\"VUID-vkDestroyPipelineLayout-pipelineLayout-00300\"",
196 "descriptorSetLayout-compatalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00284\"",
197 "descriptorSetLayout-nullalloc": "\"VUID-vkDestroyDescriptorSetLayout-descriptorSetLayout-00285\"",
198 "semaphore-compatalloc": "\"VUID-vkDestroySemaphore-semaphore-01138\"",
199 "semaphore-nullalloc": "\"VUID-vkDestroySemaphore-semaphore-01139\"",
200 "queryPool-compatalloc": "\"VUID-vkDestroyQueryPool-queryPool-00794\"",
201 "queryPool-nullalloc": "\"VUID-vkDestroyQueryPool-queryPool-00795\"",
202 "bufferView-compatalloc": "\"VUID-vkDestroyBufferView-bufferView-00937\"",
203 "bufferView-nullalloc": "\"VUID-vkDestroyBufferView-bufferView-00938\"",
204 "surface-compatalloc": "\"VUID-vkDestroySurfaceKHR-surface-01267\"",
205 "surface-nullalloc": "\"VUID-vkDestroySurfaceKHR-surface-01268\"",
206 "framebuffer-compatalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00893\"",
207 "framebuffer-nullalloc": "\"VUID-vkDestroyFramebuffer-framebuffer-00894\"",
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600208 }
209
210 # Commands shadowed by interface functions and are not implemented
211 self.interface_functions = [
212 ]
213 self.headerVersion = None
214 # Internal state - accumulators for different inner block text
215 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600216 self.cmd_list = [] # list of commands processed to maintain ordering
217 self.cmd_info_dict = {} # Per entry-point data for code generation and validation
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600218 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
219 self.extension_structs = [] # List of all structs or sister-structs containing handles
220 # A sister-struct may contain no handles but shares <validextensionstructs> with one that does
221 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
222 self.struct_member_dict = dict()
223 # Named tuples to store struct and command data
224 self.StructType = namedtuple('StructType', ['name', 'value'])
John Zulaufbb6e5e42018-08-06 16:00:07 -0600225 self.CmdInfoData = namedtuple('CmdInfoData', ['name', 'cmdinfo', 'members', 'extra_protect', 'alias', 'iscreate', 'isdestroy', 'allocator'])
226 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'isconst', 'isoptional', 'iscount', 'iscreate', 'len', 'extstructs', 'cdecl', 'islocal'])
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600227 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
228 self.object_types = [] # List of all handle types
229 self.valid_vuids = set() # Set of all valid VUIDs
Dave Houlton57ae22f2018-05-18 16:20:52 -0600230 self.vuid_dict = dict() # VUID dictionary (from JSON)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600231 #
232 # Check if the parameter passed in is optional
233 def paramIsOptional(self, param):
234 # See if the handle is optional
235 isoptional = False
236 # Simple, if it's optional, return true
237 optString = param.attrib.get('optional')
238 if optString:
239 if optString == 'true':
240 isoptional = True
241 elif ',' in optString:
242 opts = []
243 for opt in optString.split(','):
244 val = opt.strip()
245 if val == 'true':
246 opts.append(True)
247 elif val == 'false':
248 opts.append(False)
249 else:
250 print('Unrecognized len attribute value',val)
251 isoptional = opts
John Zulauf9f6788c2018-04-04 14:54:11 -0600252 if not isoptional:
253 # Matching logic in parameter validation and ValidityOutputGenerator.isHandleOptional
254 optString = param.attrib.get('noautovalidity')
255 if optString and optString == 'true':
256 isoptional = True;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600257 return isoptional
258 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600259 # Get VUID identifier from implicit VUID tag
Dave Houlton57ae22f2018-05-18 16:20:52 -0600260 def GetVuid(self, parent, suffix):
261 vuid_string = 'VUID-%s-%s' % (parent, suffix)
262 vuid = "kVUIDUndefined"
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600263 if '->' in vuid_string:
Dave Houlton57ae22f2018-05-18 16:20:52 -0600264 return vuid
265 if vuid_string in self.valid_vuids:
266 vuid = "\"%s\"" % vuid_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600267 else:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600268 alias = self.cmd_info_dict[parent].alias if parent in self.cmd_info_dict else None
269 if alias:
270 alias_string = 'VUID-%s-%s' % (alias, suffix)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600271 if alias_string in self.valid_vuids:
Shannon McPhersonb1a8dd62019-06-06 11:42:47 -0600272 vuid = "\"%s\"" % alias_string
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600273 return vuid
274 #
275 # Increases indent by 4 spaces and tracks it globally
276 def incIndent(self, indent):
277 inc = ' ' * self.INDENT_SPACES
278 if indent:
279 return indent + inc
280 return inc
281 #
282 # Decreases indent by 4 spaces and tracks it globally
283 def decIndent(self, indent):
284 if indent and (len(indent) > self.INDENT_SPACES):
285 return indent[:-self.INDENT_SPACES]
286 return ''
287 #
288 # Override makeProtoName to drop the "vk" prefix
289 def makeProtoName(self, name, tail):
290 return self.genOpts.apientry + name[2:] + tail
291 #
292 # Check if the parameter passed in is a pointer to an array
293 def paramIsArray(self, param):
294 return param.attrib.get('len') is not None
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000295
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600296 #
297 # Generate the object tracker undestroyed object validation function
298 def GenReportFunc(self):
299 output_func = ''
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600300 output_func += 'bool ObjectLifetimes::ReportUndestroyedObjects(VkDevice device, const std::string& error_code) {\n'
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600301 output_func += ' bool skip = false;\n'
302 output_func += ' skip |= DeviceReportUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer, error_code);\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600303 for handle in self.object_types:
304 if self.isHandleTypeNonDispatchable(handle):
Mark Lobodzinski5183a032018-09-13 14:44:28 -0600305 output_func += ' skip |= DeviceReportUndestroyedObjects(device, %s, error_code);\n' % (self.GetVulkanObjType(handle))
306 output_func += ' return skip;\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600307 output_func += '}\n'
308 return output_func
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000309
310 #
311 # Generate the object tracker undestroyed object destruction function
312 def GenDestroyFunc(self):
313 output_func = ''
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600314 output_func += 'void ObjectLifetimes::DestroyUndestroyedObjects(VkDevice device) {\n'
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000315 output_func += ' DeviceDestroyUndestroyedObjects(device, kVulkanObjectTypeCommandBuffer);\n'
316 for handle in self.object_types:
317 if self.isHandleTypeNonDispatchable(handle):
318 output_func += ' DeviceDestroyUndestroyedObjects(device, %s);\n' % (self.GetVulkanObjType(handle))
319 output_func += '}\n'
320 return output_func
321
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600322 #
Dave Houlton57ae22f2018-05-18 16:20:52 -0600323 # Walk the JSON-derived dict and find all "vuid" key values
324 def ExtractVUIDs(self, d):
325 if hasattr(d, 'items'):
326 for k, v in d.items():
327 if k == "vuid":
328 yield v
329 elif isinstance(v, dict):
330 for s in self.ExtractVUIDs(v):
331 yield s
332 elif isinstance (v, list):
333 for l in v:
334 for s in self.ExtractVUIDs(l):
335 yield s
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600336 #
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600337 # Separate content for validation source and header files
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600338 def otwrite(self, dest, formatstring):
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600339 if 'object_tracker.h' in self.genOpts.filename and (dest == 'hdr' or dest == 'both'):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600340 write(formatstring, file=self.outFile)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600341 elif 'object_tracker.cpp' in self.genOpts.filename and (dest == 'cpp' or dest == 'both'):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600342 write(formatstring, file=self.outFile)
Dave Houlton57ae22f2018-05-18 16:20:52 -0600343
344 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600345 # Called at beginning of processing as file is opened
346 def beginFile(self, genOpts):
347 OutputGenerator.beginFile(self, genOpts)
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600348
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700349 # Initialize members that require the tree
350 self.handle_types = GetHandleTypes(self.registry.tree)
351 self.type_categories = GetTypeCategories(self.registry.tree)
352
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600353 header_file = (genOpts.filename == 'object_tracker.h')
354 source_file = (genOpts.filename == 'object_tracker.cpp')
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600355
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600356 if not header_file and not source_file:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600357 print("Error: Output Filenames have changed, update generator source.\n")
358 sys.exit(1)
359
Mark Lobodzinski27a9e7c2018-05-31 16:01:57 -0600360 self.valid_usage_path = genOpts.valid_usage_path
361 vu_json_filename = os.path.join(self.valid_usage_path + os.sep, 'validusage.json')
362 if os.path.isfile(vu_json_filename):
363 json_file = open(vu_json_filename, 'r')
364 self.vuid_dict = json.load(json_file)
365 json_file.close()
366 if len(self.vuid_dict) == 0:
367 print("Error: Could not find, or error loading %s/validusage.json\n", vu_json_filename)
368 sys.exit(1)
369
Dave Houlton57ae22f2018-05-18 16:20:52 -0600370 # Build a set of all vuid text strings found in validusage.json
371 for json_vuid_string in self.ExtractVUIDs(self.vuid_dict):
372 self.valid_vuids.add(json_vuid_string)
373
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600374 # File Comment
375 file_comment = '// *** THIS FILE IS GENERATED - DO NOT EDIT ***\n'
376 file_comment += '// See object_tracker_generator.py for modifications\n'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600377 self.otwrite('both', file_comment)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600378 # Copyright Statement
379 copyright = ''
380 copyright += '\n'
381 copyright += '/***************************************************************************\n'
382 copyright += ' *\n'
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700383 copyright += ' * Copyright (c) 2015-2019 The Khronos Group Inc.\n'
384 copyright += ' * Copyright (c) 2015-2019 Valve Corporation\n'
385 copyright += ' * Copyright (c) 2015-2019 LunarG, Inc.\n'
386 copyright += ' * Copyright (c) 2015-2019 Google Inc.\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600387 copyright += ' *\n'
388 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
389 copyright += ' * you may not use this file except in compliance with the License.\n'
390 copyright += ' * You may obtain a copy of the License at\n'
391 copyright += ' *\n'
392 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
393 copyright += ' *\n'
394 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
395 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
396 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
397 copyright += ' * See the License for the specific language governing permissions and\n'
398 copyright += ' * limitations under the License.\n'
399 copyright += ' *\n'
400 copyright += ' * Author: Mark Lobodzinski <mark@lunarg.com>\n'
Dave Houlton57ae22f2018-05-18 16:20:52 -0600401 copyright += ' * Author: Dave Houlton <daveh@lunarg.com>\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600402 copyright += ' *\n'
403 copyright += ' ****************************************************************************/\n'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600404 self.otwrite('both', copyright)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600405 self.newline()
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600406 self.otwrite('cpp', '#include "chassis.h"')
407 self.otwrite('cpp', '#include "object_lifetime_validation.h"')
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600408
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600409 #
410 # Now that the data is all collected and complete, generate and output the object validation routines
411 def endFile(self):
412 self.struct_member_dict = dict(self.structMembers)
413 # Generate the list of APIs that might need to handle wrapped extension structs
414 # self.GenerateCommandWrapExtensionList()
415 self.WrapCommands()
416 # Build undestroyed objects reporting function
417 report_func = self.GenReportFunc()
418 self.newline()
Gabríel Arthúr Péturssonfdcb5402018-03-20 21:52:06 +0000419 # Build undestroyed objects destruction function
420 destroy_func = self.GenDestroyFunc()
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600421 self.otwrite('cpp', '\n')
422 self.otwrite('cpp', '// ObjectTracker undestroyed objects validation function')
423 self.otwrite('cpp', '%s' % report_func)
424 self.otwrite('cpp', '%s' % destroy_func)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600425 # Actually write the interface to the output file.
426 if (self.emit):
427 self.newline()
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600428 if self.featureExtraProtect is not None:
429 prot = '#ifdef %s' % self.featureExtraProtect
430 self.otwrite('both', '%s' % prot)
431 # Write the object_tracker code to the file
432 if self.sections['command']:
433 source = ('\n'.join(self.sections['command']))
434 self.otwrite('both', '%s' % source)
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100435 if (self.featureExtraProtect is not None):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600436 prot = '\n#endif // %s', self.featureExtraProtect
437 self.otwrite('both', prot)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600438 else:
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600439 self.otwrite('both', '\n')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600440
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600441
442 self.otwrite('hdr', 'void PostCallRecordDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator);')
443 self.otwrite('hdr', 'void PreCallRecordResetDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags);')
444 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties *pQueueFamilyProperties);')
445 self.otwrite('hdr', 'void PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers);')
446 self.otwrite('hdr', 'void PreCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount, const VkDescriptorSet *pDescriptorSets);')
447 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR *pQueueFamilyProperties);')
448 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR *pQueueFamilyProperties);')
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700449 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceDisplayPropertiesKHR(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, VkDisplayPropertiesKHR *pProperties, VkResult result);')
450 self.otwrite('hdr', 'void PostCallRecordGetDisplayModePropertiesKHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t *pPropertyCount, VkDisplayModePropertiesKHR *pProperties, VkResult result);')
451 self.otwrite('hdr', 'void PostCallRecordGetPhysicalDeviceDisplayProperties2KHR(VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, VkDisplayProperties2KHR *pProperties, VkResult result);')
452 self.otwrite('hdr', 'void PostCallRecordGetDisplayModeProperties2KHR(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t *pPropertyCount, VkDisplayModeProperties2KHR *pProperties, VkResult result);')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600453 OutputGenerator.endFile(self)
454 #
455 # Processing point at beginning of each extension definition
456 def beginFeature(self, interface, emit):
457 # Start processing in superclass
458 OutputGenerator.beginFeature(self, interface, emit)
459 self.headerVersion = None
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600460 self.featureExtraProtect = GetFeatureProtect(interface)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600461
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600462 if self.featureName != 'VK_VERSION_1_0' and self.featureName != 'VK_VERSION_1_1':
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600463 white_list_entry = []
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100464 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600465 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
466 white_list_entry += [ '"%s"' % self.featureName ]
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100467 if (self.featureExtraProtect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600468 white_list_entry += [ '#endif' ]
469 featureType = interface.get('type')
470 if featureType == 'instance':
471 self.instance_extensions += white_list_entry
472 elif featureType == 'device':
473 self.device_extensions += white_list_entry
474 #
475 # Processing point at end of each extension definition
476 def endFeature(self):
477 # Finish processing in superclass
478 OutputGenerator.endFeature(self)
479 #
480 # Process enums, structs, etc.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700481 def genType(self, typeinfo, name, alias):
482 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600483 typeElem = typeinfo.elem
484 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
485 # Otherwise, emit the tag text.
486 category = typeElem.get('category')
487 if (category == 'struct' or category == 'union'):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700488 self.genStruct(typeinfo, name, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600489 if category == 'handle':
490 self.object_types.append(name)
491 #
492 # Append a definition to the specified section
493 def appendSection(self, section, text):
494 # self.sections[section].append('SECTION: ' + section + '\n')
495 self.sections[section].append(text)
496 #
497 # Check if the parameter passed in is a pointer
498 def paramIsPointer(self, param):
499 ispointer = False
500 for elem in param:
Raul Tambre7b300182019-05-04 11:25:14 +0300501 if elem.tag == 'type' and elem.tail is not None and '*' in elem.tail:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600502 ispointer = True
503 return ispointer
504 #
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600505 # Check if a parent object is dispatchable or not
506 def isHandleTypeObject(self, handletype):
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700507 return handletype in self.handle_types
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600508 #
509 # Check if a parent object is dispatchable or not
510 def isHandleTypeNonDispatchable(self, handletype):
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700511 return self.handle_types.get(handletype) == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600512 #
513 # Retrieve the type and name for a parameter
514 def getTypeNameTuple(self, param):
515 type = ''
516 name = ''
517 for elem in param:
518 if elem.tag == 'type':
519 type = noneStr(elem.text)
520 elif elem.tag == 'name':
521 name = noneStr(elem.text)
522 return (type, name)
523 #
524 # Retrieve the value of the len tag
525 def getLen(self, param):
526 result = None
527 len = param.attrib.get('len')
528 if len and len != 'null-terminated':
529 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
530 # have a null terminated array of strings. We strip the null-terminated from the
531 # 'len' field and only return the parameter specifying the string count
532 if 'null-terminated' in len:
533 result = len.split(',')[0]
534 else:
535 result = len
536 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
537 result = str(result).replace('::', '->')
538 return result
539 #
540 # Generate a VkStructureType based on a structure typename
541 def genVkStructureType(self, typename):
542 # Add underscore between lowercase then uppercase
543 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
544 # Change to uppercase
545 value = value.upper()
546 # Add STRUCTURE_TYPE_
547 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
548 #
549 # Struct parameter check generation.
550 # This is a special case of the <type> tag where the contents are interpreted as a set of
551 # <member> tags instead of freeform C type declarations. The <member> tags are just like
552 # <param> tags - they are a declaration of a struct or union member. Only simple member
553 # declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700554 def genStruct(self, typeinfo, typeName, alias):
555 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600556 members = typeinfo.elem.findall('.//member')
557 # Iterate over members once to get length parameters for arrays
558 lens = set()
559 for member in members:
560 len = self.getLen(member)
561 if len:
562 lens.add(len)
563 # Generate member info
564 membersInfo = []
565 for member in members:
566 # Get the member's type and name
567 info = self.getTypeNameTuple(member)
568 type = info[0]
569 name = info[1]
570 cdecl = self.makeCParamDecl(member, 0)
571 # Process VkStructureType
572 if type == 'VkStructureType':
573 # Extract the required struct type value from the comments
574 # embedded in the original text defining the 'typeinfo' element
575 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
576 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
577 if result:
578 value = result.group(0)
579 else:
580 value = self.genVkStructureType(typeName)
581 # Store the required type value
582 self.structTypes[typeName] = self.StructType(name=name, value=value)
583 # Store pointer/array/string info
584 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
585 membersInfo.append(self.CommandParam(type=type,
586 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600587 isconst=True if 'const' in cdecl else False,
588 isoptional=self.paramIsOptional(member),
589 iscount=True if name in lens else False,
590 len=self.getLen(member),
591 extstructs=extstructs,
592 cdecl=cdecl,
593 islocal=False,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600594 iscreate=False))
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600595 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
596 #
597 # Insert a lock_guard line
598 def lock_guard(self, indent):
599 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
600 #
601 # Determine if a struct has an object as a member or an embedded member
602 def struct_contains_object(self, struct_item):
603 struct_member_dict = dict(self.structMembers)
604 struct_members = struct_member_dict[struct_item]
605
606 for member in struct_members:
607 if self.isHandleTypeObject(member.type):
608 return True
Mike Schuchardtcf2eda02018-08-11 20:34:07 -0700609 # recurse for member structs, guard against infinite recursion
610 elif member.type in struct_member_dict and member.type != struct_item:
611 if self.struct_contains_object(member.type):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600612 return True
613 return False
614 #
615 # Return list of struct members which contain, or whose sub-structures contain an obj in a given list of parameters or members
616 def getParmeterStructsWithObjects(self, item_list):
617 struct_list = set()
618 for item in item_list:
619 paramtype = item.find('type')
Mike Schuchardt09a1c752019-06-20 12:04:38 -0700620 typecategory = self.type_categories[paramtype.text]
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600621 if typecategory == 'struct':
622 if self.struct_contains_object(paramtype.text) == True:
623 struct_list.add(item)
624 return struct_list
625 #
626 # Return list of objects from a given list of parameters or members
627 def getObjectsInParameterList(self, item_list, create_func):
628 object_list = set()
629 if create_func == True:
630 member_list = item_list[0:-1]
631 else:
632 member_list = item_list
633 for item in member_list:
634 if self.isHandleTypeObject(paramtype.text):
635 object_list.add(item)
636 return object_list
637 #
638 # Construct list of extension structs containing handles, or extension structs that share a <validextensionstructs>
Shannon McPherson9d5167f2018-05-02 15:24:37 -0600639 # tag WITH an extension struct containing handles.
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600640 def GenerateCommandWrapExtensionList(self):
641 for struct in self.structMembers:
642 if (len(struct.members) > 1) and struct.members[1].extstructs is not None:
643 found = False;
644 for item in struct.members[1].extstructs.split(','):
645 if item != '' and self.struct_contains_object(item) == True:
646 found = True
647 if found == True:
648 for item in struct.members[1].extstructs.split(','):
649 if item != '' and item not in self.extension_structs:
650 self.extension_structs.append(item)
651 #
652 # Returns True if a struct may have a pNext chain containing an object
653 def StructWithExtensions(self, struct_type):
654 if struct_type in self.struct_member_dict:
655 param_info = self.struct_member_dict[struct_type]
656 if (len(param_info) > 1) and param_info[1].extstructs is not None:
657 for item in param_info[1].extstructs.split(','):
658 if item in self.extension_structs:
659 return True
660 return False
661 #
662 # Generate VulkanObjectType from object type
663 def GetVulkanObjType(self, type):
664 return 'kVulkanObjectType%s' % type[2:]
665 #
666 # Return correct dispatch table type -- instance or device
667 def GetDispType(self, type):
668 return 'instance' if type in ['VkInstance', 'VkPhysicalDevice'] else 'device'
669 #
670 # Generate source for creating a Vulkan object
John Zulaufbb6e5e42018-08-06 16:00:07 -0600671 def generate_create_object_code(self, indent, proto, params, cmd_info, allocator):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600672 create_obj_code = ''
673 handle_type = params[-1].find('type')
Mark Lobodzinskidcf2bd22019-02-27 16:30:35 -0700674 is_create_pipelines = False
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600675
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600676 if self.isHandleTypeObject(handle_type.text):
677 # Check for special case where multiple handles are returned
678 object_array = False
679 if cmd_info[-1].len is not None:
680 object_array = True;
681 handle_name = params[-1].find('name')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600682 object_dest = '*%s' % handle_name.text
683 if object_array == True:
Mark Lobodzinskidcf2bd22019-02-27 16:30:35 -0700684 if 'CreateGraphicsPipelines' in proto.text or 'CreateComputePipelines' in proto.text or 'CreateRayTracingPipelines' in proto.text:
685 is_create_pipelines = True
686 create_obj_code += '%sif (VK_ERROR_VALIDATION_FAILED_EXT == result) return;\n' % indent
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600687 create_obj_code += '%sif (%s) {\n' % (indent, handle_name.text)
688 indent = self.incIndent(indent)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600689 countispointer = ''
690 if 'uint32_t*' in cmd_info[-2].cdecl:
691 countispointer = '*'
692 create_obj_code += '%sfor (uint32_t index = 0; index < %s%s; index++) {\n' % (indent, countispointer, cmd_info[-1].len)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600693 indent = self.incIndent(indent)
694 object_dest = '%s[index]' % cmd_info[-1].name
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600695
696 dispobj = params[0].find('type').text
Mark Lobodzinskidcf2bd22019-02-27 16:30:35 -0700697 if is_create_pipelines:
Mark Lobodzinskifd2d0a42019-02-20 16:34:56 -0700698 create_obj_code += '%sif (!pPipelines[index]) continue;\n' % indent
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600699 create_obj_code += '%sCreateObject(%s, %s, %s, %s);\n' % (indent, params[0].find('name').text, object_dest, self.GetVulkanObjType(cmd_info[-1].type), allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600700 if object_array == True:
701 indent = self.decIndent(indent)
702 create_obj_code += '%s}\n' % indent
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600703 indent = self.decIndent(indent)
704 create_obj_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600705 indent = self.decIndent(indent)
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600706
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600707 return create_obj_code
708 #
709 # Generate source for destroying a non-dispatchable object
710 def generate_destroy_object_code(self, indent, proto, cmd_info):
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600711 validate_code = ''
712 record_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600713 object_array = False
714 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
715 # Check for special case where multiple handles are returned
716 if cmd_info[-1].len is not None:
717 object_array = True;
718 param = -1
719 else:
720 param = -2
721 compatalloc_vuid_string = '%s-compatalloc' % cmd_info[param].name
722 nullalloc_vuid_string = '%s-nullalloc' % cmd_info[param].name
Dave Houlton57ae22f2018-05-18 16:20:52 -0600723 compatalloc_vuid = self.manual_vuids.get(compatalloc_vuid_string, "kVUIDUndefined")
724 nullalloc_vuid = self.manual_vuids.get(nullalloc_vuid_string, "kVUIDUndefined")
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600725 if self.isHandleTypeObject(cmd_info[param].type) == True:
726 if object_array == True:
727 # This API is freeing an array of handles -- add loop control
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600728 validate_code += 'HEY, NEED TO DESTROY AN ARRAY\n'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600729 else:
Mark Lobodzinskic3ff7a92018-09-20 11:05:57 -0600730 dispobj = cmd_info[0].type
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600731 # Call Destroy a single time
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600732 validate_code += '%sskip |= ValidateDestroyObject(%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)
733 record_code += '%sRecordDestroyObject(%s, %s, %s);\n' % (indent, cmd_info[0].name, cmd_info[param].name, self.GetVulkanObjType(cmd_info[param].type))
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600734 return object_array, validate_code, record_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600735 #
736 # Output validation for a single object (obj_count is NULL) or a counted list of objects
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600737 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 -0600738 pre_call_code = ''
Dave Houlton57ae22f2018-05-18 16:20:52 -0600739 param_suffix = '%s-parameter' % (obj_name)
740 parent_suffix = '%s-parent' % (obj_name)
741 param_vuid = self.GetVuid(parent_name, param_suffix)
742 parent_vuid = self.GetVuid(parent_name, parent_suffix)
743
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600744 # If no parent VUID for this member, look for a commonparent VUID
Dave Houlton57ae22f2018-05-18 16:20:52 -0600745 if parent_vuid == 'kVUIDUndefined':
746 parent_vuid = self.GetVuid(parent_name, 'commonparent')
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600747 if obj_count is not None:
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600748
749 pre_call_code += '%sif (%s%s) {\n' % (indent, prefix, obj_name)
750 indent = self.incIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600751 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 -0600752 indent = self.incIndent(indent)
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600753 pre_call_code += '%sskip |= 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)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600754 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600755 pre_call_code += '%s}\n' % indent
Mark Lobodzinski1b3b6cc2019-07-09 09:19:13 -0600756 indent = self.decIndent(indent)
757 pre_call_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600758 else:
Mark Lobodzinskiadd93232018-10-09 11:49:42 -0600759 pre_call_code += '%sskip |= 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)
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600760 return pre_call_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600761 #
762 # 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 -0600763 def validate_objects(self, members, indent, prefix, array_index, disp_name, parent_name, first_level_param):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600764 pre_code = ''
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600765 index = 'index%s' % str(array_index)
766 array_index += 1
767 # Process any objects in this structure and recurse for any sub-structs in this struct
768 for member in members:
769 # Handle objects
770 if member.iscreate and first_level_param and member == members[-1]:
771 continue
772 if self.isHandleTypeObject(member.type) == True:
773 count_name = member.len
774 if (count_name is not None):
775 count_name = '%s%s' % (prefix, member.len)
776 null_allowed = member.isoptional
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600777 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 -0600778 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600779 # Handle Structs that contain objects at some level
780 elif member.type in self.struct_member_dict:
781 # Structs at first level will have an object
782 if self.struct_contains_object(member.type) == True:
783 struct_info = self.struct_member_dict[member.type]
Jeff Bolz38b3ce72018-09-19 12:53:38 -0500784 # TODO (jbolz): Can this use paramIsPointer?
Jeff Bolzba74d972018-09-12 15:54:57 -0500785 ispointer = '*' in member.cdecl;
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600786 # Struct Array
787 if member.len is not None:
788 # Update struct prefix
789 new_prefix = '%s%s' % (prefix, member.name)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600790 pre_code += '%sif (%s%s) {\n' % (indent, prefix, member.name)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600791 indent = self.incIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600792 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 -0600793 indent = self.incIndent(indent)
794 local_prefix = '%s[%s].' % (new_prefix, index)
795 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600796 tmp_pre = self.validate_objects(struct_info, indent, local_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600797 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600798 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600799 pre_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600800 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600801 pre_code += '%s}\n' % indent
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600802 # Single Struct
Jeff Bolzba74d972018-09-12 15:54:57 -0500803 elif ispointer:
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600804 # Update struct prefix
805 new_prefix = '%s%s->' % (prefix, member.name)
806 # Declare safe_VarType for struct
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600807 pre_code += '%sif (%s%s) {\n' % (indent, prefix, member.name)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600808 indent = self.incIndent(indent)
809 # Process sub-structs in this struct
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600810 tmp_pre = self.validate_objects(struct_info, indent, new_prefix, array_index, disp_name, member.type, False)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600811 pre_code += tmp_pre
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600812 indent = self.decIndent(indent)
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600813 pre_code += '%s}\n' % indent
Mark Lobodzinski8c0d3f92018-09-13 10:45:20 -0600814 return pre_code
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600815 #
816 # For a particular API, generate the object handling code
817 def generate_wrapping_code(self, cmd):
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600818 indent = ' '
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600819 pre_call_validate = ''
820 pre_call_record = ''
821 post_call_record = ''
822
823 destroy_array = False
824 validate_destroy_code = ''
825 record_destroy_code = ''
826
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600827 proto = cmd.find('proto/name')
828 params = cmd.findall('param')
829 if proto.text is not None:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600830 cmddata = self.cmd_info_dict[proto.text]
831 cmd_info = cmddata.members
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600832 disp_name = cmd_info[0].name
John Zulaufbb6e5e42018-08-06 16:00:07 -0600833 # Handle object create operations if last parameter is created by this call
834 if cmddata.iscreate:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600835 post_call_record += self.generate_create_object_code(indent, proto, params, cmd_info, cmddata.allocator)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600836 # Handle object destroy operations
John Zulaufbb6e5e42018-08-06 16:00:07 -0600837 if cmddata.isdestroy:
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600838 (destroy_array, validate_destroy_code, record_destroy_code) = self.generate_destroy_object_code(indent, proto, cmd_info)
Mark Lobodzinski2a51e802018-09-12 16:07:01 -0600839
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600840 pre_call_record += record_destroy_code
841 pre_call_validate += self.validate_objects(cmd_info, indent, '', 0, disp_name, proto.text, True)
842 pre_call_validate += validate_destroy_code
843
844 return pre_call_validate, pre_call_record, post_call_record
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600845 #
846 # Capture command parameter info needed to create, destroy, and validate objects
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700847 def genCmd(self, cmdinfo, cmdname, alias):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600848
849 # Add struct-member type information to command parameter information
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700850 OutputGenerator.genCmd(self, cmdinfo, cmdname, alias)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600851 members = cmdinfo.elem.findall('.//param')
852 # Iterate over members once to get length parameters for arrays
853 lens = set()
854 for member in members:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600855 length = self.getLen(member)
856 if length:
857 lens.add(length)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600858 struct_member_dict = dict(self.structMembers)
John Zulaufbb6e5e42018-08-06 16:00:07 -0600859
860 # Set command invariant information needed at a per member level in validate...
861 is_create_command = any(filter(lambda pat: pat in cmdname, ('Create', 'Allocate', 'Enumerate', 'RegisterDeviceEvent', 'RegisterDisplayEvent')))
862 last_member_is_pointer = len(members) and self.paramIsPointer(members[-1])
863 iscreate = is_create_command or ('vkGet' in cmdname and last_member_is_pointer)
864 isdestroy = any([destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']])
865
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600866 # Generate member info
867 membersInfo = []
868 constains_extension_structs = False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600869 allocator = 'nullptr'
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600870 for member in members:
871 # Get type and name of member
872 info = self.getTypeNameTuple(member)
873 type = info[0]
874 name = info[1]
875 cdecl = self.makeCParamDecl(member, 0)
876 # Check for parameter name in lens set
877 iscount = True if name in lens else False
John Zulaufbb6e5e42018-08-06 16:00:07 -0600878 length = self.getLen(member)
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600879 isconst = True if 'const' in cdecl else False
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600880 # Mark param as local if it is an array of objects
881 islocal = False;
882 if self.isHandleTypeObject(type) == True:
John Zulaufbb6e5e42018-08-06 16:00:07 -0600883 if (length is not None) and (isconst == True):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600884 islocal = True
885 # Or if it's a struct that contains an object
886 elif type in struct_member_dict:
887 if self.struct_contains_object(type) == True:
888 islocal = True
John Zulaufbb6e5e42018-08-06 16:00:07 -0600889 if type == 'VkAllocationCallbacks':
890 allocator = name
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600891 extstructs = member.attrib.get('validextensionstructs') if name == 'pNext' else None
892 membersInfo.append(self.CommandParam(type=type,
893 name=name,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600894 isconst=isconst,
895 isoptional=self.paramIsOptional(member),
896 iscount=iscount,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600897 len=length,
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600898 extstructs=extstructs,
899 cdecl=cdecl,
900 islocal=islocal,
John Zulaufbb6e5e42018-08-06 16:00:07 -0600901 iscreate=iscreate))
902
903 self.cmd_list.append(cmdname)
904 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 -0600905 #
906 # Create code Create, Destroy, and validate Vulkan objects
907 def WrapCommands(self):
John Zulaufbb6e5e42018-08-06 16:00:07 -0600908 for cmdname in self.cmd_list:
909 cmddata = self.cmd_info_dict[cmdname]
910 cmdinfo = cmddata.cmdinfo
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600911 if cmdname in self.interface_functions:
912 continue
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600913 manual = False
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600914 if cmdname in self.no_autogen_list:
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600915 manual = True
916
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600917 # Generate object handling code
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600918 (pre_call_validate, pre_call_record, post_call_record) = self.generate_wrapping_code(cmdinfo.elem)
919
John Zulaufbb6e5e42018-08-06 16:00:07 -0600920 feature_extra_protect = cmddata.extra_protect
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100921 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600922 self.appendSection('command', '')
923 self.appendSection('command', '#ifdef '+ feature_extra_protect)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600924 self.prototypes += [ '#ifdef %s' % feature_extra_protect ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600925
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600926 # Add intercept to procmap
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600927 self.prototypes += [ ' {"%s", (void*)%s},' % (cmdname,cmdname[2:]) ]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600928
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600929 decls = self.makeCDecls(cmdinfo.elem)
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600930
931 # Gather the parameter items
932 params = cmdinfo.elem.findall('param/name')
933 # Pull out the text for each of the parameters, separate them by commas in a list
934 paramstext = ', '.join([str(param.text) for param in params])
935 # Generate the API call template
936 fcn_call = cmdinfo.elem.attrib.get('name').replace('vk', 'TOKEN', 1) + '(' + paramstext + ');'
937
938 func_decl_template = decls[0][:-1].split('VKAPI_CALL ')
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600939 func_decl_template = func_decl_template[1]
Mark Lobodzinskia9e7e9c2018-09-13 13:29:49 -0600940
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700941 result_type = cmdinfo.elem.find('proto/type')
942
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600943 if 'object_tracker.h' in self.genOpts.filename:
944 # Output PreCallValidateAPI prototype if necessary
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600945 if pre_call_validate:
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600946 pre_cv_func_decl = 'bool PreCallValidate' + func_decl_template + ';'
947 self.appendSection('command', pre_cv_func_decl)
948
949 # Output PreCallRecordAPI prototype if necessary
950 if pre_call_record:
951 pre_cr_func_decl = 'void PreCallRecord' + func_decl_template + ';'
952 self.appendSection('command', pre_cr_func_decl)
953
954 # Output PosCallRecordAPI prototype if necessary
955 if post_call_record:
956 post_cr_func_decl = 'void PostCallRecord' + func_decl_template + ';'
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700957 if result_type.text == 'VkResult':
958 post_cr_func_decl = post_cr_func_decl.replace(')', ',\n VkResult result)')
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600959 self.appendSection('command', post_cr_func_decl)
960
961 if 'object_tracker.cpp' in self.genOpts.filename:
962 # Output PreCallValidateAPI function if necessary
963 if pre_call_validate and not manual:
964 pre_cv_func_decl = 'bool ObjectLifetimes::PreCallValidate' + func_decl_template + ' {'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600965 self.appendSection('command', '')
966 self.appendSection('command', pre_cv_func_decl)
967 self.appendSection('command', ' bool skip = false;')
968 self.appendSection('command', pre_call_validate)
969 self.appendSection('command', ' return skip;')
970 self.appendSection('command', '}')
971
972 # Output PreCallRecordAPI function if necessary
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600973 if pre_call_record and not manual:
974 pre_cr_func_decl = 'void ObjectLifetimes::PreCallRecord' + func_decl_template + ' {'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600975 self.appendSection('command', '')
976 self.appendSection('command', pre_cr_func_decl)
977 self.appendSection('command', pre_call_record)
978 self.appendSection('command', '}')
979
980 # Output PosCallRecordAPI function if necessary
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600981 if post_call_record and not manual:
982 post_cr_func_decl = 'void ObjectLifetimes::PostCallRecord' + func_decl_template + ' {'
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600983 self.appendSection('command', '')
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700984
985 if result_type.text == 'VkResult':
986 post_cr_func_decl = post_cr_func_decl.replace(')', ',\n VkResult result)')
Mark Lobodzinskifd2d0a42019-02-20 16:34:56 -0700987 # The two createpipelines APIs may create on failure -- skip the success result check
988 if 'CreateGraphicsPipelines' not in cmdname and 'CreateComputePipelines' not in cmdname and 'CreateRayTracingPipelines' not in cmdname:
989 post_cr_func_decl = post_cr_func_decl.replace('{', '{\n if (result != VK_SUCCESS) return;')
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600990 self.appendSection('command', post_cr_func_decl)
Mark Lobodzinskicd05c1e2019-01-17 15:33:46 -0700991
992
Mark Lobodzinski63902f02018-09-21 10:36:44 -0600993 self.appendSection('command', post_call_record)
994 self.appendSection('command', '}')
995
Michał Janiszewski3c3ce9e2018-10-30 23:25:21 +0100996 if (feature_extra_protect is not None):
Mark Lobodzinskid1461482017-07-18 13:56:09 -0600997 self.appendSection('command', '#endif // '+ feature_extra_protect)
Mark Lobodzinski0c668462018-09-27 10:13:19 -0600998 self.prototypes += [ '#endif' ]