blob: 44c657650a8edbea89dfb354c4532095f6d50070 [file] [log] [blame]
Mark Lobodzinski85672672016-10-13 08:36:42 -06001#!/usr/bin/python3 -i
2#
3# Copyright (c) 2015-2016 The Khronos Group Inc.
4# Copyright (c) 2015-2016 Valve Corporation
5# Copyright (c) 2015-2016 LunarG, Inc.
6# Copyright (c) 2015-2016 Google Inc.
7#
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: Dustin Graves <dustin@lunarg.com>
Mark Lobodzinski26112592017-05-30 12:02:17 -060021# Author: Mark Lobodzinski <mark@lunarg.com>
Mark Lobodzinski85672672016-10-13 08:36:42 -060022
Mark Lobodzinski06954ea2017-06-21 12:21:45 -060023import os,re,sys,string
Mark Lobodzinski85672672016-10-13 08:36:42 -060024import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
Mark Lobodzinski06954ea2017-06-21 12:21:45 -060027from vuid_mapping import *
Mark Lobodzinski62f71562017-10-24 13:41:18 -060028from common_codegen import *
Mark Lobodzinski06954ea2017-06-21 12:21:45 -060029
Jamie Madill8d4cda22017-11-08 13:40:09 -050030# This is a workaround to use a Python 2.7 and 3.x compatible syntax.
31from io import open
Mark Lobodzinski85672672016-10-13 08:36:42 -060032
Mark Lobodzinskid4950072017-08-01 13:02:20 -060033# ParameterValidationGeneratorOptions - subclass of GeneratorOptions.
Mark Lobodzinski85672672016-10-13 08:36:42 -060034#
Mark Lobodzinskid4950072017-08-01 13:02:20 -060035# Adds options used by ParameterValidationOutputGenerator object during Parameter validation layer generation.
Mark Lobodzinski85672672016-10-13 08:36:42 -060036#
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
Mark Lobodzinskid4950072017-08-01 13:02:20 -060065class ParameterValidationGeneratorOptions(GeneratorOptions):
Mark Lobodzinski85672672016-10-13 08:36:42 -060066 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 Lobodzinski85672672016-10-13 08:36:42 -060077 sortProcedure = regSortFeatures,
78 prefixText = "",
Mark Lobodzinski85672672016-10-13 08:36:42 -060079 apicall = '',
80 apientry = '',
81 apientryp = '',
82 indentFuncProto = True,
83 indentFuncPointer = False,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060084 alignFuncParam = 0,
85 expandEnumerants = True):
Mark Lobodzinski85672672016-10-13 08:36:42 -060086 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
87 versions, emitversions, defaultExtensions,
Mark Lobodzinski62f71562017-10-24 13:41:18 -060088 addExtensions, removeExtensions, emitExtensions, sortProcedure)
Mark Lobodzinski85672672016-10-13 08:36:42 -060089 self.prefixText = prefixText
Mark Lobodzinski85672672016-10-13 08:36:42 -060090 self.apicall = apicall
91 self.apientry = apientry
92 self.apientryp = apientryp
93 self.indentFuncProto = indentFuncProto
94 self.indentFuncPointer = indentFuncPointer
95 self.alignFuncParam = alignFuncParam
Mark Lobodzinski62f71562017-10-24 13:41:18 -060096 self.expandEnumerants = expandEnumerants
Mark Lobodzinski85672672016-10-13 08:36:42 -060097
Mark Lobodzinskid4950072017-08-01 13:02:20 -060098# ParameterValidationOutputGenerator - subclass of OutputGenerator.
Mark Lobodzinski85672672016-10-13 08:36:42 -060099# Generates param checker layer code.
100#
101# ---- methods ----
102# ParamCheckerOutputGenerator(errFile, warnFile, diagFile) - args as for
103# OutputGenerator. Defines additional internal state.
104# ---- methods overriding base class ----
105# beginFile(genOpts)
106# endFile()
107# beginFeature(interface, emit)
108# endFeature()
109# genType(typeinfo,name)
110# genStruct(typeinfo,name)
111# genGroup(groupinfo,name)
112# genEnum(enuminfo, name)
113# genCmd(cmdinfo)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600114class ParameterValidationOutputGenerator(OutputGenerator):
115 """Generate Parameter Validation code based on XML element attributes"""
Mark Lobodzinski85672672016-10-13 08:36:42 -0600116 # This is an ordered list of sections in the header file.
117 ALL_SECTIONS = ['command']
118 def __init__(self,
119 errFile = sys.stderr,
120 warnFile = sys.stderr,
121 diagFile = sys.stdout):
122 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
123 self.INDENT_SPACES = 4
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700124 self.intercepts = []
125 self.declarations = []
Mark Lobodzinski85672672016-10-13 08:36:42 -0600126 # Commands to ignore
127 self.blacklist = [
128 'vkGetInstanceProcAddr',
129 'vkGetDeviceProcAddr',
Mark Young6ba8abe2017-11-09 10:37:04 -0700130 'vkEnumerateInstanceVersion',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600131 'vkEnumerateInstanceLayerProperties',
132 'vkEnumerateInstanceExtensionProperties',
133 'vkEnumerateDeviceLayerProperties',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600134 'vkEnumerateDeviceExtensionProperties',
Mark Young6ba8abe2017-11-09 10:37:04 -0700135 'vkCmdDebugMarkerEndEXT',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600136 ]
137 self.validate_only = [
138 'vkCreateInstance',
139 'vkDestroyInstance',
140 'vkCreateDevice',
141 'vkDestroyDevice',
142 'vkCreateQueryPool',
Mark Lobodzinski85672672016-10-13 08:36:42 -0600143 'vkCreateDebugReportCallbackEXT',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600144 'vkDestroyDebugReportCallbackEXT',
145 'vkCreateCommandPool',
Petr Krause91f7a12017-12-14 20:57:36 +0100146 'vkCreateRenderPass',
147 'vkDestroyRenderPass',
Mark Young6ba8abe2017-11-09 10:37:04 -0700148 'vkCreateDebugUtilsMessengerEXT',
149 'vkDestroyDebugUtilsMessengerEXT',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600150 ]
Dustin Gravesce68f082017-03-30 15:42:16 -0600151 # Structure fields to ignore
152 self.structMemberBlacklist = { 'VkWriteDescriptorSet' : ['dstSet'] }
Mark Lobodzinski85672672016-10-13 08:36:42 -0600153 # Validation conditions for some special case struct members that are conditionally validated
154 self.structMemberValidationConditions = { 'VkPipelineColorBlendStateCreateInfo' : { 'logicOp' : '{}logicOpEnable == VK_TRUE' } }
155 # Header version
156 self.headerVersion = None
157 # Internal state - accumulators for different inner block text
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600158 self.validation = [] # Text comprising the main per-api parameter validation routines
Mark Lobodzinski85672672016-10-13 08:36:42 -0600159 self.structNames = [] # List of Vulkan struct typenames
160 self.stypes = [] # Values from the VkStructureType enumeration
161 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
162 self.handleTypes = set() # Set of handle type names
163 self.commands = [] # List of CommandData records for all Vulkan commands
164 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
165 self.validatedStructs = dict() # Map of structs type names to generated validation code for that struct type
166 self.enumRanges = dict() # Map of enum name to BEGIN/END range values
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600167 self.enumValueLists = '' # String containing enumerated type map definitions
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600168 self.func_pointers = '' # String containing function pointers for manual PV functions
169 self.typedefs = '' # String containing function pointer typedefs
Mark Lobodzinski85672672016-10-13 08:36:42 -0600170 self.flags = set() # Map of flags typenames
171 self.flagBits = dict() # Map of flag bits typename to list of values
Chris Forbes78ea32d2016-11-28 11:14:17 +1300172 self.newFlags = set() # Map of flags typenames /defined in the current feature/
Mike Schuchardtafd00482017-08-24 15:15:02 -0600173 self.required_extensions = dict() # Dictionary of required extensions for each item in the current extension
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600174 self.extension_type = '' # Type of active feature (extension), device or instance
175 self.extension_names = dict() # Dictionary of extension names to extension name defines
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600176 self.valid_vuids = set() # Set of all valid VUIDs
Mark Lobodzinski85672672016-10-13 08:36:42 -0600177 # Named tuples to store struct and command data
178 self.StructType = namedtuple('StructType', ['name', 'value'])
179 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isbool', 'israngedenum',
180 'isconst', 'isoptional', 'iscount', 'noautovalidity', 'len', 'extstructs',
181 'condition', 'cdecl'])
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600182 self.CommandData = namedtuple('CommandData', ['name', 'params', 'cdecl', 'extension_type', 'result'])
Mark Lobodzinski85672672016-10-13 08:36:42 -0600183 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600184
185 self.vuid_file = None
186 # Cover cases where file is built from scripts directory, Lin/Win, or Android build structure
Jamie Madill74627c42017-12-15 15:54:05 -0500187 # Set cwd to the script directory to more easily locate the header.
188 previous_dir = os.getcwd()
189 os.chdir(os.path.dirname(sys.argv[0]))
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600190 vuid_filename_locations = [
Mark Lobodzinskifc20c4d2017-07-03 15:50:39 -0600191 './vk_validation_error_messages.h',
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600192 '../layers/vk_validation_error_messages.h',
193 '../../layers/vk_validation_error_messages.h',
194 '../../../layers/vk_validation_error_messages.h',
195 ]
196 for vuid_filename in vuid_filename_locations:
197 if os.path.isfile(vuid_filename):
Lenny Komowb79f04a2017-09-18 17:07:00 -0600198 self.vuid_file = open(vuid_filename, "r", encoding="utf8")
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600199 break
200 if self.vuid_file == None:
201 print("Error: Could not find vk_validation_error_messages.h")
Jamie Madill3935f7c2017-11-08 13:50:14 -0500202 sys.exit(1)
Jamie Madill74627c42017-12-15 15:54:05 -0500203 os.chdir(previous_dir)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600204 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600205 # Generate Copyright comment block for file
206 def GenerateCopyright(self):
207 copyright = '/* *** THIS FILE IS GENERATED - DO NOT EDIT! ***\n'
208 copyright += ' * See parameter_validation_generator.py for modifications\n'
209 copyright += ' *\n'
210 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
211 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
212 copyright += ' * Copyright (C) 2015-2017 Google Inc.\n'
213 copyright += ' *\n'
214 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
215 copyright += ' * you may not use this file except in compliance with the License.\n'
216 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
217 copyright += ' * You may obtain a copy of the License at\n'
218 copyright += ' *\n'
219 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
220 copyright += ' *\n'
221 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
222 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
223 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
224 copyright += ' * See the License for the specific language governing permissions and\n'
225 copyright += ' * limitations under the License.\n'
226 copyright += ' *\n'
227 copyright += ' * Author: Mark Lobodzinski <mark@LunarG.com>\n'
228 copyright += ' */\n\n'
229 return copyright
230 #
231 # Increases the global indent variable
Mark Lobodzinski85672672016-10-13 08:36:42 -0600232 def incIndent(self, indent):
233 inc = ' ' * self.INDENT_SPACES
234 if indent:
235 return indent + inc
236 return inc
237 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600238 # Decreases the global indent variable
Mark Lobodzinski85672672016-10-13 08:36:42 -0600239 def decIndent(self, indent):
240 if indent and (len(indent) > self.INDENT_SPACES):
241 return indent[:-self.INDENT_SPACES]
242 return ''
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600243 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600244 # Convert decimal number to 8 digit hexadecimal lower-case representation
245 def IdToHex(self, dec_num):
246 if dec_num > 4294967295:
247 print ("ERROR: Decimal # %d can't be represented in 8 hex digits" % (dec_num))
Jamie Madill3935f7c2017-11-08 13:50:14 -0500248 sys.exit(1)
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600249 hex_num = hex(dec_num)
250 return hex_num[2:].zfill(8)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600251 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600252 # Called at file creation time
Mark Lobodzinski85672672016-10-13 08:36:42 -0600253 def beginFile(self, genOpts):
254 OutputGenerator.beginFile(self, genOpts)
255 # C-specific
256 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600257 # Open vk_validation_error_messages.h file to verify computed VUIDs
258 for line in self.vuid_file:
259 # Grab hex number from enum definition
260 vuid_list = line.split('0x')
261 # If this is a valid enumeration line, remove trailing comma and CR
262 if len(vuid_list) == 2:
263 vuid_num = vuid_list[1][:-2]
264 # Make sure this is a good hex number before adding to set
265 if len(vuid_num) == 8 and all(c in string.hexdigits for c in vuid_num):
266 self.valid_vuids.add(vuid_num)
267 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600268 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600269 s = self.GenerateCopyright()
270 write(s, file=self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600271 #
272 # Headers
273 write('#include <string>', file=self.outFile)
274 self.newline()
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600275 write('#include "vk_loader_platform.h"', file=self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600276 write('#include "vulkan/vulkan.h"', file=self.outFile)
277 write('#include "vk_layer_extension_utils.h"', file=self.outFile)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600278 write('#include "parameter_validation.h"', file=self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600279 #
280 # Macros
281 self.newline()
282 write('#ifndef UNUSED_PARAMETER', file=self.outFile)
283 write('#define UNUSED_PARAMETER(x) (void)(x)', file=self.outFile)
284 write('#endif // UNUSED_PARAMETER', file=self.outFile)
285 #
286 # Namespace
287 self.newline()
288 write('namespace parameter_validation {', file = self.outFile)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600289 self.newline()
290 write('extern std::mutex global_lock;', file = self.outFile)
291 write('extern std::unordered_map<void *, layer_data *> layer_data_map;', file = self.outFile)
292 write('extern std::unordered_map<void *, instance_layer_data *> instance_layer_data_map;', file = self.outFile)
293 self.newline()
Mark Lobodzinski78a12a92017-08-08 14:16:51 -0600294 #
295 # FuncPtrMap
296 self.func_pointers += 'std::unordered_map<std::string, void *> custom_functions = {\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600297 #
298 # Called at end-time for final content output
Mark Lobodzinski85672672016-10-13 08:36:42 -0600299 def endFile(self):
300 # C-specific
301 self.newline()
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600302 write(self.enumValueLists, file=self.outFile)
303 self.newline()
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600304 write(self.typedefs, file=self.outFile)
305 self.newline()
Mark Lobodzinski78a12a92017-08-08 14:16:51 -0600306 self.func_pointers += '};\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600307 write(self.func_pointers, file=self.outFile)
308 self.newline()
309 ext_template = 'template <typename T>\n'
310 ext_template += 'bool OutputExtensionError(const T *layer_data, const std::string &api_name, const std::string &extension_name) {\n'
Mark Lobodzinskib1fd9d12018-03-30 14:26:00 -0600311 ext_template += ' return log_msg(layer_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,\n'
Mark Lobodzinski88529492018-04-01 10:38:15 -0600312 ext_template += ' EXTENSION_NOT_ENABLED, "Attemped to call %s() but its required extension %s has not been enabled\\n",\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600313 ext_template += ' api_name.c_str(), extension_name.c_str());\n'
314 ext_template += '}\n'
315 write(ext_template, file=self.outFile)
316 self.newline()
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600317 commands_text = '\n'.join(self.validation)
318 write(commands_text, file=self.outFile)
319 self.newline()
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700320 # Output declarations and record intercepted procedures
321 write('// Declarations', file=self.outFile)
322 write('\n'.join(self.declarations), file=self.outFile)
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600323 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600324 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700325 write('\n'.join(self.intercepts), file=self.outFile)
326 write('};\n', file=self.outFile)
327 self.newline()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600328 # Namespace
329 write('} // namespace parameter_validation', file = self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600330 # Finish processing in superclass
331 OutputGenerator.endFile(self)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600332 #
333 # Processing at beginning of each feature or extension
Mark Lobodzinski85672672016-10-13 08:36:42 -0600334 def beginFeature(self, interface, emit):
335 # Start processing in superclass
336 OutputGenerator.beginFeature(self, interface, emit)
337 # C-specific
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600338 # Accumulate includes, defines, types, enums, function pointer typedefs, end function prototypes separately for this
339 # feature. They're only printed in endFeature().
Mark Lobodzinski85672672016-10-13 08:36:42 -0600340 self.headerVersion = None
Mark Lobodzinski85672672016-10-13 08:36:42 -0600341 self.structNames = []
342 self.stypes = []
Mark Lobodzinski85672672016-10-13 08:36:42 -0600343 self.commands = []
344 self.structMembers = []
Chris Forbes78ea32d2016-11-28 11:14:17 +1300345 self.newFlags = set()
Mark Lobodzinski62f71562017-10-24 13:41:18 -0600346 self.featureExtraProtect = GetFeatureProtect(interface)
Mike Schuchardtafd00482017-08-24 15:15:02 -0600347 # Get base list of extension dependencies for all items in this extension
348 base_required_extensions = []
Mark Lobodzinski31964ca2017-09-18 14:15:09 -0600349 if "VK_VERSION_1" not in self.featureName:
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600350 # Save Name Define to get correct enable name later
351 nameElem = interface[0][1]
352 name = nameElem.get('name')
353 self.extension_names[self.featureName] = name
354 # This extension is the first dependency for this command
Mike Schuchardtafd00482017-08-24 15:15:02 -0600355 base_required_extensions.append(self.featureName)
356 # Add any defined extension dependencies to the base dependency list for this extension
357 requires = interface.get('requires')
358 if requires is not None:
359 base_required_extensions.extend(requires.split(','))
Mike Schuchardtafd00482017-08-24 15:15:02 -0600360 # Build dictionary of extension dependencies for each item in this extension
361 self.required_extensions = dict()
362 for require_element in interface.findall('require'):
363 # Copy base extension dependency list
364 required_extensions = list(base_required_extensions)
365 # Add any additional extension dependencies specified in this require block
366 additional_extensions = require_element.get('extension')
367 if additional_extensions:
368 required_extensions.extend(additional_extensions.split(','))
369 # Save full extension list for all named items
370 for element in require_element.findall('*[@name]'):
371 self.required_extensions[element.get('name')] = required_extensions
372
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600373 # And note if this is an Instance or Device extension
374 self.extension_type = interface.get('type')
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600375 #
376 # Called at the end of each extension (feature)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600377 def endFeature(self):
378 # C-specific
379 # Actually write the interface to the output file.
380 if (self.emit):
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600381 # If type declarations are needed by other features based on this one, it may be necessary to suppress the ExtraProtect,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600382 # or move it below the 'for section...' loop.
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600383 ifdef = ''
Mark Lobodzinski85672672016-10-13 08:36:42 -0600384 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600385 ifdef = '#ifdef %s\n' % self.featureExtraProtect
386 self.validation.append(ifdef)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600387 # Generate the struct member checking code from the captured data
388 self.processStructMemberData()
389 # Generate the command parameter checking code from the captured data
390 self.processCmdData()
391 # Write the declaration for the HeaderVersion
392 if self.headerVersion:
393 write('const uint32_t GeneratedHeaderVersion = {};'.format(self.headerVersion), file=self.outFile)
394 self.newline()
395 # Write the declarations for the VkFlags values combining all flag bits
Chris Forbes78ea32d2016-11-28 11:14:17 +1300396 for flag in sorted(self.newFlags):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600397 flagBits = flag.replace('Flags', 'FlagBits')
398 if flagBits in self.flagBits:
399 bits = self.flagBits[flagBits]
400 decl = 'const {} All{} = {}'.format(flag, flagBits, bits[0])
401 for bit in bits[1:]:
402 decl += '|' + bit
403 decl += ';'
404 write(decl, file=self.outFile)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600405 endif = '\n'
Mark Lobodzinski85672672016-10-13 08:36:42 -0600406 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600407 endif = '#endif // %s\n' % self.featureExtraProtect
408 self.validation.append(endif)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600409 # Finish processing in superclass
410 OutputGenerator.endFeature(self)
411 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600412 # Type generation
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700413 def genType(self, typeinfo, name, alias):
414 OutputGenerator.genType(self, typeinfo, name, alias)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600415 typeElem = typeinfo.elem
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600416 # If the type is a struct type, traverse the imbedded <member> tags generating a structure. Otherwise, emit the tag text.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600417 category = typeElem.get('category')
418 if (category == 'struct' or category == 'union'):
419 self.structNames.append(name)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700420 self.genStruct(typeinfo, name, alias)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600421 elif (category == 'handle'):
422 self.handleTypes.add(name)
423 elif (category == 'bitmask'):
424 self.flags.add(name)
Chris Forbes78ea32d2016-11-28 11:14:17 +1300425 self.newFlags.add(name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600426 elif (category == 'define'):
427 if name == 'VK_HEADER_VERSION':
428 nameElem = typeElem.find('name')
429 self.headerVersion = noneStr(nameElem.tail).strip()
430 #
431 # Struct parameter check generation.
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600432 # This is a special case of the <type> tag where the contents are interpreted as a set of <member> tags instead of freeform C
433 # type declarations. The <member> tags are just like <param> tags - they are a declaration of a struct or union member.
434 # Only simple member declarations are supported (no nested structs etc.)
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700435 def genStruct(self, typeinfo, typeName, alias):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700436 OutputGenerator.genStruct(self, typeinfo, typeName, alias)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600437 conditions = self.structMemberValidationConditions[typeName] if typeName in self.structMemberValidationConditions else None
438 members = typeinfo.elem.findall('.//member')
439 #
440 # Iterate over members once to get length parameters for arrays
441 lens = set()
442 for member in members:
443 len = self.getLen(member)
444 if len:
445 lens.add(len)
446 #
447 # Generate member info
448 membersInfo = []
449 for member in members:
450 # Get the member's type and name
451 info = self.getTypeNameTuple(member)
452 type = info[0]
453 name = info[1]
454 stypeValue = ''
455 cdecl = self.makeCParamDecl(member, 0)
456 # Process VkStructureType
457 if type == 'VkStructureType':
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600458 # Extract the required struct type value from the comments embedded in the original text defining the
459 # 'typeinfo' element
Mark Lobodzinski85672672016-10-13 08:36:42 -0600460 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
461 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
462 if result:
463 value = result.group(0)
464 else:
465 value = self.genVkStructureType(typeName)
466 # Store the required type value
467 self.structTypes[typeName] = self.StructType(name=name, value=value)
468 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600469 # Store pointer/array/string info -- Check for parameter name in lens set
Mark Lobodzinski85672672016-10-13 08:36:42 -0600470 iscount = False
471 if name in lens:
472 iscount = True
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600473 # The pNext members are not tagged as optional, but are treated as optional for parameter NULL checks. Static array
474 # members are also treated as optional to skip NULL pointer validation, as they won't be NULL.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600475 isstaticarray = self.paramIsStaticArray(member)
476 isoptional = False
477 if self.paramIsOptional(member) or (name == 'pNext') or (isstaticarray):
478 isoptional = True
Dustin Gravesce68f082017-03-30 15:42:16 -0600479 # Determine if value should be ignored by code generation.
480 noautovalidity = False
481 if (member.attrib.get('noautovalidity') is not None) or ((typeName in self.structMemberBlacklist) and (name in self.structMemberBlacklist[typeName])):
482 noautovalidity = True
Mark Lobodzinski85672672016-10-13 08:36:42 -0600483 membersInfo.append(self.CommandParam(type=type, name=name,
484 ispointer=self.paramIsPointer(member),
485 isstaticarray=isstaticarray,
486 isbool=True if type == 'VkBool32' else False,
487 israngedenum=True if type in self.enumRanges else False,
488 isconst=True if 'const' in cdecl else False,
489 isoptional=isoptional,
490 iscount=iscount,
Dustin Gravesce68f082017-03-30 15:42:16 -0600491 noautovalidity=noautovalidity,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600492 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600493 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600494 condition=conditions[name] if conditions and name in conditions else None,
495 cdecl=cdecl))
496 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
497 #
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600498 # Capture group (e.g. C "enum" type) info to be used for param check code generation.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600499 # These are concatenated together with other types.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700500 def genGroup(self, groupinfo, groupName, alias):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700501 OutputGenerator.genGroup(self, groupinfo, groupName, alias)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600502 groupElem = groupinfo.elem
Mark Lobodzinski85672672016-10-13 08:36:42 -0600503 # Store the sType values
504 if groupName == 'VkStructureType':
505 for elem in groupElem.findall('enum'):
506 self.stypes.append(elem.get('name'))
507 elif 'FlagBits' in groupName:
508 bits = []
509 for elem in groupElem.findall('enum'):
510 bits.append(elem.get('name'))
511 if bits:
512 self.flagBits[groupName] = bits
513 else:
514 # Determine if begin/end ranges are needed (we don't do this for VkStructureType, which has a more finely grained check)
515 expandName = re.sub(r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)',r'\1_\2',groupName).upper()
516 expandPrefix = expandName
517 expandSuffix = ''
518 expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName)
519 if expandSuffixMatch:
520 expandSuffix = '_' + expandSuffixMatch.group()
521 # Strip off the suffix from the prefix
522 expandPrefix = expandName.rsplit(expandSuffix, 1)[0]
523 isEnum = ('FLAG_BITS' not in expandPrefix)
524 if isEnum:
525 self.enumRanges[groupName] = (expandPrefix + '_BEGIN_RANGE' + expandSuffix, expandPrefix + '_END_RANGE' + expandSuffix)
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600526 # Create definition for a list containing valid enum values for this enumerated type
527 enum_entry = 'const std::vector<%s> All%sEnums = {' % (groupName, groupName)
528 for enum in groupElem:
529 name = enum.get('name')
Mark Lobodzinski117d88f2017-07-27 12:09:08 -0600530 if name is not None and enum.get('supported') != 'disabled':
531 enum_entry += '%s, ' % name
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600532 enum_entry += '};\n'
533 self.enumValueLists += enum_entry
Mark Lobodzinski85672672016-10-13 08:36:42 -0600534 #
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600535 # Capture command parameter info to be used for param check code generation.
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700536 def genCmd(self, cmdinfo, name, alias):
Mike Schuchardtf375c7c2017-12-28 11:23:48 -0700537 OutputGenerator.genCmd(self, cmdinfo, name, alias)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600538 decls = self.makeCDecls(cmdinfo.elem)
539 typedef = decls[1]
540 typedef = typedef.split(')',1)[1]
541 if name not in self.blacklist:
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700542 if (self.featureExtraProtect != None):
543 self.declarations += [ '#ifdef %s' % self.featureExtraProtect ]
544 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600545 if (name not in self.validate_only):
546 self.func_pointers += '#ifdef %s\n' % self.featureExtraProtect
547 self.typedefs += '#ifdef %s\n' % self.featureExtraProtect
548 if (name not in self.validate_only):
549 self.typedefs += 'typedef bool (*PFN_manual_%s)%s\n' % (name, typedef)
Mark Lobodzinski78a12a92017-08-08 14:16:51 -0600550 self.func_pointers += ' {"%s", nullptr},\n' % name
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600551 self.intercepts += [ ' {"%s", (void*)%s},' % (name,name) ]
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700552 # Strip off 'vk' from API name
553 self.declarations += [ '%s' % decls[0].replace("VKAPI_CALL vk", "VKAPI_CALL ") ]
554 if (self.featureExtraProtect != None):
555 self.intercepts += [ '#endif' ]
556 self.declarations += [ '#endif' ]
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600557 if (name not in self.validate_only):
558 self.func_pointers += '#endif\n'
559 self.typedefs += '#endif\n'
Mark Lobodzinski85672672016-10-13 08:36:42 -0600560 if name not in self.blacklist:
561 params = cmdinfo.elem.findall('param')
562 # Get list of array lengths
563 lens = set()
564 for param in params:
565 len = self.getLen(param)
566 if len:
567 lens.add(len)
568 # Get param info
569 paramsInfo = []
570 for param in params:
571 paramInfo = self.getTypeNameTuple(param)
572 cdecl = self.makeCParamDecl(param, 0)
573 # Check for parameter name in lens set
574 iscount = False
575 if paramInfo[1] in lens:
576 iscount = True
577 paramsInfo.append(self.CommandParam(type=paramInfo[0], name=paramInfo[1],
578 ispointer=self.paramIsPointer(param),
579 isstaticarray=self.paramIsStaticArray(param),
580 isbool=True if paramInfo[0] == 'VkBool32' else False,
581 israngedenum=True if paramInfo[0] in self.enumRanges else False,
582 isconst=True if 'const' in cdecl else False,
583 isoptional=self.paramIsOptional(param),
584 iscount=iscount,
585 noautovalidity=True if param.attrib.get('noautovalidity') is not None else False,
586 len=self.getLen(param),
587 extstructs=None,
588 condition=None,
589 cdecl=cdecl))
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600590 # Save return value information, if any
591 result_type = ''
592 resultinfo = cmdinfo.elem.find('proto/type')
593 if (resultinfo != None and resultinfo.text != 'void'):
594 result_type = resultinfo.text
595 self.commands.append(self.CommandData(name=name, params=paramsInfo, cdecl=self.makeCDecls(cmdinfo.elem)[0], extension_type=self.extension_type, result=result_type))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600596 #
597 # Check if the parameter passed in is a pointer
598 def paramIsPointer(self, param):
599 ispointer = 0
600 paramtype = param.find('type')
601 if (paramtype.tail is not None) and ('*' in paramtype.tail):
602 ispointer = paramtype.tail.count('*')
603 elif paramtype.text[:4] == 'PFN_':
604 # Treat function pointer typedefs as a pointer to a single value
605 ispointer = 1
606 return ispointer
607 #
608 # Check if the parameter passed in is a static array
609 def paramIsStaticArray(self, param):
610 isstaticarray = 0
611 paramname = param.find('name')
612 if (paramname.tail is not None) and ('[' in paramname.tail):
613 isstaticarray = paramname.tail.count('[')
614 return isstaticarray
615 #
616 # Check if the parameter passed in is optional
617 # Returns a list of Boolean values for comma separated len attributes (len='false,true')
618 def paramIsOptional(self, param):
619 # See if the handle is optional
620 isoptional = False
621 # Simple, if it's optional, return true
622 optString = param.attrib.get('optional')
623 if optString:
624 if optString == 'true':
625 isoptional = True
626 elif ',' in optString:
627 opts = []
628 for opt in optString.split(','):
629 val = opt.strip()
630 if val == 'true':
631 opts.append(True)
632 elif val == 'false':
633 opts.append(False)
634 else:
635 print('Unrecognized len attribute value',val)
636 isoptional = opts
637 return isoptional
638 #
639 # Check if the handle passed in is optional
640 # Uses the same logic as ValidityOutputGenerator.isHandleOptional
641 def isHandleOptional(self, param, lenParam):
642 # Simple, if it's optional, return true
643 if param.isoptional:
644 return True
645 # If no validity is being generated, it usually means that validity is complex and not absolute, so let's say yes.
646 if param.noautovalidity:
647 return True
648 # If the parameter is an array and we haven't already returned, find out if any of the len parameters are optional
649 if lenParam and lenParam.isoptional:
650 return True
651 return False
652 #
653 # Generate a VkStructureType based on a structure typename
654 def genVkStructureType(self, typename):
655 # Add underscore between lowercase then uppercase
656 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
Mark Young39389872017-01-19 21:10:49 -0700657 value = value.replace('D3_D12', 'D3D12')
658 value = value.replace('Device_IDProp', 'Device_ID_Prop')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600659 # Change to uppercase
660 value = value.upper()
661 # Add STRUCTURE_TYPE_
662 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
663 #
664 # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType
665 # value assuming the struct is defined by a different feature
666 def getStructType(self, typename):
667 value = None
668 if typename in self.structTypes:
669 value = self.structTypes[typename].value
670 else:
671 value = self.genVkStructureType(typename)
672 self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename))
673 return value
674 #
675 # Retrieve the value of the len tag
676 def getLen(self, param):
677 result = None
678 len = param.attrib.get('len')
679 if len and len != 'null-terminated':
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600680 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we have a null terminated array of
681 # strings. We strip the null-terminated from the 'len' field and only return the parameter specifying the string count
Mark Lobodzinski85672672016-10-13 08:36:42 -0600682 if 'null-terminated' in len:
683 result = len.split(',')[0]
684 else:
685 result = len
686 result = str(result).replace('::', '->')
687 return result
688 #
689 # Retrieve the type and name for a parameter
690 def getTypeNameTuple(self, param):
691 type = ''
692 name = ''
693 for elem in param:
694 if elem.tag == 'type':
695 type = noneStr(elem.text)
696 elif elem.tag == 'name':
697 name = noneStr(elem.text)
698 return (type, name)
699 #
700 # Find a named parameter in a parameter list
701 def getParamByName(self, params, name):
702 for param in params:
703 if param.name == name:
704 return param
705 return None
706 #
707 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
708 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
709 def parseLateXMath(self, source):
710 name = 'ERROR'
711 decoratedName = 'ERROR'
712 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700713 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
714 match = re.match(r'latexmath\s*\:\s*\[\s*\\l(\w+)\s*\{\s*\\mathit\s*\{\s*(\w+)\s*\}\s*\\over\s*(\d+)\s*\}\s*\\r(\w+)\s*\]', source)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600715 if not match or match.group(1) != match.group(4):
716 raise 'Unrecognized latexmath expression'
717 name = match.group(2)
718 decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3))
719 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700720 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700721 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600722 name = match.group(1)
723 decoratedName = '{}/{}'.format(*match.group(1, 2))
724 return name, decoratedName
725 #
726 # Get the length paramater record for the specified parameter name
727 def getLenParam(self, params, name):
728 lenParam = None
729 if name:
730 if '->' in name:
731 # The count is obtained by dereferencing a member of a struct parameter
732 lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False,
733 isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None,
734 condition=None, cdecl=None)
735 elif 'latexmath' in name:
736 lenName, decoratedName = self.parseLateXMath(name)
737 lenParam = self.getParamByName(params, lenName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600738 else:
739 lenParam = self.getParamByName(params, name)
740 return lenParam
741 #
742 # Convert a vulkan.h command declaration into a parameter_validation.h definition
743 def getCmdDef(self, cmd):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600744 # Strip the trailing ';' and split into individual lines
745 lines = cmd.cdecl[:-1].split('\n')
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600746 cmd_hdr = '\n'.join(lines)
747 return cmd_hdr
Mark Lobodzinski85672672016-10-13 08:36:42 -0600748 #
749 # Generate the code to check for a NULL dereference before calling the
750 # validation function
751 def genCheckedLengthCall(self, name, exprs):
752 count = name.count('->')
753 if count:
754 checkedExpr = []
755 localIndent = ''
756 elements = name.split('->')
757 # Open the if expression blocks
758 for i in range(0, count):
759 checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1])))
760 localIndent = self.incIndent(localIndent)
761 # Add the validation expression
762 for expr in exprs:
763 checkedExpr.append(localIndent + expr)
764 # Close the if blocks
765 for i in range(0, count):
766 localIndent = self.decIndent(localIndent)
767 checkedExpr.append(localIndent + '}\n')
768 return [checkedExpr]
769 # No if statements were required
770 return exprs
771 #
772 # Generate code to check for a specific condition before executing validation code
773 def genConditionalCall(self, prefix, condition, exprs):
774 checkedExpr = []
775 localIndent = ''
776 formattedCondition = condition.format(prefix)
777 checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition))
778 checkedExpr.append(localIndent + '{\n')
779 localIndent = self.incIndent(localIndent)
780 for expr in exprs:
781 checkedExpr.append(localIndent + expr)
782 localIndent = self.decIndent(localIndent)
783 checkedExpr.append(localIndent + '}\n')
784 return [checkedExpr]
785 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600786 # Get VUID identifier from implicit VUID tag
787 def GetVuid(self, vuid_string):
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600788 if '->' in vuid_string:
789 return "VALIDATION_ERROR_UNDEFINED"
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600790 vuid_num = self.IdToHex(convertVUID(vuid_string))
791 if vuid_num in self.valid_vuids:
792 vuid = "VALIDATION_ERROR_%s" % vuid_num
793 else:
794 vuid = "VALIDATION_ERROR_UNDEFINED"
795 return vuid
796 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600797 # Generate the sType check string
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600798 def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600799 checkExpr = []
800 stype = self.structTypes[value.type]
801 if lenValue:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600802 vuid_name = struct_type_name if struct_type_name is not None else funcPrintName
803 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600804 # This is an array with a pointer to a count value
805 if lenValue.ispointer:
806 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600807 checkExpr.append('skip |= validate_struct_type_array(local_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {}, {}, {});\n'.format(
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600808 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600809 # This is an array with an integer count value
810 else:
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600811 checkExpr.append('skip |= validate_struct_type_array(local_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {}, {});\n'.format(
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600812 funcPrintName, lenValueRequired, valueRequired, vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600813 # This is an individual struct
814 else:
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600815 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600816 checkExpr.append('skip |= validate_struct_type(local_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {}, {});\n'.format(
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600817 funcPrintName, valuePrintName, prefix, valueRequired, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600818 return checkExpr
819 #
820 # Generate the handle check string
821 def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
822 checkExpr = []
823 if lenValue:
824 if lenValue.ispointer:
825 # This is assumed to be an output array with a pointer to a count value
826 raise('Unsupported parameter validation case: Output handle array elements are not NULL checked')
827 else:
828 # This is an array with an integer count value
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600829 checkExpr.append('skip |= validate_handle_array(local_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format(
Mark Lobodzinski85672672016-10-13 08:36:42 -0600830 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
831 else:
832 # This is assumed to be an output handle pointer
833 raise('Unsupported parameter validation case: Output handles are not NULL checked')
834 return checkExpr
835 #
836 # Generate check string for an array of VkFlags values
837 def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
838 checkExpr = []
839 flagBitsName = value.type.replace('Flags', 'FlagBits')
840 if not flagBitsName in self.flagBits:
841 raise('Unsupported parameter validation case: array of reserved VkFlags')
842 else:
843 allFlags = 'All' + flagBitsName
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600844 checkExpr.append('skip |= validate_flags_array(local_data->report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, "{}", {}, {pf}{}, {pf}{}, {}, {});\n'.format(funcPrintName, lenPrintName, valuePrintName, flagBitsName, allFlags, lenValue.name, value.name, lenValueRequired, valueRequired, pf=prefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600845 return checkExpr
846 #
847 # Generate pNext check string
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600848 def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600849 checkExpr = []
850 # Generate an array of acceptable VkStructureType values for pNext
851 extStructCount = 0
852 extStructVar = 'NULL'
853 extStructNames = 'NULL'
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600854 vuid = self.GetVuid("VUID-%s-pNext-pNext" % struct_type_name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600855 if value.extstructs:
Mike Schuchardtc73d07e2017-07-12 10:10:01 -0600856 extStructVar = 'allowed_structs_{}'.format(struct_type_name)
857 extStructCount = 'ARRAY_SIZE({})'.format(extStructVar)
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600858 extStructNames = '"' + ', '.join(value.extstructs) + '"'
859 checkExpr.append('const VkStructureType {}[] = {{ {} }};\n'.format(extStructVar, ', '.join([self.getStructType(s) for s in value.extstructs])))
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600860 checkExpr.append('skip |= validate_struct_pnext(local_data->report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion, {});\n'.format(
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600861 funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600862 return checkExpr
863 #
864 # Generate the pointer check string
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600865 def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600866 checkExpr = []
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600867 vuid_tag_name = struct_type_name if struct_type_name is not None else funcPrintName
Mark Lobodzinski85672672016-10-13 08:36:42 -0600868 if lenValue:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600869 count_required_vuid = self.GetVuid("VUID-%s-%s-arraylength" % (vuid_tag_name, lenValue.name))
870 array_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600871 # This is an array with a pointer to a count value
872 if lenValue.ispointer:
873 # If count and array parameters are optional, there will be no validation
874 if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true':
875 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
Gabríel Arthúr Pétursson092b29b2018-03-21 22:44:11 +0000876 checkExpr.append('skip |= validate_array(local_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, &{pf}{vn}, {}, {}, {}, {}, {});\n'.format(
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600877 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, count_required_vuid, array_required_vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600878 # This is an array with an integer count value
879 else:
880 # If count and array parameters are optional, there will be no validation
881 if valueRequired == 'true' or lenValueRequired == 'true':
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600882 if value.type != 'char':
Gabríel Arthúr Pétursson092b29b2018-03-21 22:44:11 +0000883 checkExpr.append('skip |= validate_array(local_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, &{pf}{vn}, {}, {}, {}, {});\n'.format(
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600884 funcPrintName, lenValueRequired, valueRequired, count_required_vuid, array_required_vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
885 else:
886 # Arrays of strings receive special processing
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600887 checkExpr.append('skip |= validate_string_array(local_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {}, {});\n'.format(
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600888 funcPrintName, lenValueRequired, valueRequired, count_required_vuid, array_required_vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600889 if checkExpr:
890 if lenValue and ('->' in lenValue.name):
891 # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count
892 checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr)
893 # This is an individual struct that is not allowed to be NULL
894 elif not value.isoptional:
895 # Function pointers need a reinterpret_cast to void*
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600896 ptr_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600897 if value.type[:4] == 'PFN_':
Mark Lobodzinski02fa1972017-06-28 14:46:14 -0600898 allocator_dict = {'pfnAllocation': '002004f0',
899 'pfnReallocation': '002004f2',
900 'pfnFree': '002004f4',
901 'pfnInternalAllocation': '002004f6'
902 }
903 vuid = allocator_dict.get(value.name)
904 if vuid is not None:
905 ptr_required_vuid = 'VALIDATION_ERROR_%s' % vuid
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600906 checkExpr.append('skip |= validate_required_pointer(local_data->report_data, "{}", {ppp}"{}"{pps}, reinterpret_cast<const void*>({}{}), {});\n'.format(funcPrintName, valuePrintName, prefix, value.name, ptr_required_vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600907 else:
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600908 checkExpr.append('skip |= validate_required_pointer(local_data->report_data, "{}", {ppp}"{}"{pps}, {}{}, {});\n'.format(funcPrintName, valuePrintName, prefix, value.name, ptr_required_vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600909 return checkExpr
910 #
911 # Process struct member validation code, performing name suibstitution if required
912 def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec):
913 # Build format specifier list
914 kwargs = {}
915 if '{postProcPrefix}' in line:
916 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
917 if type(memberDisplayNamePrefix) is tuple:
918 kwargs['postProcPrefix'] = 'ParameterName('
919 else:
920 kwargs['postProcPrefix'] = postProcSpec['ppp']
921 if '{postProcSuffix}' in line:
922 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
923 if type(memberDisplayNamePrefix) is tuple:
924 kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
925 else:
926 kwargs['postProcSuffix'] = postProcSpec['pps']
927 if '{postProcInsert}' in line:
928 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
929 if type(memberDisplayNamePrefix) is tuple:
930 kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
931 else:
932 kwargs['postProcInsert'] = postProcSpec['ppi']
933 if '{funcName}' in line:
934 kwargs['funcName'] = funcName
935 if '{valuePrefix}' in line:
936 kwargs['valuePrefix'] = memberNamePrefix
937 if '{displayNamePrefix}' in line:
938 # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class
939 if type(memberDisplayNamePrefix) is tuple:
940 kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0]
941 else:
942 kwargs['displayNamePrefix'] = memberDisplayNamePrefix
943
944 if kwargs:
945 # Need to escape the C++ curly braces
946 if 'IndexVector' in line:
947 line = line.replace('IndexVector{ ', 'IndexVector{{ ')
948 line = line.replace(' }),', ' }}),')
949 return line.format(**kwargs)
950 return line
951 #
952 # Process struct validation code for inclusion in function or parent struct validation code
953 def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec):
954 for line in lines:
955 if output:
956 output[-1] += '\n'
957 if type(line) is list:
958 for sub in line:
959 output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
960 else:
961 output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
962 return output
963 #
964 # Process struct pointer/array validation code, perfoeming name substitution if required
965 def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec):
966 expr = []
967 expr.append('if ({}{} != NULL)\n'.format(prefix, value.name))
968 expr.append('{')
969 indent = self.incIndent(None)
970 if lenValue:
971 # Need to process all elements in the array
972 indexName = lenValue.name.replace('Count', 'Index')
973 expr[-1] += '\n'
Mark Young39389872017-01-19 21:10:49 -0700974 if lenValue.ispointer:
975 # If the length value is a pointer, de-reference it for the count.
976 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < *{}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
977 else:
978 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600979 expr.append(indent + '{')
980 indent = self.incIndent(indent)
981 # Prefix for value name to display in error message
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700982 if value.ispointer == 2:
983 memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName)
984 memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName)
985 else:
986 memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName)
987 memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600988 else:
989 memberNamePrefix = '{}{}->'.format(prefix, value.name)
990 memberDisplayNamePrefix = '{}->'.format(valueDisplayName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600991 # Expand the struct validation lines
992 expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600993 if lenValue:
994 # Close if and for scopes
995 indent = self.decIndent(indent)
996 expr.append(indent + '}\n')
997 expr.append('}\n')
998 return expr
999 #
1000 # Generate the parameter checking code
1001 def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName):
1002 lines = [] # Generated lines of code
1003 unused = [] # Unused variable names
1004 for value in values:
1005 usedLines = []
1006 lenParam = None
1007 #
1008 # Prefix and suffix for post processing of parameter names for struct members. Arrays of structures need special processing to include the array index in the full parameter name.
1009 postProcSpec = {}
1010 postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}'
1011 postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}'
1012 postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}'
1013 #
1014 # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name
1015 valueDisplayName = '{}{}'.format(displayNamePrefix, value.name)
1016 #
1017 # Check for NULL pointers, ignore the inout count parameters that
1018 # will be validated with their associated array
1019 if (value.ispointer or value.isstaticarray) and not value.iscount:
Mark Lobodzinski85672672016-10-13 08:36:42 -06001020 # Parameters for function argument generation
1021 req = 'true' # Paramerter cannot be NULL
1022 cpReq = 'true' # Count pointer cannot be NULL
1023 cvReq = 'true' # Count value cannot be 0
1024 lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied
Mark Lobodzinski85672672016-10-13 08:36:42 -06001025 # Generate required/optional parameter strings for the pointer and count values
1026 if value.isoptional:
1027 req = 'false'
1028 if value.len:
1029 # The parameter is an array with an explicit count parameter
1030 lenParam = self.getLenParam(values, value.len)
1031 lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name)
1032 if lenParam.ispointer:
1033 # Count parameters that are pointers are inout
1034 if type(lenParam.isoptional) is list:
1035 if lenParam.isoptional[0]:
1036 cpReq = 'false'
1037 if lenParam.isoptional[1]:
1038 cvReq = 'false'
1039 else:
1040 if lenParam.isoptional:
1041 cpReq = 'false'
1042 else:
1043 if lenParam.isoptional:
1044 cvReq = 'false'
1045 #
1046 # The parameter will not be processes when tagged as 'noautovalidity'
1047 # For the pointer to struct case, the struct pointer will not be validated, but any
1048 # members not tagged as 'noatuvalidity' will be validated
1049 if value.noautovalidity:
1050 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1051 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1052 else:
Mark Lobodzinski85672672016-10-13 08:36:42 -06001053 # If this is a pointer to a struct with an sType field, verify the type
1054 if value.type in self.structTypes:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -06001055 usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001056 # If this is an input handle array that is not allowed to contain NULL handles, verify that none of the handles are VK_NULL_HANDLE
1057 elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam):
1058 usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1059 elif value.type in self.flags and value.isconst:
1060 usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1061 elif value.isbool and value.isconst:
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001062 usedLines.append('skip |= validate_bool32_array(local_data->report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, {pf}{}, {pf}{}, {}, {});\n'.format(funcName, lenDisplayName, valueDisplayName, lenParam.name, value.name, cvReq, req, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001063 elif value.israngedenum and value.isconst:
Mark Lobodzinskiaff801e2017-07-25 15:29:57 -06001064 enum_value_list = 'All%sEnums' % value.type
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001065 usedLines.append('skip |= validate_ranged_enum_array(local_data->report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, "{}", {}, {pf}{}, {pf}{}, {}, {});\n'.format(funcName, lenDisplayName, valueDisplayName, value.type, enum_value_list, lenParam.name, value.name, cvReq, req, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001066 elif value.name == 'pNext':
1067 # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml
1068 if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']:
Mark Lobodzinski3c828522017-06-26 13:05:57 -06001069 usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001070 else:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -06001071 usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001072 # If this is a pointer to a struct (input), see if it contains members that need to be checked
1073 if value.type in self.validatedStructs and value.isconst:
1074 usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec))
1075 # Non-pointer types
1076 else:
Mark Lobodzinski85672672016-10-13 08:36:42 -06001077 # The parameter will not be processes when tagged as 'noautovalidity'
1078 # For the struct case, the struct type will not be validated, but any
1079 # members not tagged as 'noatuvalidity' will be validated
1080 if value.noautovalidity:
1081 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1082 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1083 else:
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001084 vuid_name_tag = structTypeName if structTypeName is not None else funcName
Mark Lobodzinski85672672016-10-13 08:36:42 -06001085 if value.type in self.structTypes:
1086 stype = self.structTypes[value.type]
Mark Lobodzinski06954ea2017-06-21 12:21:45 -06001087 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001088 usedLines.append('skip |= validate_struct_type(local_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", &({}{vn}), {sv}, false, {});\n'.format(
Mark Lobodzinski06954ea2017-06-21 12:21:45 -06001089 funcName, valueDisplayName, valuePrefix, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001090 elif value.type in self.handleTypes:
1091 if not self.isHandleOptional(value, None):
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001092 usedLines.append('skip |= validate_required_handle(local_data->report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001093 elif value.type in self.flags:
1094 flagBitsName = value.type.replace('Flags', 'FlagBits')
1095 if not flagBitsName in self.flagBits:
Mark Lobodzinskid0b0c512017-06-28 12:06:41 -06001096 vuid = self.GetVuid("VUID-%s-%s-zerobitmask" % (vuid_name_tag, value.name))
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001097 usedLines.append('skip |= validate_reserved_flags(local_data->report_data, "{}", {ppp}"{}"{pps}, {pf}{}, {});\n'.format(funcName, valueDisplayName, value.name, vuid, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001098 else:
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001099 if value.isoptional:
1100 flagsRequired = 'false'
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001101 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001102 else:
1103 flagsRequired = 'true'
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001104 vuid = self.GetVuid("VUID-%s-%s-requiredbitmask" % (vuid_name_tag, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001105 allFlagsName = 'All' + flagBitsName
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001106 usedLines.append('skip |= validate_flags(local_data->report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {pf}{}, {}, false, {});\n'.format(funcName, valueDisplayName, flagBitsName, allFlagsName, value.name, flagsRequired, vuid, pf=valuePrefix, **postProcSpec))
Mike Schuchardt47619c82017-05-31 09:14:22 -06001107 elif value.type in self.flagBits:
1108 flagsRequired = 'false' if value.isoptional else 'true'
1109 allFlagsName = 'All' + value.type
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001110 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001111 usedLines.append('skip |= validate_flags(local_data->report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {pf}{}, {}, true, {});\n'.format(funcName, valueDisplayName, value.type, allFlagsName, value.name, flagsRequired, vuid, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001112 elif value.isbool:
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001113 usedLines.append('skip |= validate_bool32(local_data->report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001114 elif value.israngedenum:
Mark Lobodzinski42eb3c32017-06-28 11:47:22 -06001115 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinski74cb45f2017-07-25 15:10:29 -06001116 enum_value_list = 'All%sEnums' % value.type
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001117 usedLines.append('skip |= validate_ranged_enum(local_data->report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {}{}, {});\n'.format(funcName, valueDisplayName, value.type, enum_value_list, valuePrefix, value.name, vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001118 # If this is a struct, see if it contains members that need to be checked
1119 if value.type in self.validatedStructs:
1120 memberNamePrefix = '{}{}.'.format(valuePrefix, value.name)
1121 memberDisplayNamePrefix = '{}.'.format(valueDisplayName)
1122 usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001123 # Append the parameter check to the function body for the current command
1124 if usedLines:
1125 # Apply special conditional checks
1126 if value.condition:
1127 usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines)
1128 lines += usedLines
1129 elif not value.iscount:
1130 # If no expression was generated for this value, it is unreferenced by the validation function, unless
1131 # it is an array count, which is indirectly referenced for array valiadation.
1132 unused.append(value.name)
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001133 if not lines:
1134 lines.append('// No xml-driven validation\n')
Mark Lobodzinski85672672016-10-13 08:36:42 -06001135 return lines, unused
1136 #
1137 # Generate the struct member check code from the captured data
1138 def processStructMemberData(self):
1139 indent = self.incIndent(None)
1140 for struct in self.structMembers:
1141 #
1142 # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented
1143 lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name)
1144 if lines:
1145 self.validatedStructs[struct.name] = lines
1146 #
1147 # Generate the command param check code from the captured data
1148 def processCmdData(self):
1149 indent = self.incIndent(None)
1150 for command in self.commands:
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001151 just_validate = False
1152 if command.name in self.validate_only:
1153 just_validate = True
Mark Lobodzinski85672672016-10-13 08:36:42 -06001154 # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance)
1155 startIndex = 0 if command.name == 'vkCreateInstance' else 1
1156 lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None)
Mark Lobodzinski3f10bfe2017-08-23 15:23:23 -06001157 # Cannot validate extension dependencies for device extension APIs having a physical device as their dispatchable object
Mike Schuchardtafd00482017-08-24 15:15:02 -06001158 if (command.name in self.required_extensions) and (self.extension_type != 'device' or command.params[0].type != 'VkPhysicalDevice'):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001159 ext_test = ''
Mike Schuchardtafd00482017-08-24 15:15:02 -06001160 for ext in self.required_extensions[command.name]:
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001161 ext_name_define = ''
1162 ext_enable_name = ''
1163 for extension in self.registry.extensions:
1164 if extension.attrib['name'] == ext:
1165 ext_name_define = extension[0][1].get('name')
1166 ext_enable_name = ext_name_define.lower()
1167 ext_enable_name = re.sub('_extension_name', '', ext_enable_name)
1168 break
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001169 ext_test = 'if (!local_data->extensions.%s) skip |= OutputExtensionError(local_data, "%s", %s);\n' % (ext_enable_name, command.name, ext_name_define)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001170 lines.insert(0, ext_test)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001171 if lines:
1172 cmdDef = self.getCmdDef(command) + '\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001173 # For a validation-only routine, change the function declaration
1174 if just_validate:
1175 jv_def = '// Generated function handles validation only -- API definition is in non-generated source\n'
1176 jv_def += 'extern %s\n\n' % command.cdecl
1177 cmdDef = 'bool parameter_validation_' + cmdDef.split('VKAPI_CALL ',1)[1]
1178 if command.name == 'vkCreateInstance':
1179 cmdDef = cmdDef.replace('(\n', '(\n VkInstance instance,\n')
1180 cmdDef = jv_def + cmdDef
Mark Lobodzinski85672672016-10-13 08:36:42 -06001181 cmdDef += '{\n'
Mark Lobodzinski26112592017-05-30 12:02:17 -06001182
Gabríel Arthúr Péturssona3b5d672017-08-19 16:44:45 +00001183 # Add list of commands to skip -- just generate the routine signature and put the manual source in parameter_validation_utils.cpp
1184 if command.params[0].type in ["VkInstance", "VkPhysicalDevice"] or command.name == 'vkCreateInstance':
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001185 map_name = 'instance_layer_data_map'
1186 map_type = 'instance_layer_data'
1187 else:
1188 map_name = 'layer_data_map'
1189 map_type = 'layer_data'
1190 instance_param = command.params[0].name
1191 if command.name == 'vkCreateInstance':
1192 instance_param = 'instance'
1193 layer_data = ' %s *local_data = GetLayerDataPtr(get_dispatch_key(%s), %s);\n' % (map_type, instance_param, map_name)
1194 cmdDef += layer_data
1195 cmdDef += '%sbool skip = false;\n' % indent
1196 if not just_validate:
1197 if command.result != '':
Jamie Madillfc315192017-11-08 14:11:26 -05001198 if command.result == "VkResult":
1199 cmdDef += indent + '%s result = VK_ERROR_VALIDATION_FAILED_EXT;\n' % command.result
1200 elif command.result == "VkBool32":
1201 cmdDef += indent + '%s result = VK_FALSE;\n' % command.result
1202 else:
1203 raise Exception("Unknown result type: " + command.result)
1204
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001205 cmdDef += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % indent
Mark Lobodzinski85672672016-10-13 08:36:42 -06001206 for line in lines:
1207 cmdDef += '\n'
1208 if type(line) is list:
1209 for sub in line:
1210 cmdDef += indent + sub
1211 else:
1212 cmdDef += indent + line
1213 cmdDef += '\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001214 if not just_validate:
1215 # Generate parameter list for manual fcn and down-chain calls
1216 params_text = ''
1217 for param in command.params:
1218 params_text += '%s, ' % param.name
1219 params_text = params_text[:-2]
1220 # Generate call to manual function if its function pointer is non-null
Mark Lobodzinski78a12a92017-08-08 14:16:51 -06001221 cmdDef += '%sPFN_manual_%s custom_func = (PFN_manual_%s)custom_functions["%s"];\n' % (indent, command.name, command.name, command.name)
1222 cmdDef += '%sif (custom_func != nullptr) {\n' % indent
1223 cmdDef += ' %sskip |= custom_func(%s);\n' % (indent, params_text)
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001224 cmdDef += '%s}\n\n' % indent
1225 # Release the validation lock
1226 cmdDef += '%slock.unlock();\n' % indent
1227 # Generate skip check and down-chain call
1228 cmdDef += '%sif (!skip) {\n' % indent
1229 down_chain_call = ' %s' % indent
1230 if command.result != '':
1231 down_chain_call += ' result = '
1232 # Generate down-chain API call
1233 api_call = '%s(%s);' % (command.name, params_text)
1234 down_chain_call += 'local_data->dispatch_table.%s\n' % api_call[2:]
1235 cmdDef += down_chain_call
1236 cmdDef += '%s}\n' % indent
1237 if command.result != '':
1238 cmdDef += '%sreturn result;\n' % indent
1239 else:
1240 cmdDef += '%sreturn skip;\n' % indent
Mark Lobodzinski85672672016-10-13 08:36:42 -06001241 cmdDef += '}\n'
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001242 self.validation.append(cmdDef)