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