#!/usr/bin/env perl # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # ##===----------------------------------------------------------------------===## # # A script designed to wrap a build so that all calls to gcc are intercepted # and piped to the static analyzer. # ##===----------------------------------------------------------------------===## use strict; use warnings; use File::Temp qw/ :mktemp /; use FindBin qw($RealBin); use Digest::MD5; use File::Basename; use Term::ANSIColor; use Term::ANSIColor qw(:constants); my $Verbose = 0; # Verbose output from this script. my $Prog = "scan-build"; my $BuildName; my $BuildDate; my $UseColor = ((($ENV{'TERM'} eq 'xterm-color') and -t STDOUT) and defined($ENV{'SCAN_BUILD_COLOR'})); ##----------------------------------------------------------------------------## # Diagnostics ##----------------------------------------------------------------------------## sub Diag { if ($UseColor) { print BOLD, MAGENTA "$Prog: @_"; print RESET; } else { print "$Prog: @_"; } } sub DieDiag { if ($UseColor) { print BOLD, RED "$Prog: "; print RESET, RED @_; print RESET; } else { print "$Prog: ", @_; } exit(0); } ##----------------------------------------------------------------------------## # Some initial preprocessing of Clang options. ##----------------------------------------------------------------------------## my $ClangSB = "$RealBin/clang"; my $Clang = $ClangSB; if (! -x $ClangSB) { $Clang = "clang"; } my %AvailableAnalyses; # Query clang for analysis options. open(PIPE, "$Clang --help |") or DieDiag("Cannot execute '$Clang'"); my $FoundAnalysis = 0; while() { if ($FoundAnalysis == 0) { if (/Available Source Code Analyses/) { $FoundAnalysis = 1; } next; } if (/^\s\s\s\s([^\s]+)\s(.+)$/) { next if ($1 =~ /-dump/ or $1 =~ /-view/ or $1 =~ /-checker-simple/ or $1 =~ /-warn-uninit/); $AvailableAnalyses{$1} = $2; next; } last; } close (PIPE); my %AnalysesDefaultEnabled = ( '-warn-dead-stores' => 1, '-checker-cfref' => 1, '-warn-objc-methodsigs' => 1, '-warn-objc-missing-dealloc' => 1 ); ##----------------------------------------------------------------------------## # GetHTMLRunDir - Construct an HTML directory name for the current run. ##----------------------------------------------------------------------------## sub GetHTMLRunDir { die "Not enough arguments." if (@_ == 0); my $Dir = shift @_; # Get current date and time. my @CurrentTime = localtime(); my $year = $CurrentTime[5] + 1900; my $day = $CurrentTime[3]; my $month = $CurrentTime[4] + 1; my $DateString = sprintf("%d-%02d-%02d", $year, $month, $day); # Determine the run number. my $RunNumber; if (-d $Dir) { if (! -r $Dir) { DieDiag("directory '$Dir' exists but is not readable.\n"); } # Iterate over all files in the specified directory. my $max = 0; opendir(DIR, $Dir); my @FILES= readdir(DIR); closedir(DIR); foreach my $f (@FILES) { my @x = split/-/, $f; next if (scalar(@x) != 4); next if ($x[0] != $year); next if ($x[1] != $month); next if ($x[2] != $day); if ($x[3] > $max) { $max = $x[3]; } } $RunNumber = $max + 1; } else { if (-x $Dir) { DieDiag("'$Dir' exists but is not a directory.\n"); } # $Dir does not exist. It will be automatically created by the # clang driver. Set the run number to 1. $RunNumber = 1; } die "RunNumber must be defined!" if (!defined($RunNumber)); # Append the run number. return "$Dir/$DateString-$RunNumber"; } sub SetHtmlEnv { die "Wrong number of arguments." if (scalar(@_) != 2); my $Args = shift; my $Dir = shift; die "No build command." if (scalar(@$Args) == 0); my $Cmd = $$Args[0]; if ($Cmd =~ /configure/) { return; } if ($Verbose) { Diag("Emitting reports for this run to '$Dir'.\n"); } $ENV{'CCC_ANALYZER_HTML'} = $Dir; } ##----------------------------------------------------------------------------## # ComputeDigest - Compute a digest of the specified file. ##----------------------------------------------------------------------------## sub ComputeDigest { my $FName = shift; DieDiag("Cannot read $FName to compute Digest.\n") if (! -r $FName); # Use Digest::MD5. We don't have to be cryptographically secure. We're # just looking for duplicate files that come from a non-malicious source. # We use Digest::MD5 because it is a standard Perl module that should # come bundled on most systems. open(FILE, $FName) or DieDiag("Cannot open $FName when computing Digest.\n"); binmode FILE; my $Result = Digest::MD5->new->addfile(*FILE)->hexdigest; close(FILE); # Return the digest. return $Result; } ##----------------------------------------------------------------------------## # UpdatePrefix - Compute the common prefix of files. ##----------------------------------------------------------------------------## my $Prefix; sub UpdatePrefix { my $x = shift; my $y = basename($x); $x =~ s/\Q$y\E$//; # Ignore /usr, /Library, /System, /Developer return if ( $x =~ /^\/usr/ or $x =~ /^\/Library/ or $x =~ /^\/System/ or $x =~ /^\/Developer/); if (!defined $Prefix) { $Prefix = $x; return; } chop $Prefix while (!($x =~ /^$Prefix/)); } sub GetPrefix { return $Prefix; } ##----------------------------------------------------------------------------## # UpdateInFilePath - Update the path in the report file. ##----------------------------------------------------------------------------## sub UpdateInFilePath { my $fname = shift; my $regex = shift; my $newtext = shift; open (RIN, $fname) or die "cannot open $fname"; open (ROUT, ">$fname.tmp") or die "cannot open $fname.tmp"; while () { s/$regex/$newtext/; print ROUT $_; } close (ROUT); close (RIN); system("mv", "$fname.tmp", $fname); } ##----------------------------------------------------------------------------## # ScanFile - Scan a report file for various identifying attributes. ##----------------------------------------------------------------------------## # Sometimes a source file is scanned more than once, and thus produces # multiple error reports. We use a cache to solve this problem. my %AlreadyScanned; sub ScanFile { my $Index = shift; my $Dir = shift; my $FName = shift; # Compute a digest for the report file. Determine if we have already # scanned a file that looks just like it. my $digest = ComputeDigest("$Dir/$FName"); if (defined($AlreadyScanned{$digest})) { # Redundant file. Remove it. system ("rm", "-f", "$Dir/$FName"); return; } $AlreadyScanned{$digest} = 1; # At this point the report file is not world readable. Make it happen. system ("chmod", "644", "$Dir/$FName"); # Scan the report file for tags. open(IN, "$Dir/$FName") or DieDiag("Cannot open '$Dir/$FName'\n"); my $BugDesc = ""; my $BugFile = ""; my $BugPathLength = 1; my $BugLine = 0; while () { if (/$/) { $BugDesc = $1; } elsif (/$/) { $BugFile = $1; UpdatePrefix($BugFile); } elsif (/$/) { $BugPathLength = $1; } elsif (/$/) { $BugLine = $1; } } close(IN); push @$Index,[ $FName, $BugDesc, $BugFile, $BugLine, $BugPathLength ]; } ##----------------------------------------------------------------------------## # CopyJS - Copy JavaScript code to target directory. ##----------------------------------------------------------------------------## sub CopyJS { my $Dir = shift; DieDiag("Cannot find 'sorttable.js'.\n") if (! -r "$RealBin/sorttable.js"); system ("cp", "$RealBin/sorttable.js", "$Dir"); DieDiag("Could not copy 'sorttable.js' to '$Dir'.\n") if (! -r "$Dir/sorttable.js"); } ##----------------------------------------------------------------------------## # Postprocess - Postprocess the results of an analysis scan. ##----------------------------------------------------------------------------## sub Postprocess { my $Dir = shift; my $BaseDir = shift; die "No directory specified." if (!defined($Dir)); die "No base directory specified." if (!defined($BaseDir)); if (! -d $Dir) { Diag("No bugs found.\n"); return 0; } opendir(DIR, $Dir); my @files = grep(/^report-.*\.html$/,readdir(DIR)); closedir(DIR); if (scalar(@files) == 0) { Diag("Removing directory '$Dir' because it contains no reports.\n"); system ("rm", "-fR", $Dir); # Remove the base directory if it contains no files (don't use '-R'). system ("rm", "-f", $BaseDir); Diag("No bugs found.\n"); return 0; } # Scan each report file and build an index. my @Index; foreach my $file (@files) { ScanFile(\@Index, $Dir, $file); } # Generate an index.html file. my $FName = "$Dir/index.html"; open(OUT, ">$FName") or DieDiag("Cannot create file '$FName'\n"); # Print out the header. print OUT < ENDTEXT # Print out the summary table. my %Totals; for my $row ( @Index ) { #my $bug_type = lc($row->[1]); my $bug_type = ($row->[1]); if (!defined($Totals{$bug_type})) { $Totals{$bug_type} = 1; } else { $Totals{$bug_type}++; } } print OUT "

