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