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