blob: 4a9ec4ea778632468e78fcb4bbeed218559f4248 [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 *
28
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
Mark Lobodzinski85672672016-10-13 08:36:42 -060031
Mark Lobodzinskid4950072017-08-01 13:02:20 -060032# ParameterValidationGeneratorOptions - subclass of GeneratorOptions.
Mark Lobodzinski85672672016-10-13 08:36:42 -060033#
Mark Lobodzinskid4950072017-08-01 13:02:20 -060034# Adds options used by ParameterValidationOutputGenerator object during Parameter validation layer generation.
Mark Lobodzinski85672672016-10-13 08:36:42 -060035#
36# Additional members
37# prefixText - list of strings to prefix generated header with
38# (usually a copyright statement + calling convention macros).
39# protectFile - True if multiple inclusion protection should be
40# generated (based on the filename) around the entire header.
41# protectFeature - True if #ifndef..#endif protection should be
42# generated around a feature interface in the header file.
43# genFuncPointers - True if function pointer typedefs should be
44# generated
45# protectProto - If conditional protection should be generated
46# around prototype declarations, set to either '#ifdef'
47# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
48# to require opt-out (#ifndef protectProtoStr). Otherwise
49# set to None.
50# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
51# declarations, if protectProto is set
52# apicall - string to use for the function declaration prefix,
53# such as APICALL on Windows.
54# apientry - string to use for the calling convention macro,
55# in typedefs, such as APIENTRY.
56# apientryp - string to use for the calling convention macro
57# in function pointer typedefs, such as APIENTRYP.
58# indentFuncProto - True if prototype declarations should put each
59# parameter on a separate line
60# indentFuncPointer - True if typedefed function pointers should put each
61# parameter on a separate line
62# alignFuncParam - if nonzero and parameters are being put on a
63# separate line, align parameter names at the specified column
Mark Lobodzinskid4950072017-08-01 13:02:20 -060064class ParameterValidationGeneratorOptions(GeneratorOptions):
Mark Lobodzinski85672672016-10-13 08:36:42 -060065 def __init__(self,
66 filename = None,
67 directory = '.',
68 apiname = None,
69 profile = None,
70 versions = '.*',
71 emitversions = '.*',
72 defaultExtensions = None,
73 addExtensions = None,
74 removeExtensions = None,
75 sortProcedure = regSortFeatures,
76 prefixText = "",
77 genFuncPointers = True,
78 protectFile = True,
79 protectFeature = True,
80 protectProto = None,
81 protectProtoStr = None,
82 apicall = '',
83 apientry = '',
84 apientryp = '',
85 indentFuncProto = True,
86 indentFuncPointer = False,
87 alignFuncParam = 0):
88 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
89 versions, emitversions, defaultExtensions,
90 addExtensions, removeExtensions, sortProcedure)
91 self.prefixText = prefixText
92 self.genFuncPointers = genFuncPointers
93 self.protectFile = protectFile
94 self.protectFeature = protectFeature
95 self.protectProto = protectProto
96 self.protectProtoStr = protectProtoStr
97 self.apicall = apicall
98 self.apientry = apientry
99 self.apientryp = apientryp
100 self.indentFuncProto = indentFuncProto
101 self.indentFuncPointer = indentFuncPointer
102 self.alignFuncParam = alignFuncParam
103
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600104# ParameterValidationOutputGenerator - subclass of OutputGenerator.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600105# Generates param checker layer code.
106#
107# ---- methods ----
108# ParamCheckerOutputGenerator(errFile, warnFile, diagFile) - args as for
109# OutputGenerator. Defines additional internal state.
110# ---- methods overriding base class ----
111# beginFile(genOpts)
112# endFile()
113# beginFeature(interface, emit)
114# endFeature()
115# genType(typeinfo,name)
116# genStruct(typeinfo,name)
117# genGroup(groupinfo,name)
118# genEnum(enuminfo, name)
119# genCmd(cmdinfo)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600120class ParameterValidationOutputGenerator(OutputGenerator):
121 """Generate Parameter Validation code based on XML element attributes"""
Mark Lobodzinski85672672016-10-13 08:36:42 -0600122 # This is an ordered list of sections in the header file.
123 ALL_SECTIONS = ['command']
124 def __init__(self,
125 errFile = sys.stderr,
126 warnFile = sys.stderr,
127 diagFile = sys.stdout):
128 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
129 self.INDENT_SPACES = 4
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700130 self.intercepts = []
131 self.declarations = []
Mark Lobodzinski85672672016-10-13 08:36:42 -0600132 # Commands to ignore
133 self.blacklist = [
134 'vkGetInstanceProcAddr',
135 'vkGetDeviceProcAddr',
136 'vkEnumerateInstanceLayerProperties',
137 'vkEnumerateInstanceExtensionsProperties',
138 'vkEnumerateDeviceLayerProperties',
139 'vkEnumerateDeviceExtensionsProperties',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600140 'vkCreateDebugReportCallbackKHR',
141 'vkDestroyDebugReportCallbackKHR',
142 'vkEnumerateInstanceLayerProperties',
143 'vkEnumerateInstanceExtensionProperties',
144 'vkEnumerateDeviceLayerProperties',
145 'vkCmdDebugMarkerEndEXT',
146 'vkEnumerateDeviceExtensionProperties',
147 ]
148 self.validate_only = [
149 'vkCreateInstance',
150 'vkDestroyInstance',
151 'vkCreateDevice',
152 'vkDestroyDevice',
153 'vkCreateQueryPool',
Mark Lobodzinski85672672016-10-13 08:36:42 -0600154 'vkCreateDebugReportCallbackEXT',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600155 'vkDestroyDebugReportCallbackEXT',
156 'vkCreateCommandPool',
Petr Krause91f7a12017-12-14 20:57:36 +0100157 'vkCreateRenderPass',
158 'vkDestroyRenderPass',
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600159 ]
Dustin Gravesce68f082017-03-30 15:42:16 -0600160 # Structure fields to ignore
161 self.structMemberBlacklist = { 'VkWriteDescriptorSet' : ['dstSet'] }
Mark Lobodzinski85672672016-10-13 08:36:42 -0600162 # Validation conditions for some special case struct members that are conditionally validated
163 self.structMemberValidationConditions = { 'VkPipelineColorBlendStateCreateInfo' : { 'logicOp' : '{}logicOpEnable == VK_TRUE' } }
164 # Header version
165 self.headerVersion = None
166 # Internal state - accumulators for different inner block text
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600167 self.validation = [] # Text comprising the main per-api parameter validation routines
Mark Lobodzinski85672672016-10-13 08:36:42 -0600168 self.structNames = [] # List of Vulkan struct typenames
169 self.stypes = [] # Values from the VkStructureType enumeration
170 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
171 self.handleTypes = set() # Set of handle type names
172 self.commands = [] # List of CommandData records for all Vulkan commands
173 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
174 self.validatedStructs = dict() # Map of structs type names to generated validation code for that struct type
175 self.enumRanges = dict() # Map of enum name to BEGIN/END range values
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600176 self.enumValueLists = '' # String containing enumerated type map definitions
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600177 self.func_pointers = '' # String containing function pointers for manual PV functions
178 self.typedefs = '' # String containing function pointer typedefs
Mark Lobodzinski85672672016-10-13 08:36:42 -0600179 self.flags = set() # Map of flags typenames
180 self.flagBits = dict() # Map of flag bits typename to list of values
Chris Forbes78ea32d2016-11-28 11:14:17 +1300181 self.newFlags = set() # Map of flags typenames /defined in the current feature/
Mike Schuchardtafd00482017-08-24 15:15:02 -0600182 self.required_extensions = dict() # Dictionary of required extensions for each item in the current extension
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600183 self.extension_type = '' # Type of active feature (extension), device or instance
184 self.extension_names = dict() # Dictionary of extension names to extension name defines
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600185 self.valid_vuids = set() # Set of all valid VUIDs
Mark Lobodzinski85672672016-10-13 08:36:42 -0600186 # Named tuples to store struct and command data
187 self.StructType = namedtuple('StructType', ['name', 'value'])
188 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isbool', 'israngedenum',
189 'isconst', 'isoptional', 'iscount', 'noautovalidity', 'len', 'extstructs',
190 'condition', 'cdecl'])
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600191 self.CommandData = namedtuple('CommandData', ['name', 'params', 'cdecl', 'extension_type', 'result'])
Mark Lobodzinski85672672016-10-13 08:36:42 -0600192 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600193
194 self.vuid_file = None
195 # Cover cases where file is built from scripts directory, Lin/Win, or Android build structure
Jamie Madill74627c42017-12-15 15:54:05 -0500196 # Set cwd to the script directory to more easily locate the header.
197 previous_dir = os.getcwd()
198 os.chdir(os.path.dirname(sys.argv[0]))
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600199 vuid_filename_locations = [
Mark Lobodzinskifc20c4d2017-07-03 15:50:39 -0600200 './vk_validation_error_messages.h',
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600201 '../layers/vk_validation_error_messages.h',
202 '../../layers/vk_validation_error_messages.h',
203 '../../../layers/vk_validation_error_messages.h',
204 ]
205 for vuid_filename in vuid_filename_locations:
206 if os.path.isfile(vuid_filename):
Lenny Komowb79f04a2017-09-18 17:07:00 -0600207 self.vuid_file = open(vuid_filename, "r", encoding="utf8")
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600208 break
209 if self.vuid_file == None:
210 print("Error: Could not find vk_validation_error_messages.h")
Jamie Madill3935f7c2017-11-08 13:50:14 -0500211 sys.exit(1)
Jamie Madill74627c42017-12-15 15:54:05 -0500212 os.chdir(previous_dir)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600213 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600214 # Generate Copyright comment block for file
215 def GenerateCopyright(self):
216 copyright = '/* *** THIS FILE IS GENERATED - DO NOT EDIT! ***\n'
217 copyright += ' * See parameter_validation_generator.py for modifications\n'
218 copyright += ' *\n'
219 copyright += ' * Copyright (c) 2015-2017 The Khronos Group Inc.\n'
220 copyright += ' * Copyright (c) 2015-2017 LunarG, Inc.\n'
221 copyright += ' * Copyright (C) 2015-2017 Google Inc.\n'
222 copyright += ' *\n'
223 copyright += ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
224 copyright += ' * you may not use this file except in compliance with the License.\n'
225 copyright += ' * Copyright (c) 2015-2017 Valve Corporation\n'
226 copyright += ' * You may obtain a copy of the License at\n'
227 copyright += ' *\n'
228 copyright += ' * http://www.apache.org/licenses/LICENSE-2.0\n'
229 copyright += ' *\n'
230 copyright += ' * Unless required by applicable law or agreed to in writing, software\n'
231 copyright += ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
232 copyright += ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
233 copyright += ' * See the License for the specific language governing permissions and\n'
234 copyright += ' * limitations under the License.\n'
235 copyright += ' *\n'
236 copyright += ' * Author: Mark Lobodzinski <mark@LunarG.com>\n'
237 copyright += ' */\n\n'
238 return copyright
239 #
240 # Increases the global indent variable
Mark Lobodzinski85672672016-10-13 08:36:42 -0600241 def incIndent(self, indent):
242 inc = ' ' * self.INDENT_SPACES
243 if indent:
244 return indent + inc
245 return inc
246 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600247 # Decreases the global indent variable
Mark Lobodzinski85672672016-10-13 08:36:42 -0600248 def decIndent(self, indent):
249 if indent and (len(indent) > self.INDENT_SPACES):
250 return indent[:-self.INDENT_SPACES]
251 return ''
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600252 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600253 # Convert decimal number to 8 digit hexadecimal lower-case representation
254 def IdToHex(self, dec_num):
255 if dec_num > 4294967295:
256 print ("ERROR: Decimal # %d can't be represented in 8 hex digits" % (dec_num))
Jamie Madill3935f7c2017-11-08 13:50:14 -0500257 sys.exit(1)
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600258 hex_num = hex(dec_num)
259 return hex_num[2:].zfill(8)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600260 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600261 # Called at file creation time
Mark Lobodzinski85672672016-10-13 08:36:42 -0600262 def beginFile(self, genOpts):
263 OutputGenerator.beginFile(self, genOpts)
264 # C-specific
265 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600266 # Open vk_validation_error_messages.h file to verify computed VUIDs
267 for line in self.vuid_file:
268 # Grab hex number from enum definition
269 vuid_list = line.split('0x')
270 # If this is a valid enumeration line, remove trailing comma and CR
271 if len(vuid_list) == 2:
272 vuid_num = vuid_list[1][:-2]
273 # Make sure this is a good hex number before adding to set
274 if len(vuid_num) == 8 and all(c in string.hexdigits for c in vuid_num):
275 self.valid_vuids.add(vuid_num)
276 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600277 # User-supplied prefix text, if any (list of strings)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600278 s = self.GenerateCopyright()
279 write(s, file=self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600280 #
281 # Headers
282 write('#include <string>', file=self.outFile)
283 self.newline()
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600284 write('#include "vk_loader_platform.h"', file=self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600285 write('#include "vulkan/vulkan.h"', file=self.outFile)
286 write('#include "vk_layer_extension_utils.h"', file=self.outFile)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600287 write('#include "parameter_validation.h"', file=self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600288 #
289 # Macros
290 self.newline()
291 write('#ifndef UNUSED_PARAMETER', file=self.outFile)
292 write('#define UNUSED_PARAMETER(x) (void)(x)', file=self.outFile)
293 write('#endif // UNUSED_PARAMETER', file=self.outFile)
294 #
295 # Namespace
296 self.newline()
297 write('namespace parameter_validation {', file = self.outFile)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600298 self.newline()
299 write('extern std::mutex global_lock;', file = self.outFile)
300 write('extern std::unordered_map<void *, layer_data *> layer_data_map;', file = self.outFile)
301 write('extern std::unordered_map<void *, instance_layer_data *> instance_layer_data_map;', file = self.outFile)
302 self.newline()
Mark Lobodzinski78a12a92017-08-08 14:16:51 -0600303 #
304 # FuncPtrMap
305 self.func_pointers += 'std::unordered_map<std::string, void *> custom_functions = {\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600306 #
307 # Called at end-time for final content output
Mark Lobodzinski85672672016-10-13 08:36:42 -0600308 def endFile(self):
309 # C-specific
310 self.newline()
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600311 write(self.enumValueLists, file=self.outFile)
312 self.newline()
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600313 write(self.typedefs, file=self.outFile)
314 self.newline()
Mark Lobodzinski78a12a92017-08-08 14:16:51 -0600315 self.func_pointers += '};\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600316 write(self.func_pointers, file=self.outFile)
317 self.newline()
318 ext_template = 'template <typename T>\n'
319 ext_template += 'bool OutputExtensionError(const T *layer_data, const std::string &api_name, const std::string &extension_name) {\n'
320 ext_template += ' return log_msg(layer_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, __LINE__,\n'
321 ext_template += ' EXTENSION_NOT_ENABLED, LayerName, "Attemped to call %s() but its required extension %s has not been enabled\\n",\n'
322 ext_template += ' api_name.c_str(), extension_name.c_str());\n'
323 ext_template += '}\n'
324 write(ext_template, file=self.outFile)
325 self.newline()
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600326 commands_text = '\n'.join(self.validation)
327 write(commands_text, file=self.outFile)
328 self.newline()
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700329 # Output declarations and record intercepted procedures
330 write('// Declarations', file=self.outFile)
331 write('\n'.join(self.declarations), file=self.outFile)
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600332 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600333 write('const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700334 write('\n'.join(self.intercepts), file=self.outFile)
335 write('};\n', file=self.outFile)
336 self.newline()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600337 # Namespace
338 write('} // namespace parameter_validation', file = self.outFile)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600339 # Finish processing in superclass
340 OutputGenerator.endFile(self)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600341 #
342 # Processing at beginning of each feature or extension
Mark Lobodzinski85672672016-10-13 08:36:42 -0600343 def beginFeature(self, interface, emit):
344 # Start processing in superclass
345 OutputGenerator.beginFeature(self, interface, emit)
346 # C-specific
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600347 # Accumulate includes, defines, types, enums, function pointer typedefs, end function prototypes separately for this
348 # feature. They're only printed in endFeature().
Mark Lobodzinski85672672016-10-13 08:36:42 -0600349 self.headerVersion = None
Mark Lobodzinski85672672016-10-13 08:36:42 -0600350 self.structNames = []
351 self.stypes = []
352 self.structTypes = dict()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600353 self.commands = []
354 self.structMembers = []
Chris Forbes78ea32d2016-11-28 11:14:17 +1300355 self.newFlags = set()
Mike Schuchardtafd00482017-08-24 15:15:02 -0600356
357 # Get base list of extension dependencies for all items in this extension
358 base_required_extensions = []
Mark Lobodzinski26112592017-05-30 12:02:17 -0600359 if self.featureName != "VK_VERSION_1_0":
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600360 # Save Name Define to get correct enable name later
361 nameElem = interface[0][1]
362 name = nameElem.get('name')
363 self.extension_names[self.featureName] = name
364 # This extension is the first dependency for this command
Mike Schuchardtafd00482017-08-24 15:15:02 -0600365 base_required_extensions.append(self.featureName)
366 # Add any defined extension dependencies to the base dependency list for this extension
367 requires = interface.get('requires')
368 if requires is not None:
369 base_required_extensions.extend(requires.split(','))
370
371 # Build dictionary of extension dependencies for each item in this extension
372 self.required_extensions = dict()
373 for require_element in interface.findall('require'):
374 # Copy base extension dependency list
375 required_extensions = list(base_required_extensions)
376 # Add any additional extension dependencies specified in this require block
377 additional_extensions = require_element.get('extension')
378 if additional_extensions:
379 required_extensions.extend(additional_extensions.split(','))
380 # Save full extension list for all named items
381 for element in require_element.findall('*[@name]'):
382 self.required_extensions[element.get('name')] = required_extensions
383
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600384 # And note if this is an Instance or Device extension
385 self.extension_type = interface.get('type')
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600386 #
387 # Called at the end of each extension (feature)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600388 def endFeature(self):
389 # C-specific
390 # Actually write the interface to the output file.
391 if (self.emit):
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600392 # 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 -0600393 # or move it below the 'for section...' loop.
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600394 ifdef = ''
Mark Lobodzinski85672672016-10-13 08:36:42 -0600395 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600396 ifdef = '#ifdef %s\n' % self.featureExtraProtect
397 self.validation.append(ifdef)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600398 # Generate the struct member checking code from the captured data
399 self.processStructMemberData()
400 # Generate the command parameter checking code from the captured data
401 self.processCmdData()
402 # Write the declaration for the HeaderVersion
403 if self.headerVersion:
404 write('const uint32_t GeneratedHeaderVersion = {};'.format(self.headerVersion), file=self.outFile)
405 self.newline()
406 # Write the declarations for the VkFlags values combining all flag bits
Chris Forbes78ea32d2016-11-28 11:14:17 +1300407 for flag in sorted(self.newFlags):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600408 flagBits = flag.replace('Flags', 'FlagBits')
409 if flagBits in self.flagBits:
410 bits = self.flagBits[flagBits]
411 decl = 'const {} All{} = {}'.format(flag, flagBits, bits[0])
412 for bit in bits[1:]:
413 decl += '|' + bit
414 decl += ';'
415 write(decl, file=self.outFile)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600416 endif = '\n'
Mark Lobodzinski85672672016-10-13 08:36:42 -0600417 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600418 endif = '#endif // %s\n' % self.featureExtraProtect
419 self.validation.append(endif)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600420 # Finish processing in superclass
421 OutputGenerator.endFeature(self)
422 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600423 # Type generation
424 def genType(self, typeinfo, name):
425 OutputGenerator.genType(self, typeinfo, name)
426 typeElem = typeinfo.elem
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600427 # 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 -0600428 category = typeElem.get('category')
429 if (category == 'struct' or category == 'union'):
430 self.structNames.append(name)
431 self.genStruct(typeinfo, name)
432 elif (category == 'handle'):
433 self.handleTypes.add(name)
434 elif (category == 'bitmask'):
435 self.flags.add(name)
Chris Forbes78ea32d2016-11-28 11:14:17 +1300436 self.newFlags.add(name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600437 elif (category == 'define'):
438 if name == 'VK_HEADER_VERSION':
439 nameElem = typeElem.find('name')
440 self.headerVersion = noneStr(nameElem.tail).strip()
441 #
442 # Struct parameter check generation.
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600443 # This is a special case of the <type> tag where the contents are interpreted as a set of <member> tags instead of freeform C
444 # type declarations. The <member> tags are just like <param> tags - they are a declaration of a struct or union member.
445 # Only simple member declarations are supported (no nested structs etc.)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600446 def genStruct(self, typeinfo, typeName):
447 OutputGenerator.genStruct(self, typeinfo, typeName)
448 conditions = self.structMemberValidationConditions[typeName] if typeName in self.structMemberValidationConditions else None
449 members = typeinfo.elem.findall('.//member')
450 #
451 # Iterate over members once to get length parameters for arrays
452 lens = set()
453 for member in members:
454 len = self.getLen(member)
455 if len:
456 lens.add(len)
457 #
458 # Generate member info
459 membersInfo = []
460 for member in members:
461 # Get the member's type and name
462 info = self.getTypeNameTuple(member)
463 type = info[0]
464 name = info[1]
465 stypeValue = ''
466 cdecl = self.makeCParamDecl(member, 0)
467 # Process VkStructureType
468 if type == 'VkStructureType':
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600469 # Extract the required struct type value from the comments embedded in the original text defining the
470 # 'typeinfo' element
Mark Lobodzinski85672672016-10-13 08:36:42 -0600471 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
472 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
473 if result:
474 value = result.group(0)
475 else:
476 value = self.genVkStructureType(typeName)
477 # Store the required type value
478 self.structTypes[typeName] = self.StructType(name=name, value=value)
479 #
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600480 # Store pointer/array/string info -- Check for parameter name in lens set
Mark Lobodzinski85672672016-10-13 08:36:42 -0600481 iscount = False
482 if name in lens:
483 iscount = True
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600484 # The pNext members are not tagged as optional, but are treated as optional for parameter NULL checks. Static array
485 # members are also treated as optional to skip NULL pointer validation, as they won't be NULL.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600486 isstaticarray = self.paramIsStaticArray(member)
487 isoptional = False
488 if self.paramIsOptional(member) or (name == 'pNext') or (isstaticarray):
489 isoptional = True
Dustin Gravesce68f082017-03-30 15:42:16 -0600490 # Determine if value should be ignored by code generation.
491 noautovalidity = False
492 if (member.attrib.get('noautovalidity') is not None) or ((typeName in self.structMemberBlacklist) and (name in self.structMemberBlacklist[typeName])):
493 noautovalidity = True
Mark Lobodzinski85672672016-10-13 08:36:42 -0600494 membersInfo.append(self.CommandParam(type=type, name=name,
495 ispointer=self.paramIsPointer(member),
496 isstaticarray=isstaticarray,
497 isbool=True if type == 'VkBool32' else False,
498 israngedenum=True if type in self.enumRanges else False,
499 isconst=True if 'const' in cdecl else False,
500 isoptional=isoptional,
501 iscount=iscount,
Dustin Gravesce68f082017-03-30 15:42:16 -0600502 noautovalidity=noautovalidity,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600503 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600504 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600505 condition=conditions[name] if conditions and name in conditions else None,
506 cdecl=cdecl))
507 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
508 #
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600509 # Capture group (e.g. C "enum" type) info to be used for param check code generation.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600510 # These are concatenated together with other types.
511 def genGroup(self, groupinfo, groupName):
512 OutputGenerator.genGroup(self, groupinfo, groupName)
513 groupElem = groupinfo.elem
Mark Lobodzinski85672672016-10-13 08:36:42 -0600514 # Store the sType values
515 if groupName == 'VkStructureType':
516 for elem in groupElem.findall('enum'):
517 self.stypes.append(elem.get('name'))
518 elif 'FlagBits' in groupName:
519 bits = []
520 for elem in groupElem.findall('enum'):
521 bits.append(elem.get('name'))
522 if bits:
523 self.flagBits[groupName] = bits
524 else:
525 # Determine if begin/end ranges are needed (we don't do this for VkStructureType, which has a more finely grained check)
526 expandName = re.sub(r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)',r'\1_\2',groupName).upper()
527 expandPrefix = expandName
528 expandSuffix = ''
529 expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName)
530 if expandSuffixMatch:
531 expandSuffix = '_' + expandSuffixMatch.group()
532 # Strip off the suffix from the prefix
533 expandPrefix = expandName.rsplit(expandSuffix, 1)[0]
534 isEnum = ('FLAG_BITS' not in expandPrefix)
535 if isEnum:
536 self.enumRanges[groupName] = (expandPrefix + '_BEGIN_RANGE' + expandSuffix, expandPrefix + '_END_RANGE' + expandSuffix)
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600537 # Create definition for a list containing valid enum values for this enumerated type
538 enum_entry = 'const std::vector<%s> All%sEnums = {' % (groupName, groupName)
539 for enum in groupElem:
540 name = enum.get('name')
Mark Lobodzinski117d88f2017-07-27 12:09:08 -0600541 if name is not None and enum.get('supported') != 'disabled':
542 enum_entry += '%s, ' % name
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600543 enum_entry += '};\n'
544 self.enumValueLists += enum_entry
Mark Lobodzinski85672672016-10-13 08:36:42 -0600545 #
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600546 # Capture command parameter info to be used for param check code generation.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600547 def genCmd(self, cmdinfo, name):
548 OutputGenerator.genCmd(self, cmdinfo, name)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600549 decls = self.makeCDecls(cmdinfo.elem)
550 typedef = decls[1]
551 typedef = typedef.split(')',1)[1]
552 if name not in self.blacklist:
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700553 if (self.featureExtraProtect != None):
554 self.declarations += [ '#ifdef %s' % self.featureExtraProtect ]
555 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600556 if (name not in self.validate_only):
557 self.func_pointers += '#ifdef %s\n' % self.featureExtraProtect
558 self.typedefs += '#ifdef %s\n' % self.featureExtraProtect
559 if (name not in self.validate_only):
560 self.typedefs += 'typedef bool (*PFN_manual_%s)%s\n' % (name, typedef)
Mark Lobodzinski78a12a92017-08-08 14:16:51 -0600561 self.func_pointers += ' {"%s", nullptr},\n' % name
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600562 self.intercepts += [ ' {"%s", (void*)%s},' % (name,name) ]
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700563 # Strip off 'vk' from API name
564 self.declarations += [ '%s' % decls[0].replace("VKAPI_CALL vk", "VKAPI_CALL ") ]
565 if (self.featureExtraProtect != None):
566 self.intercepts += [ '#endif' ]
567 self.declarations += [ '#endif' ]
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600568 if (name not in self.validate_only):
569 self.func_pointers += '#endif\n'
570 self.typedefs += '#endif\n'
Mark Lobodzinski85672672016-10-13 08:36:42 -0600571 if name not in self.blacklist:
572 params = cmdinfo.elem.findall('param')
573 # Get list of array lengths
574 lens = set()
575 for param in params:
576 len = self.getLen(param)
577 if len:
578 lens.add(len)
579 # Get param info
580 paramsInfo = []
581 for param in params:
582 paramInfo = self.getTypeNameTuple(param)
583 cdecl = self.makeCParamDecl(param, 0)
584 # Check for parameter name in lens set
585 iscount = False
586 if paramInfo[1] in lens:
587 iscount = True
588 paramsInfo.append(self.CommandParam(type=paramInfo[0], name=paramInfo[1],
589 ispointer=self.paramIsPointer(param),
590 isstaticarray=self.paramIsStaticArray(param),
591 isbool=True if paramInfo[0] == 'VkBool32' else False,
592 israngedenum=True if paramInfo[0] in self.enumRanges else False,
593 isconst=True if 'const' in cdecl else False,
594 isoptional=self.paramIsOptional(param),
595 iscount=iscount,
596 noautovalidity=True if param.attrib.get('noautovalidity') is not None else False,
597 len=self.getLen(param),
598 extstructs=None,
599 condition=None,
600 cdecl=cdecl))
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600601 # Save return value information, if any
602 result_type = ''
603 resultinfo = cmdinfo.elem.find('proto/type')
604 if (resultinfo != None and resultinfo.text != 'void'):
605 result_type = resultinfo.text
606 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 -0600607 #
608 # Check if the parameter passed in is a pointer
609 def paramIsPointer(self, param):
610 ispointer = 0
611 paramtype = param.find('type')
612 if (paramtype.tail is not None) and ('*' in paramtype.tail):
613 ispointer = paramtype.tail.count('*')
614 elif paramtype.text[:4] == 'PFN_':
615 # Treat function pointer typedefs as a pointer to a single value
616 ispointer = 1
617 return ispointer
618 #
619 # Check if the parameter passed in is a static array
620 def paramIsStaticArray(self, param):
621 isstaticarray = 0
622 paramname = param.find('name')
623 if (paramname.tail is not None) and ('[' in paramname.tail):
624 isstaticarray = paramname.tail.count('[')
625 return isstaticarray
626 #
627 # Check if the parameter passed in is optional
628 # Returns a list of Boolean values for comma separated len attributes (len='false,true')
629 def paramIsOptional(self, param):
630 # See if the handle is optional
631 isoptional = False
632 # Simple, if it's optional, return true
633 optString = param.attrib.get('optional')
634 if optString:
635 if optString == 'true':
636 isoptional = True
637 elif ',' in optString:
638 opts = []
639 for opt in optString.split(','):
640 val = opt.strip()
641 if val == 'true':
642 opts.append(True)
643 elif val == 'false':
644 opts.append(False)
645 else:
646 print('Unrecognized len attribute value',val)
647 isoptional = opts
648 return isoptional
649 #
650 # Check if the handle passed in is optional
651 # Uses the same logic as ValidityOutputGenerator.isHandleOptional
652 def isHandleOptional(self, param, lenParam):
653 # Simple, if it's optional, return true
654 if param.isoptional:
655 return True
656 # If no validity is being generated, it usually means that validity is complex and not absolute, so let's say yes.
657 if param.noautovalidity:
658 return True
659 # If the parameter is an array and we haven't already returned, find out if any of the len parameters are optional
660 if lenParam and lenParam.isoptional:
661 return True
662 return False
663 #
664 # Generate a VkStructureType based on a structure typename
665 def genVkStructureType(self, typename):
666 # Add underscore between lowercase then uppercase
667 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
Mark Young39389872017-01-19 21:10:49 -0700668 value = value.replace('D3_D12', 'D3D12')
669 value = value.replace('Device_IDProp', 'Device_ID_Prop')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600670 # Change to uppercase
671 value = value.upper()
672 # Add STRUCTURE_TYPE_
673 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
674 #
675 # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType
676 # value assuming the struct is defined by a different feature
677 def getStructType(self, typename):
678 value = None
679 if typename in self.structTypes:
680 value = self.structTypes[typename].value
681 else:
682 value = self.genVkStructureType(typename)
683 self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename))
684 return value
685 #
686 # Retrieve the value of the len tag
687 def getLen(self, param):
688 result = None
689 len = param.attrib.get('len')
690 if len and len != 'null-terminated':
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600691 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we have a null terminated array of
692 # 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 -0600693 if 'null-terminated' in len:
694 result = len.split(',')[0]
695 else:
696 result = len
697 result = str(result).replace('::', '->')
698 return result
699 #
700 # Retrieve the type and name for a parameter
701 def getTypeNameTuple(self, param):
702 type = ''
703 name = ''
704 for elem in param:
705 if elem.tag == 'type':
706 type = noneStr(elem.text)
707 elif elem.tag == 'name':
708 name = noneStr(elem.text)
709 return (type, name)
710 #
711 # Find a named parameter in a parameter list
712 def getParamByName(self, params, name):
713 for param in params:
714 if param.name == name:
715 return param
716 return None
717 #
718 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
719 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
720 def parseLateXMath(self, source):
721 name = 'ERROR'
722 decoratedName = 'ERROR'
723 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700724 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
725 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 -0600726 if not match or match.group(1) != match.group(4):
727 raise 'Unrecognized latexmath expression'
728 name = match.group(2)
729 decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3))
730 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700731 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700732 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600733 name = match.group(1)
734 decoratedName = '{}/{}'.format(*match.group(1, 2))
735 return name, decoratedName
736 #
737 # Get the length paramater record for the specified parameter name
738 def getLenParam(self, params, name):
739 lenParam = None
740 if name:
741 if '->' in name:
742 # The count is obtained by dereferencing a member of a struct parameter
743 lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False,
744 isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None,
745 condition=None, cdecl=None)
746 elif 'latexmath' in name:
747 lenName, decoratedName = self.parseLateXMath(name)
748 lenParam = self.getParamByName(params, lenName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600749 else:
750 lenParam = self.getParamByName(params, name)
751 return lenParam
752 #
753 # Convert a vulkan.h command declaration into a parameter_validation.h definition
754 def getCmdDef(self, cmd):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600755 # Strip the trailing ';' and split into individual lines
756 lines = cmd.cdecl[:-1].split('\n')
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600757 cmd_hdr = '\n'.join(lines)
758 return cmd_hdr
Mark Lobodzinski85672672016-10-13 08:36:42 -0600759 #
760 # Generate the code to check for a NULL dereference before calling the
761 # validation function
762 def genCheckedLengthCall(self, name, exprs):
763 count = name.count('->')
764 if count:
765 checkedExpr = []
766 localIndent = ''
767 elements = name.split('->')
768 # Open the if expression blocks
769 for i in range(0, count):
770 checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1])))
771 localIndent = self.incIndent(localIndent)
772 # Add the validation expression
773 for expr in exprs:
774 checkedExpr.append(localIndent + expr)
775 # Close the if blocks
776 for i in range(0, count):
777 localIndent = self.decIndent(localIndent)
778 checkedExpr.append(localIndent + '}\n')
779 return [checkedExpr]
780 # No if statements were required
781 return exprs
782 #
783 # Generate code to check for a specific condition before executing validation code
784 def genConditionalCall(self, prefix, condition, exprs):
785 checkedExpr = []
786 localIndent = ''
787 formattedCondition = condition.format(prefix)
788 checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition))
789 checkedExpr.append(localIndent + '{\n')
790 localIndent = self.incIndent(localIndent)
791 for expr in exprs:
792 checkedExpr.append(localIndent + expr)
793 localIndent = self.decIndent(localIndent)
794 checkedExpr.append(localIndent + '}\n')
795 return [checkedExpr]
796 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600797 # Get VUID identifier from implicit VUID tag
798 def GetVuid(self, vuid_string):
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600799 if '->' in vuid_string:
800 return "VALIDATION_ERROR_UNDEFINED"
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600801 vuid_num = self.IdToHex(convertVUID(vuid_string))
802 if vuid_num in self.valid_vuids:
803 vuid = "VALIDATION_ERROR_%s" % vuid_num
804 else:
805 vuid = "VALIDATION_ERROR_UNDEFINED"
806 return vuid
807 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600808 # Generate the sType check string
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600809 def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600810 checkExpr = []
811 stype = self.structTypes[value.type]
812 if lenValue:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600813 vuid_name = struct_type_name if struct_type_name is not None else funcPrintName
814 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600815 # This is an array with a pointer to a count value
816 if lenValue.ispointer:
817 # 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 -0600818 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 -0600819 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 -0600820 # This is an array with an integer count value
821 else:
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600822 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 -0600823 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 -0600824 # This is an individual struct
825 else:
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600826 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600827 checkExpr.append('skip |= validate_struct_type(local_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {}, {});\n'.format(
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600828 funcPrintName, valuePrintName, prefix, valueRequired, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600829 return checkExpr
830 #
831 # Generate the handle check string
832 def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
833 checkExpr = []
834 if lenValue:
835 if lenValue.ispointer:
836 # This is assumed to be an output array with a pointer to a count value
837 raise('Unsupported parameter validation case: Output handle array elements are not NULL checked')
838 else:
839 # This is an array with an integer count value
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600840 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 -0600841 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
842 else:
843 # This is assumed to be an output handle pointer
844 raise('Unsupported parameter validation case: Output handles are not NULL checked')
845 return checkExpr
846 #
847 # Generate check string for an array of VkFlags values
848 def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
849 checkExpr = []
850 flagBitsName = value.type.replace('Flags', 'FlagBits')
851 if not flagBitsName in self.flagBits:
852 raise('Unsupported parameter validation case: array of reserved VkFlags')
853 else:
854 allFlags = 'All' + flagBitsName
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600855 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 -0600856 return checkExpr
857 #
858 # Generate pNext check string
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600859 def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600860 checkExpr = []
861 # Generate an array of acceptable VkStructureType values for pNext
862 extStructCount = 0
863 extStructVar = 'NULL'
864 extStructNames = 'NULL'
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600865 vuid = self.GetVuid("VUID-%s-pNext-pNext" % struct_type_name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600866 if value.extstructs:
Mike Schuchardtc73d07e2017-07-12 10:10:01 -0600867 extStructVar = 'allowed_structs_{}'.format(struct_type_name)
868 extStructCount = 'ARRAY_SIZE({})'.format(extStructVar)
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600869 extStructNames = '"' + ', '.join(value.extstructs) + '"'
870 checkExpr.append('const VkStructureType {}[] = {{ {} }};\n'.format(extStructVar, ', '.join([self.getStructType(s) for s in value.extstructs])))
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600871 checkExpr.append('skip |= validate_struct_pnext(local_data->report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion, {});\n'.format(
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600872 funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600873 return checkExpr
874 #
875 # Generate the pointer check string
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600876 def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600877 checkExpr = []
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600878 vuid_tag_name = struct_type_name if struct_type_name is not None else funcPrintName
Mark Lobodzinski85672672016-10-13 08:36:42 -0600879 if lenValue:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600880 count_required_vuid = self.GetVuid("VUID-%s-%s-arraylength" % (vuid_tag_name, lenValue.name))
881 array_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600882 # This is an array with a pointer to a count value
883 if lenValue.ispointer:
884 # If count and array parameters are optional, there will be no validation
885 if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true':
886 # 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 -0600887 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 -0600888 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 -0600889 # This is an array with an integer count value
890 else:
891 # If count and array parameters are optional, there will be no validation
892 if valueRequired == 'true' or lenValueRequired == 'true':
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600893 if value.type != 'char':
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600894 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 -0600895 funcPrintName, lenValueRequired, valueRequired, count_required_vuid, array_required_vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
896 else:
897 # Arrays of strings receive special processing
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600898 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 -0600899 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 -0600900 if checkExpr:
901 if lenValue and ('->' in lenValue.name):
902 # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count
903 checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr)
904 # This is an individual struct that is not allowed to be NULL
905 elif not value.isoptional:
906 # Function pointers need a reinterpret_cast to void*
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600907 ptr_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600908 if value.type[:4] == 'PFN_':
Mark Lobodzinski02fa1972017-06-28 14:46:14 -0600909 allocator_dict = {'pfnAllocation': '002004f0',
910 'pfnReallocation': '002004f2',
911 'pfnFree': '002004f4',
912 'pfnInternalAllocation': '002004f6'
913 }
914 vuid = allocator_dict.get(value.name)
915 if vuid is not None:
916 ptr_required_vuid = 'VALIDATION_ERROR_%s' % vuid
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600917 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 -0600918 else:
Mark Lobodzinskid4950072017-08-01 13:02:20 -0600919 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 -0600920 return checkExpr
921 #
922 # Process struct member validation code, performing name suibstitution if required
923 def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec):
924 # Build format specifier list
925 kwargs = {}
926 if '{postProcPrefix}' in line:
927 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
928 if type(memberDisplayNamePrefix) is tuple:
929 kwargs['postProcPrefix'] = 'ParameterName('
930 else:
931 kwargs['postProcPrefix'] = postProcSpec['ppp']
932 if '{postProcSuffix}' in line:
933 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
934 if type(memberDisplayNamePrefix) is tuple:
935 kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
936 else:
937 kwargs['postProcSuffix'] = postProcSpec['pps']
938 if '{postProcInsert}' in line:
939 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
940 if type(memberDisplayNamePrefix) is tuple:
941 kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
942 else:
943 kwargs['postProcInsert'] = postProcSpec['ppi']
944 if '{funcName}' in line:
945 kwargs['funcName'] = funcName
946 if '{valuePrefix}' in line:
947 kwargs['valuePrefix'] = memberNamePrefix
948 if '{displayNamePrefix}' in line:
949 # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class
950 if type(memberDisplayNamePrefix) is tuple:
951 kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0]
952 else:
953 kwargs['displayNamePrefix'] = memberDisplayNamePrefix
954
955 if kwargs:
956 # Need to escape the C++ curly braces
957 if 'IndexVector' in line:
958 line = line.replace('IndexVector{ ', 'IndexVector{{ ')
959 line = line.replace(' }),', ' }}),')
960 return line.format(**kwargs)
961 return line
962 #
963 # Process struct validation code for inclusion in function or parent struct validation code
964 def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec):
965 for line in lines:
966 if output:
967 output[-1] += '\n'
968 if type(line) is list:
969 for sub in line:
970 output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
971 else:
972 output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
973 return output
974 #
975 # Process struct pointer/array validation code, perfoeming name substitution if required
976 def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec):
977 expr = []
978 expr.append('if ({}{} != NULL)\n'.format(prefix, value.name))
979 expr.append('{')
980 indent = self.incIndent(None)
981 if lenValue:
982 # Need to process all elements in the array
983 indexName = lenValue.name.replace('Count', 'Index')
984 expr[-1] += '\n'
Mark Young39389872017-01-19 21:10:49 -0700985 if lenValue.ispointer:
986 # If the length value is a pointer, de-reference it for the count.
987 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < *{}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
988 else:
989 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600990 expr.append(indent + '{')
991 indent = self.incIndent(indent)
992 # Prefix for value name to display in error message
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700993 if value.ispointer == 2:
994 memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName)
995 memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName)
996 else:
997 memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName)
998 memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600999 else:
1000 memberNamePrefix = '{}{}->'.format(prefix, value.name)
1001 memberDisplayNamePrefix = '{}->'.format(valueDisplayName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001002 # Expand the struct validation lines
1003 expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001004 if lenValue:
1005 # Close if and for scopes
1006 indent = self.decIndent(indent)
1007 expr.append(indent + '}\n')
1008 expr.append('}\n')
1009 return expr
1010 #
1011 # Generate the parameter checking code
1012 def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName):
1013 lines = [] # Generated lines of code
1014 unused = [] # Unused variable names
1015 for value in values:
1016 usedLines = []
1017 lenParam = None
1018 #
1019 # 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.
1020 postProcSpec = {}
1021 postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}'
1022 postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}'
1023 postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}'
1024 #
1025 # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name
1026 valueDisplayName = '{}{}'.format(displayNamePrefix, value.name)
1027 #
1028 # Check for NULL pointers, ignore the inout count parameters that
1029 # will be validated with their associated array
1030 if (value.ispointer or value.isstaticarray) and not value.iscount:
Mark Lobodzinski85672672016-10-13 08:36:42 -06001031 # Parameters for function argument generation
1032 req = 'true' # Paramerter cannot be NULL
1033 cpReq = 'true' # Count pointer cannot be NULL
1034 cvReq = 'true' # Count value cannot be 0
1035 lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied
Mark Lobodzinski85672672016-10-13 08:36:42 -06001036 # Generate required/optional parameter strings for the pointer and count values
1037 if value.isoptional:
1038 req = 'false'
1039 if value.len:
1040 # The parameter is an array with an explicit count parameter
1041 lenParam = self.getLenParam(values, value.len)
1042 lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name)
1043 if lenParam.ispointer:
1044 # Count parameters that are pointers are inout
1045 if type(lenParam.isoptional) is list:
1046 if lenParam.isoptional[0]:
1047 cpReq = 'false'
1048 if lenParam.isoptional[1]:
1049 cvReq = 'false'
1050 else:
1051 if lenParam.isoptional:
1052 cpReq = 'false'
1053 else:
1054 if lenParam.isoptional:
1055 cvReq = 'false'
1056 #
1057 # The parameter will not be processes when tagged as 'noautovalidity'
1058 # For the pointer to struct case, the struct pointer will not be validated, but any
1059 # members not tagged as 'noatuvalidity' will be validated
1060 if value.noautovalidity:
1061 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1062 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1063 else:
Mark Lobodzinski85672672016-10-13 08:36:42 -06001064 # If this is a pointer to a struct with an sType field, verify the type
1065 if value.type in self.structTypes:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -06001066 usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001067 # 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
1068 elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam):
1069 usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1070 elif value.type in self.flags and value.isconst:
1071 usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1072 elif value.isbool and value.isconst:
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001073 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 -06001074 elif value.israngedenum and value.isconst:
Mark Lobodzinskiaff801e2017-07-25 15:29:57 -06001075 enum_value_list = 'All%sEnums' % value.type
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001076 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 -06001077 elif value.name == 'pNext':
1078 # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml
1079 if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']:
Mark Lobodzinski3c828522017-06-26 13:05:57 -06001080 usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001081 else:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -06001082 usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001083 # If this is a pointer to a struct (input), see if it contains members that need to be checked
1084 if value.type in self.validatedStructs and value.isconst:
1085 usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec))
1086 # Non-pointer types
1087 else:
Mark Lobodzinski85672672016-10-13 08:36:42 -06001088 # The parameter will not be processes when tagged as 'noautovalidity'
1089 # For the struct case, the struct type will not be validated, but any
1090 # members not tagged as 'noatuvalidity' will be validated
1091 if value.noautovalidity:
1092 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1093 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1094 else:
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001095 vuid_name_tag = structTypeName if structTypeName is not None else funcName
Mark Lobodzinski85672672016-10-13 08:36:42 -06001096 if value.type in self.structTypes:
1097 stype = self.structTypes[value.type]
Mark Lobodzinski06954ea2017-06-21 12:21:45 -06001098 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001099 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 -06001100 funcName, valueDisplayName, valuePrefix, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001101 elif value.type in self.handleTypes:
1102 if not self.isHandleOptional(value, None):
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001103 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 -06001104 elif value.type in self.flags:
1105 flagBitsName = value.type.replace('Flags', 'FlagBits')
1106 if not flagBitsName in self.flagBits:
Mark Lobodzinskid0b0c512017-06-28 12:06:41 -06001107 vuid = self.GetVuid("VUID-%s-%s-zerobitmask" % (vuid_name_tag, value.name))
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001108 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 -06001109 else:
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001110 if value.isoptional:
1111 flagsRequired = 'false'
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001112 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001113 else:
1114 flagsRequired = 'true'
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001115 vuid = self.GetVuid("VUID-%s-%s-requiredbitmask" % (vuid_name_tag, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001116 allFlagsName = 'All' + flagBitsName
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001117 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 -06001118 elif value.type in self.flagBits:
1119 flagsRequired = 'false' if value.isoptional else 'true'
1120 allFlagsName = 'All' + value.type
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001121 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001122 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 -06001123 elif value.isbool:
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001124 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 -06001125 elif value.israngedenum:
Mark Lobodzinski42eb3c32017-06-28 11:47:22 -06001126 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinski74cb45f2017-07-25 15:10:29 -06001127 enum_value_list = 'All%sEnums' % value.type
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001128 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 -06001129 # If this is a struct, see if it contains members that need to be checked
1130 if value.type in self.validatedStructs:
1131 memberNamePrefix = '{}{}.'.format(valuePrefix, value.name)
1132 memberDisplayNamePrefix = '{}.'.format(valueDisplayName)
1133 usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001134 # Append the parameter check to the function body for the current command
1135 if usedLines:
1136 # Apply special conditional checks
1137 if value.condition:
1138 usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines)
1139 lines += usedLines
1140 elif not value.iscount:
1141 # If no expression was generated for this value, it is unreferenced by the validation function, unless
1142 # it is an array count, which is indirectly referenced for array valiadation.
1143 unused.append(value.name)
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001144 if not lines:
1145 lines.append('// No xml-driven validation\n')
Mark Lobodzinski85672672016-10-13 08:36:42 -06001146 return lines, unused
1147 #
1148 # Generate the struct member check code from the captured data
1149 def processStructMemberData(self):
1150 indent = self.incIndent(None)
1151 for struct in self.structMembers:
1152 #
1153 # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented
1154 lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name)
1155 if lines:
1156 self.validatedStructs[struct.name] = lines
1157 #
1158 # Generate the command param check code from the captured data
1159 def processCmdData(self):
1160 indent = self.incIndent(None)
1161 for command in self.commands:
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001162 just_validate = False
1163 if command.name in self.validate_only:
1164 just_validate = True
Mark Lobodzinski85672672016-10-13 08:36:42 -06001165 # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance)
1166 startIndex = 0 if command.name == 'vkCreateInstance' else 1
1167 lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None)
Mark Lobodzinski3f10bfe2017-08-23 15:23:23 -06001168 # Cannot validate extension dependencies for device extension APIs having a physical device as their dispatchable object
Mike Schuchardtafd00482017-08-24 15:15:02 -06001169 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 -06001170 ext_test = ''
Mike Schuchardtafd00482017-08-24 15:15:02 -06001171 for ext in self.required_extensions[command.name]:
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001172 ext_name_define = ''
1173 ext_enable_name = ''
1174 for extension in self.registry.extensions:
1175 if extension.attrib['name'] == ext:
1176 ext_name_define = extension[0][1].get('name')
1177 ext_enable_name = ext_name_define.lower()
1178 ext_enable_name = re.sub('_extension_name', '', ext_enable_name)
1179 break
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001180 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 -06001181 lines.insert(0, ext_test)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001182 if lines:
1183 cmdDef = self.getCmdDef(command) + '\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001184 # For a validation-only routine, change the function declaration
1185 if just_validate:
1186 jv_def = '// Generated function handles validation only -- API definition is in non-generated source\n'
1187 jv_def += 'extern %s\n\n' % command.cdecl
1188 cmdDef = 'bool parameter_validation_' + cmdDef.split('VKAPI_CALL ',1)[1]
1189 if command.name == 'vkCreateInstance':
1190 cmdDef = cmdDef.replace('(\n', '(\n VkInstance instance,\n')
1191 cmdDef = jv_def + cmdDef
Mark Lobodzinski85672672016-10-13 08:36:42 -06001192 cmdDef += '{\n'
Mark Lobodzinski26112592017-05-30 12:02:17 -06001193
Gabríel Arthúr Péturssona3b5d672017-08-19 16:44:45 +00001194 # Add list of commands to skip -- just generate the routine signature and put the manual source in parameter_validation_utils.cpp
1195 if command.params[0].type in ["VkInstance", "VkPhysicalDevice"] or command.name == 'vkCreateInstance':
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001196 map_name = 'instance_layer_data_map'
1197 map_type = 'instance_layer_data'
1198 else:
1199 map_name = 'layer_data_map'
1200 map_type = 'layer_data'
1201 instance_param = command.params[0].name
1202 if command.name == 'vkCreateInstance':
1203 instance_param = 'instance'
1204 layer_data = ' %s *local_data = GetLayerDataPtr(get_dispatch_key(%s), %s);\n' % (map_type, instance_param, map_name)
1205 cmdDef += layer_data
1206 cmdDef += '%sbool skip = false;\n' % indent
1207 if not just_validate:
1208 if command.result != '':
Jamie Madillfc315192017-11-08 14:11:26 -05001209 if command.result == "VkResult":
1210 cmdDef += indent + '%s result = VK_ERROR_VALIDATION_FAILED_EXT;\n' % command.result
1211 elif command.result == "VkBool32":
1212 cmdDef += indent + '%s result = VK_FALSE;\n' % command.result
1213 else:
1214 raise Exception("Unknown result type: " + command.result)
1215
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001216 cmdDef += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % indent
Mark Lobodzinski85672672016-10-13 08:36:42 -06001217 for line in lines:
1218 cmdDef += '\n'
1219 if type(line) is list:
1220 for sub in line:
1221 cmdDef += indent + sub
1222 else:
1223 cmdDef += indent + line
1224 cmdDef += '\n'
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001225 if not just_validate:
1226 # Generate parameter list for manual fcn and down-chain calls
1227 params_text = ''
1228 for param in command.params:
1229 params_text += '%s, ' % param.name
1230 params_text = params_text[:-2]
1231 # Generate call to manual function if its function pointer is non-null
Mark Lobodzinski78a12a92017-08-08 14:16:51 -06001232 cmdDef += '%sPFN_manual_%s custom_func = (PFN_manual_%s)custom_functions["%s"];\n' % (indent, command.name, command.name, command.name)
1233 cmdDef += '%sif (custom_func != nullptr) {\n' % indent
1234 cmdDef += ' %sskip |= custom_func(%s);\n' % (indent, params_text)
Mark Lobodzinskid4950072017-08-01 13:02:20 -06001235 cmdDef += '%s}\n\n' % indent
1236 # Release the validation lock
1237 cmdDef += '%slock.unlock();\n' % indent
1238 # Generate skip check and down-chain call
1239 cmdDef += '%sif (!skip) {\n' % indent
1240 down_chain_call = ' %s' % indent
1241 if command.result != '':
1242 down_chain_call += ' result = '
1243 # Generate down-chain API call
1244 api_call = '%s(%s);' % (command.name, params_text)
1245 down_chain_call += 'local_data->dispatch_table.%s\n' % api_call[2:]
1246 cmdDef += down_chain_call
1247 cmdDef += '%s}\n' % indent
1248 if command.result != '':
1249 cmdDef += '%sreturn result;\n' % indent
1250 else:
1251 cmdDef += '%sreturn skip;\n' % indent
Mark Lobodzinski85672672016-10-13 08:36:42 -06001252 cmdDef += '}\n'
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001253 self.validation.append(cmdDef)