blob: ab68518b5ac4fd36cefcbf3aabb464a56bde93d7 [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.
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000157# The script that downloads the project.
158DownloadScript = "download_project.sh"
Ted Kremenek42c14422012-08-28 20:40:02 +0000159# The script that needs to be executed before the build can start.
160CleanupScript = "cleanup_run_static_analyzer.sh"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000161# This is a file containing commands for scan-build.
Ted Kremenek42c14422012-08-28 20:40:02 +0000162BuildScript = "run_static_analyzer.cmd"
163
164# The log file name.
165LogFolderName = "Logs"
166BuildLogName = "run_static_analyzer.log"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000167# Summary file - contains the summary of the failures. Ex: This info can be be
Ted Kremenek42c14422012-08-28 20:40:02 +0000168# displayed when buildbot detects a build failure.
169NumOfFailuresInSummary = 10
170FailuresSummaryFileName = "failures.txt"
171# Summary of the result diffs.
172DiffsSummaryFileName = "diffs.txt"
173
174# The scan-build result directory.
175SBOutputDirName = "ScanBuildResults"
176SBOutputDirReferencePrefix = "Ref"
177
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000178# The name of the directory storing the cached project source. If this directory
179# does not exist, the download script will be executed. That script should
180# create the "CachedSource" directory and download the project source into it.
181CachedSourceDirName = "CachedSource"
182
183# The name of the directory containing the source code that will be analyzed.
184# Each time a project is analyzed, a fresh copy of its CachedSource directory
185# will be copied to the PatchedSource directory and then the local patches
186# in PatchfileName will be applied (if PatchfileName exists).
187PatchedSourceDirName = "PatchedSource"
188
189# The name of the patchfile specifying any changes that should be applied
190# to the CachedSource before analyzing.
191PatchfileName = "changes_for_analyzer.patch"
192
Ted Kremenek42c14422012-08-28 20:40:02 +0000193# The list of checkers used during analyzes.
Alp Tokerd4733632013-12-05 04:47:09 +0000194# Currently, consists of all the non-experimental checkers, plus a few alpha
Jordan Rose10ad0812013-04-05 17:55:07 +0000195# checkers we don't want to regress on.
Anna Zaks8a020312014-10-31 17:40:14 +0000196Checkers="alpha.unix.SimpleStream,alpha.security.taint,cplusplus.NewDeleteLeaks,core,cplusplus,deadcode,security,unix,osx"
Ted Kremenek42c14422012-08-28 20:40:02 +0000197
198Verbose = 1
199
200#------------------------------------------------------------------------------
201# Test harness logic.
202#------------------------------------------------------------------------------
203
Anna Zaksf0c41162011-10-06 23:26:27 +0000204# Run pre-processing script if any.
Anna Zaks42a44632011-11-02 20:46:50 +0000205def runCleanupScript(Dir, PBuildLogFile):
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000206 Cwd = os.path.join(Dir, PatchedSourceDirName)
Anna Zaks42a44632011-11-02 20:46:50 +0000207 ScriptPath = os.path.join(Dir, CleanupScript)
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000208 runScript(ScriptPath, PBuildLogFile, Cwd)
209
210# Run the script to download the project, if it exists.
211def runDownloadScript(Dir, PBuildLogFile):
212 ScriptPath = os.path.join(Dir, DownloadScript)
213 runScript(ScriptPath, PBuildLogFile, Dir)
214
215# Run the provided script if it exists.
216def runScript(ScriptPath, PBuildLogFile, Cwd):
Anna Zaksf0c41162011-10-06 23:26:27 +0000217 if os.path.exists(ScriptPath):
218 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000219 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000220 print " Executing: %s" % (ScriptPath,)
Devin Coughlinab95cd22016-01-22 07:08:06 +0000221 check_call("chmod +x '%s'" % ScriptPath, cwd = Cwd,
Anna Zaksf0c41162011-10-06 23:26:27 +0000222 stderr=PBuildLogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000223 stdout=PBuildLogFile,
224 shell=True)
Devin Coughlinab95cd22016-01-22 07:08:06 +0000225 check_call("'%s'" % ScriptPath, cwd = Cwd, stderr=PBuildLogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000226 stdout=PBuildLogFile,
Anna Zaksf0c41162011-10-06 23:26:27 +0000227 shell=True)
228 except:
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000229 print "Error: Running %s failed. See %s for details." % (ScriptPath,
230 PBuildLogFile.name)
Anna Zaksf0c41162011-10-06 23:26:27 +0000231 sys.exit(-1)
232
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000233# Download the project and apply the local patchfile if it exists.
234def downloadAndPatch(Dir, PBuildLogFile):
235 CachedSourceDirPath = os.path.join(Dir, CachedSourceDirName)
236
237 # If the we don't already have the cached source, run the project's
238 # download script to download it.
239 if not os.path.exists(CachedSourceDirPath):
240 runDownloadScript(Dir, PBuildLogFile)
241 if not os.path.exists(CachedSourceDirPath):
242 print "Error: '%s' not found after download." % (CachedSourceDirPath)
243 exit(-1)
244
245 PatchedSourceDirPath = os.path.join(Dir, PatchedSourceDirName)
246
247 # Remove potentially stale patched source.
248 if os.path.exists(PatchedSourceDirPath):
249 shutil.rmtree(PatchedSourceDirPath)
250
251 # Copy the cached source and apply any patches to the copy.
252 shutil.copytree(CachedSourceDirPath, PatchedSourceDirPath, symlinks=True)
253 applyPatch(Dir, PBuildLogFile)
254
255def applyPatch(Dir, PBuildLogFile):
256 PatchfilePath = os.path.join(Dir, PatchfileName)
257 PatchedSourceDirPath = os.path.join(Dir, PatchedSourceDirName)
258 if not os.path.exists(PatchfilePath):
259 print " No local patches."
260 return
261
262 print " Applying patch."
263 try:
Devin Coughlinab95cd22016-01-22 07:08:06 +0000264 check_call("patch -p1 < '%s'" % (PatchfilePath),
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000265 cwd = PatchedSourceDirPath,
266 stderr=PBuildLogFile,
267 stdout=PBuildLogFile,
268 shell=True)
269 except:
270 print "Error: Patch failed. See %s for details." % (PBuildLogFile.name)
271 sys.exit(-1)
272
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000273# Build the project with scan-build by reading in the commands and
Anna Zaksf0c41162011-10-06 23:26:27 +0000274# prefixing them with the scan-build options.
275def runScanBuild(Dir, SBOutputDir, PBuildLogFile):
276 BuildScriptPath = os.path.join(Dir, BuildScript)
277 if not os.path.exists(BuildScriptPath):
278 print "Error: build script is not defined: %s" % BuildScriptPath
Ted Kremenek6cb20802012-08-28 20:20:52 +0000279 sys.exit(-1)
Devin Coughlinf3695c82015-09-16 01:52:32 +0000280
281 AllCheckers = Checkers
282 if os.environ.has_key('SA_ADDITIONAL_CHECKERS'):
283 AllCheckers = AllCheckers + ',' + os.environ['SA_ADDITIONAL_CHECKERS']
284
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000285 # Run scan-build from within the patched source directory.
286 SBCwd = os.path.join(Dir, PatchedSourceDirName)
287
Devin Coughlin86f61a92016-01-22 18:45:22 +0000288 SBOptions = "--use-analyzer '%s' " % Clang
289 SBOptions += "-plist-html -o '%s' " % SBOutputDir
Devin Coughlinf3695c82015-09-16 01:52:32 +0000290 SBOptions += "-enable-checker " + AllCheckers + " "
Jordan Roseb18179d2013-01-24 23:07:59 +0000291 SBOptions += "--keep-empty "
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000292 # Always use ccc-analyze to ensure that we can locate the failures
Anna Zaks7b4f8a42013-05-31 02:31:09 +0000293 # directory.
294 SBOptions += "--override-compiler "
Anna Zaksf0c41162011-10-06 23:26:27 +0000295 try:
296 SBCommandFile = open(BuildScriptPath, "r")
297 SBPrefix = "scan-build " + SBOptions + " "
298 for Command in SBCommandFile:
Jordan Rose7bd91862013-09-06 16:12:41 +0000299 Command = Command.strip()
Gabor Horvath93fde942015-06-30 15:31:17 +0000300 if len(Command) == 0:
301 continue;
Ted Kremenekf9a539d2012-08-28 20:40:04 +0000302 # If using 'make', auto imply a -jX argument
303 # to speed up analysis. xcodebuild will
304 # automatically use the maximum number of cores.
Jordan Rose64e4cf02012-11-26 19:59:57 +0000305 if (Command.startswith("make ") or Command == "make") and \
306 "-j" not in Command:
Jordan Rose88329242012-11-16 17:41:21 +0000307 Command += " -j%d" % Jobs
Anna Zaksf0c41162011-10-06 23:26:27 +0000308 SBCommand = SBPrefix + Command
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000309 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000310 print " Executing: %s" % (SBCommand,)
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000311 check_call(SBCommand, cwd = SBCwd, stderr=PBuildLogFile,
312 stdout=PBuildLogFile,
313 shell=True)
Anna Zaksf0c41162011-10-06 23:26:27 +0000314 except:
315 print "Error: scan-build failed. See ",PBuildLogFile.name,\
316 " for details."
Anna Zaks4720a732011-11-05 05:20:48 +0000317 raise
Anna Zaksf0c41162011-10-06 23:26:27 +0000318
Anna Zaks4720a732011-11-05 05:20:48 +0000319def hasNoExtension(FileName):
320 (Root, Ext) = os.path.splitext(FileName)
321 if ((Ext == "")) :
322 return True
323 return False
324
325def isValidSingleInputFile(FileName):
326 (Root, Ext) = os.path.splitext(FileName)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000327 if ((Ext == ".i") | (Ext == ".ii") |
328 (Ext == ".c") | (Ext == ".cpp") |
Anna Zaks4720a732011-11-05 05:20:48 +0000329 (Ext == ".m") | (Ext == "")) :
330 return True
331 return False
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000332
Devin Coughlinbace0322015-09-14 21:22:24 +0000333# Get the path to the SDK for the given SDK name. Returns None if
334# the path cannot be determined.
335def getSDKPath(SDKName):
336 if which("xcrun") is None:
337 return None
338
339 Cmd = "xcrun --sdk " + SDKName + " --show-sdk-path"
340 return check_output(Cmd, shell=True).rstrip()
341
Anna Zaks4720a732011-11-05 05:20:48 +0000342# Run analysis on a set of preprocessed files.
Anna Zaksa2f970b2012-09-06 23:30:27 +0000343def runAnalyzePreprocessed(Dir, SBOutputDir, Mode):
Anna Zaks4720a732011-11-05 05:20:48 +0000344 if os.path.exists(os.path.join(Dir, BuildScript)):
345 print "Error: The preprocessed files project should not contain %s" % \
346 BuildScript
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000347 raise Exception()
Anna Zaks4720a732011-11-05 05:20:48 +0000348
Devin Coughlinbace0322015-09-14 21:22:24 +0000349 CmdPrefix = Clang + " -cc1 "
350
351 # For now, we assume the preprocessed files should be analyzed
352 # with the OS X SDK.
353 SDKPath = getSDKPath("macosx")
354 if SDKPath is not None:
355 CmdPrefix += "-isysroot " + SDKPath + " "
356
357 CmdPrefix += "-analyze -analyzer-output=plist -w "
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000358 CmdPrefix += "-analyzer-checker=" + Checkers +" -fcxx-exceptions -fblocks "
359
Anna Zaksa2f970b2012-09-06 23:30:27 +0000360 if (Mode == 2) :
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000361 CmdPrefix += "-std=c++11 "
362
Anna Zaks4720a732011-11-05 05:20:48 +0000363 PlistPath = os.path.join(Dir, SBOutputDir, "date")
364 FailPath = os.path.join(PlistPath, "failures");
365 os.makedirs(FailPath);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000366
Anna Zaks4720a732011-11-05 05:20:48 +0000367 for FullFileName in glob.glob(Dir + "/*"):
368 FileName = os.path.basename(FullFileName)
369 Failed = False
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000370
Anna Zaks4720a732011-11-05 05:20:48 +0000371 # Only run the analyzes on supported files.
372 if (hasNoExtension(FileName)):
373 continue
374 if (isValidSingleInputFile(FileName) == False):
375 print "Error: Invalid single input file %s." % (FullFileName,)
376 raise Exception()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000377
Anna Zaks4720a732011-11-05 05:20:48 +0000378 # Build and call the analyzer command.
Devin Coughlinab95cd22016-01-22 07:08:06 +0000379 OutputOption = "-o '%s.plist' " % os.path.join(PlistPath, FileName)
380 Command = CmdPrefix + OutputOption + ("'%s'" % FileName)
Anna Zaks4720a732011-11-05 05:20:48 +0000381 LogFile = open(os.path.join(FailPath, FileName + ".stderr.txt"), "w+b")
382 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000383 if Verbose == 1:
Anna Zaks4720a732011-11-05 05:20:48 +0000384 print " Executing: %s" % (Command,)
385 check_call(Command, cwd = Dir, stderr=LogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000386 stdout=LogFile,
Anna Zaks4720a732011-11-05 05:20:48 +0000387 shell=True)
388 except CalledProcessError, e:
389 print "Error: Analyzes of %s failed. See %s for details." \
390 "Error code %d." % \
391 (FullFileName, LogFile.name, e.returncode)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000392 Failed = True
Anna Zaks4720a732011-11-05 05:20:48 +0000393 finally:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000394 LogFile.close()
395
Anna Zaks4720a732011-11-05 05:20:48 +0000396 # If command did not fail, erase the log file.
397 if Failed == False:
398 os.remove(LogFile.name);
399
Devin Coughlin9ea80332016-01-23 01:09:07 +0000400def getBuildLogPath(SBOutputDir):
401 return os.path.join(SBOutputDir, LogFolderName, BuildLogName)
402
403def removeLogFile(SBOutputDir):
404 BuildLogPath = getBuildLogPath(SBOutputDir)
405 # Clean up the log file.
406 if (os.path.exists(BuildLogPath)) :
407 RmCommand = "rm '%s'" % BuildLogPath
408 if Verbose == 1:
409 print " Executing: %s" % (RmCommand,)
410 check_call(RmCommand, shell=True)
411
Anna Zaksa2f970b2012-09-06 23:30:27 +0000412def buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000413 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000414
Devin Coughlin9ea80332016-01-23 01:09:07 +0000415 BuildLogPath = getBuildLogPath(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000416 print "Log file: %s" % (BuildLogPath,)
Anna Zaks4720a732011-11-05 05:20:48 +0000417 print "Output directory: %s" %(SBOutputDir, )
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000418
Devin Coughlin9ea80332016-01-23 01:09:07 +0000419 removeLogFile(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000420
Anna Zaks4720a732011-11-05 05:20:48 +0000421 # Clean up scan build results.
422 if (os.path.exists(SBOutputDir)) :
Devin Coughlinab95cd22016-01-22 07:08:06 +0000423 RmCommand = "rm -r '%s'" % SBOutputDir
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000424 if Verbose == 1:
Anna Zaks4720a732011-11-05 05:20:48 +0000425 print " Executing: %s" % (RmCommand,)
426 check_call(RmCommand, shell=True)
427 assert(not os.path.exists(SBOutputDir))
428 os.makedirs(os.path.join(SBOutputDir, LogFolderName))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000429
Anna Zaksf0c41162011-10-06 23:26:27 +0000430 # Open the log file.
431 PBuildLogFile = open(BuildLogPath, "wb+")
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000432
Anna Zaks4720a732011-11-05 05:20:48 +0000433 # Build and analyze the project.
434 try:
Anna Zaksa2f970b2012-09-06 23:30:27 +0000435 if (ProjectBuildMode == 1):
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000436 downloadAndPatch(Dir, PBuildLogFile)
437 runCleanupScript(Dir, PBuildLogFile)
Anna Zaks4720a732011-11-05 05:20:48 +0000438 runScanBuild(Dir, SBOutputDir, PBuildLogFile)
439 else:
Anna Zaksa2f970b2012-09-06 23:30:27 +0000440 runAnalyzePreprocessed(Dir, SBOutputDir, ProjectBuildMode)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000441
Anna Zaks4720a732011-11-05 05:20:48 +0000442 if IsReferenceBuild :
Anna Zaks42a44632011-11-02 20:46:50 +0000443 runCleanupScript(Dir, PBuildLogFile)
Gabor Horvathc3177f22015-07-08 18:39:31 +0000444
445 # Make the absolute paths relative in the reference results.
446 for (DirPath, Dirnames, Filenames) in os.walk(SBOutputDir):
447 for F in Filenames:
448 if (not F.endswith('plist')):
449 continue
450 Plist = os.path.join(DirPath, F)
451 Data = plistlib.readPlist(Plist)
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000452 PathPrefix = Dir
453 if (ProjectBuildMode == 1):
454 PathPrefix = os.path.join(Dir, PatchedSourceDirName)
455 Paths = [SourceFile[len(PathPrefix)+1:]\
456 if SourceFile.startswith(PathPrefix)\
457 else SourceFile for SourceFile in Data['files']]
Gabor Horvathc3177f22015-07-08 18:39:31 +0000458 Data['files'] = Paths
459 plistlib.writePlist(Data, Plist)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000460
Anna Zaksf0c41162011-10-06 23:26:27 +0000461 finally:
462 PBuildLogFile.close()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000463
Anna Zaksf0c41162011-10-06 23:26:27 +0000464 print "Build complete (time: %.2f). See the log for more details: %s" % \
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000465 ((time.time()-TBegin), BuildLogPath)
466
Anna Zaksf0c41162011-10-06 23:26:27 +0000467# A plist file is created for each call to the analyzer(each source file).
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000468# We are only interested on the once that have bug reports, so delete the rest.
Anna Zaksf0c41162011-10-06 23:26:27 +0000469def CleanUpEmptyPlists(SBOutputDir):
470 for F in glob.glob(SBOutputDir + "/*/*.plist"):
471 P = os.path.join(SBOutputDir, F)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000472
Anna Zaksf0c41162011-10-06 23:26:27 +0000473 Data = plistlib.readPlist(P)
474 # Delete empty reports.
475 if not Data['files']:
476 os.remove(P)
477 continue
478
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000479# Given the scan-build output directory, checks if the build failed
480# (by searching for the failures directories). If there are failures, it
481# creates a summary file in the output directory.
Anna Zaksf0c41162011-10-06 23:26:27 +0000482def checkBuild(SBOutputDir):
483 # Check if there are failures.
484 Failures = glob.glob(SBOutputDir + "/*/failures/*.stderr.txt")
485 TotalFailed = len(Failures);
486 if TotalFailed == 0:
Jordan Rose9858b122012-08-31 00:36:30 +0000487 CleanUpEmptyPlists(SBOutputDir)
488 Plists = glob.glob(SBOutputDir + "/*/*.plist")
Alp Tokerd4733632013-12-05 04:47:09 +0000489 print "Number of bug reports (non-empty plist files) produced: %d" %\
Jordan Rose9858b122012-08-31 00:36:30 +0000490 len(Plists)
Anna Zaksf0c41162011-10-06 23:26:27 +0000491 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000492
Anna Zaksf0c41162011-10-06 23:26:27 +0000493 # Create summary file to display when the build fails.
Anna Zaks4720a732011-11-05 05:20:48 +0000494 SummaryPath = os.path.join(SBOutputDir, LogFolderName, FailuresSummaryFileName)
Anna Zaksf0c41162011-10-06 23:26:27 +0000495 if (Verbose > 0):
Anna Zaks4720a732011-11-05 05:20:48 +0000496 print " Creating the failures summary file %s" % (SummaryPath,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000497
Anna Zaksf0c41162011-10-06 23:26:27 +0000498 SummaryLog = open(SummaryPath, "w+")
499 try:
500 SummaryLog.write("Total of %d failures discovered.\n" % (TotalFailed,))
501 if TotalFailed > NumOfFailuresInSummary:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000502 SummaryLog.write("See the first %d below.\n"
Anna Zaksf0c41162011-10-06 23:26:27 +0000503 % (NumOfFailuresInSummary,))
504 # TODO: Add a line "See the results folder for more."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000505
Anna Zaksf0c41162011-10-06 23:26:27 +0000506 FailuresCopied = NumOfFailuresInSummary
507 Idx = 0
Jordan Rosedc191a12012-06-01 16:24:43 +0000508 for FailLogPathI in Failures:
Anna Zaksf0c41162011-10-06 23:26:27 +0000509 if Idx >= NumOfFailuresInSummary:
510 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000511 Idx += 1
Anna Zaksf0c41162011-10-06 23:26:27 +0000512 SummaryLog.write("\n-- Error #%d -----------\n" % (Idx,));
513 FailLogI = open(FailLogPathI, "r");
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000514 try:
Anna Zaksf0c41162011-10-06 23:26:27 +0000515 shutil.copyfileobj(FailLogI, SummaryLog);
516 finally:
517 FailLogI.close()
518 finally:
519 SummaryLog.close()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000520
Anna Zaks5acd9602012-01-04 23:53:50 +0000521 print "Error: analysis failed. See ", SummaryPath
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000522 sys.exit(-1)
Anna Zaksf0c41162011-10-06 23:26:27 +0000523
524# Auxiliary object to discard stdout.
525class Discarder(object):
526 def write(self, text):
527 pass # do nothing
528
529# Compare the warnings produced by scan-build.
Gabor Horvath93fde942015-06-30 15:31:17 +0000530# Strictness defines the success criteria for the test:
531# 0 - success if there are no crashes or analyzer failure.
532# 1 - success if there are no difference in the number of reported bugs.
533# 2 - success if all the bug reports are identical.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000534def runCmpResults(Dir, Strictness = 0):
535 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000536
537 RefDir = os.path.join(Dir, SBOutputDirReferencePrefix + SBOutputDirName)
538 NewDir = os.path.join(Dir, SBOutputDirName)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000539
Anna Zaksf0c41162011-10-06 23:26:27 +0000540 # We have to go one level down the directory tree.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000541 RefList = glob.glob(RefDir + "/*")
Anna Zaksf0c41162011-10-06 23:26:27 +0000542 NewList = glob.glob(NewDir + "/*")
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000543
Jordan Rosec7b992e2013-06-10 19:34:30 +0000544 # Log folders are also located in the results dir, so ignore them.
545 RefLogDir = os.path.join(RefDir, LogFolderName)
546 if RefLogDir in RefList:
547 RefList.remove(RefLogDir)
Anna Zaks4720a732011-11-05 05:20:48 +0000548 NewList.remove(os.path.join(NewDir, LogFolderName))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000549
Anna Zaksf0c41162011-10-06 23:26:27 +0000550 if len(RefList) == 0 or len(NewList) == 0:
551 return False
552 assert(len(RefList) == len(NewList))
553
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000554 # There might be more then one folder underneath - one per each scan-build
Anna Zaksf0c41162011-10-06 23:26:27 +0000555 # command (Ex: one for configure and one for make).
556 if (len(RefList) > 1):
557 # Assume that the corresponding folders have the same names.
558 RefList.sort()
559 NewList.sort()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000560
Anna Zaksf0c41162011-10-06 23:26:27 +0000561 # Iterate and find the differences.
Anna Zaks767d3562011-11-08 19:56:31 +0000562 NumDiffs = 0
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000563 PairList = zip(RefList, NewList)
564 for P in PairList:
565 RefDir = P[0]
Anna Zaksf0c41162011-10-06 23:26:27 +0000566 NewDir = P[1]
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000567
568 assert(RefDir != NewDir)
569 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000570 print " Comparing Results: %s %s" % (RefDir, NewDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000571
Anna Zaksf0c41162011-10-06 23:26:27 +0000572 DiffsPath = os.path.join(NewDir, DiffsSummaryFileName)
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000573 PatchedSourceDirPath = os.path.join(Dir, PatchedSourceDirName)
574 Opts = CmpRuns.CmpOptions(DiffsPath, "", PatchedSourceDirPath)
Anna Zaksf0c41162011-10-06 23:26:27 +0000575 # Discard everything coming out of stdout (CmpRun produces a lot of them).
576 OLD_STDOUT = sys.stdout
577 sys.stdout = Discarder()
578 # Scan the results, delete empty plist files.
Gabor Horvath93fde942015-06-30 15:31:17 +0000579 NumDiffs, ReportsInRef, ReportsInNew = \
580 CmpRuns.dumpScanBuildResultsDiff(RefDir, NewDir, Opts, False)
Anna Zaksf0c41162011-10-06 23:26:27 +0000581 sys.stdout = OLD_STDOUT
Anna Zaks767d3562011-11-08 19:56:31 +0000582 if (NumDiffs > 0) :
583 print "Warning: %r differences in diagnostics. See %s" % \
584 (NumDiffs, DiffsPath,)
Gabor Horvath93fde942015-06-30 15:31:17 +0000585 if Strictness >= 2 and NumDiffs > 0:
586 print "Error: Diffs found in strict mode (2)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000587 sys.exit(-1)
Gabor Horvath93fde942015-06-30 15:31:17 +0000588 elif Strictness >= 1 and ReportsInRef != ReportsInNew:
589 print "Error: The number of results are different in strict mode (1)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000590 sys.exit(-1)
591
592 print "Diagnostic comparison complete (time: %.2f)." % (time.time()-TBegin)
Anna Zaks767d3562011-11-08 19:56:31 +0000593 return (NumDiffs > 0)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000594
Devin Coughlin9ea80332016-01-23 01:09:07 +0000595def cleanupReferenceResults(SBOutputDir):
596 # Delete html, css, and js files from reference results. These can
597 # include multiple copies of the benchmark source and so get very large.
598 Extensions = ["html", "css", "js"]
599 for E in Extensions:
600 for F in glob.glob("%s/*/*.%s" % (SBOutputDir, E)):
601 P = os.path.join(SBOutputDir, F)
602 RmCommand = "rm '%s'" % P
603 check_call(RmCommand, shell=True)
604
605 # Remove the log file. It leaks absolute path names.
606 removeLogFile(SBOutputDir)
607
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000608def updateSVN(Mode, ProjectsMap):
609 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000610 ProjectsMap.seek(0)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000611 for I in csv.reader(ProjectsMap):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000612 ProjName = I[0]
Jordan Rose01ac5722012-06-01 16:24:38 +0000613 Path = os.path.join(ProjName, getSBOutputDirName(True))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000614
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000615 if Mode == "delete":
Devin Coughlinab95cd22016-01-22 07:08:06 +0000616 Command = "svn delete '%s'" % (Path,)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000617 else:
Devin Coughlinab95cd22016-01-22 07:08:06 +0000618 Command = "svn add '%s'" % (Path,)
Anna Zaksf0c41162011-10-06 23:26:27 +0000619
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000620 if Verbose == 1:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000621 print " Executing: %s" % (Command,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000622 check_call(Command, shell=True)
623
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000624 if Mode == "delete":
625 CommitCommand = "svn commit -m \"[analyzer tests] Remove " \
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000626 "reference results.\""
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000627 else:
628 CommitCommand = "svn commit -m \"[analyzer tests] Add new " \
629 "reference results.\""
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000630 if Verbose == 1:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000631 print " Executing: %s" % (CommitCommand,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000632 check_call(CommitCommand, shell=True)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000633 except:
634 print "Error: SVN update failed."
635 sys.exit(-1)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000636
Gabor Horvath93fde942015-06-30 15:31:17 +0000637def testProject(ID, ProjectBuildMode, IsReferenceBuild=False, Dir=None, Strictness = 0):
Anna Zaks4720a732011-11-05 05:20:48 +0000638 print " \n\n--- Building project %s" % (ID,)
639
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000640 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000641
642 if Dir is None :
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000643 Dir = getProjectDir(ID)
644 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000645 print " Build directory: %s." % (Dir,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000646
Anna Zaksf0c41162011-10-06 23:26:27 +0000647 # Set the build results directory.
Jordan Rose01ac5722012-06-01 16:24:38 +0000648 RelOutputDir = getSBOutputDirName(IsReferenceBuild)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000649 SBOutputDir = os.path.join(Dir, RelOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000650
Anna Zaksa2f970b2012-09-06 23:30:27 +0000651 buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild)
Anna Zaksf0c41162011-10-06 23:26:27 +0000652
653 checkBuild(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000654
Jordan Rose9858b122012-08-31 00:36:30 +0000655 if IsReferenceBuild == False:
Gabor Horvath93fde942015-06-30 15:31:17 +0000656 runCmpResults(Dir, Strictness)
Devin Coughlin9ea80332016-01-23 01:09:07 +0000657 else:
658 cleanupReferenceResults(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000659
Anna Zaksf0c41162011-10-06 23:26:27 +0000660 print "Completed tests for project %s (time: %.2f)." % \
661 (ID, (time.time()-TBegin))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000662
Gabor Horvath93fde942015-06-30 15:31:17 +0000663def testAll(IsReferenceBuild = False, UpdateSVN = False, Strictness = 0):
Anna Zaksf0c41162011-10-06 23:26:27 +0000664 PMapFile = open(getProjectMapPath(), "rb")
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000665 try:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000666 # Validate the input.
667 for I in csv.reader(PMapFile):
Anna Zaks4720a732011-11-05 05:20:48 +0000668 if (len(I) != 2) :
669 print "Error: Rows in the ProjectMapFile should have 3 entries."
670 raise Exception()
Anna Zaksa2f970b2012-09-06 23:30:27 +0000671 if (not ((I[1] == "0") | (I[1] == "1") | (I[1] == "2"))):
672 print "Error: Second entry in the ProjectMapFile should be 0" \
673 " (single file), 1 (project), or 2(single file c++11)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000674 raise Exception()
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000675
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000676 # When we are regenerating the reference results, we might need to
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000677 # update svn. Remove reference results from SVN.
678 if UpdateSVN == True:
Jordan Rose01ac5722012-06-01 16:24:38 +0000679 assert(IsReferenceBuild == True);
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000680 updateSVN("delete", PMapFile);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000681
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000682 # Test the projects.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000683 PMapFile.seek(0)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000684 for I in csv.reader(PMapFile):
Gabor Horvath93fde942015-06-30 15:31:17 +0000685 testProject(I[0], int(I[1]), IsReferenceBuild, None, Strictness)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000686
687 # Add reference results to SVN.
688 if UpdateSVN == True:
689 updateSVN("add", PMapFile);
690
Anna Zaks4720a732011-11-05 05:20:48 +0000691 except:
692 print "Error occurred. Premature termination."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000693 raise
Anna Zaksf0c41162011-10-06 23:26:27 +0000694 finally:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000695 PMapFile.close()
696
Anna Zaksf0c41162011-10-06 23:26:27 +0000697if __name__ == '__main__':
Gabor Horvath93fde942015-06-30 15:31:17 +0000698 # Parse command line arguments.
699 Parser = argparse.ArgumentParser(description='Test the Clang Static Analyzer.')
700 Parser.add_argument('--strictness', dest='strictness', type=int, default=0,
701 help='0 to fail on runtime errors, 1 to fail when the number\
702 of found bugs are different from the reference, 2 to \
703 fail on any difference from the reference. Default is 0.')
704 Parser.add_argument('-r', dest='regenerate', action='store_true', default=False,
705 help='Regenerate reference output.')
706 Parser.add_argument('-rs', dest='update_reference', action='store_true',
707 default=False, help='Regenerate reference output and update svn.')
708 Args = Parser.parse_args()
709
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000710 IsReference = False
711 UpdateSVN = False
Gabor Horvath93fde942015-06-30 15:31:17 +0000712 Strictness = Args.strictness
713 if Args.regenerate:
714 IsReference = True
715 elif Args.update_reference:
716 IsReference = True
717 UpdateSVN = True
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000718
Gabor Horvath93fde942015-06-30 15:31:17 +0000719 testAll(IsReference, UpdateSVN, Strictness)