Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 1 | #!/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> |
| 21 | |
| 22 | import os,re,sys |
| 23 | import xml.etree.ElementTree as etree |
| 24 | from generator import * |
| 25 | from collections import namedtuple |
| 26 | |
| 27 | |
| 28 | # ParamCheckerGeneratorOptions - subclass of GeneratorOptions. |
| 29 | # |
| 30 | # Adds options used by ParamCheckerOutputGenerator object during Parameter |
| 31 | # validation layer generation. |
| 32 | # |
| 33 | # Additional members |
| 34 | # prefixText - list of strings to prefix generated header with |
| 35 | # (usually a copyright statement + calling convention macros). |
| 36 | # protectFile - True if multiple inclusion protection should be |
| 37 | # generated (based on the filename) around the entire header. |
| 38 | # protectFeature - True if #ifndef..#endif protection should be |
| 39 | # generated around a feature interface in the header file. |
| 40 | # genFuncPointers - True if function pointer typedefs should be |
| 41 | # generated |
| 42 | # protectProto - If conditional protection should be generated |
| 43 | # around prototype declarations, set to either '#ifdef' |
| 44 | # to require opt-in (#ifdef protectProtoStr) or '#ifndef' |
| 45 | # to require opt-out (#ifndef protectProtoStr). Otherwise |
| 46 | # set to None. |
| 47 | # protectProtoStr - #ifdef/#ifndef symbol to use around prototype |
| 48 | # declarations, if protectProto is set |
| 49 | # apicall - string to use for the function declaration prefix, |
| 50 | # such as APICALL on Windows. |
| 51 | # apientry - string to use for the calling convention macro, |
| 52 | # in typedefs, such as APIENTRY. |
| 53 | # apientryp - string to use for the calling convention macro |
| 54 | # in function pointer typedefs, such as APIENTRYP. |
| 55 | # indentFuncProto - True if prototype declarations should put each |
| 56 | # parameter on a separate line |
| 57 | # indentFuncPointer - True if typedefed function pointers should put each |
| 58 | # parameter on a separate line |
| 59 | # alignFuncParam - if nonzero and parameters are being put on a |
| 60 | # separate line, align parameter names at the specified column |
| 61 | class ParamCheckerGeneratorOptions(GeneratorOptions): |
| 62 | def __init__(self, |
| 63 | filename = None, |
| 64 | directory = '.', |
| 65 | apiname = None, |
| 66 | profile = None, |
| 67 | versions = '.*', |
| 68 | emitversions = '.*', |
| 69 | defaultExtensions = None, |
| 70 | addExtensions = None, |
| 71 | removeExtensions = None, |
| 72 | sortProcedure = regSortFeatures, |
| 73 | prefixText = "", |
| 74 | genFuncPointers = True, |
| 75 | protectFile = True, |
| 76 | protectFeature = True, |
| 77 | protectProto = None, |
| 78 | protectProtoStr = None, |
| 79 | apicall = '', |
| 80 | apientry = '', |
| 81 | apientryp = '', |
| 82 | indentFuncProto = True, |
| 83 | indentFuncPointer = False, |
| 84 | alignFuncParam = 0): |
| 85 | GeneratorOptions.__init__(self, filename, directory, apiname, profile, |
| 86 | versions, emitversions, defaultExtensions, |
| 87 | addExtensions, removeExtensions, sortProcedure) |
| 88 | self.prefixText = prefixText |
| 89 | self.genFuncPointers = genFuncPointers |
| 90 | self.protectFile = protectFile |
| 91 | self.protectFeature = protectFeature |
| 92 | self.protectProto = protectProto |
| 93 | self.protectProtoStr = protectProtoStr |
| 94 | self.apicall = apicall |
| 95 | self.apientry = apientry |
| 96 | self.apientryp = apientryp |
| 97 | self.indentFuncProto = indentFuncProto |
| 98 | self.indentFuncPointer = indentFuncPointer |
| 99 | self.alignFuncParam = alignFuncParam |
| 100 | |
| 101 | # ParamCheckerOutputGenerator - subclass of OutputGenerator. |
| 102 | # Generates param checker layer code. |
| 103 | # |
| 104 | # ---- methods ---- |
| 105 | # ParamCheckerOutputGenerator(errFile, warnFile, diagFile) - args as for |
| 106 | # OutputGenerator. Defines additional internal state. |
| 107 | # ---- methods overriding base class ---- |
| 108 | # beginFile(genOpts) |
| 109 | # endFile() |
| 110 | # beginFeature(interface, emit) |
| 111 | # endFeature() |
| 112 | # genType(typeinfo,name) |
| 113 | # genStruct(typeinfo,name) |
| 114 | # genGroup(groupinfo,name) |
| 115 | # genEnum(enuminfo, name) |
| 116 | # genCmd(cmdinfo) |
| 117 | class ParamCheckerOutputGenerator(OutputGenerator): |
| 118 | """Generate ParamChecker code based on XML element attributes""" |
| 119 | # This is an ordered list of sections in the header file. |
| 120 | ALL_SECTIONS = ['command'] |
| 121 | def __init__(self, |
| 122 | errFile = sys.stderr, |
| 123 | warnFile = sys.stderr, |
| 124 | diagFile = sys.stdout): |
| 125 | OutputGenerator.__init__(self, errFile, warnFile, diagFile) |
| 126 | self.INDENT_SPACES = 4 |
Mark Lobodzinski | b6b8bbd | 2017-02-08 14:37:15 -0700 | [diff] [blame] | 127 | self.intercepts = [] |
| 128 | self.declarations = [] |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 129 | # Commands to ignore |
| 130 | self.blacklist = [ |
| 131 | 'vkGetInstanceProcAddr', |
| 132 | 'vkGetDeviceProcAddr', |
| 133 | 'vkEnumerateInstanceLayerProperties', |
| 134 | 'vkEnumerateInstanceExtensionsProperties', |
| 135 | 'vkEnumerateDeviceLayerProperties', |
| 136 | 'vkEnumerateDeviceExtensionsProperties', |
| 137 | 'vkCreateDebugReportCallbackEXT', |
| 138 | 'vkDebugReportMessageEXT'] |
| 139 | # Validation conditions for some special case struct members that are conditionally validated |
| 140 | self.structMemberValidationConditions = { 'VkPipelineColorBlendStateCreateInfo' : { 'logicOp' : '{}logicOpEnable == VK_TRUE' } } |
| 141 | # Header version |
| 142 | self.headerVersion = None |
| 143 | # Internal state - accumulators for different inner block text |
| 144 | self.sections = dict([(section, []) for section in self.ALL_SECTIONS]) |
| 145 | self.structNames = [] # List of Vulkan struct typenames |
| 146 | self.stypes = [] # Values from the VkStructureType enumeration |
| 147 | self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType |
| 148 | self.handleTypes = set() # Set of handle type names |
| 149 | self.commands = [] # List of CommandData records for all Vulkan commands |
| 150 | self.structMembers = [] # List of StructMemberData records for all Vulkan structs |
| 151 | self.validatedStructs = dict() # Map of structs type names to generated validation code for that struct type |
| 152 | self.enumRanges = dict() # Map of enum name to BEGIN/END range values |
| 153 | self.flags = set() # Map of flags typenames |
| 154 | self.flagBits = dict() # Map of flag bits typename to list of values |
Chris Forbes | 78ea32d | 2016-11-28 11:14:17 +1300 | [diff] [blame] | 155 | self.newFlags = set() # Map of flags typenames /defined in the current feature/ |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 156 | # Named tuples to store struct and command data |
| 157 | self.StructType = namedtuple('StructType', ['name', 'value']) |
| 158 | self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isstaticarray', 'isbool', 'israngedenum', |
| 159 | 'isconst', 'isoptional', 'iscount', 'noautovalidity', 'len', 'extstructs', |
| 160 | 'condition', 'cdecl']) |
| 161 | self.CommandData = namedtuple('CommandData', ['name', 'params', 'cdecl']) |
| 162 | self.StructMemberData = namedtuple('StructMemberData', ['name', 'members']) |
| 163 | # |
| 164 | def incIndent(self, indent): |
| 165 | inc = ' ' * self.INDENT_SPACES |
| 166 | if indent: |
| 167 | return indent + inc |
| 168 | return inc |
| 169 | # |
| 170 | def decIndent(self, indent): |
| 171 | if indent and (len(indent) > self.INDENT_SPACES): |
| 172 | return indent[:-self.INDENT_SPACES] |
| 173 | return '' |
| 174 | # |
| 175 | def beginFile(self, genOpts): |
| 176 | OutputGenerator.beginFile(self, genOpts) |
| 177 | # C-specific |
| 178 | # |
| 179 | # User-supplied prefix text, if any (list of strings) |
| 180 | if (genOpts.prefixText): |
| 181 | for s in genOpts.prefixText: |
| 182 | write(s, file=self.outFile) |
| 183 | # |
| 184 | # Multiple inclusion protection & C++ wrappers. |
| 185 | if (genOpts.protectFile and self.genOpts.filename): |
| 186 | headerSym = re.sub('\.h', '_H', os.path.basename(self.genOpts.filename)).upper() |
| 187 | write('#ifndef', headerSym, file=self.outFile) |
| 188 | write('#define', headerSym, '1', file=self.outFile) |
| 189 | self.newline() |
| 190 | # |
| 191 | # Headers |
| 192 | write('#include <string>', file=self.outFile) |
| 193 | self.newline() |
| 194 | write('#include "vulkan/vulkan.h"', file=self.outFile) |
| 195 | write('#include "vk_layer_extension_utils.h"', file=self.outFile) |
| 196 | write('#include "parameter_validation_utils.h"', file=self.outFile) |
| 197 | # |
| 198 | # Macros |
| 199 | self.newline() |
| 200 | write('#ifndef UNUSED_PARAMETER', file=self.outFile) |
| 201 | write('#define UNUSED_PARAMETER(x) (void)(x)', file=self.outFile) |
| 202 | write('#endif // UNUSED_PARAMETER', file=self.outFile) |
| 203 | # |
| 204 | # Namespace |
| 205 | self.newline() |
| 206 | write('namespace parameter_validation {', file = self.outFile) |
| 207 | def endFile(self): |
| 208 | # C-specific |
| 209 | self.newline() |
Mark Lobodzinski | b6b8bbd | 2017-02-08 14:37:15 -0700 | [diff] [blame] | 210 | |
| 211 | # Output declarations and record intercepted procedures |
| 212 | write('// Declarations', file=self.outFile) |
| 213 | write('\n'.join(self.declarations), file=self.outFile) |
| 214 | write('// Intercepts', file=self.outFile) |
| 215 | write('struct { const char* name; PFN_vkVoidFunction pFunc;} procmap[] = {', file=self.outFile) |
| 216 | write('\n'.join(self.intercepts), file=self.outFile) |
| 217 | write('};\n', file=self.outFile) |
| 218 | self.newline() |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 219 | # Namespace |
| 220 | write('} // namespace parameter_validation', file = self.outFile) |
| 221 | # Finish C++ wrapper and multiple inclusion protection |
| 222 | if (self.genOpts.protectFile and self.genOpts.filename): |
| 223 | self.newline() |
| 224 | write('#endif', file=self.outFile) |
| 225 | # Finish processing in superclass |
| 226 | OutputGenerator.endFile(self) |
| 227 | def beginFeature(self, interface, emit): |
| 228 | # Start processing in superclass |
| 229 | OutputGenerator.beginFeature(self, interface, emit) |
| 230 | # C-specific |
| 231 | # Accumulate includes, defines, types, enums, function pointer typedefs, |
| 232 | # end function prototypes separately for this feature. They're only |
| 233 | # printed in endFeature(). |
| 234 | self.headerVersion = None |
| 235 | self.sections = dict([(section, []) for section in self.ALL_SECTIONS]) |
| 236 | self.structNames = [] |
| 237 | self.stypes = [] |
| 238 | self.structTypes = dict() |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 239 | self.commands = [] |
| 240 | self.structMembers = [] |
| 241 | self.validatedStructs = dict() |
Chris Forbes | 78ea32d | 2016-11-28 11:14:17 +1300 | [diff] [blame] | 242 | self.newFlags = set() |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 243 | def endFeature(self): |
| 244 | # C-specific |
| 245 | # Actually write the interface to the output file. |
| 246 | if (self.emit): |
| 247 | self.newline() |
| 248 | # If type declarations are needed by other features based on |
| 249 | # this one, it may be necessary to suppress the ExtraProtect, |
| 250 | # or move it below the 'for section...' loop. |
| 251 | if (self.featureExtraProtect != None): |
| 252 | write('#ifdef', self.featureExtraProtect, file=self.outFile) |
| 253 | # Generate the struct member checking code from the captured data |
| 254 | self.processStructMemberData() |
| 255 | # Generate the command parameter checking code from the captured data |
| 256 | self.processCmdData() |
| 257 | # Write the declaration for the HeaderVersion |
| 258 | if self.headerVersion: |
| 259 | write('const uint32_t GeneratedHeaderVersion = {};'.format(self.headerVersion), file=self.outFile) |
| 260 | self.newline() |
| 261 | # Write the declarations for the VkFlags values combining all flag bits |
Chris Forbes | 78ea32d | 2016-11-28 11:14:17 +1300 | [diff] [blame] | 262 | for flag in sorted(self.newFlags): |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 263 | flagBits = flag.replace('Flags', 'FlagBits') |
| 264 | if flagBits in self.flagBits: |
| 265 | bits = self.flagBits[flagBits] |
| 266 | decl = 'const {} All{} = {}'.format(flag, flagBits, bits[0]) |
| 267 | for bit in bits[1:]: |
| 268 | decl += '|' + bit |
| 269 | decl += ';' |
| 270 | write(decl, file=self.outFile) |
| 271 | self.newline() |
| 272 | # Write the parameter validation code to the file |
| 273 | if (self.sections['command']): |
| 274 | if (self.genOpts.protectProto): |
| 275 | write(self.genOpts.protectProto, |
| 276 | self.genOpts.protectProtoStr, file=self.outFile) |
Jamie Madill | 24aa974 | 2016-12-13 17:02:57 -0500 | [diff] [blame] | 277 | write('\n'.join(self.sections['command']), end=u'', file=self.outFile) |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 278 | if (self.featureExtraProtect != None): |
| 279 | write('#endif /*', self.featureExtraProtect, '*/', file=self.outFile) |
| 280 | else: |
| 281 | self.newline() |
| 282 | # Finish processing in superclass |
| 283 | OutputGenerator.endFeature(self) |
| 284 | # |
| 285 | # Append a definition to the specified section |
| 286 | def appendSection(self, section, text): |
| 287 | # self.sections[section].append('SECTION: ' + section + '\n') |
| 288 | self.sections[section].append(text) |
| 289 | # |
| 290 | # Type generation |
| 291 | def genType(self, typeinfo, name): |
| 292 | OutputGenerator.genType(self, typeinfo, name) |
| 293 | typeElem = typeinfo.elem |
| 294 | # If the type is a struct type, traverse the imbedded <member> tags |
| 295 | # generating a structure. Otherwise, emit the tag text. |
| 296 | category = typeElem.get('category') |
| 297 | if (category == 'struct' or category == 'union'): |
| 298 | self.structNames.append(name) |
| 299 | self.genStruct(typeinfo, name) |
| 300 | elif (category == 'handle'): |
| 301 | self.handleTypes.add(name) |
| 302 | elif (category == 'bitmask'): |
| 303 | self.flags.add(name) |
Chris Forbes | 78ea32d | 2016-11-28 11:14:17 +1300 | [diff] [blame] | 304 | self.newFlags.add(name) |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 305 | elif (category == 'define'): |
| 306 | if name == 'VK_HEADER_VERSION': |
| 307 | nameElem = typeElem.find('name') |
| 308 | self.headerVersion = noneStr(nameElem.tail).strip() |
| 309 | # |
| 310 | # Struct parameter check generation. |
| 311 | # This is a special case of the <type> tag where the contents are |
| 312 | # interpreted as a set of <member> tags instead of freeform C |
| 313 | # C type declarations. The <member> tags are just like <param> |
| 314 | # tags - they are a declaration of a struct or union member. |
| 315 | # Only simple member declarations are supported (no nested |
| 316 | # structs etc.) |
| 317 | def genStruct(self, typeinfo, typeName): |
| 318 | OutputGenerator.genStruct(self, typeinfo, typeName) |
| 319 | conditions = self.structMemberValidationConditions[typeName] if typeName in self.structMemberValidationConditions else None |
| 320 | members = typeinfo.elem.findall('.//member') |
| 321 | # |
| 322 | # Iterate over members once to get length parameters for arrays |
| 323 | lens = set() |
| 324 | for member in members: |
| 325 | len = self.getLen(member) |
| 326 | if len: |
| 327 | lens.add(len) |
| 328 | # |
| 329 | # Generate member info |
| 330 | membersInfo = [] |
| 331 | for member in members: |
| 332 | # Get the member's type and name |
| 333 | info = self.getTypeNameTuple(member) |
| 334 | type = info[0] |
| 335 | name = info[1] |
| 336 | stypeValue = '' |
| 337 | cdecl = self.makeCParamDecl(member, 0) |
| 338 | # Process VkStructureType |
| 339 | if type == 'VkStructureType': |
| 340 | # Extract the required struct type value from the comments |
| 341 | # embedded in the original text defining the 'typeinfo' element |
| 342 | rawXml = etree.tostring(typeinfo.elem).decode('ascii') |
| 343 | result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml) |
| 344 | if result: |
| 345 | value = result.group(0) |
| 346 | else: |
| 347 | value = self.genVkStructureType(typeName) |
| 348 | # Store the required type value |
| 349 | self.structTypes[typeName] = self.StructType(name=name, value=value) |
| 350 | # |
| 351 | # Store pointer/array/string info |
| 352 | # Check for parameter name in lens set |
| 353 | iscount = False |
| 354 | if name in lens: |
| 355 | iscount = True |
| 356 | # The pNext members are not tagged as optional, but are treated as |
| 357 | # optional for parameter NULL checks. Static array members |
| 358 | # are also treated as optional to skip NULL pointer validation, as |
| 359 | # they won't be NULL. |
| 360 | isstaticarray = self.paramIsStaticArray(member) |
| 361 | isoptional = False |
| 362 | if self.paramIsOptional(member) or (name == 'pNext') or (isstaticarray): |
| 363 | isoptional = True |
| 364 | membersInfo.append(self.CommandParam(type=type, name=name, |
| 365 | ispointer=self.paramIsPointer(member), |
| 366 | isstaticarray=isstaticarray, |
| 367 | isbool=True if type == 'VkBool32' else False, |
| 368 | israngedenum=True if type in self.enumRanges else False, |
| 369 | isconst=True if 'const' in cdecl else False, |
| 370 | isoptional=isoptional, |
| 371 | iscount=iscount, |
| 372 | noautovalidity=True if member.attrib.get('noautovalidity') is not None else False, |
| 373 | len=self.getLen(member), |
| 374 | extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None, |
| 375 | condition=conditions[name] if conditions and name in conditions else None, |
| 376 | cdecl=cdecl)) |
| 377 | self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo)) |
| 378 | # |
| 379 | # Capture group (e.g. C "enum" type) info to be used for |
| 380 | # param check code generation. |
| 381 | # These are concatenated together with other types. |
| 382 | def genGroup(self, groupinfo, groupName): |
| 383 | OutputGenerator.genGroup(self, groupinfo, groupName) |
| 384 | groupElem = groupinfo.elem |
| 385 | # |
| 386 | # Store the sType values |
| 387 | if groupName == 'VkStructureType': |
| 388 | for elem in groupElem.findall('enum'): |
| 389 | self.stypes.append(elem.get('name')) |
| 390 | elif 'FlagBits' in groupName: |
| 391 | bits = [] |
| 392 | for elem in groupElem.findall('enum'): |
| 393 | bits.append(elem.get('name')) |
| 394 | if bits: |
| 395 | self.flagBits[groupName] = bits |
| 396 | else: |
| 397 | # Determine if begin/end ranges are needed (we don't do this for VkStructureType, which has a more finely grained check) |
| 398 | expandName = re.sub(r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)',r'\1_\2',groupName).upper() |
| 399 | expandPrefix = expandName |
| 400 | expandSuffix = '' |
| 401 | expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName) |
| 402 | if expandSuffixMatch: |
| 403 | expandSuffix = '_' + expandSuffixMatch.group() |
| 404 | # Strip off the suffix from the prefix |
| 405 | expandPrefix = expandName.rsplit(expandSuffix, 1)[0] |
| 406 | isEnum = ('FLAG_BITS' not in expandPrefix) |
| 407 | if isEnum: |
| 408 | self.enumRanges[groupName] = (expandPrefix + '_BEGIN_RANGE' + expandSuffix, expandPrefix + '_END_RANGE' + expandSuffix) |
| 409 | # |
| 410 | # Capture command parameter info to be used for param |
| 411 | # check code generation. |
| 412 | def genCmd(self, cmdinfo, name): |
| 413 | OutputGenerator.genCmd(self, cmdinfo, name) |
Mark Lobodzinski | b6b8bbd | 2017-02-08 14:37:15 -0700 | [diff] [blame] | 414 | interface_functions = [ |
| 415 | 'vkEnumerateInstanceLayerProperties', |
| 416 | 'vkEnumerateInstanceExtensionProperties', |
| 417 | 'vkEnumerateDeviceLayerProperties', |
Mark Lobodzinski | 099b3b6 | 2017-02-08 16:04:35 -0700 | [diff] [blame^] | 418 | 'vkCmdDebugMarkerEndEXT', # No validation! |
Mark Lobodzinski | b6b8bbd | 2017-02-08 14:37:15 -0700 | [diff] [blame] | 419 | ] |
| 420 | # Record that the function will be intercepted |
| 421 | if name not in interface_functions: |
| 422 | if (self.featureExtraProtect != None): |
| 423 | self.declarations += [ '#ifdef %s' % self.featureExtraProtect ] |
| 424 | self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ] |
| 425 | self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (name,name[2:]) ] |
| 426 | decls = self.makeCDecls(cmdinfo.elem) |
| 427 | # Strip off 'vk' from API name |
| 428 | self.declarations += [ '%s' % decls[0].replace("VKAPI_CALL vk", "VKAPI_CALL ") ] |
| 429 | if (self.featureExtraProtect != None): |
| 430 | self.intercepts += [ '#endif' ] |
| 431 | self.declarations += [ '#endif' ] |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 432 | if name not in self.blacklist: |
| 433 | params = cmdinfo.elem.findall('param') |
| 434 | # Get list of array lengths |
| 435 | lens = set() |
| 436 | for param in params: |
| 437 | len = self.getLen(param) |
| 438 | if len: |
| 439 | lens.add(len) |
| 440 | # Get param info |
| 441 | paramsInfo = [] |
| 442 | for param in params: |
| 443 | paramInfo = self.getTypeNameTuple(param) |
| 444 | cdecl = self.makeCParamDecl(param, 0) |
| 445 | # Check for parameter name in lens set |
| 446 | iscount = False |
| 447 | if paramInfo[1] in lens: |
| 448 | iscount = True |
| 449 | paramsInfo.append(self.CommandParam(type=paramInfo[0], name=paramInfo[1], |
| 450 | ispointer=self.paramIsPointer(param), |
| 451 | isstaticarray=self.paramIsStaticArray(param), |
| 452 | isbool=True if paramInfo[0] == 'VkBool32' else False, |
| 453 | israngedenum=True if paramInfo[0] in self.enumRanges else False, |
| 454 | isconst=True if 'const' in cdecl else False, |
| 455 | isoptional=self.paramIsOptional(param), |
| 456 | iscount=iscount, |
| 457 | noautovalidity=True if param.attrib.get('noautovalidity') is not None else False, |
| 458 | len=self.getLen(param), |
| 459 | extstructs=None, |
| 460 | condition=None, |
| 461 | cdecl=cdecl)) |
| 462 | self.commands.append(self.CommandData(name=name, params=paramsInfo, cdecl=self.makeCDecls(cmdinfo.elem)[0])) |
| 463 | # |
| 464 | # Check if the parameter passed in is a pointer |
| 465 | def paramIsPointer(self, param): |
| 466 | ispointer = 0 |
| 467 | paramtype = param.find('type') |
| 468 | if (paramtype.tail is not None) and ('*' in paramtype.tail): |
| 469 | ispointer = paramtype.tail.count('*') |
| 470 | elif paramtype.text[:4] == 'PFN_': |
| 471 | # Treat function pointer typedefs as a pointer to a single value |
| 472 | ispointer = 1 |
| 473 | return ispointer |
| 474 | # |
| 475 | # Check if the parameter passed in is a static array |
| 476 | def paramIsStaticArray(self, param): |
| 477 | isstaticarray = 0 |
| 478 | paramname = param.find('name') |
| 479 | if (paramname.tail is not None) and ('[' in paramname.tail): |
| 480 | isstaticarray = paramname.tail.count('[') |
| 481 | return isstaticarray |
| 482 | # |
| 483 | # Check if the parameter passed in is optional |
| 484 | # Returns a list of Boolean values for comma separated len attributes (len='false,true') |
| 485 | def paramIsOptional(self, param): |
| 486 | # See if the handle is optional |
| 487 | isoptional = False |
| 488 | # Simple, if it's optional, return true |
| 489 | optString = param.attrib.get('optional') |
| 490 | if optString: |
| 491 | if optString == 'true': |
| 492 | isoptional = True |
| 493 | elif ',' in optString: |
| 494 | opts = [] |
| 495 | for opt in optString.split(','): |
| 496 | val = opt.strip() |
| 497 | if val == 'true': |
| 498 | opts.append(True) |
| 499 | elif val == 'false': |
| 500 | opts.append(False) |
| 501 | else: |
| 502 | print('Unrecognized len attribute value',val) |
| 503 | isoptional = opts |
| 504 | return isoptional |
| 505 | # |
| 506 | # Check if the handle passed in is optional |
| 507 | # Uses the same logic as ValidityOutputGenerator.isHandleOptional |
| 508 | def isHandleOptional(self, param, lenParam): |
| 509 | # Simple, if it's optional, return true |
| 510 | if param.isoptional: |
| 511 | return True |
| 512 | # If no validity is being generated, it usually means that validity is complex and not absolute, so let's say yes. |
| 513 | if param.noautovalidity: |
| 514 | return True |
| 515 | # If the parameter is an array and we haven't already returned, find out if any of the len parameters are optional |
| 516 | if lenParam and lenParam.isoptional: |
| 517 | return True |
| 518 | return False |
| 519 | # |
| 520 | # Generate a VkStructureType based on a structure typename |
| 521 | def genVkStructureType(self, typename): |
| 522 | # Add underscore between lowercase then uppercase |
| 523 | value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename) |
Mark Young | 3938987 | 2017-01-19 21:10:49 -0700 | [diff] [blame] | 524 | value = value.replace('D3_D12', 'D3D12') |
| 525 | value = value.replace('Device_IDProp', 'Device_ID_Prop') |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 526 | # Change to uppercase |
| 527 | value = value.upper() |
| 528 | # Add STRUCTURE_TYPE_ |
| 529 | return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value) |
| 530 | # |
| 531 | # Get the cached VkStructureType value for the specified struct typename, or generate a VkStructureType |
| 532 | # value assuming the struct is defined by a different feature |
| 533 | def getStructType(self, typename): |
| 534 | value = None |
| 535 | if typename in self.structTypes: |
| 536 | value = self.structTypes[typename].value |
| 537 | else: |
| 538 | value = self.genVkStructureType(typename) |
| 539 | self.logMsg('diag', 'ParameterValidation: Generating {} for {} structure type that was not defined by the current feature'.format(value, typename)) |
| 540 | return value |
| 541 | # |
| 542 | # Retrieve the value of the len tag |
| 543 | def getLen(self, param): |
| 544 | result = None |
| 545 | len = param.attrib.get('len') |
| 546 | if len and len != 'null-terminated': |
| 547 | # For string arrays, 'len' can look like 'count,null-terminated', |
| 548 | # indicating that we have a null terminated array of strings. We |
| 549 | # strip the null-terminated from the 'len' field and only return |
| 550 | # the parameter specifying the string count |
| 551 | if 'null-terminated' in len: |
| 552 | result = len.split(',')[0] |
| 553 | else: |
| 554 | result = len |
| 555 | result = str(result).replace('::', '->') |
| 556 | return result |
| 557 | # |
| 558 | # Retrieve the type and name for a parameter |
| 559 | def getTypeNameTuple(self, param): |
| 560 | type = '' |
| 561 | name = '' |
| 562 | for elem in param: |
| 563 | if elem.tag == 'type': |
| 564 | type = noneStr(elem.text) |
| 565 | elif elem.tag == 'name': |
| 566 | name = noneStr(elem.text) |
| 567 | return (type, name) |
| 568 | # |
| 569 | # Find a named parameter in a parameter list |
| 570 | def getParamByName(self, params, name): |
| 571 | for param in params: |
| 572 | if param.name == name: |
| 573 | return param |
| 574 | return None |
| 575 | # |
| 576 | # Extract length values from latexmath. Currently an inflexible solution that looks for specific |
| 577 | # patterns that are found in vk.xml. Will need to be updated when new patterns are introduced. |
| 578 | def parseLateXMath(self, source): |
| 579 | name = 'ERROR' |
| 580 | decoratedName = 'ERROR' |
| 581 | if 'mathit' in source: |
| 582 | # Matches expressions similar to 'latexmath:[$\lceil{\mathit{rasterizationSamples} \over 32}\rceil$]' |
| 583 | 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) |
| 584 | if not match or match.group(1) != match.group(4): |
| 585 | raise 'Unrecognized latexmath expression' |
| 586 | name = match.group(2) |
| 587 | decoratedName = '{}({}/{})'.format(*match.group(1, 2, 3)) |
| 588 | else: |
| 589 | # Matches expressions similar to 'latexmath : [$dataSize \over 4$]' |
| 590 | match = re.match(r'latexmath\s*\:\s*\[\s*\$\s*(\w+)\s*\\over\s*(\d+)\s*\$\s*\]', source) |
| 591 | name = match.group(1) |
| 592 | decoratedName = '{}/{}'.format(*match.group(1, 2)) |
| 593 | return name, decoratedName |
| 594 | # |
| 595 | # Get the length paramater record for the specified parameter name |
| 596 | def getLenParam(self, params, name): |
| 597 | lenParam = None |
| 598 | if name: |
| 599 | if '->' in name: |
| 600 | # The count is obtained by dereferencing a member of a struct parameter |
| 601 | lenParam = self.CommandParam(name=name, iscount=True, ispointer=False, isbool=False, israngedenum=False, isconst=False, |
| 602 | isstaticarray=None, isoptional=False, type=None, noautovalidity=False, len=None, extstructs=None, |
| 603 | condition=None, cdecl=None) |
| 604 | elif 'latexmath' in name: |
| 605 | lenName, decoratedName = self.parseLateXMath(name) |
| 606 | lenParam = self.getParamByName(params, lenName) |
| 607 | # TODO: Zero-check the result produced by the equation? |
| 608 | # Copy the stored len parameter entry and overwrite the name with the processed latexmath equation |
| 609 | #param = self.getParamByName(params, lenName) |
| 610 | #lenParam = self.CommandParam(name=decoratedName, iscount=param.iscount, ispointer=param.ispointer, |
| 611 | # isoptional=param.isoptional, type=param.type, len=param.len, |
| 612 | # isstaticarray=param.isstaticarray, extstructs=param.extstructs, |
| 613 | # noautovalidity=True, condition=None, cdecl=param.cdecl) |
| 614 | else: |
| 615 | lenParam = self.getParamByName(params, name) |
| 616 | return lenParam |
| 617 | # |
| 618 | # Convert a vulkan.h command declaration into a parameter_validation.h definition |
| 619 | def getCmdDef(self, cmd): |
| 620 | # |
| 621 | # Strip the trailing ';' and split into individual lines |
| 622 | lines = cmd.cdecl[:-1].split('\n') |
| 623 | # Replace Vulkan prototype |
| 624 | lines[0] = 'static bool parameter_validation_' + cmd.name + '(' |
| 625 | # Replace the first argument with debug_report_data, when the first |
| 626 | # argument is a handle (not vkCreateInstance) |
| 627 | reportData = ' debug_report_data*'.ljust(self.genOpts.alignFuncParam) + 'report_data,' |
| 628 | if cmd.name != 'vkCreateInstance': |
| 629 | lines[1] = reportData |
| 630 | else: |
| 631 | lines.insert(1, reportData) |
| 632 | return '\n'.join(lines) |
| 633 | # |
| 634 | # Generate the code to check for a NULL dereference before calling the |
| 635 | # validation function |
| 636 | def genCheckedLengthCall(self, name, exprs): |
| 637 | count = name.count('->') |
| 638 | if count: |
| 639 | checkedExpr = [] |
| 640 | localIndent = '' |
| 641 | elements = name.split('->') |
| 642 | # Open the if expression blocks |
| 643 | for i in range(0, count): |
| 644 | checkedExpr.append(localIndent + 'if ({} != NULL) {{\n'.format('->'.join(elements[0:i+1]))) |
| 645 | localIndent = self.incIndent(localIndent) |
| 646 | # Add the validation expression |
| 647 | for expr in exprs: |
| 648 | checkedExpr.append(localIndent + expr) |
| 649 | # Close the if blocks |
| 650 | for i in range(0, count): |
| 651 | localIndent = self.decIndent(localIndent) |
| 652 | checkedExpr.append(localIndent + '}\n') |
| 653 | return [checkedExpr] |
| 654 | # No if statements were required |
| 655 | return exprs |
| 656 | # |
| 657 | # Generate code to check for a specific condition before executing validation code |
| 658 | def genConditionalCall(self, prefix, condition, exprs): |
| 659 | checkedExpr = [] |
| 660 | localIndent = '' |
| 661 | formattedCondition = condition.format(prefix) |
| 662 | checkedExpr.append(localIndent + 'if ({})\n'.format(formattedCondition)) |
| 663 | checkedExpr.append(localIndent + '{\n') |
| 664 | localIndent = self.incIndent(localIndent) |
| 665 | for expr in exprs: |
| 666 | checkedExpr.append(localIndent + expr) |
| 667 | localIndent = self.decIndent(localIndent) |
| 668 | checkedExpr.append(localIndent + '}\n') |
| 669 | return [checkedExpr] |
| 670 | # |
| 671 | # Generate the sType check string |
| 672 | def makeStructTypeCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec): |
| 673 | checkExpr = [] |
| 674 | stype = self.structTypes[value.type] |
| 675 | if lenValue: |
| 676 | # This is an array with a pointer to a count value |
| 677 | if lenValue.ispointer: |
| 678 | # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required |
| 679 | checkExpr.append('skipCall |= validate_struct_type_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {}, {});\n'.format( |
| 680 | funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec)) |
| 681 | # This is an array with an integer count value |
| 682 | else: |
| 683 | checkExpr.append('skipCall |= validate_struct_type_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, "{sv}", {pf}{ln}, {pf}{vn}, {sv}, {}, {});\n'.format( |
| 684 | funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, sv=stype.value, pf=prefix, **postProcSpec)) |
| 685 | # This is an individual struct |
| 686 | else: |
| 687 | checkExpr.append('skipCall |= validate_struct_type(report_data, "{}", {ppp}"{}"{pps}, "{sv}", {}{vn}, {sv}, {});\n'.format( |
| 688 | funcPrintName, valuePrintName, prefix, valueRequired, vn=value.name, sv=stype.value, **postProcSpec)) |
| 689 | return checkExpr |
| 690 | # |
| 691 | # Generate the handle check string |
| 692 | def makeHandleCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec): |
| 693 | checkExpr = [] |
| 694 | if lenValue: |
| 695 | if lenValue.ispointer: |
| 696 | # This is assumed to be an output array with a pointer to a count value |
| 697 | raise('Unsupported parameter validation case: Output handle array elements are not NULL checked') |
| 698 | else: |
| 699 | # This is an array with an integer count value |
| 700 | checkExpr.append('skipCall |= validate_handle_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format( |
| 701 | funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec)) |
| 702 | else: |
| 703 | # This is assumed to be an output handle pointer |
| 704 | raise('Unsupported parameter validation case: Output handles are not NULL checked') |
| 705 | return checkExpr |
| 706 | # |
| 707 | # Generate check string for an array of VkFlags values |
| 708 | def makeFlagsArrayCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec): |
| 709 | checkExpr = [] |
| 710 | flagBitsName = value.type.replace('Flags', 'FlagBits') |
| 711 | if not flagBitsName in self.flagBits: |
| 712 | raise('Unsupported parameter validation case: array of reserved VkFlags') |
| 713 | else: |
| 714 | allFlags = 'All' + flagBitsName |
| 715 | checkExpr.append('skipCall |= validate_flags_array(report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, "{}", {}, {pf}{}, {pf}{}, {}, {});\n'.format(funcPrintName, lenPrintName, valuePrintName, flagBitsName, allFlags, lenValue.name, value.name, lenValueRequired, valueRequired, pf=prefix, **postProcSpec)) |
| 716 | return checkExpr |
| 717 | # |
| 718 | # Generate pNext check string |
| 719 | def makeStructNextCheck(self, prefix, value, funcPrintName, valuePrintName, postProcSpec): |
| 720 | checkExpr = [] |
| 721 | # Generate an array of acceptable VkStructureType values for pNext |
| 722 | extStructCount = 0 |
| 723 | extStructVar = 'NULL' |
| 724 | extStructNames = 'NULL' |
| 725 | if value.extstructs: |
| 726 | structs = value.extstructs.split(',') |
| 727 | checkExpr.append('const VkStructureType allowedStructs[] = {' + ', '.join([self.getStructType(s) for s in structs]) + '};\n') |
| 728 | extStructCount = 'ARRAY_SIZE(allowedStructs)' |
| 729 | extStructVar = 'allowedStructs' |
| 730 | extStructNames = '"' + ', '.join(structs) + '"' |
| 731 | checkExpr.append('skipCall |= validate_struct_pnext(report_data, "{}", {ppp}"{}"{pps}, {}, {}{}, {}, {}, GeneratedHeaderVersion);\n'.format( |
| 732 | funcPrintName, valuePrintName, extStructNames, prefix, value.name, extStructCount, extStructVar, **postProcSpec)) |
| 733 | return checkExpr |
| 734 | # |
| 735 | # Generate the pointer check string |
| 736 | def makePointerCheck(self, prefix, value, lenValue, valueRequired, lenValueRequired, lenPtrRequired, funcPrintName, lenPrintName, valuePrintName, postProcSpec): |
| 737 | checkExpr = [] |
| 738 | if lenValue: |
| 739 | # This is an array with a pointer to a count value |
| 740 | if lenValue.ispointer: |
| 741 | # If count and array parameters are optional, there will be no validation |
| 742 | if valueRequired == 'true' or lenPtrRequired == 'true' or lenValueRequired == 'true': |
| 743 | # When the length parameter is a pointer, there is an extra Boolean parameter in the function call to indicate if it is required |
| 744 | checkExpr.append('skipCall |= validate_array(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {}, {});\n'.format( |
| 745 | funcPrintName, lenPtrRequired, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec)) |
| 746 | # This is an array with an integer count value |
| 747 | else: |
| 748 | # If count and array parameters are optional, there will be no validation |
| 749 | if valueRequired == 'true' or lenValueRequired == 'true': |
| 750 | # Arrays of strings receive special processing |
| 751 | validationFuncName = 'validate_array' if value.type != 'char' else 'validate_string_array' |
| 752 | checkExpr.append('skipCall |= {}(report_data, "{}", {ppp}"{ldn}"{pps}, {ppp}"{dn}"{pps}, {pf}{ln}, {pf}{vn}, {}, {});\n'.format( |
| 753 | validationFuncName, funcPrintName, lenValueRequired, valueRequired, ln=lenValue.name, ldn=lenPrintName, dn=valuePrintName, vn=value.name, pf=prefix, **postProcSpec)) |
| 754 | if checkExpr: |
| 755 | if lenValue and ('->' in lenValue.name): |
| 756 | # Add checks to ensure the validation call does not dereference a NULL pointer to obtain the count |
| 757 | checkExpr = self.genCheckedLengthCall(lenValue.name, checkExpr) |
| 758 | # This is an individual struct that is not allowed to be NULL |
| 759 | elif not value.isoptional: |
| 760 | # Function pointers need a reinterpret_cast to void* |
| 761 | if value.type[:4] == 'PFN_': |
| 762 | checkExpr.append('skipCall |= validate_required_pointer(report_data, "{}", {ppp}"{}"{pps}, reinterpret_cast<const void*>({}{}));\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec)) |
| 763 | else: |
| 764 | checkExpr.append('skipCall |= validate_required_pointer(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcPrintName, valuePrintName, prefix, value.name, **postProcSpec)) |
| 765 | return checkExpr |
| 766 | # |
| 767 | # Process struct member validation code, performing name suibstitution if required |
| 768 | def processStructMemberCode(self, line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec): |
| 769 | # Build format specifier list |
| 770 | kwargs = {} |
| 771 | if '{postProcPrefix}' in line: |
| 772 | # If we have a tuple that includes a format string and format parameters, need to use ParameterName class |
| 773 | if type(memberDisplayNamePrefix) is tuple: |
| 774 | kwargs['postProcPrefix'] = 'ParameterName(' |
| 775 | else: |
| 776 | kwargs['postProcPrefix'] = postProcSpec['ppp'] |
| 777 | if '{postProcSuffix}' in line: |
| 778 | # If we have a tuple that includes a format string and format parameters, need to use ParameterName class |
| 779 | if type(memberDisplayNamePrefix) is tuple: |
| 780 | kwargs['postProcSuffix'] = ', ParameterName::IndexVector{{ {}{} }})'.format(postProcSpec['ppi'], memberDisplayNamePrefix[1]) |
| 781 | else: |
| 782 | kwargs['postProcSuffix'] = postProcSpec['pps'] |
| 783 | if '{postProcInsert}' in line: |
| 784 | # If we have a tuple that includes a format string and format parameters, need to use ParameterName class |
| 785 | if type(memberDisplayNamePrefix) is tuple: |
| 786 | kwargs['postProcInsert'] = '{}{}, '.format(postProcSpec['ppi'], memberDisplayNamePrefix[1]) |
| 787 | else: |
| 788 | kwargs['postProcInsert'] = postProcSpec['ppi'] |
| 789 | if '{funcName}' in line: |
| 790 | kwargs['funcName'] = funcName |
| 791 | if '{valuePrefix}' in line: |
| 792 | kwargs['valuePrefix'] = memberNamePrefix |
| 793 | if '{displayNamePrefix}' in line: |
| 794 | # Check for a tuple that includes a format string and format parameters to be used with the ParameterName class |
| 795 | if type(memberDisplayNamePrefix) is tuple: |
| 796 | kwargs['displayNamePrefix'] = memberDisplayNamePrefix[0] |
| 797 | else: |
| 798 | kwargs['displayNamePrefix'] = memberDisplayNamePrefix |
| 799 | |
| 800 | if kwargs: |
| 801 | # Need to escape the C++ curly braces |
| 802 | if 'IndexVector' in line: |
| 803 | line = line.replace('IndexVector{ ', 'IndexVector{{ ') |
| 804 | line = line.replace(' }),', ' }}),') |
| 805 | return line.format(**kwargs) |
| 806 | return line |
| 807 | # |
| 808 | # Process struct validation code for inclusion in function or parent struct validation code |
| 809 | def expandStructCode(self, lines, funcName, memberNamePrefix, memberDisplayNamePrefix, indent, output, postProcSpec): |
| 810 | for line in lines: |
| 811 | if output: |
| 812 | output[-1] += '\n' |
| 813 | if type(line) is list: |
| 814 | for sub in line: |
| 815 | output.append(self.processStructMemberCode(indent + sub, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec)) |
| 816 | else: |
| 817 | output.append(self.processStructMemberCode(indent + line, funcName, memberNamePrefix, memberDisplayNamePrefix, postProcSpec)) |
| 818 | return output |
| 819 | # |
| 820 | # Process struct pointer/array validation code, perfoeming name substitution if required |
| 821 | def expandStructPointerCode(self, prefix, value, lenValue, funcName, valueDisplayName, postProcSpec): |
| 822 | expr = [] |
| 823 | expr.append('if ({}{} != NULL)\n'.format(prefix, value.name)) |
| 824 | expr.append('{') |
| 825 | indent = self.incIndent(None) |
| 826 | if lenValue: |
| 827 | # Need to process all elements in the array |
| 828 | indexName = lenValue.name.replace('Count', 'Index') |
| 829 | expr[-1] += '\n' |
Mark Young | 3938987 | 2017-01-19 21:10:49 -0700 | [diff] [blame] | 830 | if lenValue.ispointer: |
| 831 | # If the length value is a pointer, de-reference it for the count. |
| 832 | expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < *{}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName)) |
| 833 | else: |
| 834 | expr.append(indent + 'for (uint32_t {iname} = 0; {iname} < {}{}; ++{iname})\n'.format(prefix, lenValue.name, iname=indexName)) |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 835 | expr.append(indent + '{') |
| 836 | indent = self.incIndent(indent) |
| 837 | # Prefix for value name to display in error message |
Mark Lobodzinski | 6f82eb5 | 2016-12-05 07:38:41 -0700 | [diff] [blame] | 838 | if value.ispointer == 2: |
| 839 | memberNamePrefix = '{}{}[{}]->'.format(prefix, value.name, indexName) |
| 840 | memberDisplayNamePrefix = ('{}[%i]->'.format(valueDisplayName), indexName) |
| 841 | else: |
| 842 | memberNamePrefix = '{}{}[{}].'.format(prefix, value.name, indexName) |
| 843 | memberDisplayNamePrefix = ('{}[%i].'.format(valueDisplayName), indexName) |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 844 | else: |
| 845 | memberNamePrefix = '{}{}->'.format(prefix, value.name) |
| 846 | memberDisplayNamePrefix = '{}->'.format(valueDisplayName) |
| 847 | # |
| 848 | # Expand the struct validation lines |
| 849 | expr = self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, indent, expr, postProcSpec) |
| 850 | # |
| 851 | if lenValue: |
| 852 | # Close if and for scopes |
| 853 | indent = self.decIndent(indent) |
| 854 | expr.append(indent + '}\n') |
| 855 | expr.append('}\n') |
| 856 | return expr |
| 857 | # |
| 858 | # Generate the parameter checking code |
| 859 | def genFuncBody(self, funcName, values, valuePrefix, displayNamePrefix, structTypeName): |
| 860 | lines = [] # Generated lines of code |
| 861 | unused = [] # Unused variable names |
| 862 | for value in values: |
| 863 | usedLines = [] |
| 864 | lenParam = None |
| 865 | # |
| 866 | # 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. |
| 867 | postProcSpec = {} |
| 868 | postProcSpec['ppp'] = '' if not structTypeName else '{postProcPrefix}' |
| 869 | postProcSpec['pps'] = '' if not structTypeName else '{postProcSuffix}' |
| 870 | postProcSpec['ppi'] = '' if not structTypeName else '{postProcInsert}' |
| 871 | # |
| 872 | # Generate the full name of the value, which will be printed in the error message, by adding the variable prefix to the value name |
| 873 | valueDisplayName = '{}{}'.format(displayNamePrefix, value.name) |
| 874 | # |
| 875 | # Check for NULL pointers, ignore the inout count parameters that |
| 876 | # will be validated with their associated array |
| 877 | if (value.ispointer or value.isstaticarray) and not value.iscount: |
| 878 | # |
| 879 | # Parameters for function argument generation |
| 880 | req = 'true' # Paramerter cannot be NULL |
| 881 | cpReq = 'true' # Count pointer cannot be NULL |
| 882 | cvReq = 'true' # Count value cannot be 0 |
| 883 | lenDisplayName = None # Name of length parameter to print with validation messages; parameter name with prefix applied |
| 884 | # |
| 885 | # Generate required/optional parameter strings for the pointer and count values |
| 886 | if value.isoptional: |
| 887 | req = 'false' |
| 888 | if value.len: |
| 889 | # The parameter is an array with an explicit count parameter |
| 890 | lenParam = self.getLenParam(values, value.len) |
| 891 | lenDisplayName = '{}{}'.format(displayNamePrefix, lenParam.name) |
| 892 | if lenParam.ispointer: |
| 893 | # Count parameters that are pointers are inout |
| 894 | if type(lenParam.isoptional) is list: |
| 895 | if lenParam.isoptional[0]: |
| 896 | cpReq = 'false' |
| 897 | if lenParam.isoptional[1]: |
| 898 | cvReq = 'false' |
| 899 | else: |
| 900 | if lenParam.isoptional: |
| 901 | cpReq = 'false' |
| 902 | else: |
| 903 | if lenParam.isoptional: |
| 904 | cvReq = 'false' |
| 905 | # |
| 906 | # The parameter will not be processes when tagged as 'noautovalidity' |
| 907 | # For the pointer to struct case, the struct pointer will not be validated, but any |
| 908 | # members not tagged as 'noatuvalidity' will be validated |
| 909 | if value.noautovalidity: |
| 910 | # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually |
| 911 | self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name)) |
| 912 | else: |
| 913 | # |
| 914 | # If this is a pointer to a struct with an sType field, verify the type |
| 915 | if value.type in self.structTypes: |
| 916 | usedLines += self.makeStructTypeCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec) |
| 917 | # 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 |
| 918 | elif value.type in self.handleTypes and value.isconst and not self.isHandleOptional(value, lenParam): |
| 919 | usedLines += self.makeHandleCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec) |
| 920 | elif value.type in self.flags and value.isconst: |
| 921 | usedLines += self.makeFlagsArrayCheck(valuePrefix, value, lenParam, req, cvReq, funcName, lenDisplayName, valueDisplayName, postProcSpec) |
| 922 | elif value.isbool and value.isconst: |
| 923 | usedLines.append('skipCall |= validate_bool32_array(report_data, "{}", {ppp}"{}"{pps}, {ppp}"{}"{pps}, {pf}{}, {pf}{}, {}, {});\n'.format(funcName, lenDisplayName, valueDisplayName, lenParam.name, value.name, cvReq, req, pf=valuePrefix, **postProcSpec)) |
| 924 | elif value.israngedenum and value.isconst: |
| 925 | enumRange = self.enumRanges[value.type] |
| 926 | usedLines.append('skipCall |= validate_ranged_enum_array(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)) |
| 927 | elif value.name == 'pNext': |
| 928 | # We need to ignore VkDeviceCreateInfo and VkInstanceCreateInfo, as the loader manipulates them in a way that is not documented in vk.xml |
| 929 | if not structTypeName in ['VkDeviceCreateInfo', 'VkInstanceCreateInfo']: |
| 930 | usedLines += self.makeStructNextCheck(valuePrefix, value, funcName, valueDisplayName, postProcSpec) |
| 931 | else: |
| 932 | usedLines += self.makePointerCheck(valuePrefix, value, lenParam, req, cvReq, cpReq, funcName, lenDisplayName, valueDisplayName, postProcSpec) |
| 933 | # |
| 934 | # If this is a pointer to a struct (input), see if it contains members that need to be checked |
| 935 | if value.type in self.validatedStructs and value.isconst: |
| 936 | usedLines.append(self.expandStructPointerCode(valuePrefix, value, lenParam, funcName, valueDisplayName, postProcSpec)) |
| 937 | # Non-pointer types |
| 938 | else: |
| 939 | # |
| 940 | # The parameter will not be processes when tagged as 'noautovalidity' |
| 941 | # For the struct case, the struct type will not be validated, but any |
| 942 | # members not tagged as 'noatuvalidity' will be validated |
| 943 | if value.noautovalidity: |
| 944 | # Log a diagnostic message when validation cannot be automatically generated and must be implemented manually |
| 945 | self.logMsg('diag', 'ParameterValidation: No validation for {} {}'.format(structTypeName if structTypeName else funcName, value.name)) |
| 946 | else: |
| 947 | if value.type in self.structTypes: |
| 948 | stype = self.structTypes[value.type] |
| 949 | usedLines.append('skipCall |= validate_struct_type(report_data, "{}", {ppp}"{}"{pps}, "{sv}", &({}{vn}), {sv}, false);\n'.format( |
| 950 | funcName, valueDisplayName, valuePrefix, vn=value.name, sv=stype.value, **postProcSpec)) |
| 951 | elif value.type in self.handleTypes: |
| 952 | if not self.isHandleOptional(value, None): |
| 953 | usedLines.append('skipCall |= validate_required_handle(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec)) |
| 954 | elif value.type in self.flags: |
| 955 | flagBitsName = value.type.replace('Flags', 'FlagBits') |
| 956 | if not flagBitsName in self.flagBits: |
| 957 | usedLines.append('skipCall |= validate_reserved_flags(report_data, "{}", {ppp}"{}"{pps}, {pf}{});\n'.format(funcName, valueDisplayName, value.name, pf=valuePrefix, **postProcSpec)) |
| 958 | else: |
| 959 | flagsRequired = 'false' if value.isoptional else 'true' |
| 960 | allFlagsName = 'All' + flagBitsName |
| 961 | usedLines.append('skipCall |= validate_flags(report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {pf}{}, {});\n'.format(funcName, valueDisplayName, flagBitsName, allFlagsName, value.name, flagsRequired, pf=valuePrefix, **postProcSpec)) |
| 962 | elif value.isbool: |
| 963 | usedLines.append('skipCall |= validate_bool32(report_data, "{}", {ppp}"{}"{pps}, {}{});\n'.format(funcName, valueDisplayName, valuePrefix, value.name, **postProcSpec)) |
| 964 | elif value.israngedenum: |
| 965 | enumRange = self.enumRanges[value.type] |
Mark Lobodzinski | 6f82eb5 | 2016-12-05 07:38:41 -0700 | [diff] [blame] | 966 | if value.type == "VkObjectEntryTypeNVX": |
| 967 | garbage = 2 |
Mark Lobodzinski | 8567267 | 2016-10-13 08:36:42 -0600 | [diff] [blame] | 968 | usedLines.append('skipCall |= validate_ranged_enum(report_data, "{}", {ppp}"{}"{pps}, "{}", {}, {}, {}{});\n'.format(funcName, valueDisplayName, value.type, enumRange[0], enumRange[1], valuePrefix, value.name, **postProcSpec)) |
| 969 | # |
| 970 | # If this is a struct, see if it contains members that need to be checked |
| 971 | if value.type in self.validatedStructs: |
| 972 | memberNamePrefix = '{}{}.'.format(valuePrefix, value.name) |
| 973 | memberDisplayNamePrefix = '{}.'.format(valueDisplayName) |
| 974 | usedLines.append(self.expandStructCode(self.validatedStructs[value.type], funcName, memberNamePrefix, memberDisplayNamePrefix, '', [], postProcSpec)) |
| 975 | # |
| 976 | # Append the parameter check to the function body for the current command |
| 977 | if usedLines: |
| 978 | # Apply special conditional checks |
| 979 | if value.condition: |
| 980 | usedLines = self.genConditionalCall(valuePrefix, value.condition, usedLines) |
| 981 | lines += usedLines |
| 982 | elif not value.iscount: |
| 983 | # If no expression was generated for this value, it is unreferenced by the validation function, unless |
| 984 | # it is an array count, which is indirectly referenced for array valiadation. |
| 985 | unused.append(value.name) |
| 986 | return lines, unused |
| 987 | # |
| 988 | # Generate the struct member check code from the captured data |
| 989 | def processStructMemberData(self): |
| 990 | indent = self.incIndent(None) |
| 991 | for struct in self.structMembers: |
| 992 | # |
| 993 | # The string returned by genFuncBody will be nested in an if check for a NULL pointer, so needs its indent incremented |
| 994 | lines, unused = self.genFuncBody('{funcName}', struct.members, '{valuePrefix}', '{displayNamePrefix}', struct.name) |
| 995 | if lines: |
| 996 | self.validatedStructs[struct.name] = lines |
| 997 | # |
| 998 | # Generate the command param check code from the captured data |
| 999 | def processCmdData(self): |
| 1000 | indent = self.incIndent(None) |
| 1001 | for command in self.commands: |
| 1002 | # Skip first parameter if it is a dispatch handle (everything except vkCreateInstance) |
| 1003 | startIndex = 0 if command.name == 'vkCreateInstance' else 1 |
| 1004 | lines, unused = self.genFuncBody(command.name, command.params[startIndex:], '', '', None) |
| 1005 | if lines: |
| 1006 | cmdDef = self.getCmdDef(command) + '\n' |
| 1007 | cmdDef += '{\n' |
| 1008 | # Process unused parameters, Ignoring the first dispatch handle parameter, which is not |
| 1009 | # processed by parameter_validation (except for vkCreateInstance, which does not have a |
| 1010 | # handle as its first parameter) |
| 1011 | if unused: |
| 1012 | for name in unused: |
| 1013 | cmdDef += indent + 'UNUSED_PARAMETER({});\n'.format(name) |
| 1014 | if len(unused) > 0: |
| 1015 | cmdDef += '\n' |
| 1016 | cmdDef += indent + 'bool skipCall = false;\n' |
| 1017 | for line in lines: |
| 1018 | cmdDef += '\n' |
| 1019 | if type(line) is list: |
| 1020 | for sub in line: |
| 1021 | cmdDef += indent + sub |
| 1022 | else: |
| 1023 | cmdDef += indent + line |
| 1024 | cmdDef += '\n' |
| 1025 | cmdDef += indent + 'return skipCall;\n' |
| 1026 | cmdDef += '}\n' |
| 1027 | self.appendSection('command', cmdDef) |