blob: 9a613d1f44f002ee6c1d0c4610972a8b1d776a78 [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
Mark Lobodzinski85672672016-10-13 08:36:42 -060029
30
31# ParamCheckerGeneratorOptions - subclass of GeneratorOptions.
32#
33# Adds options used by ParamCheckerOutputGenerator object during Parameter
34# validation layer generation.
35#
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
64class ParamCheckerGeneratorOptions(GeneratorOptions):
65 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
104# ParamCheckerOutputGenerator - subclass of OutputGenerator.
105# 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)
120class ParamCheckerOutputGenerator(OutputGenerator):
121 """Generate ParamChecker code based on XML element attributes"""
122 # This is an ordered list of sections in the header file.
123 ALL_SECTIONS = ['command']
124 def __init__(self,
125 errFile = sys.stderr,
126 warnFile = sys.stderr,
127 diagFile = sys.stdout):
128 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
129 self.INDENT_SPACES = 4
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',
140 'vkCreateDebugReportCallbackEXT',
141 'vkDebugReportMessageEXT']
Dustin Gravesce68f082017-03-30 15:42:16 -0600142 # Structure fields to ignore
143 self.structMemberBlacklist = { 'VkWriteDescriptorSet' : ['dstSet'] }
Mark Lobodzinski85672672016-10-13 08:36:42 -0600144 # Validation conditions for some special case struct members that are conditionally validated
145 self.structMemberValidationConditions = { 'VkPipelineColorBlendStateCreateInfo' : { 'logicOp' : '{}logicOpEnable == VK_TRUE' } }
146 # Header version
147 self.headerVersion = None
148 # Internal state - accumulators for different inner block text
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600149 self.validation = [] # Text comprising the main per-api parameter validation routines
Mark Lobodzinski85672672016-10-13 08:36:42 -0600150 self.structNames = [] # List of Vulkan struct typenames
151 self.stypes = [] # Values from the VkStructureType enumeration
152 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
153 self.handleTypes = set() # Set of handle type names
154 self.commands = [] # List of CommandData records for all Vulkan commands
155 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
156 self.validatedStructs = dict() # Map of structs type names to generated validation code for that struct type
157 self.enumRanges = dict() # Map of enum name to BEGIN/END range values
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600158 self.enumValueLists = '' # String containing enumerated type map definitions
Mark Lobodzinski85672672016-10-13 08:36:42 -0600159 self.flags = set() # Map of flags typenames
160 self.flagBits = dict() # Map of flag bits typename to list of values
Chris Forbes78ea32d2016-11-28 11:14:17 +1300161 self.newFlags = set() # Map of flags typenames /defined in the current feature/
Mark Lobodzinski26112592017-05-30 12:02:17 -0600162 self.required_extensions = [] # List of required extensions for the current extension
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600163 self.extension_type = '' # Type of active feature (extension), device or instance
164 self.extension_names = dict() # Dictionary of extension names to extension name defines
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600165 self.valid_vuids = set() # Set of all valid VUIDs
Mark Lobodzinski85672672016-10-13 08:36:42 -0600166 # Named tuples to store struct and command data
167 self.StructType = namedtuple('StructType', ['name', 'value'])
168 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isbool', 'israngedenum',
169 'isconst', 'isoptional', 'iscount', 'noautovalidity', 'len', 'extstructs',
170 'condition', 'cdecl'])
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600171 self.CommandData = namedtuple('CommandData', ['name', 'params', 'cdecl', 'extension_type'])
Mark Lobodzinski85672672016-10-13 08:36:42 -0600172 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600173
174 self.vuid_file = None
175 # Cover cases where file is built from scripts directory, Lin/Win, or Android build structure
176 vuid_filename_locations = [
Mark Lobodzinskifc20c4d2017-07-03 15:50:39 -0600177 './vk_validation_error_messages.h',
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600178 '../layers/vk_validation_error_messages.h',
179 '../../layers/vk_validation_error_messages.h',
180 '../../../layers/vk_validation_error_messages.h',
181 ]
182 for vuid_filename in vuid_filename_locations:
183 if os.path.isfile(vuid_filename):
184 self.vuid_file = open(vuid_filename, "r")
185 break
186 if self.vuid_file == None:
187 print("Error: Could not find vk_validation_error_messages.h")
188 quit()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600189 #
190 def incIndent(self, indent):
191 inc = ' ' * self.INDENT_SPACES
192 if indent:
193 return indent + inc
194 return inc
195 #
196 def decIndent(self, indent):
197 if indent and (len(indent) > self.INDENT_SPACES):
198 return indent[:-self.INDENT_SPACES]
199 return ''
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600200 # Convert decimal number to 8 digit hexadecimal lower-case representation
201 def IdToHex(self, dec_num):
202 if dec_num > 4294967295:
203 print ("ERROR: Decimal # %d can't be represented in 8 hex digits" % (dec_num))
204 sys.exit()
205 hex_num = hex(dec_num)
206 return hex_num[2:].zfill(8)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600207 #
208 def beginFile(self, genOpts):
209 OutputGenerator.beginFile(self, genOpts)
210 # C-specific
211 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600212 # Open vk_validation_error_messages.h file to verify computed VUIDs
213 for line in self.vuid_file:
214 # Grab hex number from enum definition
215 vuid_list = line.split('0x')
216 # If this is a valid enumeration line, remove trailing comma and CR
217 if len(vuid_list) == 2:
218 vuid_num = vuid_list[1][:-2]
219 # Make sure this is a good hex number before adding to set
220 if len(vuid_num) == 8 and all(c in string.hexdigits for c in vuid_num):
221 self.valid_vuids.add(vuid_num)
222 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600223 # User-supplied prefix text, if any (list of strings)
224 if (genOpts.prefixText):
225 for s in genOpts.prefixText:
226 write(s, file=self.outFile)
227 #
228 # Multiple inclusion protection & C++ wrappers.
229 if (genOpts.protectFile and self.genOpts.filename):
230 headerSym = re.sub('\.h', '_H', os.path.basename(self.genOpts.filename)).upper()
231 write('#ifndef', headerSym, file=self.outFile)
232 write('#define', headerSym, '1', file=self.outFile)
233 self.newline()
234 #
235 # Headers
236 write('#include <string>', file=self.outFile)
237 self.newline()
238 write('#include "vulkan/vulkan.h"', file=self.outFile)
239 write('#include "vk_layer_extension_utils.h"', file=self.outFile)
240 write('#include "parameter_validation_utils.h"', file=self.outFile)
241 #
242 # Macros
243 self.newline()
244 write('#ifndef UNUSED_PARAMETER', file=self.outFile)
245 write('#define UNUSED_PARAMETER(x) (void)(x)', file=self.outFile)
246 write('#endif // UNUSED_PARAMETER', file=self.outFile)
247 #
248 # Namespace
249 self.newline()
250 write('namespace parameter_validation {', file = self.outFile)
251 def endFile(self):
252 # C-specific
253 self.newline()
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600254 write(self.enumValueLists, file=self.outFile)
255 self.newline()
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600256 commands_text = '\n'.join(self.validation)
257 write(commands_text, file=self.outFile)
258 self.newline()
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700259 # Output declarations and record intercepted procedures
260 write('// Declarations', file=self.outFile)
261 write('\n'.join(self.declarations), file=self.outFile)
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600262 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
263 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700264 write('\n'.join(self.intercepts), file=self.outFile)
265 write('};\n', file=self.outFile)
266 self.newline()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600267 # Namespace
268 write('} // namespace parameter_validation', file = self.outFile)
269 # Finish C++ wrapper and multiple inclusion protection
270 if (self.genOpts.protectFile and self.genOpts.filename):
271 self.newline()
272 write('#endif', file=self.outFile)
273 # Finish processing in superclass
274 OutputGenerator.endFile(self)
275 def beginFeature(self, interface, emit):
276 # Start processing in superclass
277 OutputGenerator.beginFeature(self, interface, emit)
278 # C-specific
279 # Accumulate includes, defines, types, enums, function pointer typedefs,
280 # end function prototypes separately for this feature. They're only
281 # printed in endFeature().
282 self.headerVersion = None
Mark Lobodzinski85672672016-10-13 08:36:42 -0600283 self.structNames = []
284 self.stypes = []
285 self.structTypes = dict()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600286 self.commands = []
287 self.structMembers = []
Chris Forbes78ea32d2016-11-28 11:14:17 +1300288 self.newFlags = set()
Mark Lobodzinski26112592017-05-30 12:02:17 -0600289 # Save list of required extensions for this extension
290 self.required_extensions = []
291 if self.featureName != "VK_VERSION_1_0":
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600292 # Save Name Define to get correct enable name later
293 nameElem = interface[0][1]
294 name = nameElem.get('name')
295 self.extension_names[self.featureName] = name
296 # This extension is the first dependency for this command
Mark Lobodzinski26112592017-05-30 12:02:17 -0600297 self.required_extensions.append(self.featureName)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600298 # Add any defined extension dependencies to the dependency list for this command
Mark Lobodzinski26112592017-05-30 12:02:17 -0600299 required_extensions = interface.get('requires')
300 if required_extensions is not None:
301 self.required_extensions.extend(required_extensions.split(','))
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600302 # And note if this is an Instance or Device extension
303 self.extension_type = interface.get('type')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600304 def endFeature(self):
305 # C-specific
306 # Actually write the interface to the output file.
307 if (self.emit):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600308 # If type declarations are needed by other features based on
309 # this one, it may be necessary to suppress the ExtraProtect,
310 # or move it below the 'for section...' loop.
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600311 ifdef = ''
Mark Lobodzinski85672672016-10-13 08:36:42 -0600312 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600313 ifdef = '#ifdef %s\n' % self.featureExtraProtect
314 self.validation.append(ifdef)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600315 # Generate the struct member checking code from the captured data
316 self.processStructMemberData()
317 # Generate the command parameter checking code from the captured data
318 self.processCmdData()
319 # Write the declaration for the HeaderVersion
320 if self.headerVersion:
321 write('const uint32_t GeneratedHeaderVersion = {};'.format(self.headerVersion), file=self.outFile)
322 self.newline()
323 # Write the declarations for the VkFlags values combining all flag bits
Chris Forbes78ea32d2016-11-28 11:14:17 +1300324 for flag in sorted(self.newFlags):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600325 flagBits = flag.replace('Flags', 'FlagBits')
326 if flagBits in self.flagBits:
327 bits = self.flagBits[flagBits]
328 decl = 'const {} All{} = {}'.format(flag, flagBits, bits[0])
329 for bit in bits[1:]:
330 decl += '|' + bit
331 decl += ';'
332 write(decl, file=self.outFile)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600333 endif = '\n'
Mark Lobodzinski85672672016-10-13 08:36:42 -0600334 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600335 endif = '#endif // %s\n' % self.featureExtraProtect
336 self.validation.append(endif)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600337 # Finish processing in superclass
338 OutputGenerator.endFeature(self)
339 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600340 # Type generation
341 def genType(self, typeinfo, name):
342 OutputGenerator.genType(self, typeinfo, name)
343 typeElem = typeinfo.elem
344 # If the type is a struct type, traverse the imbedded <member> tags
345 # generating a structure. Otherwise, emit the tag text.
346 category = typeElem.get('category')
347 if (category == 'struct' or category == 'union'):
348 self.structNames.append(name)
349 self.genStruct(typeinfo, name)
350 elif (category == 'handle'):
351 self.handleTypes.add(name)
352 elif (category == 'bitmask'):
353 self.flags.add(name)
Chris Forbes78ea32d2016-11-28 11:14:17 +1300354 self.newFlags.add(name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600355 elif (category == 'define'):
356 if name == 'VK_HEADER_VERSION':
357 nameElem = typeElem.find('name')
358 self.headerVersion = noneStr(nameElem.tail).strip()
359 #
360 # Struct parameter check generation.
361 # This is a special case of the <type> tag where the contents are
362 # interpreted as a set of <member> tags instead of freeform C
363 # C type declarations. The <member> tags are just like <param>
364 # tags - they are a declaration of a struct or union member.
365 # Only simple member declarations are supported (no nested
366 # structs etc.)
367 def genStruct(self, typeinfo, typeName):
368 OutputGenerator.genStruct(self, typeinfo, typeName)
369 conditions = self.structMemberValidationConditions[typeName] if typeName in self.structMemberValidationConditions else None
370 members = typeinfo.elem.findall('.//member')
371 #
372 # Iterate over members once to get length parameters for arrays
373 lens = set()
374 for member in members:
375 len = self.getLen(member)
376 if len:
377 lens.add(len)
378 #
379 # Generate member info
380 membersInfo = []
381 for member in members:
382 # Get the member's type and name
383 info = self.getTypeNameTuple(member)
384 type = info[0]
385 name = info[1]
386 stypeValue = ''
387 cdecl = self.makeCParamDecl(member, 0)
388 # Process VkStructureType
389 if type == 'VkStructureType':
390 # Extract the required struct type value from the comments
391 # embedded in the original text defining the 'typeinfo' element
392 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
393 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
394 if result:
395 value = result.group(0)
396 else:
397 value = self.genVkStructureType(typeName)
398 # Store the required type value
399 self.structTypes[typeName] = self.StructType(name=name, value=value)
400 #
401 # Store pointer/array/string info
402 # Check for parameter name in lens set
403 iscount = False
404 if name in lens:
405 iscount = True
406 # The pNext members are not tagged as optional, but are treated as
407 # optional for parameter NULL checks. Static array members
408 # are also treated as optional to skip NULL pointer validation, as
409 # they won't be NULL.
410 isstaticarray = self.paramIsStaticArray(member)
411 isoptional = False
412 if self.paramIsOptional(member) or (name == 'pNext') or (isstaticarray):
413 isoptional = True
Dustin Gravesce68f082017-03-30 15:42:16 -0600414 # Determine if value should be ignored by code generation.
415 noautovalidity = False
416 if (member.attrib.get('noautovalidity') is not None) or ((typeName in self.structMemberBlacklist) and (name in self.structMemberBlacklist[typeName])):
417 noautovalidity = True
Mark Lobodzinski85672672016-10-13 08:36:42 -0600418 membersInfo.append(self.CommandParam(type=type, name=name,
419 ispointer=self.paramIsPointer(member),
420 isstaticarray=isstaticarray,
421 isbool=True if type == 'VkBool32' else False,
422 israngedenum=True if type in self.enumRanges else False,
423 isconst=True if 'const' in cdecl else False,
424 isoptional=isoptional,
425 iscount=iscount,
Dustin Gravesce68f082017-03-30 15:42:16 -0600426 noautovalidity=noautovalidity,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600427 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600428 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600429 condition=conditions[name] if conditions and name in conditions else None,
430 cdecl=cdecl))
431 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
432 #
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600433 # Capture group (e.g. C "enum" type) info to be used for param check code generation.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600434 # These are concatenated together with other types.
435 def genGroup(self, groupinfo, groupName):
436 OutputGenerator.genGroup(self, groupinfo, groupName)
437 groupElem = groupinfo.elem
438 #
439 # Store the sType values
440 if groupName == 'VkStructureType':
441 for elem in groupElem.findall('enum'):
442 self.stypes.append(elem.get('name'))
443 elif 'FlagBits' in groupName:
444 bits = []
445 for elem in groupElem.findall('enum'):
446 bits.append(elem.get('name'))
447 if bits:
448 self.flagBits[groupName] = bits
449 else:
450 # Determine if begin/end ranges are needed (we don't do this for VkStructureType, which has a more finely grained check)
451 expandName = re.sub(r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)',r'\1_\2',groupName).upper()
452 expandPrefix = expandName
453 expandSuffix = ''
454 expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName)
455 if expandSuffixMatch:
456 expandSuffix = '_' + expandSuffixMatch.group()
457 # Strip off the suffix from the prefix
458 expandPrefix = expandName.rsplit(expandSuffix, 1)[0]
459 isEnum = ('FLAG_BITS' not in expandPrefix)
460 if isEnum:
461 self.enumRanges[groupName] = (expandPrefix + '_BEGIN_RANGE' + expandSuffix, expandPrefix + '_END_RANGE' + expandSuffix)
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600462 # Create definition for a list containing valid enum values for this enumerated type
463 enum_entry = 'const std::vector<%s> All%sEnums = {' % (groupName, groupName)
464 for enum in groupElem:
465 name = enum.get('name')
Mark Lobodzinski117d88f2017-07-27 12:09:08 -0600466 if name is not None and enum.get('supported') != 'disabled':
467 enum_entry += '%s, ' % name
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600468 enum_entry += '};\n'
469 self.enumValueLists += enum_entry
Mark Lobodzinski85672672016-10-13 08:36:42 -0600470 #
Mark Lobodzinskif31e0422017-07-25 14:29:42 -0600471 # Capture command parameter info to be used for param check code generation.
Mark Lobodzinski85672672016-10-13 08:36:42 -0600472 def genCmd(self, cmdinfo, name):
473 OutputGenerator.genCmd(self, cmdinfo, name)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700474 interface_functions = [
475 'vkEnumerateInstanceLayerProperties',
476 'vkEnumerateInstanceExtensionProperties',
477 'vkEnumerateDeviceLayerProperties',
Mark Lobodzinski099b3b62017-02-08 16:04:35 -0700478 'vkCmdDebugMarkerEndEXT', # No validation!
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700479 ]
480 # Record that the function will be intercepted
481 if name not in interface_functions:
482 if (self.featureExtraProtect != None):
483 self.declarations += [ '#ifdef %s' % self.featureExtraProtect ]
484 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600485 self.intercepts += [ ' {"%s", (void*)%s},' % (name,name[2:]) ]
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700486 decls = self.makeCDecls(cmdinfo.elem)
487 # Strip off 'vk' from API name
488 self.declarations += [ '%s' % decls[0].replace("VKAPI_CALL vk", "VKAPI_CALL ") ]
489 if (self.featureExtraProtect != None):
490 self.intercepts += [ '#endif' ]
491 self.declarations += [ '#endif' ]
Mark Lobodzinski85672672016-10-13 08:36:42 -0600492 if name not in self.blacklist:
493 params = cmdinfo.elem.findall('param')
494 # Get list of array lengths
495 lens = set()
496 for param in params:
497 len = self.getLen(param)
498 if len:
499 lens.add(len)
500 # Get param info
501 paramsInfo = []
502 for param in params:
503 paramInfo = self.getTypeNameTuple(param)
504 cdecl = self.makeCParamDecl(param, 0)
505 # Check for parameter name in lens set
506 iscount = False
507 if paramInfo[1] in lens:
508 iscount = True
509 paramsInfo.append(self.CommandParam(type=paramInfo[0], name=paramInfo[1],
510 ispointer=self.paramIsPointer(param),
511 isstaticarray=self.paramIsStaticArray(param),
512 isbool=True if paramInfo[0] == 'VkBool32' else False,
513 israngedenum=True if paramInfo[0] in self.enumRanges else False,
514 isconst=True if 'const' in cdecl else False,
515 isoptional=self.paramIsOptional(param),
516 iscount=iscount,
517 noautovalidity=True if param.attrib.get('noautovalidity') is not None else False,
518 len=self.getLen(param),
519 extstructs=None,
520 condition=None,
521 cdecl=cdecl))
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600522 self.commands.append(self.CommandData(name=name, params=paramsInfo, cdecl=self.makeCDecls(cmdinfo.elem)[0], extension_type=self.extension_type))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600523 #
524 # Check if the parameter passed in is a pointer
525 def paramIsPointer(self, param):
526 ispointer = 0
527 paramtype = param.find('type')
528 if (paramtype.tail is not None) and ('*' in paramtype.tail):
529 ispointer = paramtype.tail.count('*')
530 elif paramtype.text[:4] == 'PFN_':
531 # Treat function pointer typedefs as a pointer to a single value
532 ispointer = 1
533 return ispointer
534 #
535 # Check if the parameter passed in is a static array
536 def paramIsStaticArray(self, param):
537 isstaticarray = 0
538 paramname = param.find('name')
539 if (paramname.tail is not None) and ('[' in paramname.tail):
540 isstaticarray = paramname.tail.count('[')
541 return isstaticarray
542 #
543 # Check if the parameter passed in is optional
544 # Returns a list of Boolean values for comma separated len attributes (len='false,true')
545 def paramIsOptional(self, param):
546 # See if the handle is optional
547 isoptional = False
548 # Simple, if it's optional, return true
549 optString = param.attrib.get('optional')
550 if optString:
551 if optString == 'true':
552 isoptional = True
553 elif ',' in optString:
554 opts = []
555 for opt in optString.split(','):
556 val = opt.strip()
557 if val == 'true':
558 opts.append(True)
559 elif val == 'false':
560 opts.append(False)
561 else:
562 print('Unrecognized len attribute value',val)
563 isoptional = opts
564 return isoptional
565 #
566 # Check if the handle passed in is optional
567 # Uses the same logic as ValidityOutputGenerator.isHandleOptional
568 def isHandleOptional(self, param, lenParam):
569 # Simple, if it's optional, return true
570 if param.isoptional:
571 return True
572 # If no validity is being generated, it usually means that validity is complex and not absolute, so let's say yes.
573 if param.noautovalidity:
574 return True
575 # If the parameter is an array and we haven't already returned, find out if any of the len parameters are optional
576 if lenParam and lenParam.isoptional:
577 return True
578 return False
579 #
580 # Generate a VkStructureType based on a structure typename
581 def genVkStructureType(self, typename):
582 # Add underscore between lowercase then uppercase
583 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
Mark Young39389872017-01-19 21:10:49 -0700584 value = value.replace('D3_D12', 'D3D12')
585 value = value.replace('Device_IDProp', 'Device_ID_Prop')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600586 # Change to uppercase
587 value = value.upper()
588 # Add STRUCTURE_TYPE_
589 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
590 #
591 # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType
592 # value assuming the struct is defined by a different feature
593 def getStructType(self, typename):
594 value = None
595 if typename in self.structTypes:
596 value = self.structTypes[typename].value
597 else:
598 value = self.genVkStructureType(typename)
599 self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename))
600 return value
601 #
602 # Retrieve the value of the len tag
603 def getLen(self, param):
604 result = None
605 len = param.attrib.get('len')
606 if len and len != 'null-terminated':
607 # For string arrays, 'len' can look like 'count,null-terminated',
608 # indicating that we have a null terminated array of strings. We
609 # strip the null-terminated from the 'len' field and only return
610 # the parameter specifying the string count
611 if 'null-terminated' in len:
612 result = len.split(',')[0]
613 else:
614 result = len
615 result = str(result).replace('::', '->')
616 return result
617 #
618 # Retrieve the type and name for a parameter
619 def getTypeNameTuple(self, param):
620 type = ''
621 name = ''
622 for elem in param:
623 if elem.tag == 'type':
624 type = noneStr(elem.text)
625 elif elem.tag == 'name':
626 name = noneStr(elem.text)
627 return (type, name)
628 #
629 # Find a named parameter in a parameter list
630 def getParamByName(self, params, name):
631 for param in params:
632 if param.name == name:
633 return param
634 return None
635 #
636 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
637 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
638 def parseLateXMath(self, source):
639 name = 'ERROR'
640 decoratedName = 'ERROR'
641 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700642 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
643 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 -0600644 if not match or match.group(1) != match.group(4):
645 raise 'Unrecognized latexmath expression'
646 name = match.group(2)
647 decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3))
648 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700649 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700650 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600651 name = match.group(1)
652 decoratedName = '{}/{}'.format(*match.group(1, 2))
653 return name, decoratedName
654 #
655 # Get the length paramater record for the specified parameter name
656 def getLenParam(self, params, name):
657 lenParam = None
658 if name:
659 if '->' in name:
660 # The count is obtained by dereferencing a member of a struct parameter
661 lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False,
662 isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None,
663 condition=None, cdecl=None)
664 elif 'latexmath' in name:
665 lenName, decoratedName = self.parseLateXMath(name)
666 lenParam = self.getParamByName(params, lenName)
667 # TODO: Zero-check the result produced by the equation?
668 # Copy the stored len parameter entry and overwrite the name with the processed latexmath equation
669 #param = self.getParamByName(params, lenName)
670 #lenParam = self.CommandParam(name=decoratedName, iscount=param.iscount, ispointer=param.ispointer,
671 # isoptional=param.isoptional, type=param.type, len=param.len,
672 # isstaticarray=param.isstaticarray, extstructs=param.extstructs,
673 # noautovalidity=True, condition=None, cdecl=param.cdecl)
674 else:
675 lenParam = self.getParamByName(params, name)
676 return lenParam
677 #
678 # Convert a vulkan.h command declaration into a parameter_validation.h definition
679 def getCmdDef(self, cmd):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600680 # Strip the trailing ';' and split into individual lines
681 lines = cmd.cdecl[:-1].split('\n')
682 # Replace Vulkan prototype
683 lines[0] = 'static bool parameter_validation_' + cmd.name + '('
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600684 # Replace the first argument with debug_report_data, when the first argument is a handle (not vkCreateInstance)
685 if cmd.name == 'vkCreateInstance':
686 lines.insert(1, ' instance_layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,')
687 else:
688 if cmd.params[0].type in ["VkInstance", "VkPhysicalDevice"]:
689 reportData = ' instance_layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,'
690 else:
691 reportData = ' layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,'
Mark Lobodzinski26112592017-05-30 12:02:17 -0600692 if len(lines) < 3: # Terminate correctly if single parameter
693 lines[1] = reportData[:-1] + ')'
694 else:
695 lines[1] = reportData
Mark Lobodzinski85672672016-10-13 08:36:42 -0600696 return '\n'.join(lines)
697 #
698 # Generate the code to check for a NULL dereference before calling the
699 # validation function
700 def genCheckedLengthCall(self, name, exprs):
701 count = name.count('->')
702 if count:
703 checkedExpr = []
704 localIndent = ''
705 elements = name.split('->')
706 # Open the if expression blocks
707 for i in range(0, count):
708 checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1])))
709 localIndent = self.incIndent(localIndent)
710 # Add the validation expression
711 for expr in exprs:
712 checkedExpr.append(localIndent + expr)
713 # Close the if blocks
714 for i in range(0, count):
715 localIndent = self.decIndent(localIndent)
716 checkedExpr.append(localIndent + '}\n')
717 return [checkedExpr]
718 # No if statements were required
719 return exprs
720 #
721 # Generate code to check for a specific condition before executing validation code
722 def genConditionalCall(self, prefix, condition, exprs):
723 checkedExpr = []
724 localIndent = ''
725 formattedCondition = condition.format(prefix)
726 checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition))
727 checkedExpr.append(localIndent + '{\n')
728 localIndent = self.incIndent(localIndent)
729 for expr in exprs:
730 checkedExpr.append(localIndent + expr)
731 localIndent = self.decIndent(localIndent)
732 checkedExpr.append(localIndent + '}\n')
733 return [checkedExpr]
734 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600735 # Get VUID identifier from implicit VUID tag
736 def GetVuid(self, vuid_string):
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600737 if '->' in vuid_string:
738 return "VALIDATION_ERROR_UNDEFINED"
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600739 vuid_num = self.IdToHex(convertVUID(vuid_string))
740 if vuid_num in self.valid_vuids:
741 vuid = "VALIDATION_ERROR_%s" % vuid_num
742 else:
743 vuid = "VALIDATION_ERROR_UNDEFINED"
744 return vuid
745 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600746 # Generate the sType check string
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600747 def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600748 checkExpr = []
749 stype = self.structTypes[value.type]
750 if lenValue:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600751 vuid_name = struct_type_name if struct_type_name is not None else funcPrintName
752 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600753 # This is an array with a pointer to a count value
754 if lenValue.ispointer:
755 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600756 checkExpr.append('skipCall |= validate_struct_type_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {}, {}, {});\n'.format(
757 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 -0600758 # This is an array with an integer count value
759 else:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600760 checkExpr.append('skipCall |= validate_struct_type_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {}, {});\n'.format(
761 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 -0600762 # This is an individual struct
763 else:
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600764 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
765 checkExpr.append('skipCall |= validate_struct_type(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {}, {});\n'.format(
766 funcPrintName, valuePrintName, prefix, valueRequired, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600767 return checkExpr
768 #
769 # Generate the handle check string
770 def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
771 checkExpr = []
772 if lenValue:
773 if lenValue.ispointer:
774 # This is assumed to be an output array with a pointer to a count value
775 raise('Unsupported parameter validation case: Output handle array elements are not NULL checked')
776 else:
777 # This is an array with an integer count value
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600778 checkExpr.append('skipCall |= validate_handle_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format(
Mark Lobodzinski85672672016-10-13 08:36:42 -0600779 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
780 else:
781 # This is assumed to be an output handle pointer
782 raise('Unsupported parameter validation case: Output handles are not NULL checked')
783 return checkExpr
784 #
785 # Generate check string for an array of VkFlags values
786 def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
787 checkExpr = []
788 flagBitsName = value.type.replace('Flags', 'FlagBits')
789 if not flagBitsName in self.flagBits:
790 raise('Unsupported parameter validation case: array of reserved VkFlags')
791 else:
792 allFlags = 'All' + flagBitsName
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600793 checkExpr.append('skipCall |= validate_flags_array(layer_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 -0600794 return checkExpr
795 #
796 # Generate pNext check string
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600797 def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600798 checkExpr = []
799 # Generate an array of acceptable VkStructureType values for pNext
800 extStructCount = 0
801 extStructVar = 'NULL'
802 extStructNames = 'NULL'
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600803 vuid = self.GetVuid("VUID-%s-pNext-pNext" % struct_type_name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600804 if value.extstructs:
Mike Schuchardtc73d07e2017-07-12 10:10:01 -0600805 extStructVar = 'allowed_structs_{}'.format(struct_type_name)
806 extStructCount = 'ARRAY_SIZE({})'.format(extStructVar)
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600807 extStructNames = '"' + ', '.join(value.extstructs) + '"'
808 checkExpr.append('const VkStructureType {}[] = {{ {} }};\n'.format(extStructVar, ', '.join([self.getStructType(s) for s in value.extstructs])))
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600809 checkExpr.append('skipCall |= validate_struct_pnext(layer_data->report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion, {});\n'.format(
810 funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600811 return checkExpr
812 #
813 # Generate the pointer check string
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600814 def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600815 checkExpr = []
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600816 vuid_tag_name = struct_type_name if struct_type_name is not None else funcPrintName
Mark Lobodzinski85672672016-10-13 08:36:42 -0600817 if lenValue:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600818 count_required_vuid = self.GetVuid("VUID-%s-%s-arraylength" % (vuid_tag_name, lenValue.name))
819 array_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600820 # This is an array with a pointer to a count value
821 if lenValue.ispointer:
822 # If count and array parameters are optional, there will be no validation
823 if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true':
824 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600825 checkExpr.append('skipCall |= validate_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {}, {}, {});\n'.format(
826 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 -0600827 # This is an array with an integer count value
828 else:
829 # If count and array parameters are optional, there will be no validation
830 if valueRequired == 'true' or lenValueRequired == 'true':
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600831 if value.type != 'char':
832 checkExpr.append('skipCall |= validate_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {}, {});\n'.format(
833 funcPrintName, lenValueRequired, valueRequired, count_required_vuid, array_required_vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
834 else:
835 # Arrays of strings receive special processing
836 checkExpr.append('skipCall |= validate_string_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {}, {});\n'.format(
837 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 -0600838 if checkExpr:
839 if lenValue and ('->' in lenValue.name):
840 # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count
841 checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr)
842 # This is an individual struct that is not allowed to be NULL
843 elif not value.isoptional:
844 # Function pointers need a reinterpret_cast to void*
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600845 ptr_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600846 if value.type[:4] == 'PFN_':
Mark Lobodzinski02fa1972017-06-28 14:46:14 -0600847 allocator_dict = {'pfnAllocation': '002004f0',
848 'pfnReallocation': '002004f2',
849 'pfnFree': '002004f4',
850 'pfnInternalAllocation': '002004f6'
851 }
852 vuid = allocator_dict.get(value.name)
853 if vuid is not None:
854 ptr_required_vuid = 'VALIDATION_ERROR_%s' % vuid
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600855 checkExpr.append('skipCall |= validate_required_pointer(layer_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 -0600856 else:
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600857 checkExpr.append('skipCall |= validate_required_pointer(layer_data->report_data, "{}", {ppp}"{}"{pps}, {}{}, {});\n'.format(funcPrintName, valuePrintName, prefix, value.name, ptr_required_vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600858 return checkExpr
859 #
860 # Process struct member validation code, performing name suibstitution if required
861 def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec):
862 # Build format specifier list
863 kwargs = {}
864 if '{postProcPrefix}' in line:
865 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
866 if type(memberDisplayNamePrefix) is tuple:
867 kwargs['postProcPrefix'] = 'ParameterName('
868 else:
869 kwargs['postProcPrefix'] = postProcSpec['ppp']
870 if '{postProcSuffix}' in line:
871 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
872 if type(memberDisplayNamePrefix) is tuple:
873 kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
874 else:
875 kwargs['postProcSuffix'] = postProcSpec['pps']
876 if '{postProcInsert}' in line:
877 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
878 if type(memberDisplayNamePrefix) is tuple:
879 kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
880 else:
881 kwargs['postProcInsert'] = postProcSpec['ppi']
882 if '{funcName}' in line:
883 kwargs['funcName'] = funcName
884 if '{valuePrefix}' in line:
885 kwargs['valuePrefix'] = memberNamePrefix
886 if '{displayNamePrefix}' in line:
887 # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class
888 if type(memberDisplayNamePrefix) is tuple:
889 kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0]
890 else:
891 kwargs['displayNamePrefix'] = memberDisplayNamePrefix
892
893 if kwargs:
894 # Need to escape the C++ curly braces
895 if 'IndexVector' in line:
896 line = line.replace('IndexVector{ ', 'IndexVector{{ ')
897 line = line.replace(' }),', ' }}),')
898 return line.format(**kwargs)
899 return line
900 #
901 # Process struct validation code for inclusion in function or parent struct validation code
902 def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec):
903 for line in lines:
904 if output:
905 output[-1] += '\n'
906 if type(line) is list:
907 for sub in line:
908 output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
909 else:
910 output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
911 return output
912 #
913 # Process struct pointer/array validation code, perfoeming name substitution if required
914 def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec):
915 expr = []
916 expr.append('if ({}{} != NULL)\n'.format(prefix, value.name))
917 expr.append('{')
918 indent = self.incIndent(None)
919 if lenValue:
920 # Need to process all elements in the array
921 indexName = lenValue.name.replace('Count', 'Index')
922 expr[-1] += '\n'
Mark Young39389872017-01-19 21:10:49 -0700923 if lenValue.ispointer:
924 # If the length value is a pointer, de-reference it for the count.
925 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < *{}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
926 else:
927 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600928 expr.append(indent + '{')
929 indent = self.incIndent(indent)
930 # Prefix for value name to display in error message
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700931 if value.ispointer == 2:
932 memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName)
933 memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName)
934 else:
935 memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName)
936 memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600937 else:
938 memberNamePrefix = '{}{}->'.format(prefix, value.name)
939 memberDisplayNamePrefix = '{}->'.format(valueDisplayName)
940 #
941 # Expand the struct validation lines
942 expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec)
943 #
944 if lenValue:
945 # Close if and for scopes
946 indent = self.decIndent(indent)
947 expr.append(indent + '}\n')
948 expr.append('}\n')
949 return expr
950 #
951 # Generate the parameter checking code
952 def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName):
953 lines = [] # Generated lines of code
954 unused = [] # Unused variable names
955 for value in values:
956 usedLines = []
957 lenParam = None
958 #
959 # 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.
960 postProcSpec = {}
961 postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}'
962 postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}'
963 postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}'
964 #
965 # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name
966 valueDisplayName = '{}{}'.format(displayNamePrefix, value.name)
967 #
968 # Check for NULL pointers, ignore the inout count parameters that
969 # will be validated with their associated array
970 if (value.ispointer or value.isstaticarray) and not value.iscount:
971 #
972 # Parameters for function argument generation
973 req = 'true' # Paramerter cannot be NULL
974 cpReq = 'true' # Count pointer cannot be NULL
975 cvReq = 'true' # Count value cannot be 0
976 lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied
977 #
978 # Generate required/optional parameter strings for the pointer and count values
979 if value.isoptional:
980 req = 'false'
981 if value.len:
982 # The parameter is an array with an explicit count parameter
983 lenParam = self.getLenParam(values, value.len)
984 lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name)
985 if lenParam.ispointer:
986 # Count parameters that are pointers are inout
987 if type(lenParam.isoptional) is list:
988 if lenParam.isoptional[0]:
989 cpReq = 'false'
990 if lenParam.isoptional[1]:
991 cvReq = 'false'
992 else:
993 if lenParam.isoptional:
994 cpReq = 'false'
995 else:
996 if lenParam.isoptional:
997 cvReq = 'false'
998 #
999 # The parameter will not be processes when tagged as 'noautovalidity'
1000 # For the pointer to struct case, the struct pointer will not be validated, but any
1001 # members not tagged as 'noatuvalidity' will be validated
1002 if value.noautovalidity:
1003 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1004 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1005 else:
1006 #
1007 # If this is a pointer to a struct with an sType field, verify the type
1008 if value.type in self.structTypes:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -06001009 usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001010 # 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
1011 elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam):
1012 usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1013 elif value.type in self.flags and value.isconst:
1014 usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1015 elif value.isbool and value.isconst:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001016 usedLines.append('skipCall |= validate_bool32_array(layer_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 -06001017 elif value.israngedenum and value.isconst:
Mark Lobodzinskiaff801e2017-07-25 15:29:57 -06001018 enum_value_list = 'All%sEnums' % value.type
1019 usedLines.append('skipCall |= validate_ranged_enum_array(layer_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 -06001020 elif value.name == 'pNext':
1021 # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml
1022 if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']:
Mark Lobodzinski3c828522017-06-26 13:05:57 -06001023 usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001024 else:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -06001025 usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001026 #
1027 # If this is a pointer to a struct (input), see if it contains members that need to be checked
1028 if value.type in self.validatedStructs and value.isconst:
1029 usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec))
1030 # Non-pointer types
1031 else:
1032 #
1033 # The parameter will not be processes when tagged as 'noautovalidity'
1034 # For the struct case, the struct type will not be validated, but any
1035 # members not tagged as 'noatuvalidity' will be validated
1036 if value.noautovalidity:
1037 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1038 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1039 else:
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001040 vuid_name_tag = structTypeName if structTypeName is not None else funcName
Mark Lobodzinski85672672016-10-13 08:36:42 -06001041 if value.type in self.structTypes:
1042 stype = self.structTypes[value.type]
Mark Lobodzinski06954ea2017-06-21 12:21:45 -06001043 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
1044 usedLines.append('skipCall |= validate_struct_type(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", &({}{vn}), {sv}, false, {});\n'.format(
1045 funcName, valueDisplayName, valuePrefix, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001046 elif value.type in self.handleTypes:
1047 if not self.isHandleOptional(value, None):
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001048 usedLines.append('skipCall |= validate_required_handle(layer_data->report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001049 elif value.type in self.flags:
1050 flagBitsName = value.type.replace('Flags', 'FlagBits')
1051 if not flagBitsName in self.flagBits:
Mark Lobodzinskid0b0c512017-06-28 12:06:41 -06001052 vuid = self.GetVuid("VUID-%s-%s-zerobitmask" % (vuid_name_tag, value.name))
1053 usedLines.append('skipCall |= validate_reserved_flags(layer_data->report_data, "{}", {ppp}"{}"{pps}, {pf}{}, {});\n'.format(funcName, valueDisplayName, value.name, vuid, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001054 else:
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001055 if value.isoptional:
1056 flagsRequired = 'false'
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001057 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001058 else:
1059 flagsRequired = 'true'
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001060 vuid = self.GetVuid("VUID-%s-%s-requiredbitmask" % (vuid_name_tag, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001061 allFlagsName = 'All' + flagBitsName
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001062 usedLines.append('skipCall |= validate_flags(layer_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 -06001063 elif value.type in self.flagBits:
1064 flagsRequired = 'false' if value.isoptional else 'true'
1065 allFlagsName = 'All' + value.type
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001066 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
1067 usedLines.append('skipCall |= validate_flags(layer_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 -06001068 elif value.isbool:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001069 usedLines.append('skipCall |= validate_bool32(layer_data->report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001070 elif value.israngedenum:
Mark Lobodzinski42eb3c32017-06-28 11:47:22 -06001071 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinski74cb45f2017-07-25 15:10:29 -06001072 enum_value_list = 'All%sEnums' % value.type
1073 usedLines.append('skipCall |= validate_ranged_enum(layer_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 -06001074 #
1075 # If this is a struct, see if it contains members that need to be checked
1076 if value.type in self.validatedStructs:
1077 memberNamePrefix = '{}{}.'.format(valuePrefix, value.name)
1078 memberDisplayNamePrefix = '{}.'.format(valueDisplayName)
1079 usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec))
1080 #
1081 # Append the parameter check to the function body for the current command
1082 if usedLines:
1083 # Apply special conditional checks
1084 if value.condition:
1085 usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines)
1086 lines += usedLines
1087 elif not value.iscount:
1088 # If no expression was generated for this value, it is unreferenced by the validation function, unless
1089 # it is an array count, which is indirectly referenced for array valiadation.
1090 unused.append(value.name)
1091 return lines, unused
1092 #
1093 # Generate the struct member check code from the captured data
1094 def processStructMemberData(self):
1095 indent = self.incIndent(None)
1096 for struct in self.structMembers:
1097 #
1098 # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented
1099 lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name)
1100 if lines:
1101 self.validatedStructs[struct.name] = lines
1102 #
1103 # Generate the command param check code from the captured data
1104 def processCmdData(self):
1105 indent = self.incIndent(None)
1106 for command in self.commands:
1107 # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance)
1108 startIndex = 0 if command.name == 'vkCreateInstance' else 1
1109 lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001110 # Cannot validate extension dependencies for device extension APIs a physical device as their dispatchable object
1111 if self.required_extensions and self.extension_type == 'device' and command.params[0].type != 'VkPhysicalDevice':
1112 # The actual extension names are not all available yet, so we'll tag these now and replace them just before
1113 # writing the validation routines out to a file
1114 ext_test = ''
Mark Lobodzinski26112592017-05-30 12:02:17 -06001115 for ext in self.required_extensions:
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001116 ext_name_define = ''
1117 ext_enable_name = ''
1118 for extension in self.registry.extensions:
1119 if extension.attrib['name'] == ext:
1120 ext_name_define = extension[0][1].get('name')
1121 ext_enable_name = ext_name_define.lower()
1122 ext_enable_name = re.sub('_extension_name', '', ext_enable_name)
1123 break
1124 ext_test = 'if (!layer_data->extensions.%s) skipCall |= OutputExtensionError(layer_data, "%s", %s);\n' % (ext_enable_name, command.name, ext_name_define)
1125 lines.insert(0, ext_test)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001126 if lines:
1127 cmdDef = self.getCmdDef(command) + '\n'
1128 cmdDef += '{\n'
1129 # Process unused parameters, Ignoring the first dispatch handle parameter, which is not
1130 # processed by parameter_validation (except for vkCreateInstance, which does not have a
1131 # handle as its first parameter)
1132 if unused:
1133 for name in unused:
1134 cmdDef += indent + 'UNUSED_PARAMETER({});\n'.format(name)
1135 if len(unused) > 0:
1136 cmdDef += '\n'
1137 cmdDef += indent + 'bool skipCall = false;\n'
Mark Lobodzinski26112592017-05-30 12:02:17 -06001138
Mark Lobodzinski85672672016-10-13 08:36:42 -06001139 for line in lines:
1140 cmdDef += '\n'
1141 if type(line) is list:
1142 for sub in line:
1143 cmdDef += indent + sub
1144 else:
1145 cmdDef += indent + line
1146 cmdDef += '\n'
1147 cmdDef += indent + 'return skipCall;\n'
1148 cmdDef += '}\n'
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001149 self.validation.append(cmdDef)