Home | History | Annotate | Download | only in scan-build
      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 interpose between the build system and gcc.  It invokes
     11 #  both gcc and the static analyzer.
     12 #
     13 ##===----------------------------------------------------------------------===##
     14 
     15 use strict;
     16 use warnings;
     17 use FindBin;
     18 use Cwd qw/ getcwd abs_path /;
     19 use File::Temp qw/ tempfile /;
     20 use File::Path qw / mkpath /;
     21 use File::Basename;
     22 use Text::ParseWords;
     23 
     24 ##===----------------------------------------------------------------------===##
     25 # Compiler command setup.
     26 ##===----------------------------------------------------------------------===##
     27 
     28 my $Compiler;
     29 my $Clang;
     30 
     31 if ($FindBin::Script =~ /c\+\+-analyzer/) {
     32   $Compiler = $ENV{'CCC_CXX'};
     33   if (!defined $Compiler) { $Compiler = "g++"; }
     34   
     35   $Clang = $ENV{'CLANG_CXX'};
     36   if (!defined $Clang) { $Clang = 'clang++'; }
     37 }
     38 else {
     39   $Compiler = $ENV{'CCC_CC'};
     40   if (!defined $Compiler) { $Compiler = "gcc"; }
     41 
     42   $Clang = $ENV{'CLANG'};
     43   if (!defined $Clang) { $Clang = 'clang'; }
     44 }
     45 
     46 ##===----------------------------------------------------------------------===##
     47 # Cleanup.
     48 ##===----------------------------------------------------------------------===##
     49 
     50 my $ReportFailures = $ENV{'CCC_REPORT_FAILURES'};
     51 if (!defined $ReportFailures) { $ReportFailures = 1; }
     52 
     53 my $CleanupFile;
     54 my $ResultFile;
     55 
     56 # Remove any stale files at exit.
     57 END { 
     58   if (defined $CleanupFile && -z $CleanupFile) {
     59     `rm -f $CleanupFile`;
     60   }
     61 }
     62 
     63 ##----------------------------------------------------------------------------##
     64 #  Process Clang Crashes.
     65 ##----------------------------------------------------------------------------##
     66 
     67 sub GetPPExt {
     68   my $Lang = shift;
     69   if ($Lang =~ /objective-c\+\+/) { return ".mii" };
     70   if ($Lang =~ /objective-c/) { return ".mi"; }
     71   if ($Lang =~ /c\+\+/) { return ".ii"; }
     72   return ".i";
     73 }
     74 
     75 # Set this to 1 if we want to include 'parser rejects' files.
     76 my $IncludeParserRejects = 0;
     77 my $ParserRejects = "Parser Rejects";
     78 
     79 my $AttributeIgnored = "Attribute Ignored";
     80 
     81 sub ProcessClangFailure {
     82   my ($Clang, $Lang, $file, $Args, $HtmlDir, $ErrorType, $ofile) = @_;
     83   my $Dir = "$HtmlDir/failures";
     84   mkpath $Dir;
     85   
     86   my $prefix = "clang_crash";
     87   if ($ErrorType eq $ParserRejects) {
     88     $prefix = "clang_parser_rejects";
     89   }
     90   elsif ($ErrorType eq $AttributeIgnored) {
     91     $prefix = "clang_attribute_ignored";
     92   }
     93 
     94   # Generate the preprocessed file with Clang.
     95   my ($PPH, $PPFile) = tempfile( $prefix . "_XXXXXX",
     96                                  SUFFIX => GetPPExt($Lang),
     97                                  DIR => $Dir);
     98   system $Clang, @$Args, "-E", "-o", $PPFile;
     99   close ($PPH);
    100   
    101   # Create the info file.
    102   open (OUT, ">", "$PPFile.info.txt") or die "Cannot open $PPFile.info.txt\n";
    103   print OUT abs_path($file), "\n";
    104   print OUT "$ErrorType\n";
    105   print OUT "@$Args\n";
    106   close OUT;
    107   `uname -a >> $PPFile.info.txt 2>&1`;
    108   `$Compiler -v >> $PPFile.info.txt 2>&1`;
    109   system 'mv',$ofile,"$PPFile.stderr.txt";
    110   return (basename $PPFile);
    111 }
    112 
    113 ##----------------------------------------------------------------------------##
    114 #  Running the analyzer.
    115 ##----------------------------------------------------------------------------##
    116 
    117 sub GetCCArgs {
    118   my $mode = shift;
    119   my $Args = shift;
    120   
    121   pipe (FROM_CHILD, TO_PARENT);
    122   my $pid = fork();
    123   if ($pid == 0) {
    124     close FROM_CHILD;
    125     open(STDOUT,">&", \*TO_PARENT);
    126     open(STDERR,">&", \*TO_PARENT);
    127     exec $Clang, "-###", $mode, @$Args;
    128   }  
    129   close(TO_PARENT);
    130   my $line;
    131   while (<FROM_CHILD>) {
    132     next if (!/-cc1/);
    133     $line = $_;
    134   }
    135 
    136   waitpid($pid,0);
    137   close(FROM_CHILD);
    138   
    139   die "could not find clang line\n" if (!defined $line);
    140   # Strip the newline and initial whitspace
    141   chomp $line;
    142   $line =~ s/^\s+//;
    143   my @items = quotewords('\s+', 0, $line);
    144   my $cmd = shift @items;
    145   die "cannot find 'clang' in 'clang' command\n" if (!($cmd =~ /clang/));
    146   return \@items;
    147 }
    148 
    149 sub Analyze {
    150   my ($Clang, $OriginalArgs, $AnalyzeArgs, $Lang, $Output, $Verbose, $HtmlDir,
    151       $file) = @_;
    152 
    153   my @Args = @$OriginalArgs;
    154   my $Cmd;
    155   my @CmdArgs;
    156   my @CmdArgsSansAnalyses;
    157 
    158   if ($Lang =~ /header/) {
    159     exit 0 if (!defined ($Output));
    160     $Cmd = 'cp';
    161     push @CmdArgs, $file;
    162     # Remove the PCH extension.
    163     $Output =~ s/[.]gch$//;
    164     push @CmdArgs, $Output;
    165     @CmdArgsSansAnalyses = @CmdArgs;
    166   }
    167   else {
    168     $Cmd = $Clang;
    169     if ($Lang eq "objective-c" || $Lang eq "objective-c++") {
    170       push @Args,'-DIBOutlet=__attribute__((iboutlet))';
    171       push @Args,'-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection)))';
    172       push @Args,'-DIBAction=void)__attribute__((ibaction)';
    173     }
    174 
    175     # Create arguments for doing regular parsing.
    176     my $SyntaxArgs = GetCCArgs("-fsyntax-only", \@Args);
    177     @CmdArgsSansAnalyses = @$SyntaxArgs;
    178 
    179     # Create arguments for doing static analysis.
    180     if (defined $ResultFile) {
    181       push @Args, '-o', $ResultFile;
    182     }
    183     elsif (defined $HtmlDir) {
    184       push @Args, '-o', $HtmlDir;
    185     }
    186     if ($Verbose) {
    187       push @Args, "-Xclang", "-analyzer-display-progress";
    188     }
    189 
    190     foreach my $arg (@$AnalyzeArgs) {
    191       push @Args, "-Xclang", $arg;
    192     }
    193 
    194     # Display Ubiviz graph?
    195     if (defined $ENV{'CCC_UBI'}) {   
    196       push @Args, "-Xclang", "-analyzer-viz-egraph-ubigraph";
    197     }
    198 
    199     my $AnalysisArgs = GetCCArgs("--analyze", \@Args);
    200     @CmdArgs = @$AnalysisArgs;
    201   }
    202 
    203   my @PrintArgs;
    204   my $dir;
    205 
    206   if ($Verbose) {
    207     $dir = getcwd();
    208     print STDERR "\n[LOCATION]: $dir\n";
    209     push @PrintArgs,"'$Cmd'";
    210     foreach my $arg (@CmdArgs) {
    211         push @PrintArgs,"\'$arg\'";
    212     }
    213   }
    214   if ($Verbose == 1) {
    215     # We MUST print to stderr.  Some clients use the stdout output of
    216     # gcc for various purposes. 
    217     print STDERR join(' ', @PrintArgs);
    218     print STDERR "\n";
    219   }
    220   elsif ($Verbose == 2) {
    221     print STDERR "#SHELL (cd '$dir' && @PrintArgs)\n";
    222   }
    223 
    224   # Capture the STDERR of clang and send it to a temporary file.
    225   # Capture the STDOUT of clang and reroute it to ccc-analyzer's STDERR.
    226   # We save the output file in the 'crashes' directory if clang encounters
    227   # any problems with the file.  
    228   pipe (FROM_CHILD, TO_PARENT);
    229   my $pid = fork();
    230   if ($pid == 0) {
    231     close FROM_CHILD;
    232     open(STDOUT,">&", \*TO_PARENT);
    233     open(STDERR,">&", \*TO_PARENT);
    234     exec $Cmd, @CmdArgs;
    235   }
    236 
    237   close TO_PARENT;
    238   my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);
    239   
    240   while (<FROM_CHILD>) {
    241     print $ofh $_;
    242     print STDERR $_;
    243   }
    244 
    245   waitpid($pid,0);
    246   close(FROM_CHILD);
    247   my $Result = $?;
    248 
    249   # Did the command die because of a signal?
    250   if ($ReportFailures) {
    251     if ($Result & 127 and $Cmd eq $Clang and defined $HtmlDir) {
    252       ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
    253                           $HtmlDir, "Crash", $ofile);
    254     }
    255     elsif ($Result) {
    256       if ($IncludeParserRejects && !($file =~/conftest/)) {
    257         ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
    258                             $HtmlDir, $ParserRejects, $ofile);
    259       }
    260     }
    261     else {
    262       # Check if there were any unhandled attributes.
    263       if (open(CHILD, $ofile)) {
    264         my %attributes_not_handled;
    265 
    266         # Don't flag warnings about the following attributes that we
    267         # know are currently not supported by Clang.
    268         $attributes_not_handled{"cdecl"} = 1;
    269 
    270         my $ppfile;
    271         while (<CHILD>) {
    272           next if (! /warning: '([^\']+)' attribute ignored/);
    273 
    274           # Have we already spotted this unhandled attribute?
    275           next if (defined $attributes_not_handled{$1});
    276           $attributes_not_handled{$1} = 1;
    277         
    278           # Get the name of the attribute file.
    279           my $dir = "$HtmlDir/failures";
    280           my $afile = "$dir/attribute_ignored_$1.txt";
    281         
    282           # Only create another preprocessed file if the attribute file
    283           # doesn't exist yet.
    284           next if (-e $afile);
    285         
    286           # Add this file to the list of files that contained this attribute.
    287           # Generate a preprocessed file if we haven't already.
    288           if (!(defined $ppfile)) {
    289             $ppfile = ProcessClangFailure($Clang, $Lang, $file,
    290                                           \@CmdArgsSansAnalyses,
    291                                           $HtmlDir, $AttributeIgnored, $ofile);
    292           }
    293 
    294           mkpath $dir;
    295           open(AFILE, ">$afile");
    296           print AFILE "$ppfile\n";
    297           close(AFILE);
    298         }
    299         close CHILD;
    300       }
    301     }
    302   }
    303   
    304   unlink($ofile);
    305 }
    306 
    307 ##----------------------------------------------------------------------------##
    308 #  Lookup tables.
    309 ##----------------------------------------------------------------------------##
    310 
    311 my %CompileOptionMap = (
    312   '-nostdinc' => 0,
    313   '-fblocks' => 0,
    314   '-fno-builtin' => 0,
    315   '-fobjc-gc-only' => 0,
    316   '-fobjc-gc' => 0,
    317   '-ffreestanding' => 0,
    318   '-include' => 1,
    319   '-idirafter' => 1,
    320   '-imacros' => 1,
    321   '-iprefix' => 1,
    322   '-iquote' => 1,
    323   '-isystem' => 1,
    324   '-iwithprefix' => 1,
    325   '-iwithprefixbefore' => 1
    326 );
    327 
    328 my %LinkerOptionMap = (
    329   '-framework' => 1
    330 );
    331 
    332 my %CompilerLinkerOptionMap = (
    333   '-isysroot' => 1,
    334   '-arch' => 1,
    335   '-m32' => 0,
    336   '-m64' => 0,
    337   '-v' => 0,
    338   '-fpascal-strings' => 0,
    339   '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
    340   '-miphoneos-version-min' => 0 # This is really a 1 argument, but always has '='
    341 );
    342 
    343 my %IgnoredOptionMap = (
    344   '-MT' => 1,  # Ignore these preprocessor options.
    345   '-MF' => 1,
    346 
    347   '-fsyntax-only' => 0,
    348   '-save-temps' => 0,
    349   '-install_name' => 1,
    350   '-exported_symbols_list' => 1,
    351   '-current_version' => 1,
    352   '-compatibility_version' => 1,
    353   '-init' => 1,
    354   '-e' => 1,
    355   '-seg1addr' => 1,
    356   '-bundle_loader' => 1,
    357   '-multiply_defined' => 1,
    358   '-sectorder' => 3,
    359   '--param' => 1,
    360   '-u' => 1
    361 );
    362 
    363 my %LangMap = (
    364   'c'   => 'c',
    365   'cp'  => 'c++',
    366   'cpp' => 'c++',
    367   'cc'  => 'c++',
    368   'i'   => 'c-cpp-output',
    369   'm'   => 'objective-c',
    370   'mi'  => 'objective-c-cpp-output'
    371 );
    372 
    373 my %UniqueOptions = (
    374   '-isysroot' => 0  
    375 );
    376 
    377 ##----------------------------------------------------------------------------##
    378 # Languages accepted.
    379 ##----------------------------------------------------------------------------##
    380 
    381 my %LangsAccepted = (
    382   "objective-c" => 1,
    383   "c" => 1
    384 );
    385 
    386 if (defined $ENV{'CCC_ANALYZER_CPLUSPLUS'}) {
    387   $LangsAccepted{"c++"} = 1;
    388   $LangsAccepted{"objective-c++"} = 1;
    389 }
    390 
    391 ##----------------------------------------------------------------------------##
    392 #  Main Logic.
    393 ##----------------------------------------------------------------------------##
    394 
    395 my $Action = 'link';
    396 my @CompileOpts;
    397 my @LinkOpts;
    398 my @Files;
    399 my $Lang;
    400 my $Output;
    401 my %Uniqued;
    402 
    403 # Forward arguments to gcc.
    404 my $Status = system($Compiler,@ARGV);
    405 if  (defined $ENV{'CCC_ANALYZER_LOG'}) {
    406   print "$Compiler @ARGV\n";
    407 }
    408 if ($Status) { exit($Status >> 8); }
    409 
    410 # Get the analysis options.
    411 my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};
    412 
    413 # Get the store model.
    414 my $StoreModel = $ENV{'CCC_ANALYZER_STORE_MODEL'};
    415 
    416 # Get the constraints engine.
    417 my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};
    418 
    419 # Get the output format.
    420 my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
    421 if (!defined $OutputFormat) { $OutputFormat = "html"; }
    422 
    423 # Determine the level of verbosity.
    424 my $Verbose = 0;
    425 if (defined $ENV{CCC_ANALYZER_VERBOSE}) { $Verbose = 1; }
    426 if (defined $ENV{CCC_ANALYZER_LOG}) { $Verbose = 2; }
    427 
    428 # Get the HTML output directory.
    429 my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};
    430 
    431 my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
    432 my %ArchsSeen;
    433 my $HadArch = 0;
    434 
    435 # Process the arguments.
    436 foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
    437   my $Arg = $ARGV[$i];  
    438   my ($ArgKey) = split /=/,$Arg,2;
    439 
    440   # Modes ccc-analyzer supports
    441   if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; }
    442   elsif ($Arg eq '-c') { $Action = 'compile'; }
    443   elsif ($Arg =~ /^-print-prog-name/) { exit 0; }
    444 
    445   # Specially handle duplicate cases of -arch
    446   if ($Arg eq "-arch") {
    447     my $arch = $ARGV[$i+1];
    448     # We don't want to process 'ppc' because of Clang's lack of support
    449     # for Altivec (also some #defines won't likely be defined correctly, etc.)
    450     if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; }
    451     $HadArch = 1;
    452     ++$i;
    453     next;
    454   }
    455 
    456   # Options with possible arguments that should pass through to compiler.
    457   if (defined $CompileOptionMap{$ArgKey}) {
    458     my $Cnt = $CompileOptionMap{$ArgKey};
    459     push @CompileOpts,$Arg;
    460     while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
    461     next;
    462   }
    463 
    464   # Options with possible arguments that should pass through to linker.
    465   if (defined $LinkerOptionMap{$ArgKey}) {
    466     my $Cnt = $LinkerOptionMap{$ArgKey};
    467     push @LinkOpts,$Arg;
    468     while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
    469     next;
    470   }
    471 
    472   # Options with possible arguments that should pass through to both compiler
    473   # and the linker.
    474   if (defined $CompilerLinkerOptionMap{$ArgKey}) {
    475     my $Cnt = $CompilerLinkerOptionMap{$ArgKey};
    476     
    477     # Check if this is an option that should have a unique value, and if so
    478     # determine if the value was checked before.
    479     if ($UniqueOptions{$Arg}) {
    480       if (defined $Uniqued{$Arg}) {
    481         $i += $Cnt;
    482         next;
    483       }
    484       $Uniqued{$Arg} = 1;
    485     }
    486     
    487     push @CompileOpts,$Arg;    
    488     push @LinkOpts,$Arg;
    489 
    490     while ($Cnt > 0) {
    491       ++$i; --$Cnt;
    492       push @CompileOpts, $ARGV[$i];
    493       push @LinkOpts, $ARGV[$i];
    494     }
    495     next;
    496   }
    497   
    498   # Ignored options.
    499   if (defined $IgnoredOptionMap{$ArgKey}) {
    500     my $Cnt = $IgnoredOptionMap{$ArgKey};
    501     while ($Cnt > 0) {
    502       ++$i; --$Cnt;
    503     }
    504     next;
    505   }
    506   
    507   # Compile mode flags.
    508   if ($Arg =~ /^-[D,I,U](.*)$/) {
    509     my $Tmp = $Arg;    
    510     if ($1 eq '') {
    511       # FIXME: Check if we are going off the end.
    512       ++$i;
    513       $Tmp = $Arg . $ARGV[$i];
    514     }
    515     push @CompileOpts,$Tmp;
    516     next;
    517   }
    518   
    519   # Language.
    520   if ($Arg eq '-x') {
    521     $Lang = $ARGV[$i+1];
    522     ++$i; next;
    523   }
    524 
    525   # Output file.
    526   if ($Arg eq '-o') {
    527     ++$i;
    528     $Output = $ARGV[$i];
    529     next;
    530   }
    531   
    532   # Get the link mode.
    533   if ($Arg =~ /^-[l,L,O]/) {
    534     if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
    535     elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
    536     else { push @LinkOpts,$Arg; }
    537     next;
    538   }
    539   
    540   if ($Arg =~ /^-std=/) {
    541     push @CompileOpts,$Arg;
    542     next;
    543   }
    544   
    545 #  if ($Arg =~ /^-f/) {
    546 #    # FIXME: Not sure if the remaining -fxxxx options have no arguments.
    547 #    push @CompileOpts,$Arg;
    548 #    push @LinkOpts,$Arg;  # FIXME: Not sure if these are link opts.
    549 #  }
    550   
    551   # Get the compiler/link mode.
    552   if ($Arg =~ /^-F(.+)$/) {
    553     my $Tmp = $Arg;
    554     if ($1 eq '') {
    555       # FIXME: Check if we are going off the end.
    556       ++$i;
    557       $Tmp = $Arg . $ARGV[$i];
    558     }
    559     push @CompileOpts,$Tmp;
    560     push @LinkOpts,$Tmp;
    561     next;
    562   }
    563 
    564   # Input files.
    565   if ($Arg eq '-filelist') {
    566     # FIXME: Make sure we aren't walking off the end.
    567     open(IN, $ARGV[$i+1]);
    568     while (<IN>) { s/\015?\012//; push @Files,$_; }
    569     close(IN);
    570     ++$i;
    571     next;
    572   }
    573   
    574   # Handle -Wno-.  We don't care about extra warnings, but
    575   # we should suppress ones that we don't want to see.
    576   if ($Arg =~ /^-Wno-/) {
    577     push @CompileOpts, $Arg;
    578     next;
    579   }
    580 
    581   if (!($Arg =~ /^-/)) {
    582     push @Files, $Arg;
    583     next;
    584   }
    585 }
    586 
    587 if ($Action eq 'compile' or $Action eq 'link') {
    588   my @Archs = keys %ArchsSeen;
    589   # Skip the file if we don't support the architectures specified.
    590   exit 0 if ($HadArch && scalar(@Archs) == 0);
    591   
    592   foreach my $file (@Files) {
    593     # Determine the language for the file.
    594     my $FileLang = $Lang;
    595 
    596     if (!defined($FileLang)) {
    597       # Infer the language from the extension.
    598       if ($file =~ /[.]([^.]+)$/) {
    599         $FileLang = $LangMap{$1};
    600       }
    601     }
    602     
    603     # FileLang still not defined?  Skip the file.
    604     next if (!defined $FileLang);
    605 
    606     # Language not accepted?
    607     next if (!defined $LangsAccepted{$FileLang});
    608 
    609     my @CmdArgs;
    610     my @AnalyzeArgs;    
    611     
    612     if ($FileLang ne 'unknown') {
    613       push @CmdArgs, '-x', $FileLang;
    614     }
    615 
    616     if (defined $StoreModel) {
    617       push @AnalyzeArgs, "-analyzer-store=$StoreModel";
    618     }
    619 
    620     if (defined $ConstraintsModel) {
    621       push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel";
    622     }
    623     
    624 #    if (defined $Analyses) {
    625 #      push @AnalyzeArgs, split '\s+', $Analyses;
    626 #    }
    627 
    628     if (defined $OutputFormat) {
    629       push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat;
    630       if ($OutputFormat =~ /plist/) {
    631         # Change "Output" to be a file.
    632         my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => ".plist",
    633                                DIR => $HtmlDir);
    634         $ResultFile = $f;
    635         $CleanupFile = $f;
    636       }
    637     }
    638 
    639     push @CmdArgs, @CompileOpts;
    640     push @CmdArgs, $file;
    641 
    642     if (scalar @Archs) {
    643       foreach my $arch (@Archs) {
    644         my @NewArgs;
    645         push @NewArgs, '-arch', $arch;
    646         push @NewArgs, @CmdArgs;
    647         Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output,
    648                 $Verbose, $HtmlDir, $file);
    649       }
    650     }
    651     else {
    652       Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output,
    653               $Verbose, $HtmlDir, $file);
    654     }
    655   }
    656 }
    657 
    658 exit($Status >> 8);
    659 
    660