blob: f1dfba1fc01e730140f29c9f6fc41c3a402ae7d9 [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
158 self.flags = set() # Map of flags typenames
159 self.flagBits = dict() # Map of flag bits typename to list of values
Chris Forbes78ea32d2016-11-28 11:14:17 +1300160 self.newFlags = set() # Map of flags typenames /defined in the current feature/
Mark Lobodzinski26112592017-05-30 12:02:17 -0600161 self.required_extensions = [] # List of required extensions for the current extension
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600162 self.extension_type = '' # Type of active feature (extension), device or instance
163 self.extension_names = dict() # Dictionary of extension names to extension name defines
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600164 self.valid_vuids = set() # Set of all valid VUIDs
Mark Lobodzinski85672672016-10-13 08:36:42 -0600165 # Named tuples to store struct and command data
166 self.StructType = namedtuple('StructType', ['name', 'value'])
167 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isbool', 'israngedenum',
168 'isconst', 'isoptional', 'iscount', 'noautovalidity', 'len', 'extstructs',
169 'condition', 'cdecl'])
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600170 self.CommandData = namedtuple('CommandData', ['name', 'params', 'cdecl', 'extension_type'])
Mark Lobodzinski85672672016-10-13 08:36:42 -0600171 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600172
173 self.vuid_file = None
174 # Cover cases where file is built from scripts directory, Lin/Win, or Android build structure
175 vuid_filename_locations = [
Mark Lobodzinskifc20c4d2017-07-03 15:50:39 -0600176 './vk_validation_error_messages.h',
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600177 '../layers/vk_validation_error_messages.h',
178 '../../layers/vk_validation_error_messages.h',
179 '../../../layers/vk_validation_error_messages.h',
180 ]
181 for vuid_filename in vuid_filename_locations:
182 if os.path.isfile(vuid_filename):
183 self.vuid_file = open(vuid_filename, "r")
184 break
185 if self.vuid_file == None:
186 print("Error: Could not find vk_validation_error_messages.h")
187 quit()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600188 #
189 def incIndent(self, indent):
190 inc = ' ' * self.INDENT_SPACES
191 if indent:
192 return indent + inc
193 return inc
194 #
195 def decIndent(self, indent):
196 if indent and (len(indent) > self.INDENT_SPACES):
197 return indent[:-self.INDENT_SPACES]
198 return ''
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600199 # Convert decimal number to 8 digit hexadecimal lower-case representation
200 def IdToHex(self, dec_num):
201 if dec_num > 4294967295:
202 print ("ERROR: Decimal # %d can't be represented in 8 hex digits" % (dec_num))
203 sys.exit()
204 hex_num = hex(dec_num)
205 return hex_num[2:].zfill(8)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600206 #
207 def beginFile(self, genOpts):
208 OutputGenerator.beginFile(self, genOpts)
209 # C-specific
210 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600211 # Open vk_validation_error_messages.h file to verify computed VUIDs
212 for line in self.vuid_file:
213 # Grab hex number from enum definition
214 vuid_list = line.split('0x')
215 # If this is a valid enumeration line, remove trailing comma and CR
216 if len(vuid_list) == 2:
217 vuid_num = vuid_list[1][:-2]
218 # Make sure this is a good hex number before adding to set
219 if len(vuid_num) == 8 and all(c in string.hexdigits for c in vuid_num):
220 self.valid_vuids.add(vuid_num)
221 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600222 # User-supplied prefix text, if any (list of strings)
223 if (genOpts.prefixText):
224 for s in genOpts.prefixText:
225 write(s, file=self.outFile)
226 #
227 # Multiple inclusion protection & C++ wrappers.
228 if (genOpts.protectFile and self.genOpts.filename):
229 headerSym = re.sub('\.h', '_H', os.path.basename(self.genOpts.filename)).upper()
230 write('#ifndef', headerSym, file=self.outFile)
231 write('#define', headerSym, '1', file=self.outFile)
232 self.newline()
233 #
234 # Headers
235 write('#include <string>', file=self.outFile)
236 self.newline()
237 write('#include "vulkan/vulkan.h"', file=self.outFile)
238 write('#include "vk_layer_extension_utils.h"', file=self.outFile)
239 write('#include "parameter_validation_utils.h"', file=self.outFile)
240 #
241 # Macros
242 self.newline()
243 write('#ifndef UNUSED_PARAMETER', file=self.outFile)
244 write('#define UNUSED_PARAMETER(x) (void)(x)', file=self.outFile)
245 write('#endif // UNUSED_PARAMETER', file=self.outFile)
246 #
247 # Namespace
248 self.newline()
249 write('namespace parameter_validation {', file = self.outFile)
250 def endFile(self):
251 # C-specific
252 self.newline()
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600253 commands_text = '\n'.join(self.validation)
254 write(commands_text, file=self.outFile)
255 self.newline()
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700256 # Output declarations and record intercepted procedures
257 write('// Declarations', file=self.outFile)
258 write('\n'.join(self.declarations), file=self.outFile)
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600259 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
260 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700261 write('\n'.join(self.intercepts), file=self.outFile)
262 write('};\n', file=self.outFile)
263 self.newline()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600264 # Namespace
265 write('} // namespace parameter_validation', file = self.outFile)
266 # Finish C++ wrapper and multiple inclusion protection
267 if (self.genOpts.protectFile and self.genOpts.filename):
268 self.newline()
269 write('#endif', file=self.outFile)
270 # Finish processing in superclass
271 OutputGenerator.endFile(self)
272 def beginFeature(self, interface, emit):
273 # Start processing in superclass
274 OutputGenerator.beginFeature(self, interface, emit)
275 # C-specific
276 # Accumulate includes, defines, types, enums, function pointer typedefs,
277 # end function prototypes separately for this feature. They're only
278 # printed in endFeature().
279 self.headerVersion = None
Mark Lobodzinski85672672016-10-13 08:36:42 -0600280 self.structNames = []
281 self.stypes = []
282 self.structTypes = dict()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600283 self.commands = []
284 self.structMembers = []
Chris Forbes78ea32d2016-11-28 11:14:17 +1300285 self.newFlags = set()
Mark Lobodzinski26112592017-05-30 12:02:17 -0600286 # Save list of required extensions for this extension
287 self.required_extensions = []
288 if self.featureName != "VK_VERSION_1_0":
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600289 # Save Name Define to get correct enable name later
290 nameElem = interface[0][1]
291 name = nameElem.get('name')
292 self.extension_names[self.featureName] = name
293 # This extension is the first dependency for this command
Mark Lobodzinski26112592017-05-30 12:02:17 -0600294 self.required_extensions.append(self.featureName)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600295 # Add any defined extension dependencies to the dependency list for this command
Mark Lobodzinski26112592017-05-30 12:02:17 -0600296 required_extensions = interface.get('requires')
297 if required_extensions is not None:
298 self.required_extensions.extend(required_extensions.split(','))
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600299 # And note if this is an Instance or Device extension
300 self.extension_type = interface.get('type')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600301 def endFeature(self):
302 # C-specific
303 # Actually write the interface to the output file.
304 if (self.emit):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600305 # If type declarations are needed by other features based on
306 # this one, it may be necessary to suppress the ExtraProtect,
307 # or move it below the 'for section...' loop.
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600308 ifdef = ''
Mark Lobodzinski85672672016-10-13 08:36:42 -0600309 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600310 ifdef = '#ifdef %s\n' % self.featureExtraProtect
311 self.validation.append(ifdef)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600312 # Generate the struct member checking code from the captured data
313 self.processStructMemberData()
314 # Generate the command parameter checking code from the captured data
315 self.processCmdData()
316 # Write the declaration for the HeaderVersion
317 if self.headerVersion:
318 write('const uint32_t GeneratedHeaderVersion = {};'.format(self.headerVersion), file=self.outFile)
319 self.newline()
320 # Write the declarations for the VkFlags values combining all flag bits
Chris Forbes78ea32d2016-11-28 11:14:17 +1300321 for flag in sorted(self.newFlags):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600322 flagBits = flag.replace('Flags', 'FlagBits')
323 if flagBits in self.flagBits:
324 bits = self.flagBits[flagBits]
325 decl = 'const {} All{} = {}'.format(flag, flagBits, bits[0])
326 for bit in bits[1:]:
327 decl += '|' + bit
328 decl += ';'
329 write(decl, file=self.outFile)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600330 endif = '\n'
Mark Lobodzinski85672672016-10-13 08:36:42 -0600331 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600332 endif = '#endif // %s\n' % self.featureExtraProtect
333 self.validation.append(endif)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600334 # Finish processing in superclass
335 OutputGenerator.endFeature(self)
336 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600337 # Type generation
338 def genType(self, typeinfo, name):
339 OutputGenerator.genType(self, typeinfo, name)
340 typeElem = typeinfo.elem
341 # If the type is a struct type, traverse the imbedded <member> tags
342 # generating a structure. Otherwise, emit the tag text.
343 category = typeElem.get('category')
344 if (category == 'struct' or category == 'union'):
345 self.structNames.append(name)
346 self.genStruct(typeinfo, name)
347 elif (category == 'handle'):
348 self.handleTypes.add(name)
349 elif (category == 'bitmask'):
350 self.flags.add(name)
Chris Forbes78ea32d2016-11-28 11:14:17 +1300351 self.newFlags.add(name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600352 elif (category == 'define'):
353 if name == 'VK_HEADER_VERSION':
354 nameElem = typeElem.find('name')
355 self.headerVersion = noneStr(nameElem.tail).strip()
356 #
357 # Struct parameter check generation.
358 # This is a special case of the <type> tag where the contents are
359 # interpreted as a set of <member> tags instead of freeform C
360 # C type declarations. The <member> tags are just like <param>
361 # tags - they are a declaration of a struct or union member.
362 # Only simple member declarations are supported (no nested
363 # structs etc.)
364 def genStruct(self, typeinfo, typeName):
365 OutputGenerator.genStruct(self, typeinfo, typeName)
366 conditions = self.structMemberValidationConditions[typeName] if typeName in self.structMemberValidationConditions else None
367 members = typeinfo.elem.findall('.//member')
368 #
369 # Iterate over members once to get length parameters for arrays
370 lens = set()
371 for member in members:
372 len = self.getLen(member)
373 if len:
374 lens.add(len)
375 #
376 # Generate member info
377 membersInfo = []
378 for member in members:
379 # Get the member's type and name
380 info = self.getTypeNameTuple(member)
381 type = info[0]
382 name = info[1]
383 stypeValue = ''
384 cdecl = self.makeCParamDecl(member, 0)
385 # Process VkStructureType
386 if type == 'VkStructureType':
387 # Extract the required struct type value from the comments
388 # embedded in the original text defining the 'typeinfo' element
389 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
390 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
391 if result:
392 value = result.group(0)
393 else:
394 value = self.genVkStructureType(typeName)
395 # Store the required type value
396 self.structTypes[typeName] = self.StructType(name=name, value=value)
397 #
398 # Store pointer/array/string info
399 # Check for parameter name in lens set
400 iscount = False
401 if name in lens:
402 iscount = True
403 # The pNext members are not tagged as optional, but are treated as
404 # optional for parameter NULL checks. Static array members
405 # are also treated as optional to skip NULL pointer validation, as
406 # they won't be NULL.
407 isstaticarray = self.paramIsStaticArray(member)
408 isoptional = False
409 if self.paramIsOptional(member) or (name == 'pNext') or (isstaticarray):
410 isoptional = True
Dustin Gravesce68f082017-03-30 15:42:16 -0600411 # Determine if value should be ignored by code generation.
412 noautovalidity = False
413 if (member.attrib.get('noautovalidity') is not None) or ((typeName in self.structMemberBlacklist) and (name in self.structMemberBlacklist[typeName])):
414 noautovalidity = True
Mark Lobodzinski85672672016-10-13 08:36:42 -0600415 membersInfo.append(self.CommandParam(type=type, name=name,
416 ispointer=self.paramIsPointer(member),
417 isstaticarray=isstaticarray,
418 isbool=True if type == 'VkBool32' else False,
419 israngedenum=True if type in self.enumRanges else False,
420 isconst=True if 'const' in cdecl else False,
421 isoptional=isoptional,
422 iscount=iscount,
Dustin Gravesce68f082017-03-30 15:42:16 -0600423 noautovalidity=noautovalidity,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600424 len=self.getLen(member),
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600425 extstructs=self.registry.validextensionstructs[typeName] if name == 'pNext' else None,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600426 condition=conditions[name] if conditions and name in conditions else None,
427 cdecl=cdecl))
428 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
429 #
430 # Capture group (e.g. C "enum" type) info to be used for
431 # param check code generation.
432 # These are concatenated together with other types.
433 def genGroup(self, groupinfo, groupName):
434 OutputGenerator.genGroup(self, groupinfo, groupName)
435 groupElem = groupinfo.elem
436 #
437 # Store the sType values
438 if groupName == 'VkStructureType':
439 for elem in groupElem.findall('enum'):
440 self.stypes.append(elem.get('name'))
441 elif 'FlagBits' in groupName:
442 bits = []
443 for elem in groupElem.findall('enum'):
444 bits.append(elem.get('name'))
445 if bits:
446 self.flagBits[groupName] = bits
447 else:
448 # Determine if begin/end ranges are needed (we don't do this for VkStructureType, which has a more finely grained check)
449 expandName = re.sub(r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)',r'\1_\2',groupName).upper()
450 expandPrefix = expandName
451 expandSuffix = ''
452 expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName)
453 if expandSuffixMatch:
454 expandSuffix = '_' + expandSuffixMatch.group()
455 # Strip off the suffix from the prefix
456 expandPrefix = expandName.rsplit(expandSuffix, 1)[0]
457 isEnum = ('FLAG_BITS' not in expandPrefix)
458 if isEnum:
459 self.enumRanges[groupName] = (expandPrefix + '_BEGIN_RANGE' + expandSuffix, expandPrefix + '_END_RANGE' + expandSuffix)
460 #
461 # Capture command parameter info to be used for param
462 # check code generation.
463 def genCmd(self, cmdinfo, name):
464 OutputGenerator.genCmd(self, cmdinfo, name)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700465 interface_functions = [
466 'vkEnumerateInstanceLayerProperties',
467 'vkEnumerateInstanceExtensionProperties',
468 'vkEnumerateDeviceLayerProperties',
Mark Lobodzinski099b3b62017-02-08 16:04:35 -0700469 'vkCmdDebugMarkerEndEXT', # No validation!
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700470 ]
471 # Record that the function will be intercepted
472 if name not in interface_functions:
473 if (self.featureExtraProtect != None):
474 self.declarations += [ '#ifdef %s' % self.featureExtraProtect ]
475 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600476 self.intercepts += [ ' {"%s", (void*)%s},' % (name,name[2:]) ]
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700477 decls = self.makeCDecls(cmdinfo.elem)
478 # Strip off 'vk' from API name
479 self.declarations += [ '%s' % decls[0].replace("VKAPI_CALL vk", "VKAPI_CALL ") ]
480 if (self.featureExtraProtect != None):
481 self.intercepts += [ '#endif' ]
482 self.declarations += [ '#endif' ]
Mark Lobodzinski85672672016-10-13 08:36:42 -0600483 if name not in self.blacklist:
484 params = cmdinfo.elem.findall('param')
485 # Get list of array lengths
486 lens = set()
487 for param in params:
488 len = self.getLen(param)
489 if len:
490 lens.add(len)
491 # Get param info
492 paramsInfo = []
493 for param in params:
494 paramInfo = self.getTypeNameTuple(param)
495 cdecl = self.makeCParamDecl(param, 0)
496 # Check for parameter name in lens set
497 iscount = False
498 if paramInfo[1] in lens:
499 iscount = True
500 paramsInfo.append(self.CommandParam(type=paramInfo[0], name=paramInfo[1],
501 ispointer=self.paramIsPointer(param),
502 isstaticarray=self.paramIsStaticArray(param),
503 isbool=True if paramInfo[0] == 'VkBool32' else False,
504 israngedenum=True if paramInfo[0] in self.enumRanges else False,
505 isconst=True if 'const' in cdecl else False,
506 isoptional=self.paramIsOptional(param),
507 iscount=iscount,
508 noautovalidity=True if param.attrib.get('noautovalidity') is not None else False,
509 len=self.getLen(param),
510 extstructs=None,
511 condition=None,
512 cdecl=cdecl))
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600513 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 -0600514 #
515 # Check if the parameter passed in is a pointer
516 def paramIsPointer(self, param):
517 ispointer = 0
518 paramtype = param.find('type')
519 if (paramtype.tail is not None) and ('*' in paramtype.tail):
520 ispointer = paramtype.tail.count('*')
521 elif paramtype.text[:4] == 'PFN_':
522 # Treat function pointer typedefs as a pointer to a single value
523 ispointer = 1
524 return ispointer
525 #
526 # Check if the parameter passed in is a static array
527 def paramIsStaticArray(self, param):
528 isstaticarray = 0
529 paramname = param.find('name')
530 if (paramname.tail is not None) and ('[' in paramname.tail):
531 isstaticarray = paramname.tail.count('[')
532 return isstaticarray
533 #
534 # Check if the parameter passed in is optional
535 # Returns a list of Boolean values for comma separated len attributes (len='false,true')
536 def paramIsOptional(self, param):
537 # See if the handle is optional
538 isoptional = False
539 # Simple, if it's optional, return true
540 optString = param.attrib.get('optional')
541 if optString:
542 if optString == 'true':
543 isoptional = True
544 elif ',' in optString:
545 opts = []
546 for opt in optString.split(','):
547 val = opt.strip()
548 if val == 'true':
549 opts.append(True)
550 elif val == 'false':
551 opts.append(False)
552 else:
553 print('Unrecognized len attribute value',val)
554 isoptional = opts
555 return isoptional
556 #
557 # Check if the handle passed in is optional
558 # Uses the same logic as ValidityOutputGenerator.isHandleOptional
559 def isHandleOptional(self, param, lenParam):
560 # Simple, if it's optional, return true
561 if param.isoptional:
562 return True
563 # If no validity is being generated, it usually means that validity is complex and not absolute, so let's say yes.
564 if param.noautovalidity:
565 return True
566 # If the parameter is an array and we haven't already returned, find out if any of the len parameters are optional
567 if lenParam and lenParam.isoptional:
568 return True
569 return False
570 #
571 # Generate a VkStructureType based on a structure typename
572 def genVkStructureType(self, typename):
573 # Add underscore between lowercase then uppercase
574 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
Mark Young39389872017-01-19 21:10:49 -0700575 value = value.replace('D3_D12', 'D3D12')
576 value = value.replace('Device_IDProp', 'Device_ID_Prop')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600577 # Change to uppercase
578 value = value.upper()
579 # Add STRUCTURE_TYPE_
580 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
581 #
582 # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType
583 # value assuming the struct is defined by a different feature
584 def getStructType(self, typename):
585 value = None
586 if typename in self.structTypes:
587 value = self.structTypes[typename].value
588 else:
589 value = self.genVkStructureType(typename)
590 self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename))
591 return value
592 #
593 # Retrieve the value of the len tag
594 def getLen(self, param):
595 result = None
596 len = param.attrib.get('len')
597 if len and len != 'null-terminated':
598 # For string arrays, 'len' can look like 'count,null-terminated',
599 # indicating that we have a null terminated array of strings. We
600 # strip the null-terminated from the 'len' field and only return
601 # the parameter specifying the string count
602 if 'null-terminated' in len:
603 result = len.split(',')[0]
604 else:
605 result = len
606 result = str(result).replace('::', '->')
607 return result
608 #
609 # Retrieve the type and name for a parameter
610 def getTypeNameTuple(self, param):
611 type = ''
612 name = ''
613 for elem in param:
614 if elem.tag == 'type':
615 type = noneStr(elem.text)
616 elif elem.tag == 'name':
617 name = noneStr(elem.text)
618 return (type, name)
619 #
620 # Find a named parameter in a parameter list
621 def getParamByName(self, params, name):
622 for param in params:
623 if param.name == name:
624 return param
625 return None
626 #
627 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
628 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
629 def parseLateXMath(self, source):
630 name = 'ERROR'
631 decoratedName = 'ERROR'
632 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700633 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
634 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 -0600635 if not match or match.group(1) != match.group(4):
636 raise 'Unrecognized latexmath expression'
637 name = match.group(2)
638 decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3))
639 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700640 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700641 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600642 name = match.group(1)
643 decoratedName = '{}/{}'.format(*match.group(1, 2))
644 return name, decoratedName
645 #
646 # Get the length paramater record for the specified parameter name
647 def getLenParam(self, params, name):
648 lenParam = None
649 if name:
650 if '->' in name:
651 # The count is obtained by dereferencing a member of a struct parameter
652 lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False,
653 isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None,
654 condition=None, cdecl=None)
655 elif 'latexmath' in name:
656 lenName, decoratedName = self.parseLateXMath(name)
657 lenParam = self.getParamByName(params, lenName)
658 # TODO: Zero-check the result produced by the equation?
659 # Copy the stored len parameter entry and overwrite the name with the processed latexmath equation
660 #param = self.getParamByName(params, lenName)
661 #lenParam = self.CommandParam(name=decoratedName, iscount=param.iscount, ispointer=param.ispointer,
662 # isoptional=param.isoptional, type=param.type, len=param.len,
663 # isstaticarray=param.isstaticarray, extstructs=param.extstructs,
664 # noautovalidity=True, condition=None, cdecl=param.cdecl)
665 else:
666 lenParam = self.getParamByName(params, name)
667 return lenParam
668 #
669 # Convert a vulkan.h command declaration into a parameter_validation.h definition
670 def getCmdDef(self, cmd):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600671 # Strip the trailing ';' and split into individual lines
672 lines = cmd.cdecl[:-1].split('\n')
673 # Replace Vulkan prototype
674 lines[0] = 'static bool parameter_validation_' + cmd.name + '('
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600675 # Replace the first argument with debug_report_data, when the first argument is a handle (not vkCreateInstance)
676 if cmd.name == 'vkCreateInstance':
677 lines.insert(1, ' instance_layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,')
678 else:
679 if cmd.params[0].type in ["VkInstance", "VkPhysicalDevice"]:
680 reportData = ' instance_layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,'
681 else:
682 reportData = ' layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,'
Mark Lobodzinski26112592017-05-30 12:02:17 -0600683 if len(lines) < 3: # Terminate correctly if single parameter
684 lines[1] = reportData[:-1] + ')'
685 else:
686 lines[1] = reportData
Mark Lobodzinski85672672016-10-13 08:36:42 -0600687 return '\n'.join(lines)
688 #
689 # Generate the code to check for a NULL dereference before calling the
690 # validation function
691 def genCheckedLengthCall(self, name, exprs):
692 count = name.count('->')
693 if count:
694 checkedExpr = []
695 localIndent = ''
696 elements = name.split('->')
697 # Open the if expression blocks
698 for i in range(0, count):
699 checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1])))
700 localIndent = self.incIndent(localIndent)
701 # Add the validation expression
702 for expr in exprs:
703 checkedExpr.append(localIndent + expr)
704 # Close the if blocks
705 for i in range(0, count):
706 localIndent = self.decIndent(localIndent)
707 checkedExpr.append(localIndent + '}\n')
708 return [checkedExpr]
709 # No if statements were required
710 return exprs
711 #
712 # Generate code to check for a specific condition before executing validation code
713 def genConditionalCall(self, prefix, condition, exprs):
714 checkedExpr = []
715 localIndent = ''
716 formattedCondition = condition.format(prefix)
717 checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition))
718 checkedExpr.append(localIndent + '{\n')
719 localIndent = self.incIndent(localIndent)
720 for expr in exprs:
721 checkedExpr.append(localIndent + expr)
722 localIndent = self.decIndent(localIndent)
723 checkedExpr.append(localIndent + '}\n')
724 return [checkedExpr]
725 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600726 # Get VUID identifier from implicit VUID tag
727 def GetVuid(self, vuid_string):
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600728 if '->' in vuid_string:
729 return "VALIDATION_ERROR_UNDEFINED"
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600730 vuid_num = self.IdToHex(convertVUID(vuid_string))
731 if vuid_num in self.valid_vuids:
732 vuid = "VALIDATION_ERROR_%s" % vuid_num
733 else:
734 vuid = "VALIDATION_ERROR_UNDEFINED"
735 return vuid
736 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600737 # Generate the sType check string
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600738 def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600739 checkExpr = []
740 stype = self.structTypes[value.type]
741 if lenValue:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600742 vuid_name = struct_type_name if struct_type_name is not None else funcPrintName
743 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600744 # This is an array with a pointer to a count value
745 if lenValue.ispointer:
746 # 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 -0600747 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(
748 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 -0600749 # This is an array with an integer count value
750 else:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -0600751 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(
752 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 -0600753 # This is an individual struct
754 else:
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600755 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
756 checkExpr.append('skipCall |= validate_struct_type(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {}, {});\n'.format(
757 funcPrintName, valuePrintName, prefix, valueRequired, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600758 return checkExpr
759 #
760 # Generate the handle check string
761 def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
762 checkExpr = []
763 if lenValue:
764 if lenValue.ispointer:
765 # This is assumed to be an output array with a pointer to a count value
766 raise('Unsupported parameter validation case: Output handle array elements are not NULL checked')
767 else:
768 # This is an array with an integer count value
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600769 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 -0600770 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
771 else:
772 # This is assumed to be an output handle pointer
773 raise('Unsupported parameter validation case: Output handles are not NULL checked')
774 return checkExpr
775 #
776 # Generate check string for an array of VkFlags values
777 def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
778 checkExpr = []
779 flagBitsName = value.type.replace('Flags', 'FlagBits')
780 if not flagBitsName in self.flagBits:
781 raise('Unsupported parameter validation case: array of reserved VkFlags')
782 else:
783 allFlags = 'All' + flagBitsName
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600784 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 -0600785 return checkExpr
786 #
787 # Generate pNext check string
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600788 def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600789 checkExpr = []
790 # Generate an array of acceptable VkStructureType values for pNext
791 extStructCount = 0
792 extStructVar = 'NULL'
793 extStructNames = 'NULL'
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600794 vuid = self.GetVuid("VUID-%s-pNext-pNext" % struct_type_name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600795 if value.extstructs:
Mike Schuchardtc73d07e2017-07-12 10:10:01 -0600796 extStructVar = 'allowed_structs_{}'.format(struct_type_name)
797 extStructCount = 'ARRAY_SIZE({})'.format(extStructVar)
Mike Schuchardta40d0b02017-07-23 12:47:47 -0600798 extStructNames = '"' + ', '.join(value.extstructs) + '"'
799 checkExpr.append('const VkStructureType {}[] = {{ {} }};\n'.format(extStructVar, ', '.join([self.getStructType(s) for s in value.extstructs])))
Mark Lobodzinski3c828522017-06-26 13:05:57 -0600800 checkExpr.append('skipCall |= validate_struct_pnext(layer_data->report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion, {});\n'.format(
801 funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600802 return checkExpr
803 #
804 # Generate the pointer check string
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600805 def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec, struct_type_name):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600806 checkExpr = []
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600807 vuid_tag_name = struct_type_name if struct_type_name is not None else funcPrintName
Mark Lobodzinski85672672016-10-13 08:36:42 -0600808 if lenValue:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600809 count_required_vuid = self.GetVuid("VUID-%s-%s-arraylength" % (vuid_tag_name, lenValue.name))
810 array_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600811 # This is an array with a pointer to a count value
812 if lenValue.ispointer:
813 # If count and array parameters are optional, there will be no validation
814 if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true':
815 # 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 -0600816 checkExpr.append('skipCall |= validate_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {}, {}, {});\n'.format(
817 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 -0600818 # This is an array with an integer count value
819 else:
820 # If count and array parameters are optional, there will be no validation
821 if valueRequired == 'true' or lenValueRequired == 'true':
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -0600822 if value.type != 'char':
823 checkExpr.append('skipCall |= validate_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {}, {});\n'.format(
824 funcPrintName, lenValueRequired, valueRequired, count_required_vuid, array_required_vuid, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
825 else:
826 # Arrays of strings receive special processing
827 checkExpr.append('skipCall |= validate_string_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {}, {});\n'.format(
828 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 -0600829 if checkExpr:
830 if lenValue and ('->' in lenValue.name):
831 # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count
832 checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr)
833 # This is an individual struct that is not allowed to be NULL
834 elif not value.isoptional:
835 # Function pointers need a reinterpret_cast to void*
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600836 ptr_required_vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_tag_name, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600837 if value.type[:4] == 'PFN_':
Mark Lobodzinski02fa1972017-06-28 14:46:14 -0600838 allocator_dict = {'pfnAllocation': '002004f0',
839 'pfnReallocation': '002004f2',
840 'pfnFree': '002004f4',
841 'pfnInternalAllocation': '002004f6'
842 }
843 vuid = allocator_dict.get(value.name)
844 if vuid is not None:
845 ptr_required_vuid = 'VALIDATION_ERROR_%s' % vuid
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600846 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 -0600847 else:
Mark Lobodzinskidead0b62017-06-28 13:22:03 -0600848 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 -0600849 return checkExpr
850 #
851 # Process struct member validation code, performing name suibstitution if required
852 def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec):
853 # Build format specifier list
854 kwargs = {}
855 if '{postProcPrefix}' in line:
856 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
857 if type(memberDisplayNamePrefix) is tuple:
858 kwargs['postProcPrefix'] = 'ParameterName('
859 else:
860 kwargs['postProcPrefix'] = postProcSpec['ppp']
861 if '{postProcSuffix}' in line:
862 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
863 if type(memberDisplayNamePrefix) is tuple:
864 kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
865 else:
866 kwargs['postProcSuffix'] = postProcSpec['pps']
867 if '{postProcInsert}' in line:
868 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
869 if type(memberDisplayNamePrefix) is tuple:
870 kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
871 else:
872 kwargs['postProcInsert'] = postProcSpec['ppi']
873 if '{funcName}' in line:
874 kwargs['funcName'] = funcName
875 if '{valuePrefix}' in line:
876 kwargs['valuePrefix'] = memberNamePrefix
877 if '{displayNamePrefix}' in line:
878 # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class
879 if type(memberDisplayNamePrefix) is tuple:
880 kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0]
881 else:
882 kwargs['displayNamePrefix'] = memberDisplayNamePrefix
883
884 if kwargs:
885 # Need to escape the C++ curly braces
886 if 'IndexVector' in line:
887 line = line.replace('IndexVector{ ', 'IndexVector{{ ')
888 line = line.replace(' }),', ' }}),')
889 return line.format(**kwargs)
890 return line
891 #
892 # Process struct validation code for inclusion in function or parent struct validation code
893 def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec):
894 for line in lines:
895 if output:
896 output[-1] += '\n'
897 if type(line) is list:
898 for sub in line:
899 output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
900 else:
901 output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
902 return output
903 #
904 # Process struct pointer/array validation code, perfoeming name substitution if required
905 def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec):
906 expr = []
907 expr.append('if ({}{} != NULL)\n'.format(prefix, value.name))
908 expr.append('{')
909 indent = self.incIndent(None)
910 if lenValue:
911 # Need to process all elements in the array
912 indexName = lenValue.name.replace('Count', 'Index')
913 expr[-1] += '\n'
Mark Young39389872017-01-19 21:10:49 -0700914 if lenValue.ispointer:
915 # If the length value is a pointer, de-reference it for the count.
916 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < *{}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
917 else:
918 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600919 expr.append(indent + '{')
920 indent = self.incIndent(indent)
921 # Prefix for value name to display in error message
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700922 if value.ispointer == 2:
923 memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName)
924 memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName)
925 else:
926 memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName)
927 memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600928 else:
929 memberNamePrefix = '{}{}->'.format(prefix, value.name)
930 memberDisplayNamePrefix = '{}->'.format(valueDisplayName)
931 #
932 # Expand the struct validation lines
933 expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec)
934 #
935 if lenValue:
936 # Close if and for scopes
937 indent = self.decIndent(indent)
938 expr.append(indent + '}\n')
939 expr.append('}\n')
940 return expr
941 #
942 # Generate the parameter checking code
943 def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName):
944 lines = [] # Generated lines of code
945 unused = [] # Unused variable names
946 for value in values:
947 usedLines = []
948 lenParam = None
949 #
950 # 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.
951 postProcSpec = {}
952 postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}'
953 postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}'
954 postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}'
955 #
956 # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name
957 valueDisplayName = '{}{}'.format(displayNamePrefix, value.name)
958 #
959 # Check for NULL pointers, ignore the inout count parameters that
960 # will be validated with their associated array
961 if (value.ispointer or value.isstaticarray) and not value.iscount:
962 #
963 # Parameters for function argument generation
964 req = 'true' # Paramerter cannot be NULL
965 cpReq = 'true' # Count pointer cannot be NULL
966 cvReq = 'true' # Count value cannot be 0
967 lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied
968 #
969 # Generate required/optional parameter strings for the pointer and count values
970 if value.isoptional:
971 req = 'false'
972 if value.len:
973 # The parameter is an array with an explicit count parameter
974 lenParam = self.getLenParam(values, value.len)
975 lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name)
976 if lenParam.ispointer:
977 # Count parameters that are pointers are inout
978 if type(lenParam.isoptional) is list:
979 if lenParam.isoptional[0]:
980 cpReq = 'false'
981 if lenParam.isoptional[1]:
982 cvReq = 'false'
983 else:
984 if lenParam.isoptional:
985 cpReq = 'false'
986 else:
987 if lenParam.isoptional:
988 cvReq = 'false'
989 #
990 # The parameter will not be processes when tagged as 'noautovalidity'
991 # For the pointer to struct case, the struct pointer will not be validated, but any
992 # members not tagged as 'noatuvalidity' will be validated
993 if value.noautovalidity:
994 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
995 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
996 else:
997 #
998 # If this is a pointer to a struct with an sType field, verify the type
999 if value.type in self.structTypes:
Mark Lobodzinski9cf24dd2017-06-28 14:23:22 -06001000 usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001001 # 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
1002 elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam):
1003 usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1004 elif value.type in self.flags and value.isconst:
1005 usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
1006 elif value.isbool and value.isconst:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001007 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 -06001008 elif value.israngedenum and value.isconst:
1009 enumRange = self.enumRanges[value.type]
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001010 usedLines.append('skipCall |= validate_ranged_enum_array(layer_data->report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, "{}", {}, {}, {pf}{}, {pf}{}, {}, {});\n'.format(funcName, lenDisplayName, valueDisplayName, value.type, enumRange[0], enumRange[1], lenParam.name, value.name, cvReq, req, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001011 elif value.name == 'pNext':
1012 # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml
1013 if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']:
Mark Lobodzinski3c828522017-06-26 13:05:57 -06001014 usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001015 else:
Mark Lobodzinski1e707bd2017-06-28 10:54:55 -06001016 usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec, structTypeName)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001017 #
1018 # If this is a pointer to a struct (input), see if it contains members that need to be checked
1019 if value.type in self.validatedStructs and value.isconst:
1020 usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec))
1021 # Non-pointer types
1022 else:
1023 #
1024 # The parameter will not be processes when tagged as 'noautovalidity'
1025 # For the struct case, the struct type will not be validated, but any
1026 # members not tagged as 'noatuvalidity' will be validated
1027 if value.noautovalidity:
1028 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1029 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1030 else:
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001031 vuid_name_tag = structTypeName if structTypeName is not None else funcName
Mark Lobodzinski85672672016-10-13 08:36:42 -06001032 if value.type in self.structTypes:
1033 stype = self.structTypes[value.type]
Mark Lobodzinski06954ea2017-06-21 12:21:45 -06001034 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
1035 usedLines.append('skipCall |= validate_struct_type(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", &({}{vn}), {sv}, false, {});\n'.format(
1036 funcName, valueDisplayName, valuePrefix, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001037 elif value.type in self.handleTypes:
1038 if not self.isHandleOptional(value, None):
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001039 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 -06001040 elif value.type in self.flags:
1041 flagBitsName = value.type.replace('Flags', 'FlagBits')
1042 if not flagBitsName in self.flagBits:
Mark Lobodzinskid0b0c512017-06-28 12:06:41 -06001043 vuid = self.GetVuid("VUID-%s-%s-zerobitmask" % (vuid_name_tag, value.name))
1044 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 -06001045 else:
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001046 if value.isoptional:
1047 flagsRequired = 'false'
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001048 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001049 else:
1050 flagsRequired = 'true'
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001051 vuid = self.GetVuid("VUID-%s-%s-requiredbitmask" % (vuid_name_tag, value.name))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001052 allFlagsName = 'All' + flagBitsName
Mark Lobodzinskie643fcc2017-06-26 16:27:15 -06001053 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 -06001054 elif value.type in self.flagBits:
1055 flagsRequired = 'false' if value.isoptional else 'true'
1056 allFlagsName = 'All' + value.type
Mark Lobodzinski024b2822017-06-27 13:22:05 -06001057 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
1058 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 -06001059 elif value.isbool:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001060 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 -06001061 elif value.israngedenum:
1062 enumRange = self.enumRanges[value.type]
Mark Lobodzinski42eb3c32017-06-28 11:47:22 -06001063 vuid = self.GetVuid("VUID-%s-%s-parameter" % (vuid_name_tag, value.name))
1064 usedLines.append('skipCall |= validate_ranged_enum(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {}, {}{}, {});\n'.format(funcName, valueDisplayName, value.type, enumRange[0], enumRange[1], valuePrefix, value.name, vuid, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001065 #
1066 # If this is a struct, see if it contains members that need to be checked
1067 if value.type in self.validatedStructs:
1068 memberNamePrefix = '{}{}.'.format(valuePrefix, value.name)
1069 memberDisplayNamePrefix = '{}.'.format(valueDisplayName)
1070 usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec))
1071 #
1072 # Append the parameter check to the function body for the current command
1073 if usedLines:
1074 # Apply special conditional checks
1075 if value.condition:
1076 usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines)
1077 lines += usedLines
1078 elif not value.iscount:
1079 # If no expression was generated for this value, it is unreferenced by the validation function, unless
1080 # it is an array count, which is indirectly referenced for array valiadation.
1081 unused.append(value.name)
1082 return lines, unused
1083 #
1084 # Generate the struct member check code from the captured data
1085 def processStructMemberData(self):
1086 indent = self.incIndent(None)
1087 for struct in self.structMembers:
1088 #
1089 # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented
1090 lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name)
1091 if lines:
1092 self.validatedStructs[struct.name] = lines
1093 #
1094 # Generate the command param check code from the captured data
1095 def processCmdData(self):
1096 indent = self.incIndent(None)
1097 for command in self.commands:
1098 # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance)
1099 startIndex = 0 if command.name == 'vkCreateInstance' else 1
1100 lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001101 # Cannot validate extension dependencies for device extension APIs a physical device as their dispatchable object
1102 if self.required_extensions and self.extension_type == 'device' and command.params[0].type != 'VkPhysicalDevice':
1103 # The actual extension names are not all available yet, so we'll tag these now and replace them just before
1104 # writing the validation routines out to a file
1105 ext_test = ''
Mark Lobodzinski26112592017-05-30 12:02:17 -06001106 for ext in self.required_extensions:
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001107 ext_name_define = ''
1108 ext_enable_name = ''
1109 for extension in self.registry.extensions:
1110 if extension.attrib['name'] == ext:
1111 ext_name_define = extension[0][1].get('name')
1112 ext_enable_name = ext_name_define.lower()
1113 ext_enable_name = re.sub('_extension_name', '', ext_enable_name)
1114 break
1115 ext_test = 'if (!layer_data->extensions.%s) skipCall |= OutputExtensionError(layer_data, "%s", %s);\n' % (ext_enable_name, command.name, ext_name_define)
1116 lines.insert(0, ext_test)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001117 if lines:
1118 cmdDef = self.getCmdDef(command) + '\n'
1119 cmdDef += '{\n'
1120 # Process unused parameters, Ignoring the first dispatch handle parameter, which is not
1121 # processed by parameter_validation (except for vkCreateInstance, which does not have a
1122 # handle as its first parameter)
1123 if unused:
1124 for name in unused:
1125 cmdDef += indent + 'UNUSED_PARAMETER({});\n'.format(name)
1126 if len(unused) > 0:
1127 cmdDef += '\n'
1128 cmdDef += indent + 'bool skipCall = false;\n'
Mark Lobodzinski26112592017-05-30 12:02:17 -06001129
Mark Lobodzinski85672672016-10-13 08:36:42 -06001130 for line in lines:
1131 cmdDef += '\n'
1132 if type(line) is list:
1133 for sub in line:
1134 cmdDef += indent + sub
1135 else:
1136 cmdDef += indent + line
1137 cmdDef += '\n'
1138 cmdDef += indent + 'return skipCall;\n'
1139 cmdDef += '}\n'
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001140 self.validation.append(cmdDef)