blob: 440b2ec956b07bc6f9d26a6d2c27f8a9f5999241 [file] [log] [blame]
Anna Zaksf0c41162011-10-06 23:26:27 +00001#!/usr/bin/env python
2
3"""
4Static Analyzer qualification infrastructure.
5
6The goal is to test the analyzer against different projects, check for failures,
7compare results, and measure performance.
8
Ted Kremenek3a0678e2015-09-08 03:50:52 +00009Repository Directory will contain sources of the projects as well as the
10information on how to build them and the expected output.
Anna Zaksf0c41162011-10-06 23:26:27 +000011Repository Directory structure:
12 - ProjectMap file
13 - Historical Performance Data
14 - Project Dir1
15 - ReferenceOutput
16 - Project Dir2
17 - ReferenceOutput
18 ..
Gabor Horvathc3177f22015-07-08 18:39:31 +000019Note that the build tree must be inside the project dir.
Anna Zaksf0c41162011-10-06 23:26:27 +000020
21To test the build of the analyzer one would:
Ted Kremenek3a0678e2015-09-08 03:50:52 +000022 - Copy over a copy of the Repository Directory. (TODO: Prefer to ensure that
Anna Zaksf0c41162011-10-06 23:26:27 +000023 the build directory does not pollute the repository to min network traffic).
24 - Build all projects, until error. Produce logs to report errors.
Ted Kremenek3a0678e2015-09-08 03:50:52 +000025 - Compare results.
Anna Zaksf0c41162011-10-06 23:26:27 +000026
Ted Kremenek3a0678e2015-09-08 03:50:52 +000027The files which should be kept around for failure investigations:
Anna Zaksf0c41162011-10-06 23:26:27 +000028 RepositoryCopy/Project DirI/ScanBuildResults
Ted Kremenek3a0678e2015-09-08 03:50:52 +000029 RepositoryCopy/Project DirI/run_static_analyzer.log
30
31Assumptions (TODO: shouldn't need to assume these.):
Anna Zaksf0c41162011-10-06 23:26:27 +000032 The script is being run from the Repository Directory.
Anna Zaks42a44632011-11-02 20:46:50 +000033 The compiler for scan-build and scan-build are in the PATH.
Anna Zaksf0c41162011-10-06 23:26:27 +000034 export PATH=/Users/zaks/workspace/c2llvm/build/Release+Asserts/bin:$PATH
35
36For more logging, set the env variables:
37 zaks:TI zaks$ export CCC_ANALYZER_LOG=1
38 zaks:TI zaks$ export CCC_ANALYZER_VERBOSE=1
Ted Kremenek3a0678e2015-09-08 03:50:52 +000039
Gabor Horvathda32a862015-08-20 22:59:49 +000040The list of checkers tested are hardcoded in the Checkers variable.
41For testing additional checkers, use the SA_ADDITIONAL_CHECKERS environment
42variable. It should contain a comma separated list.
Anna Zaksf0c41162011-10-06 23:26:27 +000043"""
44import CmpRuns
45
46import os
47import csv
48import sys
49import glob
Ted Kremenekf9a539d2012-08-28 20:40:04 +000050import math
Anna Zaksf0c41162011-10-06 23:26:27 +000051import shutil
52import time
53import plistlib
Gabor Horvath93fde942015-06-30 15:31:17 +000054import argparse
Devin Coughlinbace0322015-09-14 21:22:24 +000055from subprocess import check_call, check_output, CalledProcessError
Anna Zaksf0c41162011-10-06 23:26:27 +000056
Ted Kremenek42c14422012-08-28 20:40:02 +000057#------------------------------------------------------------------------------
58# Helper functions.
59#------------------------------------------------------------------------------
Anna Zaksf0c41162011-10-06 23:26:27 +000060
Ted Kremenekf9a539d2012-08-28 20:40:04 +000061def detectCPUs():
62 """
63 Detects the number of CPUs on a system. Cribbed from pp.
64 """
65 # Linux, Unix and MacOS:
66 if hasattr(os, "sysconf"):
67 if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
68 # Linux & Unix:
69 ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
70 if isinstance(ncpus, int) and ncpus > 0:
71 return ncpus
72 else: # OSX:
73 return int(capture(['sysctl', '-n', 'hw.ncpu']))
74 # Windows:
75 if os.environ.has_key("NUMBER_OF_PROCESSORS"):
76 ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
77 if ncpus > 0:
78 return ncpus
79 return 1 # Default
80
Ted Kremenek6cb20802012-08-28 20:20:52 +000081def which(command, paths = None):
82 """which(command, [paths]) - Look up the given command in the paths string
83 (or the PATH environment variable, if unspecified)."""
84
85 if paths is None:
86 paths = os.environ.get('PATH','')
87
88 # Check for absolute match first.
89 if os.path.exists(command):
90 return command
91
92 # Would be nice if Python had a lib function for this.
93 if not paths:
94 paths = os.defpath
95
96 # Get suffixes to search.
97 # On Cygwin, 'PATHEXT' may exist but it should not be used.
98 if os.pathsep == ';':
99 pathext = os.environ.get('PATHEXT', '').split(';')
100 else:
101 pathext = ['']
102
103 # Search the paths...
104 for path in paths.split(os.pathsep):
105 for ext in pathext:
106 p = os.path.join(path, command + ext)
107 if os.path.exists(p):
108 return p
109
110 return None
111
Anna Zaksde1f7f8b2012-01-10 18:10:25 +0000112# Make sure we flush the output after every print statement.
113class flushfile(object):
114 def __init__(self, f):
115 self.f = f
116 def write(self, x):
117 self.f.write(x)
118 self.f.flush()
119
120sys.stdout = flushfile(sys.stdout)
121
Anna Zaksf0c41162011-10-06 23:26:27 +0000122def getProjectMapPath():
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000123 ProjectMapPath = os.path.join(os.path.abspath(os.curdir),
Anna Zaksf0c41162011-10-06 23:26:27 +0000124 ProjectMapFile)
125 if not os.path.exists(ProjectMapPath):
126 print "Error: Cannot find the Project Map file " + ProjectMapPath +\
127 "\nRunning script for the wrong directory?"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000128 sys.exit(-1)
129 return ProjectMapPath
Anna Zaksf0c41162011-10-06 23:26:27 +0000130
131def getProjectDir(ID):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000132 return os.path.join(os.path.abspath(os.curdir), ID)
Anna Zaksf0c41162011-10-06 23:26:27 +0000133
Jordan Rose01ac5722012-06-01 16:24:38 +0000134def getSBOutputDirName(IsReferenceBuild) :
Anna Zaks4720a732011-11-05 05:20:48 +0000135 if IsReferenceBuild == True :
136 return SBOutputDirReferencePrefix + SBOutputDirName
137 else :
138 return SBOutputDirName
139
Ted Kremenek42c14422012-08-28 20:40:02 +0000140#------------------------------------------------------------------------------
141# Configuration setup.
142#------------------------------------------------------------------------------
143
144# Find Clang for static analysis.
145Clang = which("clang", os.environ['PATH'])
146if not Clang:
147 print "Error: cannot find 'clang' in PATH"
148 sys.exit(-1)
149
Ted Kremenekf9a539d2012-08-28 20:40:04 +0000150# Number of jobs.
Jordan Rose88329242012-11-16 17:41:21 +0000151Jobs = int(math.ceil(detectCPUs() * 0.75))
Ted Kremenekf9a539d2012-08-28 20:40:04 +0000152
Ted Kremenek42c14422012-08-28 20:40:02 +0000153# Project map stores info about all the "registered" projects.
154ProjectMapFile = "projectMap.csv"
155
156# Names of the project specific scripts.
157# The script that needs to be executed before the build can start.
158CleanupScript = "cleanup_run_static_analyzer.sh"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000159# This is a file containing commands for scan-build.
Ted Kremenek42c14422012-08-28 20:40:02 +0000160BuildScript = "run_static_analyzer.cmd"
161
162# The log file name.
163LogFolderName = "Logs"
164BuildLogName = "run_static_analyzer.log"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000165# Summary file - contains the summary of the failures. Ex: This info can be be
Ted Kremenek42c14422012-08-28 20:40:02 +0000166# displayed when buildbot detects a build failure.
167NumOfFailuresInSummary = 10
168FailuresSummaryFileName = "failures.txt"
169# Summary of the result diffs.
170DiffsSummaryFileName = "diffs.txt"
171
172# The scan-build result directory.
173SBOutputDirName = "ScanBuildResults"
174SBOutputDirReferencePrefix = "Ref"
175
176# The list of checkers used during analyzes.
Alp Tokerd4733632013-12-05 04:47:09 +0000177# Currently, consists of all the non-experimental checkers, plus a few alpha
Jordan Rose10ad0812013-04-05 17:55:07 +0000178# checkers we don't want to regress on.
Anna Zaks8a020312014-10-31 17:40:14 +0000179Checkers="alpha.unix.SimpleStream,alpha.security.taint,cplusplus.NewDeleteLeaks,core,cplusplus,deadcode,security,unix,osx"
Ted Kremenek42c14422012-08-28 20:40:02 +0000180
181Verbose = 1
182
183#------------------------------------------------------------------------------
184# Test harness logic.
185#------------------------------------------------------------------------------
186
Anna Zaksf0c41162011-10-06 23:26:27 +0000187# Run pre-processing script if any.
Anna Zaks42a44632011-11-02 20:46:50 +0000188def runCleanupScript(Dir, PBuildLogFile):
189 ScriptPath = os.path.join(Dir, CleanupScript)
Anna Zaksf0c41162011-10-06 23:26:27 +0000190 if os.path.exists(ScriptPath):
191 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000192 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000193 print " Executing: %s" % (ScriptPath,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000194 check_call("chmod +x %s" % ScriptPath, cwd = Dir,
Anna Zaksf0c41162011-10-06 23:26:27 +0000195 stderr=PBuildLogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000196 stdout=PBuildLogFile,
197 shell=True)
Anna Zaksf0c41162011-10-06 23:26:27 +0000198 check_call(ScriptPath, cwd = Dir, stderr=PBuildLogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000199 stdout=PBuildLogFile,
Anna Zaksf0c41162011-10-06 23:26:27 +0000200 shell=True)
201 except:
202 print "Error: The pre-processing step failed. See ", \
203 PBuildLogFile.name, " for details."
204 sys.exit(-1)
205
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000206# Build the project with scan-build by reading in the commands and
Anna Zaksf0c41162011-10-06 23:26:27 +0000207# prefixing them with the scan-build options.
208def runScanBuild(Dir, SBOutputDir, PBuildLogFile):
209 BuildScriptPath = os.path.join(Dir, BuildScript)
210 if not os.path.exists(BuildScriptPath):
211 print "Error: build script is not defined: %s" % BuildScriptPath
Ted Kremenek6cb20802012-08-28 20:20:52 +0000212 sys.exit(-1)
213 SBOptions = "--use-analyzer " + Clang + " "
214 SBOptions += "-plist-html -o " + SBOutputDir + " "
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000215 SBOptions += "-enable-checker " + Checkers + " "
Jordan Roseb18179d2013-01-24 23:07:59 +0000216 SBOptions += "--keep-empty "
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000217 # Always use ccc-analyze to ensure that we can locate the failures
Anna Zaks7b4f8a42013-05-31 02:31:09 +0000218 # directory.
219 SBOptions += "--override-compiler "
Anna Zaksf0c41162011-10-06 23:26:27 +0000220 try:
221 SBCommandFile = open(BuildScriptPath, "r")
222 SBPrefix = "scan-build " + SBOptions + " "
223 for Command in SBCommandFile:
Jordan Rose7bd91862013-09-06 16:12:41 +0000224 Command = Command.strip()
Gabor Horvath93fde942015-06-30 15:31:17 +0000225 if len(Command) == 0:
226 continue;
Ted Kremenekf9a539d2012-08-28 20:40:04 +0000227 # If using 'make', auto imply a -jX argument
228 # to speed up analysis. xcodebuild will
229 # automatically use the maximum number of cores.
Jordan Rose64e4cf02012-11-26 19:59:57 +0000230 if (Command.startswith("make ") or Command == "make") and \
231 "-j" not in Command:
Jordan Rose88329242012-11-16 17:41:21 +0000232 Command += " -j%d" % Jobs
Anna Zaksf0c41162011-10-06 23:26:27 +0000233 SBCommand = SBPrefix + Command
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000234 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000235 print " Executing: %s" % (SBCommand,)
236 check_call(SBCommand, cwd = Dir, stderr=PBuildLogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000237 stdout=PBuildLogFile,
Anna Zaksf0c41162011-10-06 23:26:27 +0000238 shell=True)
239 except:
240 print "Error: scan-build failed. See ",PBuildLogFile.name,\
241 " for details."
Anna Zaks4720a732011-11-05 05:20:48 +0000242 raise
Anna Zaksf0c41162011-10-06 23:26:27 +0000243
Anna Zaks4720a732011-11-05 05:20:48 +0000244def hasNoExtension(FileName):
245 (Root, Ext) = os.path.splitext(FileName)
246 if ((Ext == "")) :
247 return True
248 return False
249
250def isValidSingleInputFile(FileName):
251 (Root, Ext) = os.path.splitext(FileName)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000252 if ((Ext == ".i") | (Ext == ".ii") |
253 (Ext == ".c") | (Ext == ".cpp") |
Anna Zaks4720a732011-11-05 05:20:48 +0000254 (Ext == ".m") | (Ext == "")) :
255 return True
256 return False
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000257
Devin Coughlinbace0322015-09-14 21:22:24 +0000258# Get the path to the SDK for the given SDK name. Returns None if
259# the path cannot be determined.
260def getSDKPath(SDKName):
261 if which("xcrun") is None:
262 return None
263
264 Cmd = "xcrun --sdk " + SDKName + " --show-sdk-path"
265 return check_output(Cmd, shell=True).rstrip()
266
Anna Zaks4720a732011-11-05 05:20:48 +0000267# Run analysis on a set of preprocessed files.
Anna Zaksa2f970b2012-09-06 23:30:27 +0000268def runAnalyzePreprocessed(Dir, SBOutputDir, Mode):
Anna Zaks4720a732011-11-05 05:20:48 +0000269 if os.path.exists(os.path.join(Dir, BuildScript)):
270 print "Error: The preprocessed files project should not contain %s" % \
271 BuildScript
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000272 raise Exception()
Anna Zaks4720a732011-11-05 05:20:48 +0000273
Devin Coughlinbace0322015-09-14 21:22:24 +0000274 CmdPrefix = Clang + " -cc1 "
275
276 # For now, we assume the preprocessed files should be analyzed
277 # with the OS X SDK.
278 SDKPath = getSDKPath("macosx")
279 if SDKPath is not None:
280 CmdPrefix += "-isysroot " + SDKPath + " "
281
282 CmdPrefix += "-analyze -analyzer-output=plist -w "
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000283 CmdPrefix += "-analyzer-checker=" + Checkers +" -fcxx-exceptions -fblocks "
284
Anna Zaksa2f970b2012-09-06 23:30:27 +0000285 if (Mode == 2) :
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000286 CmdPrefix += "-std=c++11 "
287
Anna Zaks4720a732011-11-05 05:20:48 +0000288 PlistPath = os.path.join(Dir, SBOutputDir, "date")
289 FailPath = os.path.join(PlistPath, "failures");
290 os.makedirs(FailPath);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000291
Anna Zaks4720a732011-11-05 05:20:48 +0000292 for FullFileName in glob.glob(Dir + "/*"):
293 FileName = os.path.basename(FullFileName)
294 Failed = False
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000295
Anna Zaks4720a732011-11-05 05:20:48 +0000296 # Only run the analyzes on supported files.
297 if (hasNoExtension(FileName)):
298 continue
299 if (isValidSingleInputFile(FileName) == False):
300 print "Error: Invalid single input file %s." % (FullFileName,)
301 raise Exception()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000302
Anna Zaks4720a732011-11-05 05:20:48 +0000303 # Build and call the analyzer command.
304 OutputOption = "-o " + os.path.join(PlistPath, FileName) + ".plist "
Gabor Horvath2ed94562015-07-02 19:20:46 +0000305 Command = CmdPrefix + OutputOption + FileName
Anna Zaks4720a732011-11-05 05:20:48 +0000306 LogFile = open(os.path.join(FailPath, FileName + ".stderr.txt"), "w+b")
307 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000308 if Verbose == 1:
Anna Zaks4720a732011-11-05 05:20:48 +0000309 print " Executing: %s" % (Command,)
310 check_call(Command, cwd = Dir, stderr=LogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000311 stdout=LogFile,
Anna Zaks4720a732011-11-05 05:20:48 +0000312 shell=True)
313 except CalledProcessError, e:
314 print "Error: Analyzes of %s failed. See %s for details." \
315 "Error code %d." % \
316 (FullFileName, LogFile.name, e.returncode)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000317 Failed = True
Anna Zaks4720a732011-11-05 05:20:48 +0000318 finally:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000319 LogFile.close()
320
Anna Zaks4720a732011-11-05 05:20:48 +0000321 # If command did not fail, erase the log file.
322 if Failed == False:
323 os.remove(LogFile.name);
324
Anna Zaksa2f970b2012-09-06 23:30:27 +0000325def buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000326 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000327
Anna Zaks4720a732011-11-05 05:20:48 +0000328 BuildLogPath = os.path.join(SBOutputDir, LogFolderName, BuildLogName)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000329 print "Log file: %s" % (BuildLogPath,)
Anna Zaks4720a732011-11-05 05:20:48 +0000330 print "Output directory: %s" %(SBOutputDir, )
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000331
Anna Zaksf0c41162011-10-06 23:26:27 +0000332 # Clean up the log file.
333 if (os.path.exists(BuildLogPath)) :
334 RmCommand = "rm " + BuildLogPath
335 if Verbose == 1:
Anna Zaks42a44632011-11-02 20:46:50 +0000336 print " Executing: %s" % (RmCommand,)
Anna Zaksf0c41162011-10-06 23:26:27 +0000337 check_call(RmCommand, shell=True)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000338
Anna Zaks4720a732011-11-05 05:20:48 +0000339 # Clean up scan build results.
340 if (os.path.exists(SBOutputDir)) :
341 RmCommand = "rm -r " + SBOutputDir
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000342 if Verbose == 1:
Anna Zaks4720a732011-11-05 05:20:48 +0000343 print " Executing: %s" % (RmCommand,)
344 check_call(RmCommand, shell=True)
345 assert(not os.path.exists(SBOutputDir))
346 os.makedirs(os.path.join(SBOutputDir, LogFolderName))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000347
Anna Zaksf0c41162011-10-06 23:26:27 +0000348 # Open the log file.
349 PBuildLogFile = open(BuildLogPath, "wb+")
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000350
Anna Zaks4720a732011-11-05 05:20:48 +0000351 # Build and analyze the project.
352 try:
Anna Zaks42a44632011-11-02 20:46:50 +0000353 runCleanupScript(Dir, PBuildLogFile)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000354
Anna Zaksa2f970b2012-09-06 23:30:27 +0000355 if (ProjectBuildMode == 1):
Anna Zaks4720a732011-11-05 05:20:48 +0000356 runScanBuild(Dir, SBOutputDir, PBuildLogFile)
357 else:
Anna Zaksa2f970b2012-09-06 23:30:27 +0000358 runAnalyzePreprocessed(Dir, SBOutputDir, ProjectBuildMode)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000359
Anna Zaks4720a732011-11-05 05:20:48 +0000360 if IsReferenceBuild :
Anna Zaks42a44632011-11-02 20:46:50 +0000361 runCleanupScript(Dir, PBuildLogFile)
Gabor Horvathc3177f22015-07-08 18:39:31 +0000362
363 # Make the absolute paths relative in the reference results.
364 for (DirPath, Dirnames, Filenames) in os.walk(SBOutputDir):
365 for F in Filenames:
366 if (not F.endswith('plist')):
367 continue
368 Plist = os.path.join(DirPath, F)
369 Data = plistlib.readPlist(Plist)
370 Paths = [SourceFile[len(Dir)+1:] if SourceFile.startswith(Dir)\
371 else SourceFile for SourceFile in Data['files']]
372 Data['files'] = Paths
373 plistlib.writePlist(Data, Plist)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000374
Anna Zaksf0c41162011-10-06 23:26:27 +0000375 finally:
376 PBuildLogFile.close()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000377
Anna Zaksf0c41162011-10-06 23:26:27 +0000378 print "Build complete (time: %.2f). See the log for more details: %s" % \
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000379 ((time.time()-TBegin), BuildLogPath)
380
Anna Zaksf0c41162011-10-06 23:26:27 +0000381# A plist file is created for each call to the analyzer(each source file).
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000382# We are only interested on the once that have bug reports, so delete the rest.
Anna Zaksf0c41162011-10-06 23:26:27 +0000383def CleanUpEmptyPlists(SBOutputDir):
384 for F in glob.glob(SBOutputDir + "/*/*.plist"):
385 P = os.path.join(SBOutputDir, F)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000386
Anna Zaksf0c41162011-10-06 23:26:27 +0000387 Data = plistlib.readPlist(P)
388 # Delete empty reports.
389 if not Data['files']:
390 os.remove(P)
391 continue
392
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000393# Given the scan-build output directory, checks if the build failed
394# (by searching for the failures directories). If there are failures, it
395# creates a summary file in the output directory.
Anna Zaksf0c41162011-10-06 23:26:27 +0000396def checkBuild(SBOutputDir):
397 # Check if there are failures.
398 Failures = glob.glob(SBOutputDir + "/*/failures/*.stderr.txt")
399 TotalFailed = len(Failures);
400 if TotalFailed == 0:
Jordan Rose9858b122012-08-31 00:36:30 +0000401 CleanUpEmptyPlists(SBOutputDir)
402 Plists = glob.glob(SBOutputDir + "/*/*.plist")
Alp Tokerd4733632013-12-05 04:47:09 +0000403 print "Number of bug reports (non-empty plist files) produced: %d" %\
Jordan Rose9858b122012-08-31 00:36:30 +0000404 len(Plists)
Anna Zaksf0c41162011-10-06 23:26:27 +0000405 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000406
Anna Zaksf0c41162011-10-06 23:26:27 +0000407 # Create summary file to display when the build fails.
Anna Zaks4720a732011-11-05 05:20:48 +0000408 SummaryPath = os.path.join(SBOutputDir, LogFolderName, FailuresSummaryFileName)
Anna Zaksf0c41162011-10-06 23:26:27 +0000409 if (Verbose > 0):
Anna Zaks4720a732011-11-05 05:20:48 +0000410 print " Creating the failures summary file %s" % (SummaryPath,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000411
Anna Zaksf0c41162011-10-06 23:26:27 +0000412 SummaryLog = open(SummaryPath, "w+")
413 try:
414 SummaryLog.write("Total of %d failures discovered.\n" % (TotalFailed,))
415 if TotalFailed > NumOfFailuresInSummary:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000416 SummaryLog.write("See the first %d below.\n"
Anna Zaksf0c41162011-10-06 23:26:27 +0000417 % (NumOfFailuresInSummary,))
418 # TODO: Add a line "See the results folder for more."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000419
Anna Zaksf0c41162011-10-06 23:26:27 +0000420 FailuresCopied = NumOfFailuresInSummary
421 Idx = 0
Jordan Rosedc191a12012-06-01 16:24:43 +0000422 for FailLogPathI in Failures:
Anna Zaksf0c41162011-10-06 23:26:27 +0000423 if Idx >= NumOfFailuresInSummary:
424 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000425 Idx += 1
Anna Zaksf0c41162011-10-06 23:26:27 +0000426 SummaryLog.write("\n-- Error #%d -----------\n" % (Idx,));
427 FailLogI = open(FailLogPathI, "r");
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000428 try:
Anna Zaksf0c41162011-10-06 23:26:27 +0000429 shutil.copyfileobj(FailLogI, SummaryLog);
430 finally:
431 FailLogI.close()
432 finally:
433 SummaryLog.close()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000434
Anna Zaks5acd9602012-01-04 23:53:50 +0000435 print "Error: analysis failed. See ", SummaryPath
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000436 sys.exit(-1)
Anna Zaksf0c41162011-10-06 23:26:27 +0000437
438# Auxiliary object to discard stdout.
439class Discarder(object):
440 def write(self, text):
441 pass # do nothing
442
443# Compare the warnings produced by scan-build.
Gabor Horvath93fde942015-06-30 15:31:17 +0000444# Strictness defines the success criteria for the test:
445# 0 - success if there are no crashes or analyzer failure.
446# 1 - success if there are no difference in the number of reported bugs.
447# 2 - success if all the bug reports are identical.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000448def runCmpResults(Dir, Strictness = 0):
449 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000450
451 RefDir = os.path.join(Dir, SBOutputDirReferencePrefix + SBOutputDirName)
452 NewDir = os.path.join(Dir, SBOutputDirName)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000453
Anna Zaksf0c41162011-10-06 23:26:27 +0000454 # We have to go one level down the directory tree.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000455 RefList = glob.glob(RefDir + "/*")
Anna Zaksf0c41162011-10-06 23:26:27 +0000456 NewList = glob.glob(NewDir + "/*")
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000457
Jordan Rosec7b992e2013-06-10 19:34:30 +0000458 # Log folders are also located in the results dir, so ignore them.
459 RefLogDir = os.path.join(RefDir, LogFolderName)
460 if RefLogDir in RefList:
461 RefList.remove(RefLogDir)
Anna Zaks4720a732011-11-05 05:20:48 +0000462 NewList.remove(os.path.join(NewDir, LogFolderName))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000463
Anna Zaksf0c41162011-10-06 23:26:27 +0000464 if len(RefList) == 0 or len(NewList) == 0:
465 return False
466 assert(len(RefList) == len(NewList))
467
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000468 # There might be more then one folder underneath - one per each scan-build
Anna Zaksf0c41162011-10-06 23:26:27 +0000469 # command (Ex: one for configure and one for make).
470 if (len(RefList) > 1):
471 # Assume that the corresponding folders have the same names.
472 RefList.sort()
473 NewList.sort()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000474
Anna Zaksf0c41162011-10-06 23:26:27 +0000475 # Iterate and find the differences.
Anna Zaks767d3562011-11-08 19:56:31 +0000476 NumDiffs = 0
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000477 PairList = zip(RefList, NewList)
478 for P in PairList:
479 RefDir = P[0]
Anna Zaksf0c41162011-10-06 23:26:27 +0000480 NewDir = P[1]
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000481
482 assert(RefDir != NewDir)
483 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000484 print " Comparing Results: %s %s" % (RefDir, NewDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000485
Anna Zaksf0c41162011-10-06 23:26:27 +0000486 DiffsPath = os.path.join(NewDir, DiffsSummaryFileName)
Gabor Horvathc3177f22015-07-08 18:39:31 +0000487 Opts = CmpRuns.CmpOptions(DiffsPath, "", Dir)
Anna Zaksf0c41162011-10-06 23:26:27 +0000488 # Discard everything coming out of stdout (CmpRun produces a lot of them).
489 OLD_STDOUT = sys.stdout
490 sys.stdout = Discarder()
491 # Scan the results, delete empty plist files.
Gabor Horvath93fde942015-06-30 15:31:17 +0000492 NumDiffs, ReportsInRef, ReportsInNew = \
493 CmpRuns.dumpScanBuildResultsDiff(RefDir, NewDir, Opts, False)
Anna Zaksf0c41162011-10-06 23:26:27 +0000494 sys.stdout = OLD_STDOUT
Anna Zaks767d3562011-11-08 19:56:31 +0000495 if (NumDiffs > 0) :
496 print "Warning: %r differences in diagnostics. See %s" % \
497 (NumDiffs, DiffsPath,)
Gabor Horvath93fde942015-06-30 15:31:17 +0000498 if Strictness >= 2 and NumDiffs > 0:
499 print "Error: Diffs found in strict mode (2)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000500 sys.exit(-1)
Gabor Horvath93fde942015-06-30 15:31:17 +0000501 elif Strictness >= 1 and ReportsInRef != ReportsInNew:
502 print "Error: The number of results are different in strict mode (1)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000503 sys.exit(-1)
504
505 print "Diagnostic comparison complete (time: %.2f)." % (time.time()-TBegin)
Anna Zaks767d3562011-11-08 19:56:31 +0000506 return (NumDiffs > 0)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000507
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000508def updateSVN(Mode, ProjectsMap):
509 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000510 ProjectsMap.seek(0)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000511 for I in csv.reader(ProjectsMap):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000512 ProjName = I[0]
Jordan Rose01ac5722012-06-01 16:24:38 +0000513 Path = os.path.join(ProjName, getSBOutputDirName(True))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000514
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000515 if Mode == "delete":
516 Command = "svn delete %s" % (Path,)
517 else:
518 Command = "svn add %s" % (Path,)
Anna Zaksf0c41162011-10-06 23:26:27 +0000519
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000520 if Verbose == 1:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000521 print " Executing: %s" % (Command,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000522 check_call(Command, shell=True)
523
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000524 if Mode == "delete":
525 CommitCommand = "svn commit -m \"[analyzer tests] Remove " \
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000526 "reference results.\""
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000527 else:
528 CommitCommand = "svn commit -m \"[analyzer tests] Add new " \
529 "reference results.\""
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000530 if Verbose == 1:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000531 print " Executing: %s" % (CommitCommand,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000532 check_call(CommitCommand, shell=True)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000533 except:
534 print "Error: SVN update failed."
535 sys.exit(-1)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000536
Gabor Horvath93fde942015-06-30 15:31:17 +0000537def testProject(ID, ProjectBuildMode, IsReferenceBuild=False, Dir=None, Strictness = 0):
Anna Zaks4720a732011-11-05 05:20:48 +0000538 print " \n\n--- Building project %s" % (ID,)
539
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000540 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000541
542 if Dir is None :
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000543 Dir = getProjectDir(ID)
544 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000545 print " Build directory: %s." % (Dir,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000546
Anna Zaksf0c41162011-10-06 23:26:27 +0000547 # Set the build results directory.
Jordan Rose01ac5722012-06-01 16:24:38 +0000548 RelOutputDir = getSBOutputDirName(IsReferenceBuild)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000549 SBOutputDir = os.path.join(Dir, RelOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000550
Anna Zaksa2f970b2012-09-06 23:30:27 +0000551 buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild)
Anna Zaksf0c41162011-10-06 23:26:27 +0000552
553 checkBuild(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000554
Jordan Rose9858b122012-08-31 00:36:30 +0000555 if IsReferenceBuild == False:
Gabor Horvath93fde942015-06-30 15:31:17 +0000556 runCmpResults(Dir, Strictness)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000557
Anna Zaksf0c41162011-10-06 23:26:27 +0000558 print "Completed tests for project %s (time: %.2f)." % \
559 (ID, (time.time()-TBegin))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000560
Gabor Horvath93fde942015-06-30 15:31:17 +0000561def testAll(IsReferenceBuild = False, UpdateSVN = False, Strictness = 0):
Anna Zaksf0c41162011-10-06 23:26:27 +0000562 PMapFile = open(getProjectMapPath(), "rb")
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000563 try:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000564 # Validate the input.
565 for I in csv.reader(PMapFile):
Anna Zaks4720a732011-11-05 05:20:48 +0000566 if (len(I) != 2) :
567 print "Error: Rows in the ProjectMapFile should have 3 entries."
568 raise Exception()
Anna Zaksa2f970b2012-09-06 23:30:27 +0000569 if (not ((I[1] == "0") | (I[1] == "1") | (I[1] == "2"))):
570 print "Error: Second entry in the ProjectMapFile should be 0" \
571 " (single file), 1 (project), or 2(single file c++11)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000572 raise Exception()
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000573
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000574 # When we are regenerating the reference results, we might need to
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000575 # update svn. Remove reference results from SVN.
576 if UpdateSVN == True:
Jordan Rose01ac5722012-06-01 16:24:38 +0000577 assert(IsReferenceBuild == True);
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000578 updateSVN("delete", PMapFile);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000579
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000580 # Test the projects.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000581 PMapFile.seek(0)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000582 for I in csv.reader(PMapFile):
Gabor Horvath93fde942015-06-30 15:31:17 +0000583 testProject(I[0], int(I[1]), IsReferenceBuild, None, Strictness)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000584
585 # Add reference results to SVN.
586 if UpdateSVN == True:
587 updateSVN("add", PMapFile);
588
Anna Zaks4720a732011-11-05 05:20:48 +0000589 except:
590 print "Error occurred. Premature termination."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000591 raise
Anna Zaksf0c41162011-10-06 23:26:27 +0000592 finally:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000593 PMapFile.close()
594
Anna Zaksf0c41162011-10-06 23:26:27 +0000595if __name__ == '__main__':
Gabor Horvath93fde942015-06-30 15:31:17 +0000596 # Parse command line arguments.
597 Parser = argparse.ArgumentParser(description='Test the Clang Static Analyzer.')
598 Parser.add_argument('--strictness', dest='strictness', type=int, default=0,
599 help='0 to fail on runtime errors, 1 to fail when the number\
600 of found bugs are different from the reference, 2 to \
601 fail on any difference from the reference. Default is 0.')
602 Parser.add_argument('-r', dest='regenerate', action='store_true', default=False,
603 help='Regenerate reference output.')
604 Parser.add_argument('-rs', dest='update_reference', action='store_true',
605 default=False, help='Regenerate reference output and update svn.')
606 Args = Parser.parse_args()
607
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000608 IsReference = False
609 UpdateSVN = False
Gabor Horvath93fde942015-06-30 15:31:17 +0000610 Strictness = Args.strictness
611 if Args.regenerate:
612 IsReference = True
613 elif Args.update_reference:
614 IsReference = True
615 UpdateSVN = True
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000616
Gabor Horvathda32a862015-08-20 22:59:49 +0000617 if os.environ.has_key('SA_ADDITIONAL_CHECKERS'):
618 Checkers = Checkers + ',' + os.environ['SA_ADDITIONAL_CHECKERS']
619
Gabor Horvath93fde942015-06-30 15:31:17 +0000620 testAll(IsReference, UpdateSVN, Strictness)