blob: 1868bfd6e284623efffe0a13e649ce9bb453b0ea [file] [log] [blame]
Tobin Ehlis35308dd2016-10-31 13:27:36 -06001#!/usr/bin/env python3
2# Copyright (c) 2015-2016 The Khronos Group Inc.
3# Copyright (c) 2015-2016 Valve Corporation
4# Copyright (c) 2015-2016 LunarG, Inc.
5# Copyright (c) 2015-2016 Google Inc.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19# Author: Tobin Ehlis <tobine@google.com>
20
21import argparse
22import os
23import sys
24import platform
25
26# vk_validation_stats.py overview
27# This script is intended to generate statistics on the state of validation code
28# based on information parsed from the source files and the database file
29# Here's what it currently does:
30# 1. Parse vk_validation_error_database.txt to store claimed state of validation checks
31# 2. Parse vk_validation_error_messages.h to verify the actual checks in header vs. the
32# claimed state of the checks
33# 3. Parse source files to identify which checks are implemented and verify that this
34# exactly matches the list of checks claimed to be implemented in the database
35# 4. Parse test file(s) and verify that reported tests exist
36# 5. Report out stats on number of checks, implemented checks, and duplicated checks
37#
Tobin Ehlis20e32582016-12-05 14:50:03 -070038# If a mis-match is found during steps 2, 3, or 4, then the script exits w/ a non-zero error code
39# otherwise, the script will exit(0)
40#
Tobin Ehlis35308dd2016-10-31 13:27:36 -060041# TODO:
42# 1. Would also like to report out number of existing checks that don't yet use new, unique enum
43# 2. Could use notes to store custom fields (like TODO) and print those out here
44# 3. Update test code to check if tests use new, unique enums to check for errors instead of strings
45
46db_file = 'vk_validation_error_database.txt'
47layer_source_files = [
48'core_validation.cpp',
49'descriptor_sets.cpp',
50'parameter_validation.cpp',
51'object_tracker.cpp',
Mike Weiblen6a27de52016-12-09 17:36:28 -070052'image.cpp',
53'swapchain.cpp'
Tobin Ehlis35308dd2016-10-31 13:27:36 -060054]
55header_file = 'vk_validation_error_messages.h'
56# TODO : Don't hardcode linux path format if we want this to run on windows
57test_file = '../tests/layer_validation_tests.cpp'
Tobin Ehlis225b59c2016-12-22 13:59:42 -070058# List of enums that are allowed to be used more than once so don't warn on their duplicates
59duplicate_exceptions = [
60'VALIDATION_ERROR_00942', # This is a descriptor set write update error that we use for a couple copy cases as well
61]
Tobin Ehlis35308dd2016-10-31 13:27:36 -060062
63class ValidationDatabase:
64 def __init__(self, filename=db_file):
65 self.db_file = filename
66 self.delimiter = '~^~'
67 self.db_dict = {} # complete dict of all db values per error enum
68 # specialized data structs with slices of complete dict
69 self.db_implemented_enums = [] # list of all error enums claiming to be implemented in database file
70 self.db_enum_to_tests = {} # dict where enum is key to lookup list of tests implementing the enum
71 #self.src_implemented_enums
72 def read(self):
73 """Read a database file into internal data structures, format of each line is <enum><implemented Y|N?><testname><api><errormsg><notes>"""
74 #db_dict = {} # This is a simple db of just enum->errormsg, the same as is created from spec
75 #max_id = 0
76 with open(self.db_file, "r") as infile:
77 for line in infile:
78 line = line.strip()
79 if line.startswith('#') or '' == line:
80 continue
81 db_line = line.split(self.delimiter)
82 if len(db_line) != 6:
Tobin Ehlis027f3212016-12-09 12:15:26 -070083 print("ERROR: Bad database line doesn't have 6 elements: %s" % (line))
Tobin Ehlis35308dd2016-10-31 13:27:36 -060084 error_enum = db_line[0]
85 implemented = db_line[1]
86 testname = db_line[2]
87 api = db_line[3]
88 error_str = db_line[4]
89 note = db_line[5]
90 # Read complete database contents into our class var for later use
91 self.db_dict[error_enum] = {}
92 self.db_dict[error_enum]['check_implemented'] = implemented
93 self.db_dict[error_enum]['testname'] = testname
94 self.db_dict[error_enum]['api'] = api
95 self.db_dict[error_enum]['error_string'] = error_str
96 self.db_dict[error_enum]['note'] = note
97 # Now build custom data structs
98 if 'Y' == implemented:
99 self.db_implemented_enums.append(error_enum)
100 if testname.lower() not in ['unknown', 'none']:
101 self.db_enum_to_tests[error_enum] = testname.split(',')
102 #if len(self.db_enum_to_tests[error_enum]) > 1:
103 # print "Found check %s that has multiple tests: %s" % (error_enum, self.db_enum_to_tests[error_enum])
104 #else:
105 # print "Check %s has single test: %s" % (error_enum, self.db_enum_to_tests[error_enum])
106 #unique_id = int(db_line[0].split('_')[-1])
107 #if unique_id > max_id:
108 # max_id = unique_id
109 #print "Found %d total enums in database" % (len(self.db_dict.keys()))
110 #print "Found %d enums claiming to be implemented in source" % (len(self.db_implemented_enums))
111 #print "Found %d enums claiming to have tests implemented" % (len(self.db_enum_to_tests.keys()))
112
113class ValidationHeader:
114 def __init__(self, filename=header_file):
115 self.filename = header_file
116 self.enums = []
117 def read(self):
118 """Read unique error enum header file into internal data structures"""
119 grab_enums = False
120 with open(self.filename, "r") as infile:
121 for line in infile:
122 line = line.strip()
123 if 'enum UNIQUE_VALIDATION_ERROR_CODE {' in line:
124 grab_enums = True
125 continue
126 if grab_enums:
127 if 'VALIDATION_ERROR_MAX_ENUM' in line:
128 grab_enums = False
129 break # done
Tobin Ehlisf53eac32016-12-09 14:10:47 -0700130 elif 'VALIDATION_ERROR_UNDEFINED' in line:
131 continue
132 elif 'VALIDATION_ERROR_' in line:
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600133 enum = line.split(' = ')[0]
134 self.enums.append(enum)
135 #print "Found %d error enums. First is %s and last is %s." % (len(self.enums), self.enums[0], self.enums[-1])
136
137class ValidationSource:
138 def __init__(self, source_file_list):
139 self.source_files = source_file_list
Tobin Ehlis3d1f2bd2016-12-22 11:19:15 -0700140 self.enum_count_dict = {} # dict of enum values to the count of how much they're used, and location of where they're used
Tobin Ehlis3d9dd942016-11-23 13:08:01 -0700141 # 1790 is a special case that provides an exception when an extension is enabled. No specific error is flagged, but the exception is handled so add it here
Tobin Ehlis3d1f2bd2016-12-22 11:19:15 -0700142 self.enum_count_dict['VALIDATION_ERROR_01790'] = {}
143 self.enum_count_dict['VALIDATION_ERROR_01790']['count'] = 1
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600144 def parse(self):
145 duplicate_checks = 0
146 for sf in self.source_files:
Tobin Ehlis3d1f2bd2016-12-22 11:19:15 -0700147 line_num = 0
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600148 with open(sf) as f:
149 for line in f:
Tobin Ehlis3d1f2bd2016-12-22 11:19:15 -0700150 line_num = line_num + 1
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600151 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
152 continue
153 # Find enums
154 #if 'VALIDATION_ERROR_' in line and True not in [ignore in line for ignore in ['[VALIDATION_ERROR_', 'UNIQUE_VALIDATION_ERROR_CODE']]:
Tobin Ehlisf53eac32016-12-09 14:10:47 -0700155 if ' VALIDATION_ERROR_' in line:
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600156 # Need to isolate the validation error enum
157 #print("Line has check:%s" % (line))
158 line_list = line.split()
Tobin Ehlis928742e2016-12-09 17:11:13 -0700159 enum_list = []
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600160 for str in line_list:
Tobin Ehlisf53eac32016-12-09 14:10:47 -0700161 if 'VALIDATION_ERROR_' in str and True not in [ignore_str in str for ignore_str in ['[VALIDATION_ERROR_', 'VALIDATION_ERROR_UNDEFINED', 'UNIQUE_VALIDATION_ERROR_CODE']]:
Tobin Ehlis928742e2016-12-09 17:11:13 -0700162 enum_list.append(str.strip(',);'))
163 #break
164 for enum in enum_list:
165 if enum != '':
166 if enum not in self.enum_count_dict:
Tobin Ehlis3d1f2bd2016-12-22 11:19:15 -0700167 self.enum_count_dict[enum] = {}
168 self.enum_count_dict[enum]['count'] = 1
169 self.enum_count_dict[enum]['file_line'] = []
170 self.enum_count_dict[enum]['file_line'].append('%s,%d' % (sf, line_num))
Tobin Ehlis928742e2016-12-09 17:11:13 -0700171 #print "Found enum %s implemented for first time in file %s" % (enum, sf)
172 else:
Tobin Ehlis3d1f2bd2016-12-22 11:19:15 -0700173 self.enum_count_dict[enum]['count'] = self.enum_count_dict[enum]['count'] + 1
174 self.enum_count_dict[enum]['file_line'].append('%s,%d' % (sf, line_num))
Tobin Ehlis928742e2016-12-09 17:11:13 -0700175 #print "Found enum %s implemented for %d time in file %s" % (enum, self.enum_count_dict[enum], sf)
176 duplicate_checks = duplicate_checks + 1
177 #else:
178 #print("Didn't find actual check in line:%s" % (line))
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600179 #print "Found %d unique implemented checks and %d are duplicated at least once" % (len(self.enum_count_dict.keys()), duplicate_checks)
180
181# Class to parse the validation layer test source and store testnames
182# TODO: Enhance class to detect use of unique error enums in the test
183class TestParser:
184 def __init__(self, test_file_list, test_group_name=['VkLayerTest', 'VkPositiveLayerTest', 'VkWsiEnabledLayerTest']):
185 self.test_files = test_file_list
186 self.tests_set = set()
187 self.test_trigger_txt_list = []
188 for tg in test_group_name:
189 self.test_trigger_txt_list.append('TEST_F(%s' % tg)
190 #print('Test trigger test list: %s' % (self.test_trigger_txt_list))
191
192 # Parse test files into internal data struct
193 def parse(self):
194 # For each test file, parse test names into set
195 grab_next_line = False # handle testname on separate line than wildcard
196 for test_file in self.test_files:
197 with open(test_file) as tf:
198 for line in tf:
199 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
200 continue
201
202 if True in [ttt in line for ttt in self.test_trigger_txt_list]:
203 #print('Test wildcard in line: %s' % (line))
204 testname = line.split(',')[-1]
205 testname = testname.strip().strip(' {)')
206 #print('Inserting test: "%s"' % (testname))
207 if ('' == testname):
208 grab_next_line = True
209 continue
210 self.tests_set.add(testname)
211 if grab_next_line: # test name on its own line
212 grab_next_line = False
213 testname = testname.strip().strip(' {)')
214 self.tests_set.add(testname)
215
216# Little helper class for coloring cmd line output
217class bcolors:
218
219 def __init__(self):
220 self.GREEN = '\033[0;32m'
221 self.RED = '\033[0;31m'
222 self.YELLOW = '\033[1;33m'
223 self.ENDC = '\033[0m'
224 if 'Linux' != platform.system():
225 self.GREEN = ''
226 self.RED = ''
227 self.YELLOW = ''
228 self.ENDC = ''
229
230 def green(self):
231 return self.GREEN
232
233 def red(self):
234 return self.RED
235
236 def yellow(self):
237 return self.YELLOW
238
239 def endc(self):
240 return self.ENDC
241
242# Class to parse the validation layer test source and store testnames
243class TestParser:
244 def __init__(self, test_file_list, test_group_name=['VkLayerTest', 'VkPositiveLayerTest', 'VkWsiEnabledLayerTest']):
245 self.test_files = test_file_list
246 self.tests_set = set()
247 self.test_trigger_txt_list = []
248 for tg in test_group_name:
249 self.test_trigger_txt_list.append('TEST_F(%s' % tg)
250 #print('Test trigger test list: %s' % (self.test_trigger_txt_list))
251
252 # Parse test files into internal data struct
253 def parse(self):
254 # For each test file, parse test names into set
255 grab_next_line = False # handle testname on separate line than wildcard
256 for test_file in self.test_files:
257 with open(test_file) as tf:
258 for line in tf:
259 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
260 continue
261
262 if True in [ttt in line for ttt in self.test_trigger_txt_list]:
263 #print('Test wildcard in line: %s' % (line))
264 testname = line.split(',')[-1]
265 testname = testname.strip().strip(' {)')
266 #print('Inserting test: "%s"' % (testname))
267 if ('' == testname):
268 grab_next_line = True
269 continue
270 self.tests_set.add(testname)
271 if grab_next_line: # test name on its own line
272 grab_next_line = False
273 testname = testname.strip().strip(' {)')
274 self.tests_set.add(testname)
275
276def main(argv=None):
Tobin Ehlis20e32582016-12-05 14:50:03 -0700277 result = 0 # Non-zero result indicates an error case
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600278 # parse db
279 val_db = ValidationDatabase()
280 val_db.read()
281 # parse header
282 val_header = ValidationHeader()
283 val_header.read()
284 # Create parser for layer files
285 val_source = ValidationSource(layer_source_files)
286 val_source.parse()
287 # Parse test files
288 test_parser = TestParser([test_file, ])
289 test_parser.parse()
290
291 # Process stats - Just doing this inline in main, could make a fancy class to handle
292 # all the processing of data and then get results from that
293 txt_color = bcolors()
294 print("Validation Statistics")
295 # First give number of checks in db & header and report any discrepancies
296 db_enums = len(val_db.db_dict.keys())
297 hdr_enums = len(val_header.enums)
298 print(" Database file includes %d unique checks" % (db_enums))
299 print(" Header file declares %d unique checks" % (hdr_enums))
300 tmp_db_dict = val_db.db_dict
301 db_missing = []
302 for enum in val_header.enums:
303 if not tmp_db_dict.pop(enum, False):
304 db_missing.append(enum)
305 if db_enums == hdr_enums and len(db_missing) == 0 and len(tmp_db_dict.keys()) == 0:
306 print(txt_color.green() + " Database and Header match, GREAT!" + txt_color.endc())
307 else:
308 print(txt_color.red() + " Uh oh, Database doesn't match Header :(" + txt_color.endc())
Tobin Ehlis20e32582016-12-05 14:50:03 -0700309 result = 1
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600310 if len(db_missing) != 0:
311 print(txt_color.red() + " The following checks are in header but missing from database:" + txt_color.endc())
312 for missing_enum in db_missing:
313 print(txt_color.red() + " %s" % (missing_enum) + txt_color.endc())
314 if len(tmp_db_dict.keys()) != 0:
315 print(txt_color.red() + " The following checks are in database but haven't been declared in the header:" + txt_color.endc())
316 for extra_enum in tmp_db_dict:
317 print(txt_color.red() + " %s" % (extra_enum) + txt_color.endc())
318 # Report out claimed implemented checks vs. found actual implemented checks
319 imp_not_found = [] # Checks claimed to implemented in DB file but no source found
320 imp_not_claimed = [] # Checks found implemented but not claimed to be in DB
321 multiple_uses = False # Flag if any enums are used multiple times
322 for db_imp in val_db.db_implemented_enums:
323 if db_imp not in val_source.enum_count_dict:
324 imp_not_found.append(db_imp)
325 for src_enum in val_source.enum_count_dict:
Tobin Ehlis225b59c2016-12-22 13:59:42 -0700326 if val_source.enum_count_dict[src_enum]['count'] > 1 and src_enum not in duplicate_exceptions:
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600327 multiple_uses = True
328 if src_enum not in val_db.db_implemented_enums:
329 imp_not_claimed.append(src_enum)
330 print(" Database file claims that %d checks (%s) are implemented in source." % (len(val_db.db_implemented_enums), "{0:.0f}%".format(float(len(val_db.db_implemented_enums))/db_enums * 100)))
331 if len(imp_not_found) == 0 and len(imp_not_claimed) == 0:
332 print(txt_color.green() + " All claimed Database implemented checks have been found in source, and no source checks aren't claimed in Database, GREAT!" + txt_color.endc())
333 else:
Tobin Ehlis20e32582016-12-05 14:50:03 -0700334 result = 1
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600335 print(txt_color.red() + " Uh oh, Database claimed implemented don't match Source :(" + txt_color.endc())
336 if len(imp_not_found) != 0:
Tobin Ehlis3f0b2772016-11-18 16:56:15 -0700337 print(txt_color.red() + " The following %d checks are claimed to be implemented in Database, but weren't found in source:" % (len(imp_not_found)) + txt_color.endc())
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600338 for not_imp_enum in imp_not_found:
339 print(txt_color.red() + " %s" % (not_imp_enum) + txt_color.endc())
340 if len(imp_not_claimed) != 0:
341 print(txt_color.red() + " The following checks are implemented in source, but not claimed to be in Database:" + txt_color.endc())
342 for imp_enum in imp_not_claimed:
343 print(txt_color.red() + " %s" % (imp_enum) + txt_color.endc())
344 if multiple_uses:
345 print(txt_color.yellow() + " Note that some checks are used multiple times. These may be good candidates for new valid usage spec language." + txt_color.endc())
346 print(txt_color.yellow() + " Here is a list of each check used multiple times with its number of uses:" + txt_color.endc())
347 for enum in val_source.enum_count_dict:
Tobin Ehlis225b59c2016-12-22 13:59:42 -0700348 if val_source.enum_count_dict[enum]['count'] > 1 and enum not in duplicate_exceptions:
Tobin Ehlis3d1f2bd2016-12-22 11:19:15 -0700349 print(txt_color.yellow() + " %s: %d uses in file,line:" % (enum, val_source.enum_count_dict[enum]['count']) + txt_color.endc())
350 for file_line in val_source.enum_count_dict[enum]['file_line']:
351 print(txt_color.yellow() + " \t%s" % (file_line) + txt_color.endc())
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600352 # Now check that tests claimed to be implemented are actual test names
353 bad_testnames = []
354 for enum in val_db.db_enum_to_tests:
355 for testname in val_db.db_enum_to_tests[enum]:
356 if testname not in test_parser.tests_set:
357 bad_testnames.append(testname)
358 print(" Database file claims that %d checks have tests written." % len(val_db.db_enum_to_tests))
359 if len(bad_testnames) == 0:
360 print(txt_color.green() + " All claimed tests have valid names. That's good!" + txt_color.endc())
361 else:
362 print(txt_color.red() + " The following testnames in Database appear to be invalid:")
Tobin Ehlis20e32582016-12-05 14:50:03 -0700363 result = 1
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600364 for bt in bad_testnames:
Tobin Ehlisb04c2c62016-11-21 15:51:45 -0700365 print(txt_color.red() + " %s" % (bt) + txt_color.endc())
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600366
Tobin Ehlis20e32582016-12-05 14:50:03 -0700367 return result
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600368
369if __name__ == "__main__":
370 sys.exit(main())
371