ccc-analyzer revision 501be138462d9d6fe1b55ea92c3a14a2d7501c5f
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
256  waitpid($pid,0);
257  close(FROM_CHILD);
258  my $Result = $?;
259
260  # Did the command die because of a signal?
261  if ($ReportFailures) {
262    if ($Result & 127 and $Cmd eq $Clang and defined $HtmlDir) {
263      ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
264                          $HtmlDir, "Crash", $ofile);
265    }
266    elsif ($Result) {
267      if ($IncludeParserRejects && !($file =~/conftest/)) {
268        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
269                            $HtmlDir, $ParserRejects, $ofile);
270      } else {
271        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
272                            $HtmlDir, $OtherError, $ofile);      	
273      }
274    }
275    else {
276      # Check if there were any unhandled attributes.
277      if (open(CHILD, $ofile)) {
278        my %attributes_not_handled;
279
280        # Don't flag warnings about the following attributes that we
281        # know are currently not supported by Clang.
282        $attributes_not_handled{"cdecl"} = 1;
283
284        my $ppfile;
285        while (<CHILD>) {
286          next if (! /warning: '([^\']+)' attribute ignored/);
287
288          # Have we already spotted this unhandled attribute?
289          next if (defined $attributes_not_handled{$1});
290          $attributes_not_handled{$1} = 1;
291        
292          # Get the name of the attribute file.
293          my $dir = "$HtmlDir/failures";
294          my $afile = "$dir/attribute_ignored_$1.txt";
295        
296          # Only create another preprocessed file if the attribute file
297          # doesn't exist yet.
298          next if (-e $afile);
299        
300          # Add this file to the list of files that contained this attribute.
301          # Generate a preprocessed file if we haven't already.
302          if (!(defined $ppfile)) {
303            $ppfile = ProcessClangFailure($Clang, $Lang, $file,
304                                          \@CmdArgsSansAnalyses,
305                                          $HtmlDir, $AttributeIgnored, $ofile);
306          }
307
308          mkpath $dir;
309          open(AFILE, ">$afile");
310          print AFILE "$ppfile\n";
311          close(AFILE);
312        }
313        close CHILD;
314      }
315    }
316  }
317  
318  unlink($ofile);
319}
320
321##----------------------------------------------------------------------------##
322#  Lookup tables.
323##----------------------------------------------------------------------------##
324
325my %CompileOptionMap = (
326  '-nostdinc' => 0,
327  '-fblocks' => 0,
328  '-fno-builtin' => 0,
329  '-fobjc-gc-only' => 0,
330  '-fobjc-gc' => 0,
331  '-ffreestanding' => 0,
332  '-include' => 1,
333  '-idirafter' => 1,
334  '-imacros' => 1,
335  '-iprefix' => 1,
336  '-iquote' => 1,
337  '-isystem' => 1,
338  '-iwithprefix' => 1,
339  '-iwithprefixbefore' => 1
340);
341
342my %LinkerOptionMap = (
343  '-framework' => 1,
344  '-fobjc-link-runtime' => 0
345);
346
347my %CompilerLinkerOptionMap = (
348  '-fobjc-arc' => 0,
349  '-fno-objc-arc' => 0,
350  '-fobjc-abi-version' => 0, # This is really a 1 argument, but always has '='
351  '-fobjc-legacy-dispatch' => 0,
352  '-mios-simulator-version-min' => 0, # This really has 1 argument, but always has '='
353  '-isysroot' => 1,
354  '-arch' => 1,
355  '-m32' => 0,
356  '-m64' => 0,
357  '-stdlib' => 0, # This is really a 1 argument, but always has '='
358  '-v' => 0,
359  '-fpascal-strings' => 0,
360  '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
361  '-miphoneos-version-min' => 0 # This is really a 1 argument, but always has '='
362);
363
364my %IgnoredOptionMap = (
365  '-MT' => 1,  # Ignore these preprocessor options.
366  '-MF' => 1,
367
368  '-fsyntax-only' => 0,
369  '-save-temps' => 0,
370  '-install_name' => 1,
371  '-exported_symbols_list' => 1,
372  '-current_version' => 1,
373  '-compatibility_version' => 1,
374  '-init' => 1,
375  '-e' => 1,
376  '-seg1addr' => 1,
377  '-bundle_loader' => 1,
378  '-multiply_defined' => 1,
379  '-sectorder' => 3,
380  '--param' => 1,
381  '-u' => 1,
382  '--serialize-diagnostics' => 1
383);
384
385my %LangMap = (
386  'c'   => 'c',
387  'cp'  => 'c++',
388  'cpp' => 'c++',
389  'cxx' => 'c++',
390  'txx' => 'c++',
391  'cc'  => 'c++',
392  'C'   => 'c++',
393  'ii'  => 'c++',
394  'i'   => 'c-cpp-output',
395  'm'   => 'objective-c',
396  'mi'  => 'objective-c-cpp-output',
397  'mm'  => 'objective-c++'
398);
399
400my %UniqueOptions = (
401  '-isysroot' => 0  
402);
403
404##----------------------------------------------------------------------------##
405# Languages accepted.
406##----------------------------------------------------------------------------##
407
408my %LangsAccepted = (
409  "objective-c" => 1,
410  "c" => 1,
411  "c++" => 1,
412  "objective-c++" => 1
413);
414
415##----------------------------------------------------------------------------##
416#  Main Logic.
417##----------------------------------------------------------------------------##
418
419my $Action = 'link';
420my @CompileOpts;
421my @LinkOpts;
422my @Files;
423my $Lang;
424my $Output;
425my %Uniqued;
426
427# Forward arguments to gcc.
428my $Status = system($Compiler,@ARGV);
429if  (defined $ENV{'CCC_ANALYZER_LOG'}) {
430  print "$Compiler @ARGV\n";
431}
432if ($Status) { exit($Status >> 8); }
433
434# Get the analysis options.
435my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};
436
437# Get the plugins to load.
438my $Plugins = $ENV{'CCC_ANALYZER_PLUGINS'};
439
440# Get the store model.
441my $StoreModel = $ENV{'CCC_ANALYZER_STORE_MODEL'};
442
443# Get the constraints engine.
444my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};
445
446#Get the internal stats setting.
447my $InternalStats = $ENV{'CCC_ANALYZER_INTERNAL_STATS'};
448
449# Get the output format.
450my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
451if (!defined $OutputFormat) { $OutputFormat = "html"; }
452
453# Determine the level of verbosity.
454my $Verbose = 0;
455if (defined $ENV{CCC_ANALYZER_VERBOSE}) { $Verbose = 1; }
456if (defined $ENV{CCC_ANALYZER_LOG}) { $Verbose = 2; }
457
458# Get the HTML output directory.
459my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};
460
461my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
462my %ArchsSeen;
463my $HadArch = 0;
464
465# Process the arguments.
466foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
467  my $Arg = $ARGV[$i];  
468  my ($ArgKey) = split /=/,$Arg,2;
469
470  # Modes ccc-analyzer supports
471  if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; }
472  elsif ($Arg eq '-c') { $Action = 'compile'; }
473  elsif ($Arg =~ /^-print-prog-name/) { exit 0; }
474
475  # Specially handle duplicate cases of -arch
476  if ($Arg eq "-arch") {
477    my $arch = $ARGV[$i+1];
478    # We don't want to process 'ppc' because of Clang's lack of support
479    # for Altivec (also some #defines won't likely be defined correctly, etc.)
480    if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; }
481    $HadArch = 1;
482    ++$i;
483    next;
484  }
485
486  # Options with possible arguments that should pass through to compiler.
487  if (defined $CompileOptionMap{$ArgKey}) {
488    my $Cnt = $CompileOptionMap{$ArgKey};
489    push @CompileOpts,$Arg;
490    while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
491    next;
492  }
493
494  # Options with possible arguments that should pass through to linker.
495  if (defined $LinkerOptionMap{$ArgKey}) {
496    my $Cnt = $LinkerOptionMap{$ArgKey};
497    push @LinkOpts,$Arg;
498    while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
499    next;
500  }
501
502  # Options with possible arguments that should pass through to both compiler
503  # and the linker.
504  if (defined $CompilerLinkerOptionMap{$ArgKey}) {
505    my $Cnt = $CompilerLinkerOptionMap{$ArgKey};
506    
507    # Check if this is an option that should have a unique value, and if so
508    # determine if the value was checked before.
509    if ($UniqueOptions{$Arg}) {
510      if (defined $Uniqued{$Arg}) {
511        $i += $Cnt;
512        next;
513      }
514      $Uniqued{$Arg} = 1;
515    }
516    
517    push @CompileOpts,$Arg;    
518    push @LinkOpts,$Arg;
519
520    while ($Cnt > 0) {
521      ++$i; --$Cnt;
522      push @CompileOpts, $ARGV[$i];
523      push @LinkOpts, $ARGV[$i];
524    }
525    next;
526  }
527  
528  # Ignored options.
529  if (defined $IgnoredOptionMap{$ArgKey}) {
530    my $Cnt = $IgnoredOptionMap{$ArgKey};
531    while ($Cnt > 0) {
532      ++$i; --$Cnt;
533    }
534    next;
535  }
536  
537  # Compile mode flags.
538  if ($Arg =~ /^-[D,I,U](.*)$/) {
539    my $Tmp = $Arg;    
540    if ($1 eq '') {
541      # FIXME: Check if we are going off the end.
542      ++$i;
543      $Tmp = $Arg . $ARGV[$i];
544    }
545    push @CompileOpts,$Tmp;
546    next;
547  }
548  
549  # Language.
550  if ($Arg eq '-x') {
551    $Lang = $ARGV[$i+1];
552    ++$i; next;
553  }
554
555  # Output file.
556  if ($Arg eq '-o') {
557    ++$i;
558    $Output = $ARGV[$i];
559    next;
560  }
561  
562  # Get the link mode.
563  if ($Arg =~ /^-[l,L,O]/) {
564    if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
565    elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
566    else { push @LinkOpts,$Arg; }
567    next;
568  }
569  
570  if ($Arg =~ /^-std=/) {
571    push @CompileOpts,$Arg;
572    next;
573  }
574  
575#  if ($Arg =~ /^-f/) {
576#    # FIXME: Not sure if the remaining -fxxxx options have no arguments.
577#    push @CompileOpts,$Arg;
578#    push @LinkOpts,$Arg;  # FIXME: Not sure if these are link opts.
579#  }
580  
581  # Get the compiler/link mode.
582  if ($Arg =~ /^-F(.+)$/) {
583    my $Tmp = $Arg;
584    if ($1 eq '') {
585      # FIXME: Check if we are going off the end.
586      ++$i;
587      $Tmp = $Arg . $ARGV[$i];
588    }
589    push @CompileOpts,$Tmp;
590    push @LinkOpts,$Tmp;
591    next;
592  }
593
594  # Input files.
595  if ($Arg eq '-filelist') {
596    # FIXME: Make sure we aren't walking off the end.
597    open(IN, $ARGV[$i+1]);
598    while (<IN>) { s/\015?\012//; push @Files,$_; }
599    close(IN);
600    ++$i;
601    next;
602  }
603  
604  # Handle -Wno-.  We don't care about extra warnings, but
605  # we should suppress ones that we don't want to see.
606  if ($Arg =~ /^-Wno-/) {
607    push @CompileOpts, $Arg;
608    next;
609  }
610
611  if (!($Arg =~ /^-/)) {
612    push @Files, $Arg;
613    next;
614  }
615}
616
617if ($Action eq 'compile' or $Action eq 'link') {
618  my @Archs = keys %ArchsSeen;
619  # Skip the file if we don't support the architectures specified.
620  exit 0 if ($HadArch && scalar(@Archs) == 0);
621  
622  foreach my $file (@Files) {
623    # Determine the language for the file.
624    my $FileLang = $Lang;
625
626    if (!defined($FileLang)) {
627      # Infer the language from the extension.
628      if ($file =~ /[.]([^.]+)$/) {
629        $FileLang = $LangMap{$1};
630      }
631    }
632    
633    # FileLang still not defined?  Skip the file.
634    next if (!defined $FileLang);
635
636    # Language not accepted?
637    next if (!defined $LangsAccepted{$FileLang});
638
639    my @CmdArgs;
640    my @AnalyzeArgs;    
641    
642    if ($FileLang ne 'unknown') {
643      push @CmdArgs, '-x', $FileLang;
644    }
645
646    if (defined $StoreModel) {
647      push @AnalyzeArgs, "-analyzer-store=$StoreModel";
648    }
649
650    if (defined $ConstraintsModel) {
651      push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel";
652    }
653
654    if (defined $InternalStats) {
655      push @AnalyzeArgs, "-analyzer-stats";
656    }
657    
658    if (defined $Analyses) {
659      push @AnalyzeArgs, split '\s+', $Analyses;
660    }
661
662    if (defined $Plugins) {
663      push @AnalyzeArgs, split '\s+', $Plugins;
664    }
665
666    if (defined $OutputFormat) {
667      push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat;
668      if ($OutputFormat =~ /plist/) {
669        # Change "Output" to be a file.
670        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => ".plist",
671                               DIR => $HtmlDir);
672        $ResultFile = $f;
673        # If the HtmlDir is not set, we sould clean up the plist files.
674        if (!defined $HtmlDir || -z $HtmlDir) {
675        	$CleanupFile = $f; 
676        }
677      }
678    }
679
680    push @CmdArgs, @CompileOpts;
681    push @CmdArgs, $file;
682
683    if (scalar @Archs) {
684      foreach my $arch (@Archs) {
685        my @NewArgs;
686        push @NewArgs, '-arch', $arch;
687        push @NewArgs, @CmdArgs;
688        Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output,
689                $Verbose, $HtmlDir, $file);
690      }
691    }
692    else {
693      Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output,
694              $Verbose, $HtmlDir, $file);
695    }
696  }
697}
698
699exit($Status >> 8);
700
701