blob: 707b258c74093d3f3f3062b756df3d2415c75c98 [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 = [
176 '../layers/vk_validation_error_messages.h',
177 '../../layers/vk_validation_error_messages.h',
178 '../../../layers/vk_validation_error_messages.h',
179 ]
180 for vuid_filename in vuid_filename_locations:
181 if os.path.isfile(vuid_filename):
182 self.vuid_file = open(vuid_filename, "r")
183 break
184 if self.vuid_file == None:
185 print("Error: Could not find vk_validation_error_messages.h")
186 quit()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600187 #
188 def incIndent(self, indent):
189 inc = ' ' * self.INDENT_SPACES
190 if indent:
191 return indent + inc
192 return inc
193 #
194 def decIndent(self, indent):
195 if indent and (len(indent) > self.INDENT_SPACES):
196 return indent[:-self.INDENT_SPACES]
197 return ''
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600198 # Convert decimal number to 8 digit hexadecimal lower-case representation
199 def IdToHex(self, dec_num):
200 if dec_num > 4294967295:
201 print ("ERROR: Decimal # %d can't be represented in 8 hex digits" % (dec_num))
202 sys.exit()
203 hex_num = hex(dec_num)
204 return hex_num[2:].zfill(8)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600205 #
206 def beginFile(self, genOpts):
207 OutputGenerator.beginFile(self, genOpts)
208 # C-specific
209 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600210 # Open vk_validation_error_messages.h file to verify computed VUIDs
211 for line in self.vuid_file:
212 # Grab hex number from enum definition
213 vuid_list = line.split('0x')
214 # If this is a valid enumeration line, remove trailing comma and CR
215 if len(vuid_list) == 2:
216 vuid_num = vuid_list[1][:-2]
217 # Make sure this is a good hex number before adding to set
218 if len(vuid_num) == 8 and all(c in string.hexdigits for c in vuid_num):
219 self.valid_vuids.add(vuid_num)
220 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600221 # User-supplied prefix text, if any (list of strings)
222 if (genOpts.prefixText):
223 for s in genOpts.prefixText:
224 write(s, file=self.outFile)
225 #
226 # Multiple inclusion protection & C++ wrappers.
227 if (genOpts.protectFile and self.genOpts.filename):
228 headerSym = re.sub('\.h', '_H', os.path.basename(self.genOpts.filename)).upper()
229 write('#ifndef', headerSym, file=self.outFile)
230 write('#define', headerSym, '1', file=self.outFile)
231 self.newline()
232 #
233 # Headers
234 write('#include <string>', file=self.outFile)
235 self.newline()
236 write('#include "vulkan/vulkan.h"', file=self.outFile)
237 write('#include "vk_layer_extension_utils.h"', file=self.outFile)
238 write('#include "parameter_validation_utils.h"', file=self.outFile)
239 #
240 # Macros
241 self.newline()
242 write('#ifndef UNUSED_PARAMETER', file=self.outFile)
243 write('#define UNUSED_PARAMETER(x) (void)(x)', file=self.outFile)
244 write('#endif // UNUSED_PARAMETER', file=self.outFile)
245 #
246 # Namespace
247 self.newline()
248 write('namespace parameter_validation {', file = self.outFile)
249 def endFile(self):
250 # C-specific
251 self.newline()
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600252 commands_text = '\n'.join(self.validation)
253 write(commands_text, file=self.outFile)
254 self.newline()
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700255 # Output declarations and record intercepted procedures
256 write('// Declarations', file=self.outFile)
257 write('\n'.join(self.declarations), file=self.outFile)
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600258 write('// Map of all APIs to be intercepted by this layer', file=self.outFile)
259 write('static const std::unordered_map<std::string, void*> name_to_funcptr_map = {', file=self.outFile)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700260 write('\n'.join(self.intercepts), file=self.outFile)
261 write('};\n', file=self.outFile)
262 self.newline()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600263 # Namespace
264 write('} // namespace parameter_validation', file = self.outFile)
265 # Finish C++ wrapper and multiple inclusion protection
266 if (self.genOpts.protectFile and self.genOpts.filename):
267 self.newline()
268 write('#endif', file=self.outFile)
269 # Finish processing in superclass
270 OutputGenerator.endFile(self)
271 def beginFeature(self, interface, emit):
272 # Start processing in superclass
273 OutputGenerator.beginFeature(self, interface, emit)
274 # C-specific
275 # Accumulate includes, defines, types, enums, function pointer typedefs,
276 # end function prototypes separately for this feature. They're only
277 # printed in endFeature().
278 self.headerVersion = None
Mark Lobodzinski85672672016-10-13 08:36:42 -0600279 self.structNames = []
280 self.stypes = []
281 self.structTypes = dict()
Mark Lobodzinski85672672016-10-13 08:36:42 -0600282 self.commands = []
283 self.structMembers = []
Chris Forbes78ea32d2016-11-28 11:14:17 +1300284 self.newFlags = set()
Mark Lobodzinski26112592017-05-30 12:02:17 -0600285 # Save list of required extensions for this extension
286 self.required_extensions = []
287 if self.featureName != "VK_VERSION_1_0":
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600288 # Save Name Define to get correct enable name later
289 nameElem = interface[0][1]
290 name = nameElem.get('name')
291 self.extension_names[self.featureName] = name
292 # This extension is the first dependency for this command
Mark Lobodzinski26112592017-05-30 12:02:17 -0600293 self.required_extensions.append(self.featureName)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600294 # Add any defined extension dependencies to the dependency list for this command
Mark Lobodzinski26112592017-05-30 12:02:17 -0600295 required_extensions = interface.get('requires')
296 if required_extensions is not None:
297 self.required_extensions.extend(required_extensions.split(','))
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600298 # And note if this is an Instance or Device extension
299 self.extension_type = interface.get('type')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600300 def endFeature(self):
301 # C-specific
302 # Actually write the interface to the output file.
303 if (self.emit):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600304 # If type declarations are needed by other features based on
305 # this one, it may be necessary to suppress the ExtraProtect,
306 # or move it below the 'for section...' loop.
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600307 ifdef = ''
Mark Lobodzinski85672672016-10-13 08:36:42 -0600308 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600309 ifdef = '#ifdef %s\n' % self.featureExtraProtect
310 self.validation.append(ifdef)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600311 # Generate the struct member checking code from the captured data
312 self.processStructMemberData()
313 # Generate the command parameter checking code from the captured data
314 self.processCmdData()
315 # Write the declaration for the HeaderVersion
316 if self.headerVersion:
317 write('const uint32_t GeneratedHeaderVersion = {};'.format(self.headerVersion), file=self.outFile)
318 self.newline()
319 # Write the declarations for the VkFlags values combining all flag bits
Chris Forbes78ea32d2016-11-28 11:14:17 +1300320 for flag in sorted(self.newFlags):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600321 flagBits = flag.replace('Flags', 'FlagBits')
322 if flagBits in self.flagBits:
323 bits = self.flagBits[flagBits]
324 decl = 'const {} All{} = {}'.format(flag, flagBits, bits[0])
325 for bit in bits[1:]:
326 decl += '|' + bit
327 decl += ';'
328 write(decl, file=self.outFile)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600329 endif = '\n'
Mark Lobodzinski85672672016-10-13 08:36:42 -0600330 if (self.featureExtraProtect != None):
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600331 endif = '#endif // %s\n' % self.featureExtraProtect
332 self.validation.append(endif)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600333 # Finish processing in superclass
334 OutputGenerator.endFeature(self)
335 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600336 # Type generation
337 def genType(self, typeinfo, name):
338 OutputGenerator.genType(self, typeinfo, name)
339 typeElem = typeinfo.elem
340 # If the type is a struct type, traverse the imbedded <member> tags
341 # generating a structure. Otherwise, emit the tag text.
342 category = typeElem.get('category')
343 if (category == 'struct' or category == 'union'):
344 self.structNames.append(name)
345 self.genStruct(typeinfo, name)
346 elif (category == 'handle'):
347 self.handleTypes.add(name)
348 elif (category == 'bitmask'):
349 self.flags.add(name)
Chris Forbes78ea32d2016-11-28 11:14:17 +1300350 self.newFlags.add(name)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600351 elif (category == 'define'):
352 if name == 'VK_HEADER_VERSION':
353 nameElem = typeElem.find('name')
354 self.headerVersion = noneStr(nameElem.tail).strip()
355 #
356 # Struct parameter check generation.
357 # This is a special case of the <type> tag where the contents are
358 # interpreted as a set of <member> tags instead of freeform C
359 # C type declarations. The <member> tags are just like <param>
360 # tags - they are a declaration of a struct or union member.
361 # Only simple member declarations are supported (no nested
362 # structs etc.)
363 def genStruct(self, typeinfo, typeName):
364 OutputGenerator.genStruct(self, typeinfo, typeName)
365 conditions = self.structMemberValidationConditions[typeName] if typeName in self.structMemberValidationConditions else None
366 members = typeinfo.elem.findall('.//member')
367 #
368 # Iterate over members once to get length parameters for arrays
369 lens = set()
370 for member in members:
371 len = self.getLen(member)
372 if len:
373 lens.add(len)
374 #
375 # Generate member info
376 membersInfo = []
377 for member in members:
378 # Get the member's type and name
379 info = self.getTypeNameTuple(member)
380 type = info[0]
381 name = info[1]
382 stypeValue = ''
383 cdecl = self.makeCParamDecl(member, 0)
384 # Process VkStructureType
385 if type == 'VkStructureType':
386 # Extract the required struct type value from the comments
387 # embedded in the original text defining the 'typeinfo' element
388 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
389 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
390 if result:
391 value = result.group(0)
392 else:
393 value = self.genVkStructureType(typeName)
394 # Store the required type value
395 self.structTypes[typeName] = self.StructType(name=name, value=value)
396 #
397 # Store pointer/array/string info
398 # Check for parameter name in lens set
399 iscount = False
400 if name in lens:
401 iscount = True
402 # The pNext members are not tagged as optional, but are treated as
403 # optional for parameter NULL checks. Static array members
404 # are also treated as optional to skip NULL pointer validation, as
405 # they won't be NULL.
406 isstaticarray = self.paramIsStaticArray(member)
407 isoptional = False
408 if self.paramIsOptional(member) or (name == 'pNext') or (isstaticarray):
409 isoptional = True
Dustin Gravesce68f082017-03-30 15:42:16 -0600410 # Determine if value should be ignored by code generation.
411 noautovalidity = False
412 if (member.attrib.get('noautovalidity') is not None) or ((typeName in self.structMemberBlacklist) and (name in self.structMemberBlacklist[typeName])):
413 noautovalidity = True
Mark Lobodzinski85672672016-10-13 08:36:42 -0600414 membersInfo.append(self.CommandParam(type=type, name=name,
415 ispointer=self.paramIsPointer(member),
416 isstaticarray=isstaticarray,
417 isbool=True if type == 'VkBool32' else False,
418 israngedenum=True if type in self.enumRanges else False,
419 isconst=True if 'const' in cdecl else False,
420 isoptional=isoptional,
421 iscount=iscount,
Dustin Gravesce68f082017-03-30 15:42:16 -0600422 noautovalidity=noautovalidity,
Mark Lobodzinski85672672016-10-13 08:36:42 -0600423 len=self.getLen(member),
424 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
425 condition=conditions[name] if conditions and name in conditions else None,
426 cdecl=cdecl))
427 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
428 #
429 # Capture group (e.g. C "enum" type) info to be used for
430 # param check code generation.
431 # These are concatenated together with other types.
432 def genGroup(self, groupinfo, groupName):
433 OutputGenerator.genGroup(self, groupinfo, groupName)
434 groupElem = groupinfo.elem
435 #
436 # Store the sType values
437 if groupName == 'VkStructureType':
438 for elem in groupElem.findall('enum'):
439 self.stypes.append(elem.get('name'))
440 elif 'FlagBits' in groupName:
441 bits = []
442 for elem in groupElem.findall('enum'):
443 bits.append(elem.get('name'))
444 if bits:
445 self.flagBits[groupName] = bits
446 else:
447 # Determine if begin/end ranges are needed (we don't do this for VkStructureType, which has a more finely grained check)
448 expandName = re.sub(r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)',r'\1_\2',groupName).upper()
449 expandPrefix = expandName
450 expandSuffix = ''
451 expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName)
452 if expandSuffixMatch:
453 expandSuffix = '_' + expandSuffixMatch.group()
454 # Strip off the suffix from the prefix
455 expandPrefix = expandName.rsplit(expandSuffix, 1)[0]
456 isEnum = ('FLAG_BITS' not in expandPrefix)
457 if isEnum:
458 self.enumRanges[groupName] = (expandPrefix + '_BEGIN_RANGE' + expandSuffix, expandPrefix + '_END_RANGE' + expandSuffix)
459 #
460 # Capture command parameter info to be used for param
461 # check code generation.
462 def genCmd(self, cmdinfo, name):
463 OutputGenerator.genCmd(self, cmdinfo, name)
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700464 interface_functions = [
465 'vkEnumerateInstanceLayerProperties',
466 'vkEnumerateInstanceExtensionProperties',
467 'vkEnumerateDeviceLayerProperties',
Mark Lobodzinski099b3b62017-02-08 16:04:35 -0700468 'vkCmdDebugMarkerEndEXT', # No validation!
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700469 ]
470 # Record that the function will be intercepted
471 if name not in interface_functions:
472 if (self.featureExtraProtect != None):
473 self.declarations += [ '#ifdef %s' % self.featureExtraProtect ]
474 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
Mark Lobodzinskide43e642017-06-07 14:00:31 -0600475 self.intercepts += [ ' {"%s", (void*)%s},' % (name,name[2:]) ]
Mark Lobodzinskib6b8bbd2017-02-08 14:37:15 -0700476 decls = self.makeCDecls(cmdinfo.elem)
477 # Strip off 'vk' from API name
478 self.declarations += [ '%s' % decls[0].replace("VKAPI_CALL vk", "VKAPI_CALL ") ]
479 if (self.featureExtraProtect != None):
480 self.intercepts += [ '#endif' ]
481 self.declarations += [ '#endif' ]
Mark Lobodzinski85672672016-10-13 08:36:42 -0600482 if name not in self.blacklist:
483 params = cmdinfo.elem.findall('param')
484 # Get list of array lengths
485 lens = set()
486 for param in params:
487 len = self.getLen(param)
488 if len:
489 lens.add(len)
490 # Get param info
491 paramsInfo = []
492 for param in params:
493 paramInfo = self.getTypeNameTuple(param)
494 cdecl = self.makeCParamDecl(param, 0)
495 # Check for parameter name in lens set
496 iscount = False
497 if paramInfo[1] in lens:
498 iscount = True
499 paramsInfo.append(self.CommandParam(type=paramInfo[0], name=paramInfo[1],
500 ispointer=self.paramIsPointer(param),
501 isstaticarray=self.paramIsStaticArray(param),
502 isbool=True if paramInfo[0] == 'VkBool32' else False,
503 israngedenum=True if paramInfo[0] in self.enumRanges else False,
504 isconst=True if 'const' in cdecl else False,
505 isoptional=self.paramIsOptional(param),
506 iscount=iscount,
507 noautovalidity=True if param.attrib.get('noautovalidity') is not None else False,
508 len=self.getLen(param),
509 extstructs=None,
510 condition=None,
511 cdecl=cdecl))
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -0600512 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 -0600513 #
514 # Check if the parameter passed in is a pointer
515 def paramIsPointer(self, param):
516 ispointer = 0
517 paramtype = param.find('type')
518 if (paramtype.tail is not None) and ('*' in paramtype.tail):
519 ispointer = paramtype.tail.count('*')
520 elif paramtype.text[:4] == 'PFN_':
521 # Treat function pointer typedefs as a pointer to a single value
522 ispointer = 1
523 return ispointer
524 #
525 # Check if the parameter passed in is a static array
526 def paramIsStaticArray(self, param):
527 isstaticarray = 0
528 paramname = param.find('name')
529 if (paramname.tail is not None) and ('[' in paramname.tail):
530 isstaticarray = paramname.tail.count('[')
531 return isstaticarray
532 #
533 # Check if the parameter passed in is optional
534 # Returns a list of Boolean values for comma separated len attributes (len='false,true')
535 def paramIsOptional(self, param):
536 # See if the handle is optional
537 isoptional = False
538 # Simple, if it's optional, return true
539 optString = param.attrib.get('optional')
540 if optString:
541 if optString == 'true':
542 isoptional = True
543 elif ',' in optString:
544 opts = []
545 for opt in optString.split(','):
546 val = opt.strip()
547 if val == 'true':
548 opts.append(True)
549 elif val == 'false':
550 opts.append(False)
551 else:
552 print('Unrecognized len attribute value',val)
553 isoptional = opts
554 return isoptional
555 #
556 # Check if the handle passed in is optional
557 # Uses the same logic as ValidityOutputGenerator.isHandleOptional
558 def isHandleOptional(self, param, lenParam):
559 # Simple, if it's optional, return true
560 if param.isoptional:
561 return True
562 # If no validity is being generated, it usually means that validity is complex and not absolute, so let's say yes.
563 if param.noautovalidity:
564 return True
565 # If the parameter is an array and we haven't already returned, find out if any of the len parameters are optional
566 if lenParam and lenParam.isoptional:
567 return True
568 return False
569 #
570 # Generate a VkStructureType based on a structure typename
571 def genVkStructureType(self, typename):
572 # Add underscore between lowercase then uppercase
573 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
Mark Young39389872017-01-19 21:10:49 -0700574 value = value.replace('D3_D12', 'D3D12')
575 value = value.replace('Device_IDProp', 'Device_ID_Prop')
Mark Lobodzinski85672672016-10-13 08:36:42 -0600576 # Change to uppercase
577 value = value.upper()
578 # Add STRUCTURE_TYPE_
579 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
580 #
581 # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType
582 # value assuming the struct is defined by a different feature
583 def getStructType(self, typename):
584 value = None
585 if typename in self.structTypes:
586 value = self.structTypes[typename].value
587 else:
588 value = self.genVkStructureType(typename)
589 self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename))
590 return value
591 #
592 # Retrieve the value of the len tag
593 def getLen(self, param):
594 result = None
595 len = param.attrib.get('len')
596 if len and len != 'null-terminated':
597 # For string arrays, 'len' can look like 'count,null-terminated',
598 # indicating that we have a null terminated array of strings. We
599 # strip the null-terminated from the 'len' field and only return
600 # the parameter specifying the string count
601 if 'null-terminated' in len:
602 result = len.split(',')[0]
603 else:
604 result = len
605 result = str(result).replace('::', '->')
606 return result
607 #
608 # Retrieve the type and name for a parameter
609 def getTypeNameTuple(self, param):
610 type = ''
611 name = ''
612 for elem in param:
613 if elem.tag == 'type':
614 type = noneStr(elem.text)
615 elif elem.tag == 'name':
616 name = noneStr(elem.text)
617 return (type, name)
618 #
619 # Find a named parameter in a parameter list
620 def getParamByName(self, params, name):
621 for param in params:
622 if param.name == name:
623 return param
624 return None
625 #
626 # Extract length values from latexmath. Currently an inflexible solution that looks for specific
627 # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced.
628 def parseLateXMath(self, source):
629 name = 'ERROR'
630 decoratedName = 'ERROR'
631 if 'mathit' in source:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700632 # Matches expressions similar to 'latexmath:[\lceil{\mathit{rasterizationSamples} \over 32}\rceil]'
633 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 -0600634 if not match or match.group(1) != match.group(4):
635 raise 'Unrecognized latexmath expression'
636 name = match.group(2)
637 decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3))
638 else:
Mark Lobodzinski36c33862017-02-13 10:15:53 -0700639 # Matches expressions similar to 'latexmath : [dataSize \over 4]'
Mark Young0f183a82017-02-28 09:58:04 -0700640 match = re.match(r'latexmath\s*\:\s*\[\s*(\w+)\s*\\over\s*(\d+)\s*\]', source)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600641 name = match.group(1)
642 decoratedName = '{}/{}'.format(*match.group(1, 2))
643 return name, decoratedName
644 #
645 # Get the length paramater record for the specified parameter name
646 def getLenParam(self, params, name):
647 lenParam = None
648 if name:
649 if '->' in name:
650 # The count is obtained by dereferencing a member of a struct parameter
651 lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False,
652 isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None,
653 condition=None, cdecl=None)
654 elif 'latexmath' in name:
655 lenName, decoratedName = self.parseLateXMath(name)
656 lenParam = self.getParamByName(params, lenName)
657 # TODO: Zero-check the result produced by the equation?
658 # Copy the stored len parameter entry and overwrite the name with the processed latexmath equation
659 #param = self.getParamByName(params, lenName)
660 #lenParam = self.CommandParam(name=decoratedName, iscount=param.iscount, ispointer=param.ispointer,
661 # isoptional=param.isoptional, type=param.type, len=param.len,
662 # isstaticarray=param.isstaticarray, extstructs=param.extstructs,
663 # noautovalidity=True, condition=None, cdecl=param.cdecl)
664 else:
665 lenParam = self.getParamByName(params, name)
666 return lenParam
667 #
668 # Convert a vulkan.h command declaration into a parameter_validation.h definition
669 def getCmdDef(self, cmd):
Mark Lobodzinski85672672016-10-13 08:36:42 -0600670 # Strip the trailing ';' and split into individual lines
671 lines = cmd.cdecl[:-1].split('\n')
672 # Replace Vulkan prototype
673 lines[0] = 'static bool parameter_validation_' + cmd.name + '('
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600674 # Replace the first argument with debug_report_data, when the first argument is a handle (not vkCreateInstance)
675 if cmd.name == 'vkCreateInstance':
676 lines.insert(1, ' instance_layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,')
677 else:
678 if cmd.params[0].type in ["VkInstance", "VkPhysicalDevice"]:
679 reportData = ' instance_layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,'
680 else:
681 reportData = ' layer_data*'.ljust(self.genOpts.alignFuncParam) + 'layer_data,'
Mark Lobodzinski26112592017-05-30 12:02:17 -0600682 if len(lines) < 3: # Terminate correctly if single parameter
683 lines[1] = reportData[:-1] + ')'
684 else:
685 lines[1] = reportData
Mark Lobodzinski85672672016-10-13 08:36:42 -0600686 return '\n'.join(lines)
687 #
688 # Generate the code to check for a NULL dereference before calling the
689 # validation function
690 def genCheckedLengthCall(self, name, exprs):
691 count = name.count('->')
692 if count:
693 checkedExpr = []
694 localIndent = ''
695 elements = name.split('->')
696 # Open the if expression blocks
697 for i in range(0, count):
698 checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1])))
699 localIndent = self.incIndent(localIndent)
700 # Add the validation expression
701 for expr in exprs:
702 checkedExpr.append(localIndent + expr)
703 # Close the if blocks
704 for i in range(0, count):
705 localIndent = self.decIndent(localIndent)
706 checkedExpr.append(localIndent + '}\n')
707 return [checkedExpr]
708 # No if statements were required
709 return exprs
710 #
711 # Generate code to check for a specific condition before executing validation code
712 def genConditionalCall(self, prefix, condition, exprs):
713 checkedExpr = []
714 localIndent = ''
715 formattedCondition = condition.format(prefix)
716 checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition))
717 checkedExpr.append(localIndent + '{\n')
718 localIndent = self.incIndent(localIndent)
719 for expr in exprs:
720 checkedExpr.append(localIndent + expr)
721 localIndent = self.decIndent(localIndent)
722 checkedExpr.append(localIndent + '}\n')
723 return [checkedExpr]
724 #
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600725 # Get VUID identifier from implicit VUID tag
726 def GetVuid(self, vuid_string):
727 vuid_num = self.IdToHex(convertVUID(vuid_string))
728 if vuid_num in self.valid_vuids:
729 vuid = "VALIDATION_ERROR_%s" % vuid_num
730 else:
731 vuid = "VALIDATION_ERROR_UNDEFINED"
732 return vuid
733 #
Mark Lobodzinski85672672016-10-13 08:36:42 -0600734 # Generate the sType check string
735 def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
736 checkExpr = []
737 stype = self.structTypes[value.type]
738 if lenValue:
739 # This is an array with a pointer to a count value
740 if lenValue.ispointer:
741 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600742 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(
Mark Lobodzinski85672672016-10-13 08:36:42 -0600743 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
744 # This is an array with an integer count value
745 else:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600746 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(
Mark Lobodzinski85672672016-10-13 08:36:42 -0600747 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec))
748 # This is an individual struct
749 else:
Mark Lobodzinski06954ea2017-06-21 12:21:45 -0600750 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
751 checkExpr.append('skipCall |= validate_struct_type(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {}, {});\n'.format(
752 funcPrintName, valuePrintName, prefix, valueRequired, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600753 return checkExpr
754 #
755 # Generate the handle check string
756 def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
757 checkExpr = []
758 if lenValue:
759 if lenValue.ispointer:
760 # This is assumed to be an output array with a pointer to a count value
761 raise('Unsupported parameter validation case: Output handle array elements are not NULL checked')
762 else:
763 # This is an array with an integer count value
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600764 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 -0600765 funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
766 else:
767 # This is assumed to be an output handle pointer
768 raise('Unsupported parameter validation case: Output handles are not NULL checked')
769 return checkExpr
770 #
771 # Generate check string for an array of VkFlags values
772 def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
773 checkExpr = []
774 flagBitsName = value.type.replace('Flags', 'FlagBits')
775 if not flagBitsName in self.flagBits:
776 raise('Unsupported parameter validation case: array of reserved VkFlags')
777 else:
778 allFlags = 'All' + flagBitsName
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600779 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 -0600780 return checkExpr
781 #
782 # Generate pNext check string
783 def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec):
784 checkExpr = []
785 # Generate an array of acceptable VkStructureType values for pNext
786 extStructCount = 0
787 extStructVar = 'NULL'
788 extStructNames = 'NULL'
789 if value.extstructs:
790 structs = value.extstructs.split(',')
791 checkExpr.append('const VkStructureType allowedStructs[] = {' + ', '.join([self.getStructType(s) for s in structs]) + '};\n')
792 extStructCount = 'ARRAY_SIZE(allowedStructs)'
793 extStructVar = 'allowedStructs'
794 extStructNames = '"' + ', '.join(structs) + '"'
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600795 checkExpr.append('skipCall |= validate_struct_pnext(layer_data->report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion);\n'.format(
Mark Lobodzinski85672672016-10-13 08:36:42 -0600796 funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, **postProcSpec))
797 return checkExpr
798 #
799 # Generate the pointer check string
800 def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec):
801 checkExpr = []
802 if lenValue:
803 # This is an array with a pointer to a count value
804 if lenValue.ispointer:
805 # If count and array parameters are optional, there will be no validation
806 if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true':
807 # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600808 checkExpr.append('skipCall |= validate_array(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {});\n'.format(
Mark Lobodzinski85672672016-10-13 08:36:42 -0600809 funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
810 # This is an array with an integer count value
811 else:
812 # If count and array parameters are optional, there will be no validation
813 if valueRequired == 'true' or lenValueRequired == 'true':
814 # Arrays of strings receive special processing
815 validationFuncName = 'validate_array' if value.type != 'char' else 'validate_string_array'
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600816 checkExpr.append('skipCall |= {}(layer_data->report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format(
Mark Lobodzinski85672672016-10-13 08:36:42 -0600817 validationFuncName, funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec))
818 if checkExpr:
819 if lenValue and ('->' in lenValue.name):
820 # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count
821 checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr)
822 # This is an individual struct that is not allowed to be NULL
823 elif not value.isoptional:
824 # Function pointers need a reinterpret_cast to void*
825 if value.type[:4] == 'PFN_':
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600826 checkExpr.append('skipCall |= validate_required_pointer(layer_data->report_data, "{}", {ppp}"{}"{pps}, reinterpret_cast<const void*>({}{}));\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600827 else:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600828 checkExpr.append('skipCall |= validate_required_pointer(layer_data->report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600829 return checkExpr
830 #
831 # Process struct member validation code, performing name suibstitution if required
832 def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec):
833 # Build format specifier list
834 kwargs = {}
835 if '{postProcPrefix}' in line:
836 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
837 if type(memberDisplayNamePrefix) is tuple:
838 kwargs['postProcPrefix'] = 'ParameterName('
839 else:
840 kwargs['postProcPrefix'] = postProcSpec['ppp']
841 if '{postProcSuffix}' in line:
842 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
843 if type(memberDisplayNamePrefix) is tuple:
844 kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
845 else:
846 kwargs['postProcSuffix'] = postProcSpec['pps']
847 if '{postProcInsert}' in line:
848 # If we have a tuple that includes a format string and format parameters, need to use ParameterName class
849 if type(memberDisplayNamePrefix) is tuple:
850 kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1])
851 else:
852 kwargs['postProcInsert'] = postProcSpec['ppi']
853 if '{funcName}' in line:
854 kwargs['funcName'] = funcName
855 if '{valuePrefix}' in line:
856 kwargs['valuePrefix'] = memberNamePrefix
857 if '{displayNamePrefix}' in line:
858 # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class
859 if type(memberDisplayNamePrefix) is tuple:
860 kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0]
861 else:
862 kwargs['displayNamePrefix'] = memberDisplayNamePrefix
863
864 if kwargs:
865 # Need to escape the C++ curly braces
866 if 'IndexVector' in line:
867 line = line.replace('IndexVector{ ', 'IndexVector{{ ')
868 line = line.replace(' }),', ' }}),')
869 return line.format(**kwargs)
870 return line
871 #
872 # Process struct validation code for inclusion in function or parent struct validation code
873 def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec):
874 for line in lines:
875 if output:
876 output[-1] += '\n'
877 if type(line) is list:
878 for sub in line:
879 output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
880 else:
881 output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec))
882 return output
883 #
884 # Process struct pointer/array validation code, perfoeming name substitution if required
885 def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec):
886 expr = []
887 expr.append('if ({}{} != NULL)\n'.format(prefix, value.name))
888 expr.append('{')
889 indent = self.incIndent(None)
890 if lenValue:
891 # Need to process all elements in the array
892 indexName = lenValue.name.replace('Count', 'Index')
893 expr[-1] += '\n'
Mark Young39389872017-01-19 21:10:49 -0700894 if lenValue.ispointer:
895 # If the length value is a pointer, de-reference it for the count.
896 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < *{}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
897 else:
898 expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName))
Mark Lobodzinski85672672016-10-13 08:36:42 -0600899 expr.append(indent + '{')
900 indent = self.incIndent(indent)
901 # Prefix for value name to display in error message
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -0700902 if value.ispointer == 2:
903 memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName)
904 memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName)
905 else:
906 memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName)
907 memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName)
Mark Lobodzinski85672672016-10-13 08:36:42 -0600908 else:
909 memberNamePrefix = '{}{}->'.format(prefix, value.name)
910 memberDisplayNamePrefix = '{}->'.format(valueDisplayName)
911 #
912 # Expand the struct validation lines
913 expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec)
914 #
915 if lenValue:
916 # Close if and for scopes
917 indent = self.decIndent(indent)
918 expr.append(indent + '}\n')
919 expr.append('}\n')
920 return expr
921 #
922 # Generate the parameter checking code
923 def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName):
924 lines = [] # Generated lines of code
925 unused = [] # Unused variable names
926 for value in values:
927 usedLines = []
928 lenParam = None
929 #
930 # 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.
931 postProcSpec = {}
932 postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}'
933 postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}'
934 postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}'
935 #
936 # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name
937 valueDisplayName = '{}{}'.format(displayNamePrefix, value.name)
938 #
939 # Check for NULL pointers, ignore the inout count parameters that
940 # will be validated with their associated array
941 if (value.ispointer or value.isstaticarray) and not value.iscount:
942 #
943 # Parameters for function argument generation
944 req = 'true' # Paramerter cannot be NULL
945 cpReq = 'true' # Count pointer cannot be NULL
946 cvReq = 'true' # Count value cannot be 0
947 lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied
948 #
949 # Generate required/optional parameter strings for the pointer and count values
950 if value.isoptional:
951 req = 'false'
952 if value.len:
953 # The parameter is an array with an explicit count parameter
954 lenParam = self.getLenParam(values, value.len)
955 lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name)
956 if lenParam.ispointer:
957 # Count parameters that are pointers are inout
958 if type(lenParam.isoptional) is list:
959 if lenParam.isoptional[0]:
960 cpReq = 'false'
961 if lenParam.isoptional[1]:
962 cvReq = 'false'
963 else:
964 if lenParam.isoptional:
965 cpReq = 'false'
966 else:
967 if lenParam.isoptional:
968 cvReq = 'false'
969 #
970 # The parameter will not be processes when tagged as 'noautovalidity'
971 # For the pointer to struct case, the struct pointer will not be validated, but any
972 # members not tagged as 'noatuvalidity' will be validated
973 if value.noautovalidity:
974 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
975 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
976 else:
977 #
978 # If this is a pointer to a struct with an sType field, verify the type
979 if value.type in self.structTypes:
980 usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
981 # 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
982 elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam):
983 usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
984 elif value.type in self.flags and value.isconst:
985 usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
986 elif value.isbool and value.isconst:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600987 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 -0600988 elif value.israngedenum and value.isconst:
989 enumRange = self.enumRanges[value.type]
Mark Lobodzinski858d5df2017-05-30 14:11:04 -0600990 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 -0600991 elif value.name == 'pNext':
992 # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml
993 if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']:
994 usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec)
995 else:
996 usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec)
997 #
998 # If this is a pointer to a struct (input), see if it contains members that need to be checked
999 if value.type in self.validatedStructs and value.isconst:
1000 usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec))
1001 # Non-pointer types
1002 else:
1003 #
1004 # The parameter will not be processes when tagged as 'noautovalidity'
1005 # For the struct case, the struct type will not be validated, but any
1006 # members not tagged as 'noatuvalidity' will be validated
1007 if value.noautovalidity:
1008 # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually
1009 self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name))
1010 else:
1011 if value.type in self.structTypes:
1012 stype = self.structTypes[value.type]
Mark Lobodzinski06954ea2017-06-21 12:21:45 -06001013 vuid = self.GetVuid("VUID-%s-sType-sType" % value.type)
1014 usedLines.append('skipCall |= validate_struct_type(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{sv}", &({}{vn}), {sv}, false, {});\n'.format(
1015 funcName, valueDisplayName, valuePrefix, vuid, vn=value.name, sv=stype.value, vt=value.type, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001016 elif value.type in self.handleTypes:
1017 if not self.isHandleOptional(value, None):
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001018 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 -06001019 elif value.type in self.flags:
1020 flagBitsName = value.type.replace('Flags', 'FlagBits')
1021 if not flagBitsName in self.flagBits:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001022 usedLines.append('skipCall |= validate_reserved_flags(layer_data->report_data, "{}", {ppp}"{}"{pps}, {pf}{});\n'.format(funcName, valueDisplayName, value.name, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001023 else:
1024 flagsRequired = 'false' if value.isoptional else 'true'
1025 allFlagsName = 'All' + flagBitsName
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001026 usedLines.append('skipCall |= validate_flags(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {pf}{}, {}, false);\n'.format(funcName, valueDisplayName, flagBitsName, allFlagsName, value.name, flagsRequired, pf=valuePrefix, **postProcSpec))
Mike Schuchardt47619c82017-05-31 09:14:22 -06001027 elif value.type in self.flagBits:
1028 flagsRequired = 'false' if value.isoptional else 'true'
1029 allFlagsName = 'All' + value.type
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001030 usedLines.append('skipCall |= validate_flags(layer_data->report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {pf}{}, {}, true);\n'.format(funcName, valueDisplayName, value.type, allFlagsName, value.name, flagsRequired, pf=valuePrefix, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001031 elif value.isbool:
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001032 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 -06001033 elif value.israngedenum:
1034 enumRange = self.enumRanges[value.type]
Mark Lobodzinski6f82eb52016-12-05 07:38:41 -07001035 if value.type == "VkObjectEntryTypeNVX":
1036 garbage = 2
Mark Lobodzinski858d5df2017-05-30 14:11:04 -06001037 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, **postProcSpec))
Mark Lobodzinski85672672016-10-13 08:36:42 -06001038 #
1039 # If this is a struct, see if it contains members that need to be checked
1040 if value.type in self.validatedStructs:
1041 memberNamePrefix = '{}{}.'.format(valuePrefix, value.name)
1042 memberDisplayNamePrefix = '{}.'.format(valueDisplayName)
1043 usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec))
1044 #
1045 # Append the parameter check to the function body for the current command
1046 if usedLines:
1047 # Apply special conditional checks
1048 if value.condition:
1049 usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines)
1050 lines += usedLines
1051 elif not value.iscount:
1052 # If no expression was generated for this value, it is unreferenced by the validation function, unless
1053 # it is an array count, which is indirectly referenced for array valiadation.
1054 unused.append(value.name)
1055 return lines, unused
1056 #
1057 # Generate the struct member check code from the captured data
1058 def processStructMemberData(self):
1059 indent = self.incIndent(None)
1060 for struct in self.structMembers:
1061 #
1062 # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented
1063 lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name)
1064 if lines:
1065 self.validatedStructs[struct.name] = lines
1066 #
1067 # Generate the command param check code from the captured data
1068 def processCmdData(self):
1069 indent = self.incIndent(None)
1070 for command in self.commands:
1071 # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance)
1072 startIndex = 0 if command.name == 'vkCreateInstance' else 1
1073 lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None)
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001074 # Cannot validate extension dependencies for device extension APIs a physical device as their dispatchable object
1075 if self.required_extensions and self.extension_type == 'device' and command.params[0].type != 'VkPhysicalDevice':
1076 # The actual extension names are not all available yet, so we'll tag these now and replace them just before
1077 # writing the validation routines out to a file
1078 ext_test = ''
Mark Lobodzinski26112592017-05-30 12:02:17 -06001079 for ext in self.required_extensions:
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001080 ext_name_define = ''
1081 ext_enable_name = ''
1082 for extension in self.registry.extensions:
1083 if extension.attrib['name'] == ext:
1084 ext_name_define = extension[0][1].get('name')
1085 ext_enable_name = ext_name_define.lower()
1086 ext_enable_name = re.sub('_extension_name', '', ext_enable_name)
1087 break
1088 ext_test = 'if (!layer_data->extensions.%s) skipCall |= OutputExtensionError(layer_data, "%s", %s);\n' % (ext_enable_name, command.name, ext_name_define)
1089 lines.insert(0, ext_test)
Mark Lobodzinski85672672016-10-13 08:36:42 -06001090 if lines:
1091 cmdDef = self.getCmdDef(command) + '\n'
1092 cmdDef += '{\n'
1093 # Process unused parameters, Ignoring the first dispatch handle parameter, which is not
1094 # processed by parameter_validation (except for vkCreateInstance, which does not have a
1095 # handle as its first parameter)
1096 if unused:
1097 for name in unused:
1098 cmdDef += indent + 'UNUSED_PARAMETER({});\n'.format(name)
1099 if len(unused) > 0:
1100 cmdDef += '\n'
1101 cmdDef += indent + 'bool skipCall = false;\n'
Mark Lobodzinski26112592017-05-30 12:02:17 -06001102
Mark Lobodzinski85672672016-10-13 08:36:42 -06001103 for line in lines:
1104 cmdDef += '\n'
1105 if type(line) is list:
1106 for sub in line:
1107 cmdDef += indent + sub
1108 else:
1109 cmdDef += indent + line
1110 cmdDef += '\n'
1111 cmdDef += indent + 'return skipCall;\n'
1112 cmdDef += '}\n'
Mark Lobodzinskid8b7e022017-06-01 15:10:13 -06001113 self.validation.append(cmdDef)