Summary

"; if (defined($BuildName)) { print OUT "\n

Results in this analysis run are based on analyzer build $BuildName.

\n" } print OUT < Bug Type Quantity Display? ENDTEXT for my $key ( sort { $a cmp $b } keys %Totals ) { my $x = lc($key); $x =~ s/\s[,]/_/g; print OUT "$key$Totals{$key}\n"; } # Print out the table of errors. print OUT <

Reports

ENDTEXT my $prefix = GetPrefix(); my $regex; my $InFileRegex; my $InFilePrefix = "File:\n"; my $ReportFile = $row->[0]; print OUT " \n"; # Update the file prefix. my $fname = $row->[2]; if (defined($regex)) { $fname =~ s/$regex//; UpdateInFilePath("$Dir/$ReportFile", $InFileRegex, $InFilePrefix) } print OUT "\n"; # Print the rest of the columns. for my $j ( 3 .. $#{$row} ) { print OUT "\n" } # Emit the "View" link. print OUT " \n"; # End the row. print OUT "\n"; } print OUT "
Bug Type ▾ File Line Path Length
"; if (defined($prefix)) { $regex = qr/^\Q$prefix\E/is; $InFileRegex = qr/\Q$InFilePrefix$prefix\E/is; } for my $row ( sort { $a->[1] cmp $b->[1] } @Index ) { my $x = lc($row->[1]); $x =~ s/\s[,]/_/g; print OUT "
"; #print OUT lc($row->[1]); print OUT $row->[1]; print OUT "$fname$row->[$j]View
\n\n"; close(OUT); CopyJS($Dir); # Make sure $Dir and $BaseDir are world readable/executable. system("chmod", "755", $Dir); system("chmod", "755", $BaseDir); my $Num = scalar(@Index); Diag("$Num bugs found.\n"); if ($Num > 0 && -r "$Dir/index.html") { Diag("Open '$Dir/index.html' to examine bug reports.\n"); } return $Num; } ##----------------------------------------------------------------------------## # RunBuildCommand - Run the build command. ##----------------------------------------------------------------------------## sub AddIfNotPresent { my $Args = shift; my $Arg = shift; my $found = 0; foreach my $k (@$Args) { if ($k eq $Arg) { $found = 1; last; } } if ($found == 0) { push @$Args, $Arg; } } sub RunBuildCommand { my $Args = shift; my $IgnoreErrors = shift; my $Cmd = $Args->[0]; my $CCAnalyzer = shift; # Get only the part of the command after the last '/'. if ($Cmd =~ /\/([^\/]+)$/) { $Cmd = $1; } if ($Cmd eq "gcc" or $Cmd eq "cc" or $Cmd eq "llvm-gcc") { shift @$Args; unshift @$Args, $CCAnalyzer; } elsif ($IgnoreErrors) { if ($Cmd eq "make" or $Cmd eq "gmake") { AddIfNotPresent($Args,"-k"); AddIfNotPresent($Args,"-i"); } elsif ($Cmd eq "xcodebuild") { AddIfNotPresent($Args,"-PBXBuildsContinueAfterErrors=YES"); } } if ($Cmd eq "xcodebuild") { # Disable distributed builds for xcodebuild. AddIfNotPresent($Args,"-nodistribute"); # Disable PCH files until clang supports them. AddIfNotPresent($Args,"GCC_PRECOMPILE_PREFIX_HEADER=NO"); # When 'CC' is set, xcodebuild uses it to do all linking, even if we are # linking C++ object files. Set 'LDPLUSPLUS' so that xcodebuild uses 'g++' # when linking such files. my $LDPLUSPLUS = `which g++`; $LDPLUSPLUS =~ s/\015?\012//; # strip newlines $ENV{'LDPLUSPLUS'} = $LDPLUSPLUS; } return system(@$Args); } ##----------------------------------------------------------------------------## # DisplayHelp - Utility function to display all help options. ##----------------------------------------------------------------------------## sub DisplayHelp { print < [build options] ENDTEXT if (defined($BuildName)) { print "ANALYZER BUILD: $BuildName ($BuildDate)\n\n"; } print <= 2) { $ENV{'CCC_ANALYZER_VERBOSE'} = 1; } if ($Verbose >= 3) { $ENV{'CCC_ANALYZER_LOG'} = 1; } if (scalar(@AnalysesToRun) == 0) { foreach my $key (keys %AnalysesDefaultEnabled) { push @AnalysesToRun,$key; } } $ENV{'CCC_ANALYZER_ANALYSIS'} = join ' ',@AnalysesToRun; # Run the build. my $ExitStatus = RunBuildCommand(\@ARGV, $IgnoreErrors, $Cmd); # Postprocess the HTML directory. my $NumBugs = Postprocess($HtmlDir, $BaseDir); if ($ViewResults and -r "$HtmlDir/index.html") { # Only works on Mac OS X (for now). print "Viewing analysis results: '$HtmlDir/index.html'\n"; system("open", "$HtmlDir/index.html"); } if ($ExitStatusFoundBugs) { exit 1 if ($NumBugs > 0); exit 0; } exit $ExitStatus;