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