scan-build 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  1. #!/usr/bin/env perl
  2. #
  3. # The LLVM Compiler Infrastructure
  4. #
  5. # This file is distributed under the University of Illinois Open Source
  6. # License. See LICENSE.TXT for details.
  7. #
  8. ##===----------------------------------------------------------------------===##
  9. #
  10. # A script designed to wrap a build so that all calls to gcc are intercepted
  11. # and piped to the static analyzer.
  12. #
  13. ##===----------------------------------------------------------------------===##
  14. use strict;
  15. use warnings;
  16. use FindBin qw($RealBin);
  17. use Digest::MD5;
  18. use File::Basename;
  19. use File::Find;
  20. use File::Copy qw(copy);
  21. use File::Path qw( rmtree mkpath );
  22. use Term::ANSIColor;
  23. use Term::ANSIColor qw(:constants);
  24. use Cwd qw/ getcwd abs_path /;
  25. use Sys::Hostname;
  26. use Hash::Util qw(lock_keys);
  27. my $Prog = "scan-build";
  28. my $BuildName;
  29. my $BuildDate;
  30. my $TERM = $ENV{'TERM'};
  31. my $UseColor = (defined $TERM and $TERM =~ 'xterm-.*color' and -t STDOUT
  32. and defined $ENV{'SCAN_BUILD_COLOR'});
  33. # Portability: getpwuid is not implemented for Win32 (see Perl language
  34. # reference, perlport), use getlogin instead.
  35. my $UserName = HtmlEscape(getlogin() || getpwuid($<) || 'unknown');
  36. my $HostName = HtmlEscape(hostname() || 'unknown');
  37. my $CurrentDir = HtmlEscape(getcwd());
  38. my $CmdArgs;
  39. my $Date = localtime();
  40. # Command-line/config arguments.
  41. my %Options = (
  42. Verbose => 0, # Verbose output from this script.
  43. AnalyzeHeaders => 0,
  44. OutputDir => undef, # Parent directory to store HTML files.
  45. HtmlTitle => basename($CurrentDir)." - scan-build results",
  46. IgnoreErrors => 0, # Ignore build errors.
  47. KeepCC => 0, # Do not override CC and CXX make variables
  48. ViewResults => 0, # View results when the build terminates.
  49. ExitStatusFoundBugs => 0, # Exit status reflects whether bugs were found
  50. ShowDescription => 0, # Display the description of the defect in the list
  51. KeepEmpty => 0, # Don't remove output directory even with 0 results.
  52. EnableCheckers => {},
  53. DisableCheckers => {},
  54. Excludes => [],
  55. UseCC => undef, # C compiler to use for compilation.
  56. UseCXX => undef, # C++ compiler to use for compilation.
  57. AnalyzerTarget => undef,
  58. StoreModel => undef,
  59. ConstraintsModel => undef,
  60. InternalStats => undef,
  61. OutputFormat => "html",
  62. ConfigOptions => [], # Options to pass through to the analyzer's -analyzer-config flag.
  63. ReportFailures => undef,
  64. AnalyzerStats => 0,
  65. MaxLoop => 0,
  66. PluginsToLoad => [],
  67. AnalyzerDiscoveryMethod => undef,
  68. OverrideCompiler => 0, # The flag corresponding to the --override-compiler command line option.
  69. ForceAnalyzeDebugCode => 0
  70. );
  71. lock_keys(%Options);
  72. ##----------------------------------------------------------------------------##
  73. # Diagnostics
  74. ##----------------------------------------------------------------------------##
  75. sub Diag {
  76. if ($UseColor) {
  77. print BOLD, MAGENTA "$Prog: @_";
  78. print RESET;
  79. }
  80. else {
  81. print "$Prog: @_";
  82. }
  83. }
  84. sub ErrorDiag {
  85. if ($UseColor) {
  86. print STDERR BOLD, RED "$Prog: ";
  87. print STDERR RESET, RED @_;
  88. print STDERR RESET;
  89. } else {
  90. print STDERR "$Prog: @_";
  91. }
  92. }
  93. sub DiagCrashes {
  94. my $Dir = shift;
  95. Diag ("The analyzer encountered problems on some source files.\n");
  96. Diag ("Preprocessed versions of these sources were deposited in '$Dir/failures'.\n");
  97. Diag ("Please consider submitting a bug report using these files:\n");
  98. Diag (" http://clang-analyzer.llvm.org/filing_bugs.html\n")
  99. }
  100. sub DieDiag {
  101. if ($UseColor) {
  102. print STDERR BOLD, RED "$Prog: ";
  103. print STDERR RESET, RED @_;
  104. print STDERR RESET;
  105. }
  106. else {
  107. print STDERR "$Prog: ", @_;
  108. }
  109. exit 1;
  110. }
  111. ##----------------------------------------------------------------------------##
  112. # Print default checker names
  113. ##----------------------------------------------------------------------------##
  114. if (grep /^--help-checkers$/, @ARGV) {
  115. my @options = qx($0 -h);
  116. foreach (@options) {
  117. next unless /^ \+/;
  118. s/^\s*//;
  119. my ($sign, $name, @text) = split ' ', $_;
  120. print $name, $/ if $sign eq '+';
  121. }
  122. exit 0;
  123. }
  124. ##----------------------------------------------------------------------------##
  125. # Declaration of Clang options. Populated later.
  126. ##----------------------------------------------------------------------------##
  127. my $Clang;
  128. my $ClangSB;
  129. my $ClangCXX;
  130. my $ClangVersion;
  131. ##----------------------------------------------------------------------------##
  132. # GetHTMLRunDir - Construct an HTML directory name for the current sub-run.
  133. ##----------------------------------------------------------------------------##
  134. sub GetHTMLRunDir {
  135. die "Not enough arguments." if (@_ == 0);
  136. my $Dir = shift @_;
  137. my $TmpMode = 0;
  138. if (!defined $Dir) {
  139. $Dir = $ENV{'TMPDIR'} || $ENV{'TEMP'} || $ENV{'TMP'} || "/tmp";
  140. $TmpMode = 1;
  141. }
  142. # Chop off any trailing '/' characters.
  143. while ($Dir =~ /\/$/) { chop $Dir; }
  144. # Get current date and time.
  145. my @CurrentTime = localtime();
  146. my $year = $CurrentTime[5] + 1900;
  147. my $day = $CurrentTime[3];
  148. my $month = $CurrentTime[4] + 1;
  149. my $hour = $CurrentTime[2];
  150. my $min = $CurrentTime[1];
  151. my $sec = $CurrentTime[0];
  152. my $TimeString = sprintf("%02d%02d%02d", $hour, $min, $sec);
  153. my $DateString = sprintf("%d-%02d-%02d-%s-$$",
  154. $year, $month, $day, $TimeString);
  155. # Determine the run number.
  156. my $RunNumber;
  157. if (-d $Dir) {
  158. if (! -r $Dir) {
  159. DieDiag("directory '$Dir' exists but is not readable.\n");
  160. }
  161. # Iterate over all files in the specified directory.
  162. my $max = 0;
  163. opendir(DIR, $Dir);
  164. my @FILES = grep { -d "$Dir/$_" } readdir(DIR);
  165. closedir(DIR);
  166. foreach my $f (@FILES) {
  167. # Strip the prefix '$Prog-' if we are dumping files to /tmp.
  168. if ($TmpMode) {
  169. next if (!($f =~ /^$Prog-(.+)/));
  170. $f = $1;
  171. }
  172. my @x = split/-/, $f;
  173. next if (scalar(@x) != 4);
  174. next if ($x[0] != $year);
  175. next if ($x[1] != $month);
  176. next if ($x[2] != $day);
  177. next if ($x[3] != $TimeString);
  178. next if ($x[4] != $$);
  179. if ($x[5] > $max) {
  180. $max = $x[5];
  181. }
  182. }
  183. $RunNumber = $max + 1;
  184. }
  185. else {
  186. if (-x $Dir) {
  187. DieDiag("'$Dir' exists but is not a directory.\n");
  188. }
  189. if ($TmpMode) {
  190. DieDiag("The directory '/tmp' does not exist or cannot be accessed.\n");
  191. }
  192. # $Dir does not exist. It will be automatically created by the
  193. # clang driver. Set the run number to 1.
  194. $RunNumber = 1;
  195. }
  196. die "RunNumber must be defined!" if (!defined $RunNumber);
  197. # Append the run number.
  198. my $NewDir;
  199. if ($TmpMode) {
  200. $NewDir = "$Dir/$Prog-$DateString-$RunNumber";
  201. }
  202. else {
  203. $NewDir = "$Dir/$DateString-$RunNumber";
  204. }
  205. # Make sure that the directory does not exist in order to avoid hijack.
  206. if (-e $NewDir) {
  207. DieDiag("The directory '$NewDir' already exists.\n");
  208. }
  209. mkpath($NewDir);
  210. return $NewDir;
  211. }
  212. sub SetHtmlEnv {
  213. die "Wrong number of arguments." if (scalar(@_) != 2);
  214. my $Args = shift;
  215. my $Dir = shift;
  216. die "No build command." if (scalar(@$Args) == 0);
  217. my $Cmd = $$Args[0];
  218. if ($Cmd =~ /configure/ || $Cmd =~ /autogen/) {
  219. return;
  220. }
  221. if ($Options{Verbose}) {
  222. Diag("Emitting reports for this run to '$Dir'.\n");
  223. }
  224. $ENV{'CCC_ANALYZER_HTML'} = $Dir;
  225. }
  226. ##----------------------------------------------------------------------------##
  227. # ComputeDigest - Compute a digest of the specified file.
  228. ##----------------------------------------------------------------------------##
  229. sub ComputeDigest {
  230. my $FName = shift;
  231. DieDiag("Cannot read $FName to compute Digest.\n") if (! -r $FName);
  232. # Use Digest::MD5. We don't have to be cryptographically secure. We're
  233. # just looking for duplicate files that come from a non-malicious source.
  234. # We use Digest::MD5 because it is a standard Perl module that should
  235. # come bundled on most systems.
  236. open(FILE, $FName) or DieDiag("Cannot open $FName when computing Digest.\n");
  237. binmode FILE;
  238. my $Result = Digest::MD5->new->addfile(*FILE)->hexdigest;
  239. close(FILE);
  240. # Return the digest.
  241. return $Result;
  242. }
  243. ##----------------------------------------------------------------------------##
  244. # UpdatePrefix - Compute the common prefix of files.
  245. ##----------------------------------------------------------------------------##
  246. my $Prefix;
  247. sub UpdatePrefix {
  248. my $x = shift;
  249. my $y = basename($x);
  250. $x =~ s/\Q$y\E$//;
  251. if (!defined $Prefix) {
  252. $Prefix = $x;
  253. return;
  254. }
  255. chop $Prefix while (!($x =~ /^\Q$Prefix/));
  256. }
  257. sub GetPrefix {
  258. return $Prefix;
  259. }
  260. ##----------------------------------------------------------------------------##
  261. # UpdateInFilePath - Update the path in the report file.
  262. ##----------------------------------------------------------------------------##
  263. sub UpdateInFilePath {
  264. my $fname = shift;
  265. my $regex = shift;
  266. my $newtext = shift;
  267. open (RIN, $fname) or die "cannot open $fname";
  268. open (ROUT, ">", "$fname.tmp") or die "cannot open $fname.tmp";
  269. while (<RIN>) {
  270. s/$regex/$newtext/;
  271. print ROUT $_;
  272. }
  273. close (ROUT);
  274. close (RIN);
  275. rename("$fname.tmp", $fname)
  276. }
  277. ##----------------------------------------------------------------------------##
  278. # AddStatLine - Decode and insert a statistics line into the database.
  279. ##----------------------------------------------------------------------------##
  280. sub AddStatLine {
  281. my $Line = shift;
  282. my $Stats = shift;
  283. my $File = shift;
  284. print $Line . "\n";
  285. my $Regex = qr/(.*?)\ ->\ Total\ CFGBlocks:\ (\d+)\ \|\ Unreachable
  286. \ CFGBlocks:\ (\d+)\ \|\ Exhausted\ Block:\ (yes|no)\ \|\ Empty\ WorkList:
  287. \ (yes|no)/x;
  288. if ($Line !~ $Regex) {
  289. return;
  290. }
  291. # Create a hash of the interesting fields
  292. my $Row = {
  293. Filename => $File,
  294. Function => $1,
  295. Total => $2,
  296. Unreachable => $3,
  297. Aborted => $4,
  298. Empty => $5
  299. };
  300. # Add them to the stats array
  301. push @$Stats, $Row;
  302. }
  303. ##----------------------------------------------------------------------------##
  304. # ScanFile - Scan a report file for various identifying attributes.
  305. ##----------------------------------------------------------------------------##
  306. # Sometimes a source file is scanned more than once, and thus produces
  307. # multiple error reports. We use a cache to solve this problem.
  308. my %AlreadyScanned;
  309. sub ScanFile {
  310. my $Index = shift;
  311. my $Dir = shift;
  312. my $FName = shift;
  313. my $Stats = shift;
  314. # Compute a digest for the report file. Determine if we have already
  315. # scanned a file that looks just like it.
  316. my $digest = ComputeDigest("$Dir/$FName");
  317. if (defined $AlreadyScanned{$digest}) {
  318. # Redundant file. Remove it.
  319. unlink("$Dir/$FName");
  320. return;
  321. }
  322. $AlreadyScanned{$digest} = 1;
  323. # At this point the report file is not world readable. Make it happen.
  324. chmod(0644, "$Dir/$FName");
  325. # Scan the report file for tags.
  326. open(IN, "$Dir/$FName") or DieDiag("Cannot open '$Dir/$FName'\n");
  327. my $BugType = "";
  328. my $BugFile = "";
  329. my $BugFunction = "";
  330. my $BugCategory = "";
  331. my $BugDescription = "";
  332. my $BugPathLength = 1;
  333. my $BugLine = 0;
  334. while (<IN>) {
  335. last if (/<!-- BUGMETAEND -->/);
  336. if (/<!-- BUGTYPE (.*) -->$/) {
  337. $BugType = $1;
  338. }
  339. elsif (/<!-- BUGFILE (.*) -->$/) {
  340. $BugFile = abs_path($1);
  341. if (!defined $BugFile) {
  342. # The file no longer exists: use the original path.
  343. $BugFile = $1;
  344. }
  345. # Get just the path
  346. my $p = dirname($BugFile);
  347. # Check if the path is found in the list of exclude
  348. if (grep { $p =~ m/$_/ } @{$Options{Excludes}}) {
  349. if ($Options{Verbose}) {
  350. Diag("File '$BugFile' deleted: part of an ignored directory.\n");
  351. }
  352. # File in an ignored directory. Remove it
  353. unlink("$Dir/$FName");
  354. return;
  355. }
  356. UpdatePrefix($BugFile);
  357. }
  358. elsif (/<!-- BUGPATHLENGTH (.*) -->$/) {
  359. $BugPathLength = $1;
  360. }
  361. elsif (/<!-- BUGLINE (.*) -->$/) {
  362. $BugLine = $1;
  363. }
  364. elsif (/<!-- BUGCATEGORY (.*) -->$/) {
  365. $BugCategory = $1;
  366. }
  367. elsif (/<!-- BUGDESC (.*) -->$/) {
  368. $BugDescription = $1;
  369. }
  370. elsif (/<!-- FUNCTIONNAME (.*) -->$/) {
  371. $BugFunction = $1;
  372. }
  373. }
  374. close(IN);
  375. if (!defined $BugCategory) {
  376. $BugCategory = "Other";
  377. }
  378. # Don't add internal statistics to the bug reports
  379. if ($BugCategory =~ /statistics/i) {
  380. AddStatLine($BugDescription, $Stats, $BugFile);
  381. return;
  382. }
  383. push @$Index,[ $FName, $BugCategory, $BugType, $BugFile, $BugFunction, $BugLine,
  384. $BugPathLength ];
  385. if ($Options{ShowDescription}) {
  386. push @{ $Index->[-1] }, $BugDescription
  387. }
  388. }
  389. ##----------------------------------------------------------------------------##
  390. # CopyFiles - Copy resource files to target directory.
  391. ##----------------------------------------------------------------------------##
  392. sub CopyFiles {
  393. my $Dir = shift;
  394. my $JS = Cwd::realpath("$RealBin/../share/scan-build/sorttable.js");
  395. DieDiag("Cannot find 'sorttable.js'.\n")
  396. if (! -r $JS);
  397. copy($JS, "$Dir");
  398. DieDiag("Could not copy 'sorttable.js' to '$Dir'.\n")
  399. if (! -r "$Dir/sorttable.js");
  400. my $CSS = Cwd::realpath("$RealBin/../share/scan-build/scanview.css");
  401. DieDiag("Cannot find 'scanview.css'.\n")
  402. if (! -r $CSS);
  403. copy($CSS, "$Dir");
  404. DieDiag("Could not copy 'scanview.css' to '$Dir'.\n")
  405. if (! -r $CSS);
  406. }
  407. ##----------------------------------------------------------------------------##
  408. # CalcStats - Calculates visitation statistics and returns the string.
  409. ##----------------------------------------------------------------------------##
  410. sub CalcStats {
  411. my $Stats = shift;
  412. my $TotalBlocks = 0;
  413. my $UnreachedBlocks = 0;
  414. my $TotalFunctions = scalar(@$Stats);
  415. my $BlockAborted = 0;
  416. my $WorkListAborted = 0;
  417. my $Aborted = 0;
  418. # Calculate the unique files
  419. my $FilesHash = {};
  420. foreach my $Row (@$Stats) {
  421. $FilesHash->{$Row->{Filename}} = 1;
  422. $TotalBlocks += $Row->{Total};
  423. $UnreachedBlocks += $Row->{Unreachable};
  424. $BlockAborted++ if $Row->{Aborted} eq 'yes';
  425. $WorkListAborted++ if $Row->{Empty} eq 'no';
  426. $Aborted++ if $Row->{Aborted} eq 'yes' || $Row->{Empty} eq 'no';
  427. }
  428. my $TotalFiles = scalar(keys(%$FilesHash));
  429. # Calculations
  430. my $PercentAborted = sprintf("%.2f", $Aborted / $TotalFunctions * 100);
  431. my $PercentBlockAborted = sprintf("%.2f", $BlockAborted / $TotalFunctions
  432. * 100);
  433. my $PercentWorkListAborted = sprintf("%.2f", $WorkListAborted /
  434. $TotalFunctions * 100);
  435. my $PercentBlocksUnreached = sprintf("%.2f", $UnreachedBlocks / $TotalBlocks
  436. * 100);
  437. my $StatsString = "Analyzed $TotalBlocks blocks in $TotalFunctions functions"
  438. . " in $TotalFiles files\n"
  439. . "$Aborted functions aborted early ($PercentAborted%)\n"
  440. . "$BlockAborted had aborted blocks ($PercentBlockAborted%)\n"
  441. . "$WorkListAborted had unfinished worklists ($PercentWorkListAborted%)\n"
  442. . "$UnreachedBlocks blocks were never reached ($PercentBlocksUnreached%)\n";
  443. return $StatsString;
  444. }
  445. ##----------------------------------------------------------------------------##
  446. # Postprocess - Postprocess the results of an analysis scan.
  447. ##----------------------------------------------------------------------------##
  448. my @filesFound;
  449. my $baseDir;
  450. sub FileWanted {
  451. my $baseDirRegEx = quotemeta $baseDir;
  452. my $file = $File::Find::name;
  453. # The name of the file is generated by clang binary (HTMLDiagnostics.cpp)
  454. if ($file =~ /report-.*\.html$/) {
  455. my $relative_file = $file;
  456. $relative_file =~ s/$baseDirRegEx//g;
  457. push @filesFound, $relative_file;
  458. }
  459. }
  460. sub Postprocess {
  461. my $Dir = shift;
  462. my $BaseDir = shift;
  463. my $AnalyzerStats = shift;
  464. my $KeepEmpty = shift;
  465. die "No directory specified." if (!defined $Dir);
  466. if (! -d $Dir) {
  467. Diag("No bugs found.\n");
  468. return 0;
  469. }
  470. $baseDir = $Dir . "/";
  471. find({ wanted => \&FileWanted, follow => 0}, $Dir);
  472. if (scalar(@filesFound) == 0 and ! -e "$Dir/failures") {
  473. if (! $KeepEmpty) {
  474. Diag("Removing directory '$Dir' because it contains no reports.\n");
  475. rmtree($Dir) or die "Cannot rmtree '$Dir' : $!";
  476. }
  477. Diag("No bugs found.\n");
  478. return 0;
  479. }
  480. # Scan each report file and build an index.
  481. my @Index;
  482. my @Stats;
  483. foreach my $file (@filesFound) { ScanFile(\@Index, $Dir, $file, \@Stats); }
  484. # Scan the failures directory and use the information in the .info files
  485. # to update the common prefix directory.
  486. my @failures;
  487. my @attributes_ignored;
  488. if (-d "$Dir/failures") {
  489. opendir(DIR, "$Dir/failures");
  490. @failures = grep { /[.]info.txt$/ && !/attribute_ignored/; } readdir(DIR);
  491. closedir(DIR);
  492. opendir(DIR, "$Dir/failures");
  493. @attributes_ignored = grep { /^attribute_ignored/; } readdir(DIR);
  494. closedir(DIR);
  495. foreach my $file (@failures) {
  496. open IN, "$Dir/failures/$file" or DieDiag("cannot open $file\n");
  497. my $Path = <IN>;
  498. if (defined $Path) { UpdatePrefix($Path); }
  499. close IN;
  500. }
  501. }
  502. # Generate an index.html file.
  503. my $FName = "$Dir/index.html";
  504. open(OUT, ">", $FName) or DieDiag("Cannot create file '$FName'\n");
  505. # Print out the header.
  506. print OUT <<ENDTEXT;
  507. <html>
  508. <head>
  509. <title>${Options{HtmlTitle}}</title>
  510. <link type="text/css" rel="stylesheet" href="scanview.css"/>
  511. <script src="sorttable.js"></script>
  512. <script language='javascript' type="text/javascript">
  513. function SetDisplay(RowClass, DisplayVal)
  514. {
  515. var Rows = document.getElementsByTagName("tr");
  516. for ( var i = 0 ; i < Rows.length; ++i ) {
  517. if (Rows[i].className == RowClass) {
  518. Rows[i].style.display = DisplayVal;
  519. }
  520. }
  521. }
  522. function CopyCheckedStateToCheckButtons(SummaryCheckButton) {
  523. var Inputs = document.getElementsByTagName("input");
  524. for ( var i = 0 ; i < Inputs.length; ++i ) {
  525. if (Inputs[i].type == "checkbox") {
  526. if(Inputs[i] != SummaryCheckButton) {
  527. Inputs[i].checked = SummaryCheckButton.checked;
  528. Inputs[i].onclick();
  529. }
  530. }
  531. }
  532. }
  533. function returnObjById( id ) {
  534. if (document.getElementById)
  535. var returnVar = document.getElementById(id);
  536. else if (document.all)
  537. var returnVar = document.all[id];
  538. else if (document.layers)
  539. var returnVar = document.layers[id];
  540. return returnVar;
  541. }
  542. var NumUnchecked = 0;
  543. function ToggleDisplay(CheckButton, ClassName) {
  544. if (CheckButton.checked) {
  545. SetDisplay(ClassName, "");
  546. if (--NumUnchecked == 0) {
  547. returnObjById("AllBugsCheck").checked = true;
  548. }
  549. }
  550. else {
  551. SetDisplay(ClassName, "none");
  552. NumUnchecked++;
  553. returnObjById("AllBugsCheck").checked = false;
  554. }
  555. }
  556. </script>
  557. <!-- SUMMARYENDHEAD -->
  558. </head>
  559. <body>
  560. <h1>${Options{HtmlTitle}}</h1>
  561. <table>
  562. <tr><th>User:</th><td>${UserName}\@${HostName}</td></tr>
  563. <tr><th>Working Directory:</th><td>${CurrentDir}</td></tr>
  564. <tr><th>Command Line:</th><td>${CmdArgs}</td></tr>
  565. <tr><th>Clang Version:</th><td>${ClangVersion}</td></tr>
  566. <tr><th>Date:</th><td>${Date}</td></tr>
  567. ENDTEXT
  568. print OUT "<tr><th>Version:</th><td>${BuildName} (${BuildDate})</td></tr>\n"
  569. if (defined($BuildName) && defined($BuildDate));
  570. print OUT <<ENDTEXT;
  571. </table>
  572. ENDTEXT
  573. if (scalar(@filesFound)) {
  574. # Print out the summary table.
  575. my %Totals;
  576. for my $row ( @Index ) {
  577. my $bug_type = ($row->[2]);
  578. my $bug_category = ($row->[1]);
  579. my $key = "$bug_category:$bug_type";
  580. if (!defined $Totals{$key}) { $Totals{$key} = [1,$bug_category,$bug_type]; }
  581. else { $Totals{$key}->[0]++; }
  582. }
  583. print OUT "<h2>Bug Summary</h2>";
  584. if (defined $BuildName) {
  585. print OUT "\n<p>Results in this analysis run are based on analyzer build <b>$BuildName</b>.</p>\n"
  586. }
  587. my $TotalBugs = scalar(@Index);
  588. print OUT <<ENDTEXT;
  589. <table>
  590. <thead><tr><td>Bug Type</td><td>Quantity</td><td class="sorttable_nosort">Display?</td></tr></thead>
  591. <tr style="font-weight:bold"><td class="SUMM_DESC">All Bugs</td><td class="Q">$TotalBugs</td><td><center><input type="checkbox" id="AllBugsCheck" onClick="CopyCheckedStateToCheckButtons(this);" checked/></center></td></tr>
  592. ENDTEXT
  593. my $last_category;
  594. for my $key (
  595. sort {
  596. my $x = $Totals{$a};
  597. my $y = $Totals{$b};
  598. my $res = $x->[1] cmp $y->[1];
  599. $res = $x->[2] cmp $y->[2] if ($res == 0);
  600. $res
  601. } keys %Totals )
  602. {
  603. my $val = $Totals{$key};
  604. my $category = $val->[1];
  605. if (!defined $last_category or $last_category ne $category) {
  606. $last_category = $category;
  607. print OUT "<tr><th>$category</th><th colspan=2></th></tr>\n";
  608. }
  609. my $x = lc $key;
  610. $x =~ s/[ ,'":\/()]+/_/g;
  611. print OUT "<tr><td class=\"SUMM_DESC\">";
  612. print OUT $val->[2];
  613. print OUT "</td><td class=\"Q\">";
  614. print OUT $val->[0];
  615. print OUT "</td><td><center><input type=\"checkbox\" onClick=\"ToggleDisplay(this,'bt_$x');\" checked/></center></td></tr>\n";
  616. }
  617. # Print out the table of errors.
  618. print OUT <<ENDTEXT;
  619. </table>
  620. <h2>Reports</h2>
  621. <table class="sortable" style="table-layout:automatic">
  622. <thead><tr>
  623. <td>Bug Group</td>
  624. <td class="sorttable_sorted">Bug Type<span id="sorttable_sortfwdind">&nbsp;&#x25BE;</span></td>
  625. <td>File</td>
  626. <td>Function/Method</td>
  627. <td class="Q">Line</td>
  628. <td class="Q">Path Length</td>
  629. ENDTEXT
  630. if ($Options{ShowDescription}) {
  631. print OUT <<ENDTEXT;
  632. <td class="Q">Description</td>
  633. ENDTEXT
  634. }
  635. print OUT <<ENDTEXT;
  636. <td class="sorttable_nosort"></td>
  637. <!-- REPORTBUGCOL -->
  638. </tr></thead>
  639. <tbody>
  640. ENDTEXT
  641. my $prefix = GetPrefix();
  642. my $regex;
  643. my $InFileRegex;
  644. my $InFilePrefix = "File:</td><td>";
  645. if (defined $prefix) {
  646. $regex = qr/^\Q$prefix\E/is;
  647. $InFileRegex = qr/\Q$InFilePrefix$prefix\E/is;
  648. }
  649. for my $row ( sort { $a->[2] cmp $b->[2] } @Index ) {
  650. my $x = "$row->[1]:$row->[2]";
  651. $x = lc $x;
  652. $x =~ s/[ ,'":\/()]+/_/g;
  653. my $ReportFile = $row->[0];
  654. print OUT "<tr class=\"bt_$x\">";
  655. print OUT "<td class=\"DESC\">";
  656. print OUT $row->[1]; # $BugCategory
  657. print OUT "</td>";
  658. print OUT "<td class=\"DESC\">";
  659. print OUT $row->[2]; # $BugType
  660. print OUT "</td>";
  661. # Update the file prefix.
  662. my $fname = $row->[3];
  663. if (defined $regex) {
  664. $fname =~ s/$regex//;
  665. UpdateInFilePath("$Dir/$ReportFile", $InFileRegex, $InFilePrefix)
  666. }
  667. print OUT "<td>";
  668. my @fname = split /\//,$fname;
  669. if ($#fname > 0) {
  670. while ($#fname >= 0) {
  671. my $x = shift @fname;
  672. print OUT $x;
  673. if ($#fname >= 0) {
  674. print OUT "/";
  675. }
  676. }
  677. }
  678. else {
  679. print OUT $fname;
  680. }
  681. print OUT "</td>";
  682. print OUT "<td class=\"DESC\">";
  683. print OUT $row->[4]; # Function
  684. print OUT "</td>";
  685. # Print out the quantities.
  686. for my $j ( 5 .. 6 ) { # Line & Path length
  687. print OUT "<td class=\"Q\">$row->[$j]</td>";
  688. }
  689. # Print the rest of the columns.
  690. for (my $j = 7; $j <= $#{$row}; ++$j) {
  691. print OUT "<td>$row->[$j]</td>"
  692. }
  693. # Emit the "View" link.
  694. print OUT "<td><a href=\"$ReportFile#EndPath\">View Report</a></td>";
  695. # Emit REPORTBUG markers.
  696. print OUT "\n<!-- REPORTBUG id=\"$ReportFile\" -->\n";
  697. # End the row.
  698. print OUT "</tr>\n";
  699. }
  700. print OUT "</tbody>\n</table>\n\n";
  701. }
  702. if (scalar (@failures) || scalar(@attributes_ignored)) {
  703. print OUT "<h2>Analyzer Failures</h2>\n";
  704. if (scalar @attributes_ignored) {
  705. print OUT "The analyzer's parser ignored the following attributes:<p>\n";
  706. print OUT "<table>\n";
  707. print OUT "<thead><tr><td>Attribute</td><td>Source File</td><td>Preprocessed File</td><td>STDERR Output</td></tr></thead>\n";
  708. foreach my $file (sort @attributes_ignored) {
  709. die "cannot demangle attribute name\n" if (! ($file =~ /^attribute_ignored_(.+).txt/));
  710. my $attribute = $1;
  711. # Open the attribute file to get the first file that failed.
  712. next if (!open (ATTR, "$Dir/failures/$file"));
  713. my $ppfile = <ATTR>;
  714. chomp $ppfile;
  715. close ATTR;
  716. next if (! -e "$Dir/failures/$ppfile");
  717. # Open the info file and get the name of the source file.
  718. open (INFO, "$Dir/failures/$ppfile.info.txt") or
  719. die "Cannot open $Dir/failures/$ppfile.info.txt\n";
  720. my $srcfile = <INFO>;
  721. chomp $srcfile;
  722. close (INFO);
  723. # Print the information in the table.
  724. my $prefix = GetPrefix();
  725. if (defined $prefix) { $srcfile =~ s/^\Q$prefix//; }
  726. print OUT "<tr><td>$attribute</td><td>$srcfile</td><td><a href=\"failures/$ppfile\">$ppfile</a></td><td><a href=\"failures/$ppfile.stderr.txt\">$ppfile.stderr.txt</a></td></tr>\n";
  727. my $ppfile_clang = $ppfile;
  728. $ppfile_clang =~ s/[.](.+)$/.clang.$1/;
  729. print OUT " <!-- REPORTPROBLEM src=\"$srcfile\" file=\"failures/$ppfile\" clangfile=\"failures/$ppfile_clang\" stderr=\"failures/$ppfile.stderr.txt\" info=\"failures/$ppfile.info.txt\" -->\n";
  730. }
  731. print OUT "</table>\n";
  732. }
  733. if (scalar @failures) {
  734. print OUT "<p>The analyzer had problems processing the following files:</p>\n";
  735. print OUT "<table>\n";
  736. print OUT "<thead><tr><td>Problem</td><td>Source File</td><td>Preprocessed File</td><td>STDERR Output</td></tr></thead>\n";
  737. foreach my $file (sort @failures) {
  738. $file =~ /(.+).info.txt$/;
  739. # Get the preprocessed file.
  740. my $ppfile = $1;
  741. # Open the info file and get the name of the source file.
  742. open (INFO, "$Dir/failures/$file") or
  743. die "Cannot open $Dir/failures/$file\n";
  744. my $srcfile = <INFO>;
  745. chomp $srcfile;
  746. my $problem = <INFO>;
  747. chomp $problem;
  748. close (INFO);
  749. # Print the information in the table.
  750. my $prefix = GetPrefix();
  751. if (defined $prefix) { $srcfile =~ s/^\Q$prefix//; }
  752. print OUT "<tr><td>$problem</td><td>$srcfile</td><td><a href=\"failures/$ppfile\">$ppfile</a></td><td><a href=\"failures/$ppfile.stderr.txt\">$ppfile.stderr.txt</a></td></tr>\n";
  753. my $ppfile_clang = $ppfile;
  754. $ppfile_clang =~ s/[.](.+)$/.clang.$1/;
  755. print OUT " <!-- REPORTPROBLEM src=\"$srcfile\" file=\"failures/$ppfile\" clangfile=\"failures/$ppfile_clang\" stderr=\"failures/$ppfile.stderr.txt\" info=\"failures/$ppfile.info.txt\" -->\n";
  756. }
  757. print OUT "</table>\n";
  758. }
  759. print OUT "<p>Please consider submitting preprocessed files as <a href=\"http://clang-analyzer.llvm.org/filing_bugs.html\">bug reports</a>. <!-- REPORTCRASHES --> </p>\n";
  760. }
  761. print OUT "</body></html>\n";
  762. close(OUT);
  763. CopyFiles($Dir);
  764. # Make sure $Dir and $BaseDir are world readable/executable.
  765. chmod(0755, $Dir);
  766. if (defined $BaseDir) { chmod(0755, $BaseDir); }
  767. # Print statistics
  768. print CalcStats(\@Stats) if $AnalyzerStats;
  769. my $Num = scalar(@Index);
  770. if ($Num == 1) {
  771. Diag("$Num bug found.\n");
  772. } else {
  773. Diag("$Num bugs found.\n");
  774. }
  775. if ($Num > 0 && -r "$Dir/index.html") {
  776. Diag("Run 'scan-view $Dir' to examine bug reports.\n");
  777. }
  778. DiagCrashes($Dir) if (scalar @failures || scalar @attributes_ignored);
  779. return $Num;
  780. }
  781. ##----------------------------------------------------------------------------##
  782. # RunBuildCommand - Run the build command.
  783. ##----------------------------------------------------------------------------##
  784. sub AddIfNotPresent {
  785. my $Args = shift;
  786. my $Arg = shift;
  787. my $found = 0;
  788. foreach my $k (@$Args) {
  789. if ($k eq $Arg) {
  790. $found = 1;
  791. last;
  792. }
  793. }
  794. if ($found == 0) {
  795. push @$Args, $Arg;
  796. }
  797. }
  798. sub SetEnv {
  799. my $EnvVars = shift @_;
  800. foreach my $var ('CC', 'CXX', 'CLANG', 'CLANG_CXX',
  801. 'CCC_ANALYZER_ANALYSIS', 'CCC_ANALYZER_PLUGINS',
  802. 'CCC_ANALYZER_CONFIG') {
  803. die "$var is undefined\n" if (!defined $var);
  804. $ENV{$var} = $EnvVars->{$var};
  805. }
  806. foreach my $var ('CCC_ANALYZER_STORE_MODEL',
  807. 'CCC_ANALYZER_CONSTRAINTS_MODEL',
  808. 'CCC_ANALYZER_INTERNAL_STATS',
  809. 'CCC_ANALYZER_OUTPUT_FORMAT',
  810. 'CCC_CC',
  811. 'CCC_CXX',
  812. 'CCC_REPORT_FAILURES',
  813. 'CLANG_ANALYZER_TARGET',
  814. 'CCC_ANALYZER_FORCE_ANALYZE_DEBUG_CODE') {
  815. my $x = $EnvVars->{$var};
  816. if (defined $x) { $ENV{$var} = $x }
  817. }
  818. my $Verbose = $EnvVars->{'VERBOSE'};
  819. if ($Verbose >= 2) {
  820. $ENV{'CCC_ANALYZER_VERBOSE'} = 1;
  821. }
  822. if ($Verbose >= 3) {
  823. $ENV{'CCC_ANALYZER_LOG'} = 1;
  824. }
  825. }
  826. sub RunXcodebuild {
  827. my $Args = shift;
  828. my $IgnoreErrors = shift;
  829. my $CCAnalyzer = shift;
  830. my $CXXAnalyzer = shift;
  831. my $EnvVars = shift;
  832. if ($IgnoreErrors) {
  833. AddIfNotPresent($Args,"-PBXBuildsContinueAfterErrors=YES");
  834. }
  835. # Detect the version of Xcode. If Xcode 4.6 or higher, use new
  836. # in situ support for analyzer interposition without needed to override
  837. # the compiler.
  838. open(DETECT_XCODE, "-|", $Args->[0], "-version") or
  839. die "error: cannot detect version of xcodebuild\n";
  840. my $oldBehavior = 1;
  841. while(<DETECT_XCODE>) {
  842. if (/^Xcode (.+)$/) {
  843. my $ver = $1;
  844. if ($ver =~ /^([0-9]+[.][0-9]+)[^0-9]?/) {
  845. if ($1 >= 4.6) {
  846. $oldBehavior = 0;
  847. last;
  848. }
  849. }
  850. }
  851. }
  852. close(DETECT_XCODE);
  853. # If --override-compiler is explicitly requested, resort to the old
  854. # behavior regardless of Xcode version.
  855. if ($Options{OverrideCompiler}) {
  856. $oldBehavior = 1;
  857. }
  858. if ($oldBehavior == 0) {
  859. my $OutputDir = $EnvVars->{"OUTPUT_DIR"};
  860. my $CLANG = $EnvVars->{"CLANG"};
  861. my $OtherFlags = $EnvVars->{"CCC_ANALYZER_ANALYSIS"};
  862. push @$Args,
  863. "RUN_CLANG_STATIC_ANALYZER=YES",
  864. "CLANG_ANALYZER_OUTPUT=plist-html",
  865. "CLANG_ANALYZER_EXEC=$CLANG",
  866. "CLANG_ANALYZER_OUTPUT_DIR=$OutputDir",
  867. "CLANG_ANALYZER_OTHER_FLAGS=$OtherFlags";
  868. return (system(@$Args) >> 8);
  869. }
  870. # Default to old behavior where we insert a bogus compiler.
  871. SetEnv($EnvVars);
  872. # Check if using iPhone SDK 3.0 (simulator). If so the compiler being
  873. # used should be gcc-4.2.
  874. if (!defined $ENV{"CCC_CC"}) {
  875. for (my $i = 0 ; $i < scalar(@$Args); ++$i) {
  876. if ($Args->[$i] eq "-sdk" && $i + 1 < scalar(@$Args)) {
  877. if (@$Args[$i+1] =~ /^iphonesimulator3/) {
  878. $ENV{"CCC_CC"} = "gcc-4.2";
  879. $ENV{"CCC_CXX"} = "g++-4.2";
  880. }
  881. }
  882. }
  883. }
  884. # Disable PCH files until clang supports them.
  885. AddIfNotPresent($Args,"GCC_PRECOMPILE_PREFIX_HEADER=NO");
  886. # When 'CC' is set, xcodebuild uses it to do all linking, even if we are
  887. # linking C++ object files. Set 'LDPLUSPLUS' so that xcodebuild uses 'g++'
  888. # (via c++-analyzer) when linking such files.
  889. $ENV{"LDPLUSPLUS"} = $CXXAnalyzer;
  890. return (system(@$Args) >> 8);
  891. }
  892. sub RunBuildCommand {
  893. my $Args = shift;
  894. my $IgnoreErrors = shift;
  895. my $KeepCC = shift;
  896. my $Cmd = $Args->[0];
  897. my $CCAnalyzer = shift;
  898. my $CXXAnalyzer = shift;
  899. my $EnvVars = shift;
  900. if ($Cmd =~ /\bxcodebuild$/) {
  901. return RunXcodebuild($Args, $IgnoreErrors, $CCAnalyzer, $CXXAnalyzer, $EnvVars);
  902. }
  903. # Setup the environment.
  904. SetEnv($EnvVars);
  905. if ($Cmd =~ /(.*\/?gcc[^\/]*$)/ or
  906. $Cmd =~ /(.*\/?cc[^\/]*$)/ or
  907. $Cmd =~ /(.*\/?llvm-gcc[^\/]*$)/ or
  908. $Cmd =~ /(.*\/?clang[^\/]*$)/ or
  909. $Cmd =~ /(.*\/?ccc-analyzer[^\/]*$)/) {
  910. if (!($Cmd =~ /ccc-analyzer/) and !defined $ENV{"CCC_CC"}) {
  911. $ENV{"CCC_CC"} = $1;
  912. }
  913. shift @$Args;
  914. unshift @$Args, $CCAnalyzer;
  915. }
  916. elsif ($Cmd =~ /(.*\/?g\+\+[^\/]*$)/ or
  917. $Cmd =~ /(.*\/?c\+\+[^\/]*$)/ or
  918. $Cmd =~ /(.*\/?llvm-g\+\+[^\/]*$)/ or
  919. $Cmd =~ /(.*\/?clang\+\+$)/ or
  920. $Cmd =~ /(.*\/?c\+\+-analyzer[^\/]*$)/) {
  921. if (!($Cmd =~ /c\+\+-analyzer/) and !defined $ENV{"CCC_CXX"}) {
  922. $ENV{"CCC_CXX"} = $1;
  923. }
  924. shift @$Args;
  925. unshift @$Args, $CXXAnalyzer;
  926. }
  927. elsif ($Cmd eq "make" or $Cmd eq "gmake" or $Cmd eq "mingw32-make") {
  928. if (!$KeepCC) {
  929. AddIfNotPresent($Args, "CC=$CCAnalyzer");
  930. AddIfNotPresent($Args, "CXX=$CXXAnalyzer");
  931. }
  932. if ($IgnoreErrors) {
  933. AddIfNotPresent($Args,"-k");
  934. AddIfNotPresent($Args,"-i");
  935. }
  936. }
  937. return (system(@$Args) >> 8);
  938. }
  939. ##----------------------------------------------------------------------------##
  940. # DisplayHelp - Utility function to display all help options.
  941. ##----------------------------------------------------------------------------##
  942. sub DisplayHelp {
  943. my $ArgClangNotFoundErrMsg = shift;
  944. print <<ENDTEXT;
  945. USAGE: $Prog [options] <build command> [build options]
  946. ENDTEXT
  947. if (defined $BuildName) {
  948. print "ANALYZER BUILD: $BuildName ($BuildDate)\n\n";
  949. }
  950. print <<ENDTEXT;
  951. OPTIONS:
  952. -analyze-headers
  953. Also analyze functions in #included files. By default, such functions
  954. are skipped unless they are called by functions within the main source file.
  955. --force-analyze-debug-code
  956. Tells analyzer to enable assertions in code even if they were disabled
  957. during compilation to enable more precise results.
  958. -o <output location>
  959. Specifies the output directory for analyzer reports. Subdirectories will be
  960. created as needed to represent separate "runs" of the analyzer. If this
  961. option is not specified, a directory is created in /tmp (TMPDIR on Mac OS X)
  962. to store the reports.
  963. -h
  964. --help
  965. Display this message.
  966. -k
  967. --keep-going
  968. Add a "keep on going" option to the specified build command. This option
  969. currently supports make and xcodebuild. This is a convenience option; one
  970. can specify this behavior directly using build options.
  971. --keep-cc
  972. Do not override CC and CXX make variables. Useful when running make in
  973. autoconf-based (and similar) projects where configure can add extra flags
  974. to those variables.
  975. --html-title [title]
  976. --html-title=[title]
  977. Specify the title used on generated HTML pages. If not specified, a default
  978. title will be used.
  979. --show-description
  980. Display the description of defects in the list
  981. -plist
  982. By default the output of scan-build is a set of HTML files. This option
  983. outputs the results as a set of .plist files.
  984. -plist-html
  985. By default the output of scan-build is a set of HTML files. This option
  986. outputs the results as a set of HTML and .plist files.
  987. --status-bugs
  988. By default, the exit status of scan-build is the same as the executed build
  989. command. Specifying this option causes the exit status of scan-build to be 1
  990. if it found potential bugs and the exit status of the build itself otherwise.
  991. --exclude <path>
  992. Do not run static analyzer against files found in this
  993. directory (You can specify this option multiple times).
  994. Could be useful when project contains 3rd party libraries.
  995. --use-cc [compiler path]
  996. --use-cc=[compiler path]
  997. scan-build analyzes a project by interposing a "fake compiler", which
  998. executes a real compiler for compilation and the static analyzer for analysis.
  999. Because of the current implementation of interposition, scan-build does not
  1000. know what compiler your project normally uses. Instead, it simply overrides
  1001. the CC environment variable, and guesses your default compiler.
  1002. In the future, this interposition mechanism to be improved, but if you need
  1003. scan-build to use a specific compiler for *compilation* then you can use
  1004. this option to specify a path to that compiler.
  1005. If the given compiler is a cross compiler, you may also need to provide
  1006. --analyzer-target option to properly analyze the source code because static
  1007. analyzer runs as if the code is compiled for the host machine by default.
  1008. --use-c++ [compiler path]
  1009. --use-c++=[compiler path]
  1010. This is the same as "--use-cc" but for C++ code.
  1011. --analyzer-target [target triple name for analysis]
  1012. --analyzer-target=[target triple name for analysis]
  1013. This provides target triple information to clang static analyzer.
  1014. It only changes the target for analysis but doesn't change the target of a
  1015. real compiler given by --use-cc and --use-c++ options.
  1016. -v
  1017. Enable verbose output from scan-build. A second and third '-v' increases
  1018. verbosity.
  1019. -V
  1020. --view
  1021. View analysis results in a web browser when the build completes.
  1022. ADVANCED OPTIONS:
  1023. -no-failure-reports
  1024. Do not create a 'failures' subdirectory that includes analyzer crash reports
  1025. and preprocessed source files.
  1026. -stats
  1027. Generates visitation statistics for the project being analyzed.
  1028. -maxloop <loop count>
  1029. Specify the number of times a block can be visited before giving up.
  1030. Default is 4. Increase for more comprehensive coverage at a cost of speed.
  1031. -internal-stats
  1032. Generate internal analyzer statistics.
  1033. --use-analyzer [Xcode|path to clang]
  1034. --use-analyzer=[Xcode|path to clang]
  1035. scan-build uses the 'clang' executable relative to itself for static
  1036. analysis. One can override this behavior with this option by using the
  1037. 'clang' packaged with Xcode (on OS X) or from the PATH.
  1038. --keep-empty
  1039. Don't remove the build results directory even if no issues were reported.
  1040. --override-compiler
  1041. Always resort to the ccc-analyzer even when better interposition methods
  1042. are available.
  1043. -analyzer-config <options>
  1044. Provide options to pass through to the analyzer's -analyzer-config flag.
  1045. Several options are separated with comma: 'key1=val1,key2=val2'
  1046. Available options:
  1047. * stable-report-filename=true or false (default)
  1048. Switch the page naming to:
  1049. report-<filename>-<function/method name>-<id>.html
  1050. instead of report-XXXXXX.html
  1051. CONTROLLING CHECKERS:
  1052. A default group of checkers are always run unless explicitly disabled.
  1053. Checkers may be enabled/disabled using the following options:
  1054. -enable-checker [checker name]
  1055. -disable-checker [checker name]
  1056. LOADING CHECKERS:
  1057. Loading external checkers using the clang plugin interface:
  1058. -load-plugin [plugin library]
  1059. ENDTEXT
  1060. if (defined $Clang && -x $Clang) {
  1061. # Query clang for list of checkers that are enabled.
  1062. # create a list to load the plugins via the 'Xclang' command line
  1063. # argument
  1064. my @PluginLoadCommandline_xclang;
  1065. foreach my $param ( @{$Options{PluginsToLoad}} ) {
  1066. push ( @PluginLoadCommandline_xclang, "-Xclang" );
  1067. push ( @PluginLoadCommandline_xclang, "-load" );
  1068. push ( @PluginLoadCommandline_xclang, "-Xclang" );
  1069. push ( @PluginLoadCommandline_xclang, $param );
  1070. }
  1071. my %EnabledCheckers;
  1072. foreach my $lang ("c", "objective-c", "objective-c++", "c++") {
  1073. my $ExecLine = join(' ', qq/"$Clang"/, @PluginLoadCommandline_xclang, "--analyze", "-x", $lang, "-", "-###", "2>&1", "|");
  1074. open(PS, $ExecLine);
  1075. while (<PS>) {
  1076. foreach my $val (split /\s+/) {
  1077. $val =~ s/\"//g;
  1078. if ($val =~ /-analyzer-checker\=([^\s]+)/) {
  1079. $EnabledCheckers{$1} = 1;
  1080. }
  1081. }
  1082. }
  1083. }
  1084. # Query clang for complete list of checkers.
  1085. my @PluginLoadCommandline;
  1086. foreach my $param ( @{$Options{PluginsToLoad}} ) {
  1087. push ( @PluginLoadCommandline, "-load" );
  1088. push ( @PluginLoadCommandline, $param );
  1089. }
  1090. my $ExecLine = join(' ', qq/"$Clang"/, "-cc1", @PluginLoadCommandline, "-analyzer-checker-help", "2>&1", "|");
  1091. open(PS, $ExecLine);
  1092. my $foundCheckers = 0;
  1093. while (<PS>) {
  1094. if (/CHECKERS:/) {
  1095. $foundCheckers = 1;
  1096. last;
  1097. }
  1098. }
  1099. if (!$foundCheckers) {
  1100. print " *** Could not query Clang for the list of available checkers.";
  1101. }
  1102. else {
  1103. print("\nAVAILABLE CHECKERS:\n\n");
  1104. my $skip = 0;
  1105. while(<PS>) {
  1106. if (/experimental/) {
  1107. $skip = 1;
  1108. next;
  1109. }
  1110. if ($skip) {
  1111. next if (!/^\s\s[^\s]/);
  1112. $skip = 0;
  1113. }
  1114. s/^\s\s//;
  1115. if (/^([^\s]+)/) {
  1116. # Is the checker enabled?
  1117. my $checker = $1;
  1118. my $enabled = 0;
  1119. my $aggregate = "";
  1120. foreach my $domain (split /\./, $checker) {
  1121. $aggregate .= $domain;
  1122. if ($EnabledCheckers{$aggregate}) {
  1123. $enabled =1;
  1124. last;
  1125. }
  1126. # append a dot, if an additional domain is added in the next iteration
  1127. $aggregate .= ".";
  1128. }
  1129. if ($enabled) {
  1130. print " + ";
  1131. }
  1132. else {
  1133. print " ";
  1134. }
  1135. }
  1136. else {
  1137. print " ";
  1138. }
  1139. print $_;
  1140. }
  1141. print "\nNOTE: \"+\" indicates that an analysis is enabled by default.\n";
  1142. }
  1143. close PS;
  1144. }
  1145. else {
  1146. print " *** Could not query Clang for the list of available checkers.\n";
  1147. if (defined $ArgClangNotFoundErrMsg) {
  1148. print " *** Reason: $ArgClangNotFoundErrMsg\n";
  1149. }
  1150. }
  1151. print <<ENDTEXT
  1152. BUILD OPTIONS
  1153. You can specify any build option acceptable to the build command.
  1154. EXAMPLE
  1155. scan-build -o /tmp/myhtmldir make -j4
  1156. The above example causes analysis reports to be deposited into a subdirectory
  1157. of "/tmp/myhtmldir" and to run "make" with the "-j4" option. A different
  1158. subdirectory is created each time scan-build analyzes a project. The analyzer
  1159. should support most parallel builds, but not distributed builds.
  1160. ENDTEXT
  1161. }
  1162. ##----------------------------------------------------------------------------##
  1163. # HtmlEscape - HTML entity encode characters that are special in HTML
  1164. ##----------------------------------------------------------------------------##
  1165. sub HtmlEscape {
  1166. # copy argument to new variable so we don't clobber the original
  1167. my $arg = shift || '';
  1168. my $tmp = $arg;
  1169. $tmp =~ s/&/&amp;/g;
  1170. $tmp =~ s/</&lt;/g;
  1171. $tmp =~ s/>/&gt;/g;
  1172. return $tmp;
  1173. }
  1174. ##----------------------------------------------------------------------------##
  1175. # ShellEscape - backslash escape characters that are special to the shell
  1176. ##----------------------------------------------------------------------------##
  1177. sub ShellEscape {
  1178. # copy argument to new variable so we don't clobber the original
  1179. my $arg = shift || '';
  1180. if ($arg =~ /["\s]/) { return "'" . $arg . "'"; }
  1181. return $arg;
  1182. }
  1183. ##----------------------------------------------------------------------------##
  1184. # FindClang - searches for 'clang' executable.
  1185. ##----------------------------------------------------------------------------##
  1186. sub FindClang {
  1187. if (!defined $Options{AnalyzerDiscoveryMethod}) {
  1188. $Clang = Cwd::realpath("$RealBin/bin/clang") if (-f "$RealBin/bin/clang");
  1189. if (!defined $Clang || ! -x $Clang) {
  1190. $Clang = Cwd::realpath("$RealBin/clang") if (-f "$RealBin/clang");
  1191. }
  1192. if (!defined $Clang || ! -x $Clang) {
  1193. $Clang = Cwd::realpath("$RealBin/hexagon-clang");
  1194. }
  1195. if (!defined $Clang || ! -x $Clang) {
  1196. return "error: Cannot find an executable 'clang' relative to" .
  1197. " scan-build. Consider using --use-analyzer to pick a version of" .
  1198. " 'clang' to use for static analysis.\n";
  1199. }
  1200. }
  1201. else {
  1202. if ($Options{AnalyzerDiscoveryMethod} =~ /^[Xx]code$/) {
  1203. my $xcrun = `which xcrun`;
  1204. chomp $xcrun;
  1205. if ($xcrun eq "") {
  1206. return "Cannot find 'xcrun' to find 'clang' for analysis.\n";
  1207. }
  1208. $Clang = `$xcrun -toolchain XcodeDefault -find clang`;
  1209. chomp $Clang;
  1210. if ($Clang eq "") {
  1211. return "No 'clang' executable found by 'xcrun'\n";
  1212. }
  1213. }
  1214. else {
  1215. $Clang = $Options{AnalyzerDiscoveryMethod};
  1216. if (!defined $Clang or not -x $Clang) {
  1217. return "Cannot find an executable clang at '$Options{AnalyzerDiscoveryMethod}'\n";
  1218. }
  1219. }
  1220. }
  1221. return undef;
  1222. }
  1223. ##----------------------------------------------------------------------------##
  1224. # Process command-line arguments.
  1225. ##----------------------------------------------------------------------------##
  1226. my $RequestDisplayHelp = 0;
  1227. my $ForceDisplayHelp = 0;
  1228. sub ProcessArgs {
  1229. my $Args = shift;
  1230. my $NumArgs = 0;
  1231. while (@$Args) {
  1232. $NumArgs++;
  1233. # Scan for options we recognize.
  1234. my $arg = $Args->[0];
  1235. if ($arg eq "-h" or $arg eq "--help") {
  1236. $RequestDisplayHelp = 1;
  1237. shift @$Args;
  1238. next;
  1239. }
  1240. if ($arg eq '-analyze-headers') {
  1241. shift @$Args;
  1242. $Options{AnalyzeHeaders} = 1;
  1243. next;
  1244. }
  1245. if ($arg eq "-o") {
  1246. shift @$Args;
  1247. if (!@$Args) {
  1248. DieDiag("'-o' option requires a target directory name.\n");
  1249. }
  1250. # Construct an absolute path. Uses the current working directory
  1251. # as a base if the original path was not absolute.
  1252. my $OutDir = shift @$Args;
  1253. mkpath($OutDir) unless (-e $OutDir); # abs_path wants existing dir
  1254. $Options{OutputDir} = abs_path($OutDir);
  1255. next;
  1256. }
  1257. if ($arg =~ /^--html-title(=(.+))?$/) {
  1258. shift @$Args;
  1259. if (!defined $2 || $2 eq '') {
  1260. if (!@$Args) {
  1261. DieDiag("'--html-title' option requires a string.\n");
  1262. }
  1263. $Options{HtmlTitle} = shift @$Args;
  1264. } else {
  1265. $Options{HtmlTitle} = $2;
  1266. }
  1267. next;
  1268. }
  1269. if ($arg eq "-k" or $arg eq "--keep-going") {
  1270. shift @$Args;
  1271. $Options{IgnoreErrors} = 1;
  1272. next;
  1273. }
  1274. if ($arg eq "--keep-cc") {
  1275. shift @$Args;
  1276. $Options{KeepCC} = 1;
  1277. next;
  1278. }
  1279. if ($arg =~ /^--use-cc(=(.+))?$/) {
  1280. shift @$Args;
  1281. my $cc;
  1282. if (!defined $2 || $2 eq "") {
  1283. if (!@$Args) {
  1284. DieDiag("'--use-cc' option requires a compiler executable name.\n");
  1285. }
  1286. $cc = shift @$Args;
  1287. }
  1288. else {
  1289. $cc = $2;
  1290. }
  1291. $Options{UseCC} = $cc;
  1292. next;
  1293. }
  1294. if ($arg =~ /^--use-c\+\+(=(.+))?$/) {
  1295. shift @$Args;
  1296. my $cxx;
  1297. if (!defined $2 || $2 eq "") {
  1298. if (!@$Args) {
  1299. DieDiag("'--use-c++' option requires a compiler executable name.\n");
  1300. }
  1301. $cxx = shift @$Args;
  1302. }
  1303. else {
  1304. $cxx = $2;
  1305. }
  1306. $Options{UseCXX} = $cxx;
  1307. next;
  1308. }
  1309. if ($arg =~ /^--analyzer-target(=(.+))?$/) {
  1310. shift @ARGV;
  1311. my $AnalyzerTarget;
  1312. if (!defined $2 || $2 eq "") {
  1313. if (!@ARGV) {
  1314. DieDiag("'--analyzer-target' option requires a target triple name.\n");
  1315. }
  1316. $AnalyzerTarget = shift @ARGV;
  1317. }
  1318. else {
  1319. $AnalyzerTarget = $2;
  1320. }
  1321. $Options{AnalyzerTarget} = $AnalyzerTarget;
  1322. next;
  1323. }
  1324. if ($arg eq "-v") {
  1325. shift @$Args;
  1326. $Options{Verbose}++;
  1327. next;
  1328. }
  1329. if ($arg eq "-V" or $arg eq "--view") {
  1330. shift @$Args;
  1331. $Options{ViewResults} = 1;
  1332. next;
  1333. }
  1334. if ($arg eq "--status-bugs") {
  1335. shift @$Args;
  1336. $Options{ExitStatusFoundBugs} = 1;
  1337. next;
  1338. }
  1339. if ($arg eq "--show-description") {
  1340. shift @$Args;
  1341. $Options{ShowDescription} = 1;
  1342. next;
  1343. }
  1344. if ($arg eq "-store") {
  1345. shift @$Args;
  1346. $Options{StoreModel} = shift @$Args;
  1347. next;
  1348. }
  1349. if ($arg eq "-constraints") {
  1350. shift @$Args;
  1351. $Options{ConstraintsModel} = shift @$Args;
  1352. next;
  1353. }
  1354. if ($arg eq "-internal-stats") {
  1355. shift @$Args;
  1356. $Options{InternalStats} = 1;
  1357. next;
  1358. }
  1359. if ($arg eq "-plist") {
  1360. shift @$Args;
  1361. $Options{OutputFormat} = "plist";
  1362. next;
  1363. }
  1364. if ($arg eq "-plist-html") {
  1365. shift @$Args;
  1366. $Options{OutputFormat} = "plist-html";
  1367. next;
  1368. }
  1369. if ($arg eq "-analyzer-config") {
  1370. shift @$Args;
  1371. push @{$Options{ConfigOptions}}, shift @$Args;
  1372. next;
  1373. }
  1374. if ($arg eq "-no-failure-reports") {
  1375. shift @$Args;
  1376. $Options{ReportFailures} = 0;
  1377. next;
  1378. }
  1379. if ($arg eq "-stats") {
  1380. shift @$Args;
  1381. $Options{AnalyzerStats} = 1;
  1382. next;
  1383. }
  1384. if ($arg eq "-maxloop") {
  1385. shift @$Args;
  1386. $Options{MaxLoop} = shift @$Args;
  1387. next;
  1388. }
  1389. if ($arg eq "-enable-checker") {
  1390. shift @$Args;
  1391. my $Checker = shift @$Args;
  1392. # Store $NumArgs to preserve the order the checkers were enabled.
  1393. $Options{EnableCheckers}{$Checker} = $NumArgs;
  1394. delete $Options{DisableCheckers}{$Checker};
  1395. next;
  1396. }
  1397. if ($arg eq "-disable-checker") {
  1398. shift @$Args;
  1399. my $Checker = shift @$Args;
  1400. # Store $NumArgs to preserve the order the checkers were disabled.
  1401. $Options{DisableCheckers}{$Checker} = $NumArgs;
  1402. delete $Options{EnableCheckers}{$Checker};
  1403. next;
  1404. }
  1405. if ($arg eq "--exclude") {
  1406. shift @$Args;
  1407. my $arg = shift @$Args;
  1408. # Remove the trailing slash if any
  1409. $arg =~ s|/$||;
  1410. push @{$Options{Excludes}}, $arg;
  1411. next;
  1412. }
  1413. if ($arg eq "-load-plugin") {
  1414. shift @$Args;
  1415. push @{$Options{PluginsToLoad}}, shift @$Args;
  1416. next;
  1417. }
  1418. if ($arg eq "--use-analyzer") {
  1419. shift @$Args;
  1420. $Options{AnalyzerDiscoveryMethod} = shift @$Args;
  1421. next;
  1422. }
  1423. if ($arg =~ /^--use-analyzer=(.+)$/) {
  1424. shift @$Args;
  1425. $Options{AnalyzerDiscoveryMethod} = $1;
  1426. next;
  1427. }
  1428. if ($arg eq "--keep-empty") {
  1429. shift @$Args;
  1430. $Options{KeepEmpty} = 1;
  1431. next;
  1432. }
  1433. if ($arg eq "--override-compiler") {
  1434. shift @$Args;
  1435. $Options{OverrideCompiler} = 1;
  1436. next;
  1437. }
  1438. if ($arg eq "--force-analyze-debug-code") {
  1439. shift @$Args;
  1440. $Options{ForceAnalyzeDebugCode} = 1;
  1441. next;
  1442. }
  1443. DieDiag("unrecognized option '$arg'\n") if ($arg =~ /^-/);
  1444. $NumArgs--;
  1445. last;
  1446. }
  1447. return $NumArgs;
  1448. }
  1449. if (!@ARGV) {
  1450. $ForceDisplayHelp = 1
  1451. }
  1452. ProcessArgs(\@ARGV);
  1453. # All arguments are now shifted from @ARGV. The rest is a build command, if any.
  1454. if (!@ARGV and !$RequestDisplayHelp) {
  1455. ErrorDiag("No build command specified.\n\n");
  1456. $ForceDisplayHelp = 1;
  1457. }
  1458. my $ClangNotFoundErrMsg = FindClang();
  1459. if ($ForceDisplayHelp || $RequestDisplayHelp) {
  1460. DisplayHelp($ClangNotFoundErrMsg);
  1461. exit $ForceDisplayHelp;
  1462. }
  1463. DieDiag($ClangNotFoundErrMsg) if (defined $ClangNotFoundErrMsg);
  1464. $ClangCXX = $Clang;
  1465. if ($Clang !~ /\+\+(\.exe)?$/) {
  1466. # If $Clang holds the name of the clang++ executable then we leave
  1467. # $ClangCXX and $Clang equal, otherwise construct the name of the clang++
  1468. # executable from the clang executable name.
  1469. # Determine operating system under which this copy of Perl was built.
  1470. my $IsWinBuild = ($^O =~/msys|cygwin|MSWin32/);
  1471. if($IsWinBuild) {
  1472. $ClangCXX =~ s/.exe$/++.exe/;
  1473. # Unix system commands and some of the perl standard library
  1474. # functions used in this script don't work on Windows.
  1475. DieDiag("Not supported for windows. Exiting...\n");
  1476. }
  1477. else {
  1478. $ClangCXX =~ s/\-\d+\.\d+$//;
  1479. $ClangCXX .= "++";
  1480. }
  1481. }
  1482. # Make sure to use "" to handle paths with spaces.
  1483. $ClangVersion = HtmlEscape(`"$Clang" --version`);
  1484. # Determine where results go.
  1485. $CmdArgs = HtmlEscape(join(' ', map(ShellEscape($_), @ARGV)));
  1486. # Determine the output directory for the HTML reports.
  1487. my $BaseDir = $Options{OutputDir};
  1488. $Options{OutputDir} = GetHTMLRunDir($Options{OutputDir});
  1489. # Determine the location of ccc-analyzer.
  1490. my $AbsRealBin = Cwd::realpath($RealBin);
  1491. my $Cmd = "$AbsRealBin/../libexec/ccc-analyzer";
  1492. my $CmdCXX = "$AbsRealBin/../libexec/c++-analyzer";
  1493. # Portability: use less strict but portable check -e (file exists) instead of
  1494. # non-portable -x (file is executable). On some windows ports -x just checks
  1495. # file extension to determine if a file is executable (see Perl language
  1496. # reference, perlport)
  1497. if (!defined $Cmd || ! -e $Cmd) {
  1498. $Cmd = "$AbsRealBin/ccc-analyzer";
  1499. DieDiag("'ccc-analyzer' does not exist at '$Cmd'\n") if(! -e $Cmd);
  1500. }
  1501. if (!defined $CmdCXX || ! -e $CmdCXX) {
  1502. $CmdCXX = "$AbsRealBin/c++-analyzer";
  1503. DieDiag("'c++-analyzer' does not exist at '$CmdCXX'\n") if(! -e $CmdCXX);
  1504. }
  1505. Diag("Using '$Clang' for static analysis\n");
  1506. SetHtmlEnv(\@ARGV, $Options{OutputDir});
  1507. my @AnalysesToRun;
  1508. foreach (sort { $Options{EnableCheckers}{$a} <=> $Options{EnableCheckers}{$b} }
  1509. keys %{$Options{EnableCheckers}}) {
  1510. # Push checkers in order they were enabled.
  1511. push @AnalysesToRun, "-analyzer-checker", $_;
  1512. }
  1513. foreach (sort { $Options{DisableCheckers}{$a} <=> $Options{DisableCheckers}{$b} }
  1514. keys %{$Options{DisableCheckers}}) {
  1515. # Push checkers in order they were disabled.
  1516. push @AnalysesToRun, "-analyzer-disable-checker", $_;
  1517. }
  1518. if ($Options{AnalyzeHeaders}) { push @AnalysesToRun, "-analyzer-opt-analyze-headers"; }
  1519. if ($Options{AnalyzerStats}) { push @AnalysesToRun, '-analyzer-checker=debug.Stats'; }
  1520. if ($Options{MaxLoop} > 0) { push @AnalysesToRun, "-analyzer-max-loop $Options{MaxLoop}"; }
  1521. # Delay setting up other environment variables in case we can do true
  1522. # interposition.
  1523. my $CCC_ANALYZER_ANALYSIS = join ' ', @AnalysesToRun;
  1524. my $CCC_ANALYZER_PLUGINS = join ' ', map { "-load ".$_ } @{$Options{PluginsToLoad}};
  1525. my $CCC_ANALYZER_CONFIG = join ' ', map { "-analyzer-config ".$_ } @{$Options{ConfigOptions}};
  1526. my %EnvVars = (
  1527. 'CC' => $Cmd,
  1528. 'CXX' => $CmdCXX,
  1529. 'CLANG' => $Clang,
  1530. 'CLANG_CXX' => $ClangCXX,
  1531. 'VERBOSE' => $Options{Verbose},
  1532. 'CCC_ANALYZER_ANALYSIS' => $CCC_ANALYZER_ANALYSIS,
  1533. 'CCC_ANALYZER_PLUGINS' => $CCC_ANALYZER_PLUGINS,
  1534. 'CCC_ANALYZER_CONFIG' => $CCC_ANALYZER_CONFIG,
  1535. 'OUTPUT_DIR' => $Options{OutputDir},
  1536. 'CCC_CC' => $Options{UseCC},
  1537. 'CCC_CXX' => $Options{UseCXX},
  1538. 'CCC_REPORT_FAILURES' => $Options{ReportFailures},
  1539. 'CCC_ANALYZER_STORE_MODEL' => $Options{StoreModel},
  1540. 'CCC_ANALYZER_CONSTRAINTS_MODEL' => $Options{ConstraintsModel},
  1541. 'CCC_ANALYZER_INTERNAL_STATS' => $Options{InternalStats},
  1542. 'CCC_ANALYZER_OUTPUT_FORMAT' => $Options{OutputFormat},
  1543. 'CLANG_ANALYZER_TARGET' => $Options{AnalyzerTarget},
  1544. 'CCC_ANALYZER_FORCE_ANALYZE_DEBUG_CODE' => $Options{ForceAnalyzeDebugCode}
  1545. );
  1546. # Run the build.
  1547. my $ExitStatus = RunBuildCommand(\@ARGV, $Options{IgnoreErrors}, $Options{KeepCC},
  1548. $Cmd, $CmdCXX, \%EnvVars);
  1549. if (defined $Options{OutputFormat}) {
  1550. if ($Options{OutputFormat} =~ /plist/) {
  1551. Diag "Analysis run complete.\n";
  1552. Diag "Analysis results (plist files) deposited in '$Options{OutputDir}'\n";
  1553. }
  1554. if ($Options{OutputFormat} =~ /html/) {
  1555. # Postprocess the HTML directory.
  1556. my $NumBugs = Postprocess($Options{OutputDir}, $BaseDir,
  1557. $Options{AnalyzerStats}, $Options{KeepEmpty});
  1558. if ($Options{ViewResults} and -r "$Options{OutputDir}/index.html") {
  1559. Diag "Analysis run complete.\n";
  1560. Diag "Viewing analysis results in '$Options{OutputDir}' using scan-view.\n";
  1561. my $ScanView = Cwd::realpath("$RealBin/scan-view");
  1562. if (! -x $ScanView) { $ScanView = "scan-view"; }
  1563. if (! -x $ScanView) { $ScanView = Cwd::realpath("$RealBin/../../scan-view/bin/scan-view"); }
  1564. exec $ScanView, "$Options{OutputDir}";
  1565. }
  1566. if ($Options{ExitStatusFoundBugs}) {
  1567. exit 1 if ($NumBugs > 0);
  1568. exit $ExitStatus;
  1569. }
  1570. }
  1571. }
  1572. exit $ExitStatus;