SATestBuild.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. #!/usr/bin/env python
  2. """
  3. Static Analyzer qualification infrastructure.
  4. The goal is to test the analyzer against different projects, check for failures,
  5. compare results, and measure performance.
  6. Repository Directory will contain sources of the projects as well as the
  7. information on how to build them and the expected output.
  8. Repository Directory structure:
  9. - ProjectMap file
  10. - Historical Performance Data
  11. - Project Dir1
  12. - ReferenceOutput
  13. - Project Dir2
  14. - ReferenceOutput
  15. ..
  16. Note that the build tree must be inside the project dir.
  17. To test the build of the analyzer one would:
  18. - Copy over a copy of the Repository Directory. (TODO: Prefer to ensure that
  19. the build directory does not pollute the repository to min network traffic).
  20. - Build all projects, until error. Produce logs to report errors.
  21. - Compare results.
  22. The files which should be kept around for failure investigations:
  23. RepositoryCopy/Project DirI/ScanBuildResults
  24. RepositoryCopy/Project DirI/run_static_analyzer.log
  25. Assumptions (TODO: shouldn't need to assume these.):
  26. The script is being run from the Repository Directory.
  27. The compiler for scan-build and scan-build are in the PATH.
  28. export PATH=/Users/zaks/workspace/c2llvm/build/Release+Asserts/bin:$PATH
  29. For more logging, set the env variables:
  30. zaks:TI zaks$ export CCC_ANALYZER_LOG=1
  31. zaks:TI zaks$ export CCC_ANALYZER_VERBOSE=1
  32. """
  33. import CmpRuns
  34. import os
  35. import csv
  36. import sys
  37. import glob
  38. import math
  39. import shutil
  40. import time
  41. import plistlib
  42. import argparse
  43. from subprocess import check_call, CalledProcessError
  44. #------------------------------------------------------------------------------
  45. # Helper functions.
  46. #------------------------------------------------------------------------------
  47. def detectCPUs():
  48. """
  49. Detects the number of CPUs on a system. Cribbed from pp.
  50. """
  51. # Linux, Unix and MacOS:
  52. if hasattr(os, "sysconf"):
  53. if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
  54. # Linux & Unix:
  55. ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
  56. if isinstance(ncpus, int) and ncpus > 0:
  57. return ncpus
  58. else: # OSX:
  59. return int(capture(['sysctl', '-n', 'hw.ncpu']))
  60. # Windows:
  61. if os.environ.has_key("NUMBER_OF_PROCESSORS"):
  62. ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
  63. if ncpus > 0:
  64. return ncpus
  65. return 1 # Default
  66. def which(command, paths = None):
  67. """which(command, [paths]) - Look up the given command in the paths string
  68. (or the PATH environment variable, if unspecified)."""
  69. if paths is None:
  70. paths = os.environ.get('PATH','')
  71. # Check for absolute match first.
  72. if os.path.exists(command):
  73. return command
  74. # Would be nice if Python had a lib function for this.
  75. if not paths:
  76. paths = os.defpath
  77. # Get suffixes to search.
  78. # On Cygwin, 'PATHEXT' may exist but it should not be used.
  79. if os.pathsep == ';':
  80. pathext = os.environ.get('PATHEXT', '').split(';')
  81. else:
  82. pathext = ['']
  83. # Search the paths...
  84. for path in paths.split(os.pathsep):
  85. for ext in pathext:
  86. p = os.path.join(path, command + ext)
  87. if os.path.exists(p):
  88. return p
  89. return None
  90. # Make sure we flush the output after every print statement.
  91. class flushfile(object):
  92. def __init__(self, f):
  93. self.f = f
  94. def write(self, x):
  95. self.f.write(x)
  96. self.f.flush()
  97. sys.stdout = flushfile(sys.stdout)
  98. def getProjectMapPath():
  99. ProjectMapPath = os.path.join(os.path.abspath(os.curdir),
  100. ProjectMapFile)
  101. if not os.path.exists(ProjectMapPath):
  102. print "Error: Cannot find the Project Map file " + ProjectMapPath +\
  103. "\nRunning script for the wrong directory?"
  104. sys.exit(-1)
  105. return ProjectMapPath
  106. def getProjectDir(ID):
  107. return os.path.join(os.path.abspath(os.curdir), ID)
  108. def getSBOutputDirName(IsReferenceBuild) :
  109. if IsReferenceBuild == True :
  110. return SBOutputDirReferencePrefix + SBOutputDirName
  111. else :
  112. return SBOutputDirName
  113. #------------------------------------------------------------------------------
  114. # Configuration setup.
  115. #------------------------------------------------------------------------------
  116. # Find Clang for static analysis.
  117. Clang = which("clang", os.environ['PATH'])
  118. if not Clang:
  119. print "Error: cannot find 'clang' in PATH"
  120. sys.exit(-1)
  121. # Number of jobs.
  122. Jobs = int(math.ceil(detectCPUs() * 0.75))
  123. # Project map stores info about all the "registered" projects.
  124. ProjectMapFile = "projectMap.csv"
  125. # Names of the project specific scripts.
  126. # The script that needs to be executed before the build can start.
  127. CleanupScript = "cleanup_run_static_analyzer.sh"
  128. # This is a file containing commands for scan-build.
  129. BuildScript = "run_static_analyzer.cmd"
  130. # The log file name.
  131. LogFolderName = "Logs"
  132. BuildLogName = "run_static_analyzer.log"
  133. # Summary file - contains the summary of the failures. Ex: This info can be be
  134. # displayed when buildbot detects a build failure.
  135. NumOfFailuresInSummary = 10
  136. FailuresSummaryFileName = "failures.txt"
  137. # Summary of the result diffs.
  138. DiffsSummaryFileName = "diffs.txt"
  139. # The scan-build result directory.
  140. SBOutputDirName = "ScanBuildResults"
  141. SBOutputDirReferencePrefix = "Ref"
  142. # The list of checkers used during analyzes.
  143. # Currently, consists of all the non-experimental checkers, plus a few alpha
  144. # checkers we don't want to regress on.
  145. Checkers="alpha.unix.SimpleStream,alpha.security.taint,cplusplus.NewDeleteLeaks,core,cplusplus,deadcode,security,unix,osx"
  146. Verbose = 1
  147. #------------------------------------------------------------------------------
  148. # Test harness logic.
  149. #------------------------------------------------------------------------------
  150. # Run pre-processing script if any.
  151. def runCleanupScript(Dir, PBuildLogFile):
  152. ScriptPath = os.path.join(Dir, CleanupScript)
  153. if os.path.exists(ScriptPath):
  154. try:
  155. if Verbose == 1:
  156. print " Executing: %s" % (ScriptPath,)
  157. check_call("chmod +x %s" % ScriptPath, cwd = Dir,
  158. stderr=PBuildLogFile,
  159. stdout=PBuildLogFile,
  160. shell=True)
  161. check_call(ScriptPath, cwd = Dir, stderr=PBuildLogFile,
  162. stdout=PBuildLogFile,
  163. shell=True)
  164. except:
  165. print "Error: The pre-processing step failed. See ", \
  166. PBuildLogFile.name, " for details."
  167. sys.exit(-1)
  168. # Build the project with scan-build by reading in the commands and
  169. # prefixing them with the scan-build options.
  170. def runScanBuild(Dir, SBOutputDir, PBuildLogFile):
  171. BuildScriptPath = os.path.join(Dir, BuildScript)
  172. if not os.path.exists(BuildScriptPath):
  173. print "Error: build script is not defined: %s" % BuildScriptPath
  174. sys.exit(-1)
  175. SBOptions = "--use-analyzer " + Clang + " "
  176. SBOptions += "-plist-html -o " + SBOutputDir + " "
  177. SBOptions += "-enable-checker " + Checkers + " "
  178. SBOptions += "--keep-empty "
  179. # Always use ccc-analyze to ensure that we can locate the failures
  180. # directory.
  181. SBOptions += "--override-compiler "
  182. try:
  183. SBCommandFile = open(BuildScriptPath, "r")
  184. SBPrefix = "scan-build " + SBOptions + " "
  185. for Command in SBCommandFile:
  186. Command = Command.strip()
  187. if len(Command) == 0:
  188. continue;
  189. # If using 'make', auto imply a -jX argument
  190. # to speed up analysis. xcodebuild will
  191. # automatically use the maximum number of cores.
  192. if (Command.startswith("make ") or Command == "make") and \
  193. "-j" not in Command:
  194. Command += " -j%d" % Jobs
  195. SBCommand = SBPrefix + Command
  196. if Verbose == 1:
  197. print " Executing: %s" % (SBCommand,)
  198. check_call(SBCommand, cwd = Dir, stderr=PBuildLogFile,
  199. stdout=PBuildLogFile,
  200. shell=True)
  201. except:
  202. print "Error: scan-build failed. See ",PBuildLogFile.name,\
  203. " for details."
  204. raise
  205. def hasNoExtension(FileName):
  206. (Root, Ext) = os.path.splitext(FileName)
  207. if ((Ext == "")) :
  208. return True
  209. return False
  210. def isValidSingleInputFile(FileName):
  211. (Root, Ext) = os.path.splitext(FileName)
  212. if ((Ext == ".i") | (Ext == ".ii") |
  213. (Ext == ".c") | (Ext == ".cpp") |
  214. (Ext == ".m") | (Ext == "")) :
  215. return True
  216. return False
  217. # Run analysis on a set of preprocessed files.
  218. def runAnalyzePreprocessed(Dir, SBOutputDir, Mode):
  219. if os.path.exists(os.path.join(Dir, BuildScript)):
  220. print "Error: The preprocessed files project should not contain %s" % \
  221. BuildScript
  222. raise Exception()
  223. CmdPrefix = Clang + " -cc1 -analyze -analyzer-output=plist -w "
  224. CmdPrefix += "-analyzer-checker=" + Checkers +" -fcxx-exceptions -fblocks "
  225. if (Mode == 2) :
  226. CmdPrefix += "-std=c++11 "
  227. PlistPath = os.path.join(Dir, SBOutputDir, "date")
  228. FailPath = os.path.join(PlistPath, "failures");
  229. os.makedirs(FailPath);
  230. for FullFileName in glob.glob(Dir + "/*"):
  231. FileName = os.path.basename(FullFileName)
  232. Failed = False
  233. # Only run the analyzes on supported files.
  234. if (hasNoExtension(FileName)):
  235. continue
  236. if (isValidSingleInputFile(FileName) == False):
  237. print "Error: Invalid single input file %s." % (FullFileName,)
  238. raise Exception()
  239. # Build and call the analyzer command.
  240. OutputOption = "-o " + os.path.join(PlistPath, FileName) + ".plist "
  241. Command = CmdPrefix + OutputOption + FileName
  242. LogFile = open(os.path.join(FailPath, FileName + ".stderr.txt"), "w+b")
  243. try:
  244. if Verbose == 1:
  245. print " Executing: %s" % (Command,)
  246. check_call(Command, cwd = Dir, stderr=LogFile,
  247. stdout=LogFile,
  248. shell=True)
  249. except CalledProcessError, e:
  250. print "Error: Analyzes of %s failed. See %s for details." \
  251. "Error code %d." % \
  252. (FullFileName, LogFile.name, e.returncode)
  253. Failed = True
  254. finally:
  255. LogFile.close()
  256. # If command did not fail, erase the log file.
  257. if Failed == False:
  258. os.remove(LogFile.name);
  259. def buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild):
  260. TBegin = time.time()
  261. BuildLogPath = os.path.join(SBOutputDir, LogFolderName, BuildLogName)
  262. print "Log file: %s" % (BuildLogPath,)
  263. print "Output directory: %s" %(SBOutputDir, )
  264. # Clean up the log file.
  265. if (os.path.exists(BuildLogPath)) :
  266. RmCommand = "rm " + BuildLogPath
  267. if Verbose == 1:
  268. print " Executing: %s" % (RmCommand,)
  269. check_call(RmCommand, shell=True)
  270. # Clean up scan build results.
  271. if (os.path.exists(SBOutputDir)) :
  272. RmCommand = "rm -r " + SBOutputDir
  273. if Verbose == 1:
  274. print " Executing: %s" % (RmCommand,)
  275. check_call(RmCommand, shell=True)
  276. assert(not os.path.exists(SBOutputDir))
  277. os.makedirs(os.path.join(SBOutputDir, LogFolderName))
  278. # Open the log file.
  279. PBuildLogFile = open(BuildLogPath, "wb+")
  280. # Build and analyze the project.
  281. try:
  282. runCleanupScript(Dir, PBuildLogFile)
  283. if (ProjectBuildMode == 1):
  284. runScanBuild(Dir, SBOutputDir, PBuildLogFile)
  285. else:
  286. runAnalyzePreprocessed(Dir, SBOutputDir, ProjectBuildMode)
  287. if IsReferenceBuild :
  288. runCleanupScript(Dir, PBuildLogFile)
  289. # Make the absolute paths relative in the reference results.
  290. for (DirPath, Dirnames, Filenames) in os.walk(SBOutputDir):
  291. for F in Filenames:
  292. if (not F.endswith('plist')):
  293. continue
  294. Plist = os.path.join(DirPath, F)
  295. Data = plistlib.readPlist(Plist)
  296. Paths = [SourceFile[len(Dir)+1:] if SourceFile.startswith(Dir)\
  297. else SourceFile for SourceFile in Data['files']]
  298. Data['files'] = Paths
  299. plistlib.writePlist(Data, Plist)
  300. finally:
  301. PBuildLogFile.close()
  302. print "Build complete (time: %.2f). See the log for more details: %s" % \
  303. ((time.time()-TBegin), BuildLogPath)
  304. # A plist file is created for each call to the analyzer(each source file).
  305. # We are only interested on the once that have bug reports, so delete the rest.
  306. def CleanUpEmptyPlists(SBOutputDir):
  307. for F in glob.glob(SBOutputDir + "/*/*.plist"):
  308. P = os.path.join(SBOutputDir, F)
  309. Data = plistlib.readPlist(P)
  310. # Delete empty reports.
  311. if not Data['files']:
  312. os.remove(P)
  313. continue
  314. # Given the scan-build output directory, checks if the build failed
  315. # (by searching for the failures directories). If there are failures, it
  316. # creates a summary file in the output directory.
  317. def checkBuild(SBOutputDir):
  318. # Check if there are failures.
  319. Failures = glob.glob(SBOutputDir + "/*/failures/*.stderr.txt")
  320. TotalFailed = len(Failures);
  321. if TotalFailed == 0:
  322. CleanUpEmptyPlists(SBOutputDir)
  323. Plists = glob.glob(SBOutputDir + "/*/*.plist")
  324. print "Number of bug reports (non-empty plist files) produced: %d" %\
  325. len(Plists)
  326. return;
  327. # Create summary file to display when the build fails.
  328. SummaryPath = os.path.join(SBOutputDir, LogFolderName, FailuresSummaryFileName)
  329. if (Verbose > 0):
  330. print " Creating the failures summary file %s" % (SummaryPath,)
  331. SummaryLog = open(SummaryPath, "w+")
  332. try:
  333. SummaryLog.write("Total of %d failures discovered.\n" % (TotalFailed,))
  334. if TotalFailed > NumOfFailuresInSummary:
  335. SummaryLog.write("See the first %d below.\n"
  336. % (NumOfFailuresInSummary,))
  337. # TODO: Add a line "See the results folder for more."
  338. FailuresCopied = NumOfFailuresInSummary
  339. Idx = 0
  340. for FailLogPathI in Failures:
  341. if Idx >= NumOfFailuresInSummary:
  342. break;
  343. Idx += 1
  344. SummaryLog.write("\n-- Error #%d -----------\n" % (Idx,));
  345. FailLogI = open(FailLogPathI, "r");
  346. try:
  347. shutil.copyfileobj(FailLogI, SummaryLog);
  348. finally:
  349. FailLogI.close()
  350. finally:
  351. SummaryLog.close()
  352. print "Error: analysis failed. See ", SummaryPath
  353. sys.exit(-1)
  354. # Auxiliary object to discard stdout.
  355. class Discarder(object):
  356. def write(self, text):
  357. pass # do nothing
  358. # Compare the warnings produced by scan-build.
  359. # Strictness defines the success criteria for the test:
  360. # 0 - success if there are no crashes or analyzer failure.
  361. # 1 - success if there are no difference in the number of reported bugs.
  362. # 2 - success if all the bug reports are identical.
  363. def runCmpResults(Dir, Strictness = 0):
  364. TBegin = time.time()
  365. RefDir = os.path.join(Dir, SBOutputDirReferencePrefix + SBOutputDirName)
  366. NewDir = os.path.join(Dir, SBOutputDirName)
  367. # We have to go one level down the directory tree.
  368. RefList = glob.glob(RefDir + "/*")
  369. NewList = glob.glob(NewDir + "/*")
  370. # Log folders are also located in the results dir, so ignore them.
  371. RefLogDir = os.path.join(RefDir, LogFolderName)
  372. if RefLogDir in RefList:
  373. RefList.remove(RefLogDir)
  374. NewList.remove(os.path.join(NewDir, LogFolderName))
  375. if len(RefList) == 0 or len(NewList) == 0:
  376. return False
  377. assert(len(RefList) == len(NewList))
  378. # There might be more then one folder underneath - one per each scan-build
  379. # command (Ex: one for configure and one for make).
  380. if (len(RefList) > 1):
  381. # Assume that the corresponding folders have the same names.
  382. RefList.sort()
  383. NewList.sort()
  384. # Iterate and find the differences.
  385. NumDiffs = 0
  386. PairList = zip(RefList, NewList)
  387. for P in PairList:
  388. RefDir = P[0]
  389. NewDir = P[1]
  390. assert(RefDir != NewDir)
  391. if Verbose == 1:
  392. print " Comparing Results: %s %s" % (RefDir, NewDir)
  393. DiffsPath = os.path.join(NewDir, DiffsSummaryFileName)
  394. Opts = CmpRuns.CmpOptions(DiffsPath, "", Dir)
  395. # Discard everything coming out of stdout (CmpRun produces a lot of them).
  396. OLD_STDOUT = sys.stdout
  397. sys.stdout = Discarder()
  398. # Scan the results, delete empty plist files.
  399. NumDiffs, ReportsInRef, ReportsInNew = \
  400. CmpRuns.dumpScanBuildResultsDiff(RefDir, NewDir, Opts, False)
  401. sys.stdout = OLD_STDOUT
  402. if (NumDiffs > 0) :
  403. print "Warning: %r differences in diagnostics. See %s" % \
  404. (NumDiffs, DiffsPath,)
  405. if Strictness >= 2 and NumDiffs > 0:
  406. print "Error: Diffs found in strict mode (2)."
  407. sys.exit(-1)
  408. elif Strictness >= 1 and ReportsInRef != ReportsInNew:
  409. print "Error: The number of results are different in strict mode (1)."
  410. sys.exit(-1)
  411. print "Diagnostic comparison complete (time: %.2f)." % (time.time()-TBegin)
  412. return (NumDiffs > 0)
  413. def updateSVN(Mode, ProjectsMap):
  414. try:
  415. ProjectsMap.seek(0)
  416. for I in csv.reader(ProjectsMap):
  417. ProjName = I[0]
  418. Path = os.path.join(ProjName, getSBOutputDirName(True))
  419. if Mode == "delete":
  420. Command = "svn delete %s" % (Path,)
  421. else:
  422. Command = "svn add %s" % (Path,)
  423. if Verbose == 1:
  424. print " Executing: %s" % (Command,)
  425. check_call(Command, shell=True)
  426. if Mode == "delete":
  427. CommitCommand = "svn commit -m \"[analyzer tests] Remove " \
  428. "reference results.\""
  429. else:
  430. CommitCommand = "svn commit -m \"[analyzer tests] Add new " \
  431. "reference results.\""
  432. if Verbose == 1:
  433. print " Executing: %s" % (CommitCommand,)
  434. check_call(CommitCommand, shell=True)
  435. except:
  436. print "Error: SVN update failed."
  437. sys.exit(-1)
  438. def testProject(ID, ProjectBuildMode, IsReferenceBuild=False, Dir=None, Strictness = 0):
  439. print " \n\n--- Building project %s" % (ID,)
  440. TBegin = time.time()
  441. if Dir is None :
  442. Dir = getProjectDir(ID)
  443. if Verbose == 1:
  444. print " Build directory: %s." % (Dir,)
  445. # Set the build results directory.
  446. RelOutputDir = getSBOutputDirName(IsReferenceBuild)
  447. SBOutputDir = os.path.join(Dir, RelOutputDir)
  448. buildProject(Dir, SBOutputDir, ProjectBuildMode, IsReferenceBuild)
  449. checkBuild(SBOutputDir)
  450. if IsReferenceBuild == False:
  451. runCmpResults(Dir, Strictness)
  452. print "Completed tests for project %s (time: %.2f)." % \
  453. (ID, (time.time()-TBegin))
  454. def testAll(IsReferenceBuild = False, UpdateSVN = False, Strictness = 0):
  455. PMapFile = open(getProjectMapPath(), "rb")
  456. try:
  457. # Validate the input.
  458. for I in csv.reader(PMapFile):
  459. if (len(I) != 2) :
  460. print "Error: Rows in the ProjectMapFile should have 3 entries."
  461. raise Exception()
  462. if (not ((I[1] == "0") | (I[1] == "1") | (I[1] == "2"))):
  463. print "Error: Second entry in the ProjectMapFile should be 0" \
  464. " (single file), 1 (project), or 2(single file c++11)."
  465. raise Exception()
  466. # When we are regenerating the reference results, we might need to
  467. # update svn. Remove reference results from SVN.
  468. if UpdateSVN == True:
  469. assert(IsReferenceBuild == True);
  470. updateSVN("delete", PMapFile);
  471. # Test the projects.
  472. PMapFile.seek(0)
  473. for I in csv.reader(PMapFile):
  474. testProject(I[0], int(I[1]), IsReferenceBuild, None, Strictness)
  475. # Add reference results to SVN.
  476. if UpdateSVN == True:
  477. updateSVN("add", PMapFile);
  478. except:
  479. print "Error occurred. Premature termination."
  480. raise
  481. finally:
  482. PMapFile.close()
  483. if __name__ == '__main__':
  484. # Parse command line arguments.
  485. Parser = argparse.ArgumentParser(description='Test the Clang Static Analyzer.')
  486. Parser.add_argument('--strictness', dest='strictness', type=int, default=0,
  487. help='0 to fail on runtime errors, 1 to fail when the number\
  488. of found bugs are different from the reference, 2 to \
  489. fail on any difference from the reference. Default is 0.')
  490. Parser.add_argument('-r', dest='regenerate', action='store_true', default=False,
  491. help='Regenerate reference output.')
  492. Parser.add_argument('-rs', dest='update_reference', action='store_true',
  493. default=False, help='Regenerate reference output and update svn.')
  494. Args = Parser.parse_args()
  495. IsReference = False
  496. UpdateSVN = False
  497. Strictness = Args.strictness
  498. if Args.regenerate:
  499. IsReference = True
  500. elif Args.update_reference:
  501. IsReference = True
  502. UpdateSVN = True
  503. testAll(IsReference, UpdateSVN, Strictness)