blob: 8d44b75729e7cd4771dedb3eb2b9d6beeab7f5e1 [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
George Karpenkov3abfc3b2017-09-22 01:41:16 +000056import multiprocessing
Anna Zaksf0c41162011-10-06 23:26:27 +000057
Ted Kremenek42c14422012-08-28 20:40:02 +000058#------------------------------------------------------------------------------
59# Helper functions.
60#------------------------------------------------------------------------------
Anna Zaksf0c41162011-10-06 23:26:27 +000061
Ted Kremenekf9a539d2012-08-28 20:40:04 +000062
Ted Kremenek6cb20802012-08-28 20:20:52 +000063def which(command, paths = None):
64 """which(command, [paths]) - Look up the given command in the paths string
65 (or the PATH environment variable, if unspecified)."""
66
67 if paths is None:
68 paths = os.environ.get('PATH','')
69
70 # Check for absolute match first.
71 if os.path.exists(command):
72 return command
73
74 # Would be nice if Python had a lib function for this.
75 if not paths:
76 paths = os.defpath
77
78 # Get suffixes to search.
79 # On Cygwin, 'PATHEXT' may exist but it should not be used.
80 if os.pathsep == ';':
81 pathext = os.environ.get('PATHEXT', '').split(';')
82 else:
83 pathext = ['']
84
85 # Search the paths...
86 for path in paths.split(os.pathsep):
87 for ext in pathext:
88 p = os.path.join(path, command + ext)
89 if os.path.exists(p):
90 return p
91
92 return None
93
Anna Zaksde1f7f8b2012-01-10 18:10:25 +000094# Make sure we flush the output after every print statement.
95class flushfile(object):
96 def __init__(self, f):
97 self.f = f
98 def write(self, x):
99 self.f.write(x)
100 self.f.flush()
101
102sys.stdout = flushfile(sys.stdout)
103
Anna Zaksf0c41162011-10-06 23:26:27 +0000104def getProjectMapPath():
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000105 ProjectMapPath = os.path.join(os.path.abspath(os.curdir),
Anna Zaksf0c41162011-10-06 23:26:27 +0000106 ProjectMapFile)
107 if not os.path.exists(ProjectMapPath):
108 print "Error: Cannot find the Project Map file " + ProjectMapPath +\
109 "\nRunning script for the wrong directory?"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000110 sys.exit(-1)
111 return ProjectMapPath
Anna Zaksf0c41162011-10-06 23:26:27 +0000112
113def getProjectDir(ID):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000114 return os.path.join(os.path.abspath(os.curdir), ID)
Anna Zaksf0c41162011-10-06 23:26:27 +0000115
Jordan Rose01ac5722012-06-01 16:24:38 +0000116def getSBOutputDirName(IsReferenceBuild) :
Anna Zaks4720a732011-11-05 05:20:48 +0000117 if IsReferenceBuild == True :
118 return SBOutputDirReferencePrefix + SBOutputDirName
119 else :
120 return SBOutputDirName
121
Ted Kremenek42c14422012-08-28 20:40:02 +0000122#------------------------------------------------------------------------------
123# Configuration setup.
124#------------------------------------------------------------------------------
125
126# Find Clang for static analysis.
George Karpenkovbe6c3292017-09-21 22:12:49 +0000127if 'CC' in os.environ:
128 Clang = os.environ['CC']
129else:
130 Clang = which("clang", os.environ['PATH'])
Ted Kremenek42c14422012-08-28 20:40:02 +0000131if not Clang:
132 print "Error: cannot find 'clang' in PATH"
133 sys.exit(-1)
134
Ted Kremenekf9a539d2012-08-28 20:40:04 +0000135# Number of jobs.
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000136Jobs = int(math.ceil(multiprocessing.cpu_count() * 0.75))
Ted Kremenekf9a539d2012-08-28 20:40:04 +0000137
Ted Kremenek42c14422012-08-28 20:40:02 +0000138# Project map stores info about all the "registered" projects.
139ProjectMapFile = "projectMap.csv"
140
141# Names of the project specific scripts.
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000142# The script that downloads the project.
143DownloadScript = "download_project.sh"
Ted Kremenek42c14422012-08-28 20:40:02 +0000144# The script that needs to be executed before the build can start.
145CleanupScript = "cleanup_run_static_analyzer.sh"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000146# This is a file containing commands for scan-build.
Ted Kremenek42c14422012-08-28 20:40:02 +0000147BuildScript = "run_static_analyzer.cmd"
148
149# The log file name.
150LogFolderName = "Logs"
151BuildLogName = "run_static_analyzer.log"
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000152# Summary file - contains the summary of the failures. Ex: This info can be be
Ted Kremenek42c14422012-08-28 20:40:02 +0000153# displayed when buildbot detects a build failure.
154NumOfFailuresInSummary = 10
155FailuresSummaryFileName = "failures.txt"
156# Summary of the result diffs.
157DiffsSummaryFileName = "diffs.txt"
158
159# The scan-build result directory.
160SBOutputDirName = "ScanBuildResults"
161SBOutputDirReferencePrefix = "Ref"
162
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000163# The name of the directory storing the cached project source. If this directory
164# does not exist, the download script will be executed. That script should
165# create the "CachedSource" directory and download the project source into it.
166CachedSourceDirName = "CachedSource"
167
168# The name of the directory containing the source code that will be analyzed.
169# Each time a project is analyzed, a fresh copy of its CachedSource directory
170# will be copied to the PatchedSource directory and then the local patches
171# in PatchfileName will be applied (if PatchfileName exists).
172PatchedSourceDirName = "PatchedSource"
173
174# The name of the patchfile specifying any changes that should be applied
175# to the CachedSource before analyzing.
176PatchfileName = "changes_for_analyzer.patch"
177
Ted Kremenek42c14422012-08-28 20:40:02 +0000178# The list of checkers used during analyzes.
Alp Tokerd4733632013-12-05 04:47:09 +0000179# Currently, consists of all the non-experimental checkers, plus a few alpha
Jordan Rose10ad0812013-04-05 17:55:07 +0000180# checkers we don't want to regress on.
Anna Zaks8a020312014-10-31 17:40:14 +0000181Checkers="alpha.unix.SimpleStream,alpha.security.taint,cplusplus.NewDeleteLeaks,core,cplusplus,deadcode,security,unix,osx"
Ted Kremenek42c14422012-08-28 20:40:02 +0000182
183Verbose = 1
184
185#------------------------------------------------------------------------------
186# Test harness logic.
187#------------------------------------------------------------------------------
188
Anna Zaksf0c41162011-10-06 23:26:27 +0000189# Run pre-processing script if any.
Anna Zaks42a44632011-11-02 20:46:50 +0000190def runCleanupScript(Dir, PBuildLogFile):
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000191 Cwd = os.path.join(Dir, PatchedSourceDirName)
Anna Zaks42a44632011-11-02 20:46:50 +0000192 ScriptPath = os.path.join(Dir, CleanupScript)
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000193 runScript(ScriptPath, PBuildLogFile, Cwd)
194
195# Run the script to download the project, if it exists.
196def runDownloadScript(Dir, PBuildLogFile):
197 ScriptPath = os.path.join(Dir, DownloadScript)
198 runScript(ScriptPath, PBuildLogFile, Dir)
199
200# Run the provided script if it exists.
201def runScript(ScriptPath, PBuildLogFile, Cwd):
Anna Zaksf0c41162011-10-06 23:26:27 +0000202 if os.path.exists(ScriptPath):
203 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000204 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000205 print " Executing: %s" % (ScriptPath,)
Devin Coughlinab95cd22016-01-22 07:08:06 +0000206 check_call("chmod +x '%s'" % ScriptPath, cwd = Cwd,
Anna Zaksf0c41162011-10-06 23:26:27 +0000207 stderr=PBuildLogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000208 stdout=PBuildLogFile,
209 shell=True)
Devin Coughlinab95cd22016-01-22 07:08:06 +0000210 check_call("'%s'" % ScriptPath, cwd = Cwd, stderr=PBuildLogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000211 stdout=PBuildLogFile,
Anna Zaksf0c41162011-10-06 23:26:27 +0000212 shell=True)
213 except:
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000214 print "Error: Running %s failed. See %s for details." % (ScriptPath,
215 PBuildLogFile.name)
Anna Zaksf0c41162011-10-06 23:26:27 +0000216 sys.exit(-1)
217
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000218# Download the project and apply the local patchfile if it exists.
219def downloadAndPatch(Dir, PBuildLogFile):
220 CachedSourceDirPath = os.path.join(Dir, CachedSourceDirName)
221
222 # If the we don't already have the cached source, run the project's
223 # download script to download it.
224 if not os.path.exists(CachedSourceDirPath):
225 runDownloadScript(Dir, PBuildLogFile)
226 if not os.path.exists(CachedSourceDirPath):
227 print "Error: '%s' not found after download." % (CachedSourceDirPath)
228 exit(-1)
229
230 PatchedSourceDirPath = os.path.join(Dir, PatchedSourceDirName)
231
232 # Remove potentially stale patched source.
233 if os.path.exists(PatchedSourceDirPath):
234 shutil.rmtree(PatchedSourceDirPath)
235
236 # Copy the cached source and apply any patches to the copy.
237 shutil.copytree(CachedSourceDirPath, PatchedSourceDirPath, symlinks=True)
238 applyPatch(Dir, PBuildLogFile)
239
240def applyPatch(Dir, PBuildLogFile):
241 PatchfilePath = os.path.join(Dir, PatchfileName)
242 PatchedSourceDirPath = os.path.join(Dir, PatchedSourceDirName)
243 if not os.path.exists(PatchfilePath):
244 print " No local patches."
245 return
246
247 print " Applying patch."
248 try:
Devin Coughlinab95cd22016-01-22 07:08:06 +0000249 check_call("patch -p1 < '%s'" % (PatchfilePath),
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000250 cwd = PatchedSourceDirPath,
251 stderr=PBuildLogFile,
252 stdout=PBuildLogFile,
253 shell=True)
254 except:
255 print "Error: Patch failed. See %s for details." % (PBuildLogFile.name)
256 sys.exit(-1)
257
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000258# Build the project with scan-build by reading in the commands and
Anna Zaksf0c41162011-10-06 23:26:27 +0000259# prefixing them with the scan-build options.
260def runScanBuild(Dir, SBOutputDir, PBuildLogFile):
261 BuildScriptPath = os.path.join(Dir, BuildScript)
262 if not os.path.exists(BuildScriptPath):
263 print "Error: build script is not defined: %s" % BuildScriptPath
Ted Kremenek6cb20802012-08-28 20:20:52 +0000264 sys.exit(-1)
Devin Coughlinf3695c82015-09-16 01:52:32 +0000265
266 AllCheckers = Checkers
267 if os.environ.has_key('SA_ADDITIONAL_CHECKERS'):
268 AllCheckers = AllCheckers + ',' + os.environ['SA_ADDITIONAL_CHECKERS']
269
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000270 # Run scan-build from within the patched source directory.
271 SBCwd = os.path.join(Dir, PatchedSourceDirName)
272
Devin Coughlin86f61a92016-01-22 18:45:22 +0000273 SBOptions = "--use-analyzer '%s' " % Clang
274 SBOptions += "-plist-html -o '%s' " % SBOutputDir
Devin Coughlinf3695c82015-09-16 01:52:32 +0000275 SBOptions += "-enable-checker " + AllCheckers + " "
Jordan Roseb18179d2013-01-24 23:07:59 +0000276 SBOptions += "--keep-empty "
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000277 # Always use ccc-analyze to ensure that we can locate the failures
Anna Zaks7b4f8a42013-05-31 02:31:09 +0000278 # directory.
279 SBOptions += "--override-compiler "
Anna Zaksf0c41162011-10-06 23:26:27 +0000280 try:
281 SBCommandFile = open(BuildScriptPath, "r")
282 SBPrefix = "scan-build " + SBOptions + " "
283 for Command in SBCommandFile:
Jordan Rose7bd91862013-09-06 16:12:41 +0000284 Command = Command.strip()
Gabor Horvath93fde942015-06-30 15:31:17 +0000285 if len(Command) == 0:
286 continue;
Ted Kremenekf9a539d2012-08-28 20:40:04 +0000287 # If using 'make', auto imply a -jX argument
288 # to speed up analysis. xcodebuild will
289 # automatically use the maximum number of cores.
Jordan Rose64e4cf02012-11-26 19:59:57 +0000290 if (Command.startswith("make ") or Command == "make") and \
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000291 "-j" not in Command:
Jordan Rose88329242012-11-16 17:41:21 +0000292 Command += " -j%d" % Jobs
Anna Zaksf0c41162011-10-06 23:26:27 +0000293 SBCommand = SBPrefix + Command
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000294 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000295 print " Executing: %s" % (SBCommand,)
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000296 check_call(SBCommand, cwd = SBCwd, stderr=PBuildLogFile,
297 stdout=PBuildLogFile,
298 shell=True)
Anna Zaksf0c41162011-10-06 23:26:27 +0000299 except:
300 print "Error: scan-build failed. See ",PBuildLogFile.name,\
301 " for details."
Anna Zaks4720a732011-11-05 05:20:48 +0000302 raise
Anna Zaksf0c41162011-10-06 23:26:27 +0000303
Anna Zaks4720a732011-11-05 05:20:48 +0000304def hasNoExtension(FileName):
305 (Root, Ext) = os.path.splitext(FileName)
306 if ((Ext == "")) :
307 return True
308 return False
309
310def isValidSingleInputFile(FileName):
311 (Root, Ext) = os.path.splitext(FileName)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000312 if ((Ext == ".i") | (Ext == ".ii") |
313 (Ext == ".c") | (Ext == ".cpp") |
Anna Zaks4720a732011-11-05 05:20:48 +0000314 (Ext == ".m") | (Ext == "")) :
315 return True
316 return False
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000317
Devin Coughlinbace0322015-09-14 21:22:24 +0000318# Get the path to the SDK for the given SDK name. Returns None if
319# the path cannot be determined.
320def getSDKPath(SDKName):
321 if which("xcrun") is None:
322 return None
323
324 Cmd = "xcrun --sdk " + SDKName + " --show-sdk-path"
325 return check_output(Cmd, shell=True).rstrip()
326
Anna Zaks4720a732011-11-05 05:20:48 +0000327# Run analysis on a set of preprocessed files.
Anna Zaksa2f970b2012-09-06 23:30:27 +0000328def runAnalyzePreprocessed(Dir, SBOutputDir, Mode):
Anna Zaks4720a732011-11-05 05:20:48 +0000329 if os.path.exists(os.path.join(Dir, BuildScript)):
330 print "Error: The preprocessed files project should not contain %s" % \
331 BuildScript
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000332 raise Exception()
Anna Zaks4720a732011-11-05 05:20:48 +0000333
Devin Coughlinbace0322015-09-14 21:22:24 +0000334 CmdPrefix = Clang + " -cc1 "
335
336 # For now, we assume the preprocessed files should be analyzed
337 # with the OS X SDK.
338 SDKPath = getSDKPath("macosx")
339 if SDKPath is not None:
340 CmdPrefix += "-isysroot " + SDKPath + " "
341
342 CmdPrefix += "-analyze -analyzer-output=plist -w "
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000343 CmdPrefix += "-analyzer-checker=" + Checkers +" -fcxx-exceptions -fblocks "
344
Anna Zaksa2f970b2012-09-06 23:30:27 +0000345 if (Mode == 2) :
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000346 CmdPrefix += "-std=c++11 "
347
Anna Zaks4720a732011-11-05 05:20:48 +0000348 PlistPath = os.path.join(Dir, SBOutputDir, "date")
349 FailPath = os.path.join(PlistPath, "failures");
350 os.makedirs(FailPath);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000351
Anna Zaks4720a732011-11-05 05:20:48 +0000352 for FullFileName in glob.glob(Dir + "/*"):
353 FileName = os.path.basename(FullFileName)
354 Failed = False
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000355
Anna Zaks4720a732011-11-05 05:20:48 +0000356 # Only run the analyzes on supported files.
357 if (hasNoExtension(FileName)):
358 continue
359 if (isValidSingleInputFile(FileName) == False):
360 print "Error: Invalid single input file %s." % (FullFileName,)
361 raise Exception()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000362
Anna Zaks4720a732011-11-05 05:20:48 +0000363 # Build and call the analyzer command.
Devin Coughlinab95cd22016-01-22 07:08:06 +0000364 OutputOption = "-o '%s.plist' " % os.path.join(PlistPath, FileName)
365 Command = CmdPrefix + OutputOption + ("'%s'" % FileName)
Anna Zaks4720a732011-11-05 05:20:48 +0000366 LogFile = open(os.path.join(FailPath, FileName + ".stderr.txt"), "w+b")
367 try:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000368 if Verbose == 1:
Anna Zaks4720a732011-11-05 05:20:48 +0000369 print " Executing: %s" % (Command,)
370 check_call(Command, cwd = Dir, stderr=LogFile,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000371 stdout=LogFile,
Anna Zaks4720a732011-11-05 05:20:48 +0000372 shell=True)
373 except CalledProcessError, e:
374 print "Error: Analyzes of %s failed. See %s for details." \
375 "Error code %d." % \
376 (FullFileName, LogFile.name, e.returncode)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000377 Failed = True
Anna Zaks4720a732011-11-05 05:20:48 +0000378 finally:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000379 LogFile.close()
380
Anna Zaks4720a732011-11-05 05:20:48 +0000381 # If command did not fail, erase the log file.
382 if Failed == False:
383 os.remove(LogFile.name);
384
Devin Coughlin9ea80332016-01-23 01:09:07 +0000385def getBuildLogPath(SBOutputDir):
386 return os.path.join(SBOutputDir, LogFolderName, BuildLogName)
387
388def removeLogFile(SBOutputDir):
389 BuildLogPath = getBuildLogPath(SBOutputDir)
390 # Clean up the log file.
391 if (os.path.exists(BuildLogPath)) :
392 RmCommand = "rm '%s'" % BuildLogPath
393 if Verbose == 1:
394 print " Executing: %s" % (RmCommand,)
395 check_call(RmCommand, shell=True)
396
Anna Zaksa2f970b2012-09-06 23:30:27 +0000397def buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000398 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000399
Devin Coughlin9ea80332016-01-23 01:09:07 +0000400 BuildLogPath = getBuildLogPath(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000401 print "Log file: %s" % (BuildLogPath,)
Anna Zaks4720a732011-11-05 05:20:48 +0000402 print "Output directory: %s" %(SBOutputDir, )
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000403
Devin Coughlin9ea80332016-01-23 01:09:07 +0000404 removeLogFile(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000405
Anna Zaks4720a732011-11-05 05:20:48 +0000406 # Clean up scan build results.
407 if (os.path.exists(SBOutputDir)) :
Devin Coughlinab95cd22016-01-22 07:08:06 +0000408 RmCommand = "rm -r '%s'" % SBOutputDir
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000409 if Verbose == 1:
Anna Zaks4720a732011-11-05 05:20:48 +0000410 print " Executing: %s" % (RmCommand,)
411 check_call(RmCommand, shell=True)
412 assert(not os.path.exists(SBOutputDir))
413 os.makedirs(os.path.join(SBOutputDir, LogFolderName))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000414
Anna Zaks4720a732011-11-05 05:20:48 +0000415 # Build and analyze the project.
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000416 with open(BuildLogPath, "wb+") as PBuildLogFile:
Anna Zaksa2f970b2012-09-06 23:30:27 +0000417 if (ProjectBuildMode == 1):
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000418 downloadAndPatch(Dir, PBuildLogFile)
419 runCleanupScript(Dir, PBuildLogFile)
Anna Zaks4720a732011-11-05 05:20:48 +0000420 runScanBuild(Dir, SBOutputDir, PBuildLogFile)
421 else:
Anna Zaksa2f970b2012-09-06 23:30:27 +0000422 runAnalyzePreprocessed(Dir, SBOutputDir, ProjectBuildMode)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000423
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000424 if IsReferenceBuild:
Anna Zaks42a44632011-11-02 20:46:50 +0000425 runCleanupScript(Dir, PBuildLogFile)
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000426 normalizeReferenceResults(Dir, SBOutputDir, ProjectBuildMode)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000427
Anna Zaksf0c41162011-10-06 23:26:27 +0000428 print "Build complete (time: %.2f). See the log for more details: %s" % \
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000429 ((time.time()-TBegin), BuildLogPath)
430
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000431def normalizeReferenceResults(Dir, SBOutputDir, ProjectBuildMode):
432 """
433 Make the absolute paths relative in the reference results.
434 """
435 for (DirPath, Dirnames, Filenames) in os.walk(SBOutputDir):
436 for F in Filenames:
437 if (not F.endswith('plist')):
438 continue
439 Plist = os.path.join(DirPath, F)
440 Data = plistlib.readPlist(Plist)
441 PathPrefix = Dir
442 if (ProjectBuildMode == 1):
443 PathPrefix = os.path.join(Dir, PatchedSourceDirName)
444 Paths = [SourceFile[len(PathPrefix)+1:]\
445 if SourceFile.startswith(PathPrefix)\
446 else SourceFile for SourceFile in Data['files']]
447 Data['files'] = Paths
448 plistlib.writePlist(Data, Plist)
449
Anna Zaksf0c41162011-10-06 23:26:27 +0000450# A plist file is created for each call to the analyzer(each source file).
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000451# We are only interested on the once that have bug reports, so delete the rest.
Anna Zaksf0c41162011-10-06 23:26:27 +0000452def CleanUpEmptyPlists(SBOutputDir):
453 for F in glob.glob(SBOutputDir + "/*/*.plist"):
454 P = os.path.join(SBOutputDir, F)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000455
Anna Zaksf0c41162011-10-06 23:26:27 +0000456 Data = plistlib.readPlist(P)
457 # Delete empty reports.
458 if not Data['files']:
459 os.remove(P)
460 continue
461
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000462# Given the scan-build output directory, checks if the build failed
463# (by searching for the failures directories). If there are failures, it
464# creates a summary file in the output directory.
Anna Zaksf0c41162011-10-06 23:26:27 +0000465def checkBuild(SBOutputDir):
466 # Check if there are failures.
467 Failures = glob.glob(SBOutputDir + "/*/failures/*.stderr.txt")
468 TotalFailed = len(Failures);
469 if TotalFailed == 0:
Jordan Rose9858b122012-08-31 00:36:30 +0000470 CleanUpEmptyPlists(SBOutputDir)
471 Plists = glob.glob(SBOutputDir + "/*/*.plist")
Alp Tokerd4733632013-12-05 04:47:09 +0000472 print "Number of bug reports (non-empty plist files) produced: %d" %\
Jordan Rose9858b122012-08-31 00:36:30 +0000473 len(Plists)
Anna Zaksf0c41162011-10-06 23:26:27 +0000474 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000475
Anna Zaksf0c41162011-10-06 23:26:27 +0000476 # Create summary file to display when the build fails.
Anna Zaks4720a732011-11-05 05:20:48 +0000477 SummaryPath = os.path.join(SBOutputDir, LogFolderName, FailuresSummaryFileName)
Anna Zaksf0c41162011-10-06 23:26:27 +0000478 if (Verbose > 0):
Anna Zaks4720a732011-11-05 05:20:48 +0000479 print " Creating the failures summary file %s" % (SummaryPath,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000480
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000481 with open(SummaryPath, "w+") as SummaryLog:
Anna Zaksf0c41162011-10-06 23:26:27 +0000482 SummaryLog.write("Total of %d failures discovered.\n" % (TotalFailed,))
483 if TotalFailed > NumOfFailuresInSummary:
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000484 SummaryLog.write("See the first %d below.\n"
Anna Zaksf0c41162011-10-06 23:26:27 +0000485 % (NumOfFailuresInSummary,))
486 # TODO: Add a line "See the results folder for more."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000487
Anna Zaksf0c41162011-10-06 23:26:27 +0000488 FailuresCopied = NumOfFailuresInSummary
489 Idx = 0
Jordan Rosedc191a12012-06-01 16:24:43 +0000490 for FailLogPathI in Failures:
Anna Zaksf0c41162011-10-06 23:26:27 +0000491 if Idx >= NumOfFailuresInSummary:
492 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000493 Idx += 1
Anna Zaksf0c41162011-10-06 23:26:27 +0000494 SummaryLog.write("\n-- Error #%d -----------\n" % (Idx,));
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000495 with open(FailLogPathI, "r") as FailLogI:
Anna Zaksf0c41162011-10-06 23:26:27 +0000496 shutil.copyfileobj(FailLogI, SummaryLog);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000497
Anna Zaks5acd9602012-01-04 23:53:50 +0000498 print "Error: analysis failed. See ", SummaryPath
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000499 sys.exit(-1)
Anna Zaksf0c41162011-10-06 23:26:27 +0000500
501# Auxiliary object to discard stdout.
502class Discarder(object):
503 def write(self, text):
504 pass # do nothing
505
506# Compare the warnings produced by scan-build.
Gabor Horvath93fde942015-06-30 15:31:17 +0000507# Strictness defines the success criteria for the test:
508# 0 - success if there are no crashes or analyzer failure.
509# 1 - success if there are no difference in the number of reported bugs.
510# 2 - success if all the bug reports are identical.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000511def runCmpResults(Dir, Strictness = 0):
512 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000513
514 RefDir = os.path.join(Dir, SBOutputDirReferencePrefix + SBOutputDirName)
515 NewDir = os.path.join(Dir, SBOutputDirName)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000516
Anna Zaksf0c41162011-10-06 23:26:27 +0000517 # We have to go one level down the directory tree.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000518 RefList = glob.glob(RefDir + "/*")
Anna Zaksf0c41162011-10-06 23:26:27 +0000519 NewList = glob.glob(NewDir + "/*")
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000520
Jordan Rosec7b992e2013-06-10 19:34:30 +0000521 # Log folders are also located in the results dir, so ignore them.
522 RefLogDir = os.path.join(RefDir, LogFolderName)
523 if RefLogDir in RefList:
524 RefList.remove(RefLogDir)
Anna Zaks4720a732011-11-05 05:20:48 +0000525 NewList.remove(os.path.join(NewDir, LogFolderName))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000526
Anna Zaksf0c41162011-10-06 23:26:27 +0000527 if len(RefList) == 0 or len(NewList) == 0:
528 return False
529 assert(len(RefList) == len(NewList))
530
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000531 # There might be more then one folder underneath - one per each scan-build
Anna Zaksf0c41162011-10-06 23:26:27 +0000532 # command (Ex: one for configure and one for make).
533 if (len(RefList) > 1):
534 # Assume that the corresponding folders have the same names.
535 RefList.sort()
536 NewList.sort()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000537
Anna Zaksf0c41162011-10-06 23:26:27 +0000538 # Iterate and find the differences.
Anna Zaks767d3562011-11-08 19:56:31 +0000539 NumDiffs = 0
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000540 PairList = zip(RefList, NewList)
541 for P in PairList:
542 RefDir = P[0]
Anna Zaksf0c41162011-10-06 23:26:27 +0000543 NewDir = P[1]
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000544
545 assert(RefDir != NewDir)
546 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000547 print " Comparing Results: %s %s" % (RefDir, NewDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000548
Anna Zaksf0c41162011-10-06 23:26:27 +0000549 DiffsPath = os.path.join(NewDir, DiffsSummaryFileName)
Devin Coughlin2cb767d2015-11-07 18:27:35 +0000550 PatchedSourceDirPath = os.path.join(Dir, PatchedSourceDirName)
551 Opts = CmpRuns.CmpOptions(DiffsPath, "", PatchedSourceDirPath)
Anna Zaksf0c41162011-10-06 23:26:27 +0000552 # Discard everything coming out of stdout (CmpRun produces a lot of them).
553 OLD_STDOUT = sys.stdout
554 sys.stdout = Discarder()
555 # Scan the results, delete empty plist files.
Gabor Horvath93fde942015-06-30 15:31:17 +0000556 NumDiffs, ReportsInRef, ReportsInNew = \
557 CmpRuns.dumpScanBuildResultsDiff(RefDir, NewDir, Opts, False)
Anna Zaksf0c41162011-10-06 23:26:27 +0000558 sys.stdout = OLD_STDOUT
Anna Zaks767d3562011-11-08 19:56:31 +0000559 if (NumDiffs > 0) :
560 print "Warning: %r differences in diagnostics. See %s" % \
561 (NumDiffs, DiffsPath,)
Gabor Horvath93fde942015-06-30 15:31:17 +0000562 if Strictness >= 2 and NumDiffs > 0:
563 print "Error: Diffs found in strict mode (2)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000564 sys.exit(-1)
Gabor Horvath93fde942015-06-30 15:31:17 +0000565 elif Strictness >= 1 and ReportsInRef != ReportsInNew:
566 print "Error: The number of results are different in strict mode (1)."
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000567 sys.exit(-1)
568
569 print "Diagnostic comparison complete (time: %.2f)." % (time.time()-TBegin)
Anna Zaks767d3562011-11-08 19:56:31 +0000570 return (NumDiffs > 0)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000571
Devin Coughlin9ea80332016-01-23 01:09:07 +0000572def cleanupReferenceResults(SBOutputDir):
573 # Delete html, css, and js files from reference results. These can
574 # include multiple copies of the benchmark source and so get very large.
575 Extensions = ["html", "css", "js"]
576 for E in Extensions:
577 for F in glob.glob("%s/*/*.%s" % (SBOutputDir, E)):
578 P = os.path.join(SBOutputDir, F)
579 RmCommand = "rm '%s'" % P
580 check_call(RmCommand, shell=True)
581
582 # Remove the log file. It leaks absolute path names.
583 removeLogFile(SBOutputDir)
584
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000585def updateSVN(Mode, PMapFile):
586 """
587 svn delete or svn add (depending on `Mode`) all folders defined in the file
588 handler `PMapFile`.
589 Commit the result to SVN.
590 """
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000591 try:
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000592 for I in iterateOverProjects(PMapFile):
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000593 ProjName = I[0]
Jordan Rose01ac5722012-06-01 16:24:38 +0000594 Path = os.path.join(ProjName, getSBOutputDirName(True))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000595
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000596 if Mode == "delete":
Devin Coughlinab95cd22016-01-22 07:08:06 +0000597 Command = "svn delete '%s'" % (Path,)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000598 else:
Devin Coughlinab95cd22016-01-22 07:08:06 +0000599 Command = "svn add '%s'" % (Path,)
Anna Zaksf0c41162011-10-06 23:26:27 +0000600
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000601 if Verbose == 1:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000602 print " Executing: %s" % (Command,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000603 check_call(Command, shell=True)
604
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000605 if Mode == "delete":
606 CommitCommand = "svn commit -m \"[analyzer tests] Remove " \
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000607 "reference results.\""
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000608 else:
609 CommitCommand = "svn commit -m \"[analyzer tests] Add new " \
610 "reference results.\""
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000611 if Verbose == 1:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000612 print " Executing: %s" % (CommitCommand,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000613 check_call(CommitCommand, shell=True)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000614 except:
615 print "Error: SVN update failed."
616 sys.exit(-1)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000617
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000618def testProject(ID, ProjectBuildMode, IsReferenceBuild=False, Strictness = 0):
Anna Zaks4720a732011-11-05 05:20:48 +0000619 print " \n\n--- Building project %s" % (ID,)
620
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000621 TBegin = time.time()
Anna Zaksf0c41162011-10-06 23:26:27 +0000622
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000623 Dir = getProjectDir(ID)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000624 if Verbose == 1:
Anna Zaksf0c41162011-10-06 23:26:27 +0000625 print " Build directory: %s." % (Dir,)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000626
Anna Zaksf0c41162011-10-06 23:26:27 +0000627 # Set the build results directory.
Jordan Rose01ac5722012-06-01 16:24:38 +0000628 RelOutputDir = getSBOutputDirName(IsReferenceBuild)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000629 SBOutputDir = os.path.join(Dir, RelOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000630
Anna Zaksa2f970b2012-09-06 23:30:27 +0000631 buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild)
Anna Zaksf0c41162011-10-06 23:26:27 +0000632
633 checkBuild(SBOutputDir)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000634
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000635 if IsReferenceBuild:
Devin Coughlin9ea80332016-01-23 01:09:07 +0000636 cleanupReferenceResults(SBOutputDir)
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000637 else:
638 runCmpResults(Dir, Strictness)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000639
Anna Zaksf0c41162011-10-06 23:26:27 +0000640 print "Completed tests for project %s (time: %.2f)." % \
641 (ID, (time.time()-TBegin))
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000642
Devin Coughlin0dfc6f02016-09-19 01:36:40 +0000643def isCommentCSVLine(Entries):
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000644 # Treat CSV lines starting with a '#' as a comment.
645 return len(Entries) > 0 and Entries[0].startswith("#")
Devin Coughlin0dfc6f02016-09-19 01:36:40 +0000646
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000647def projectFileHandler():
648 return open(getProjectMapPath(), "rb")
649
650def iterateOverProjects(PMapFile):
651 """
652 Iterate over all projects defined in the project file handler `PMapFile`
653 from the start.
654 """
655 PMapFile.seek(0)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000656 try:
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000657 for I in csv.reader(PMapFile):
Devin Coughlin0dfc6f02016-09-19 01:36:40 +0000658 if (isCommentCSVLine(I)):
659 continue
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000660 yield I
661 except:
662 print "Error occurred. Premature termination."
663 raise
664
665def validateProjectFile(PMapFile):
666 """
667 Validate project file.
668 """
669 for I in iterateOverProjects(PMapFile):
670 if (len(I) != 2) :
671 print "Error: Rows in the ProjectMapFile should have 2 entries."
672 raise Exception()
673 if (not ((I[1] == "0") | (I[1] == "1") | (I[1] == "2"))):
674 print "Error: Second entry in the ProjectMapFile should be 0" \
675 " (single file), 1 (project), or 2(single file c++11)."
676 raise Exception()
677
678def testAll(IsReferenceBuild = False, UpdateSVN = False, Strictness = 0):
679 with projectFileHandler() as PMapFile:
680 validateProjectFile(PMapFile)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000681
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000682 # When we are regenerating the reference results, we might need to
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000683 # update svn. Remove reference results from SVN.
684 if UpdateSVN == True:
Jordan Rose01ac5722012-06-01 16:24:38 +0000685 assert(IsReferenceBuild == True);
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000686 updateSVN("delete", PMapFile);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000687
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000688 # Test the projects.
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000689 for (ProjName, ProjBuildMode) in iterateOverProjects(PMapFile):
690 testProject(ProjName, int(ProjBuildMode), IsReferenceBuild, Strictness)
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000691
George Karpenkov3abfc3b2017-09-22 01:41:16 +0000692 # Re-add reference results to SVN.
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000693 if UpdateSVN == True:
694 updateSVN("add", PMapFile);
695
Anna Zaksf0c41162011-10-06 23:26:27 +0000696if __name__ == '__main__':
Gabor Horvath93fde942015-06-30 15:31:17 +0000697 # Parse command line arguments.
698 Parser = argparse.ArgumentParser(description='Test the Clang Static Analyzer.')
699 Parser.add_argument('--strictness', dest='strictness', type=int, default=0,
700 help='0 to fail on runtime errors, 1 to fail when the number\
701 of found bugs are different from the reference, 2 to \
702 fail on any difference from the reference. Default is 0.')
703 Parser.add_argument('-r', dest='regenerate', action='store_true', default=False,
704 help='Regenerate reference output.')
705 Parser.add_argument('-rs', dest='update_reference', action='store_true',
706 default=False, help='Regenerate reference output and update svn.')
707 Args = Parser.parse_args()
708
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000709 IsReference = False
710 UpdateSVN = False
Gabor Horvath93fde942015-06-30 15:31:17 +0000711 Strictness = Args.strictness
712 if Args.regenerate:
713 IsReference = True
714 elif Args.update_reference:
715 IsReference = True
716 UpdateSVN = True
Anna Zaks4c1ef9762012-02-03 06:35:23 +0000717
Gabor Horvath93fde942015-06-30 15:31:17 +0000718 testAll(IsReference, UpdateSVN, Strictness)