3 # The LLVM Compiler Infrastructure
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
8 ##===----------------------------------------------------------------------===##
10 # A script designed to interpose between the build system and gcc. It invokes
11 # both gcc and the static analyzer.
13 ##===----------------------------------------------------------------------===##
18 use Cwd qw/ getcwd abs_path /;
19 use File::Temp qw/ tempfile /;
20 use File::Path qw / mkpath /;
24 ##===----------------------------------------------------------------------===##
25 # Compiler command setup.
26 ##===----------------------------------------------------------------------===##
31 my $DefaultCXXCompiler;
33 if (`uname -a` =~ m/Darwin/) {
34 $DefaultCCompiler = 'clang';
35 $DefaultCXXCompiler = 'clang++';
37 $DefaultCCompiler = 'gcc';
38 $DefaultCXXCompiler = 'g++';
41 if ($FindBin::Script =~ /c\+\+-analyzer/) {
42 $Compiler = $ENV{'CCC_CXX'};
43 if (!defined $Compiler) { $Compiler = $DefaultCXXCompiler; }
45 $Clang = $ENV{'CLANG_CXX'};
46 if (!defined $Clang) { $Clang = 'clang++'; }
49 $Compiler = $ENV{'CCC_CC'};
50 if (!defined $Compiler) { $Compiler = $DefaultCCompiler; }
52 $Clang = $ENV{'CLANG'};
53 if (!defined $Clang) { $Clang = 'clang'; }
56 ##===----------------------------------------------------------------------===##
58 ##===----------------------------------------------------------------------===##
60 my $ReportFailures = $ENV{'CCC_REPORT_FAILURES'};
61 if (!defined $ReportFailures) { $ReportFailures = 1; }
66 # Remove any stale files at exit.
68 if (defined $ResultFile && -z $ResultFile) {
71 if (defined $CleanupFile) {
76 ##----------------------------------------------------------------------------##
77 # Process Clang Crashes.
78 ##----------------------------------------------------------------------------##
82 if ($Lang =~ /objective-c\+\+/) { return ".mii" };
83 if ($Lang =~ /objective-c/) { return ".mi"; }
84 if ($Lang =~ /c\+\+/) { return ".ii"; }
88 # Set this to 1 if we want to include 'parser rejects' files.
89 my $IncludeParserRejects = 0;
90 my $ParserRejects = "Parser Rejects";
91 my $AttributeIgnored = "Attribute Ignored";
92 my $OtherError = "Other Error";
94 sub ProcessClangFailure {
95 my ($Clang, $Lang, $file, $Args, $HtmlDir, $ErrorType, $ofile) = @_;
96 my $Dir = "$HtmlDir/failures";
99 my $prefix = "clang_crash";
100 if ($ErrorType eq $ParserRejects) {
101 $prefix = "clang_parser_rejects";
103 elsif ($ErrorType eq $AttributeIgnored) {
104 $prefix = "clang_attribute_ignored";
106 elsif ($ErrorType eq $OtherError) {
107 $prefix = "clang_other_error";
110 # Generate the preprocessed file with Clang.
111 my ($PPH, $PPFile) = tempfile( $prefix . "_XXXXXX",
112 SUFFIX => GetPPExt($Lang),
114 system $Clang, @$Args, "-E", "-o", $PPFile;
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";
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);
129 ##----------------------------------------------------------------------------##
130 # Running the analyzer.
131 ##----------------------------------------------------------------------------##
137 pipe (FROM_CHILD, TO_PARENT);
141 open(STDOUT,">&", \*TO_PARENT);
142 open(STDERR,">&", \*TO_PARENT);
143 exec $Clang, "-###", $mode, @$Args;
147 while (<FROM_CHILD>) {
155 die "could not find clang line\n" if (!defined $line);
156 # Strip the newline and initial whitspace
159 my @items = quotewords('\s+', 0, $line);
160 my $cmd = shift @items;
161 die "cannot find 'clang' in 'clang' command\n" if (!($cmd =~ /clang/));
166 my ($Clang, $OriginalArgs, $AnalyzeArgs, $Lang, $Output, $Verbose, $HtmlDir,
169 my @Args = @$OriginalArgs;
172 my @CmdArgsSansAnalyses;
174 if ($Lang =~ /header/) {
175 exit 0 if (!defined ($Output));
177 push @CmdArgs, $file;
178 # Remove the PCH extension.
179 $Output =~ s/[.]gch$//;
180 push @CmdArgs, $Output;
181 @CmdArgsSansAnalyses = @CmdArgs;
185 if ($Lang eq "objective-c" || $Lang eq "objective-c++") {
186 push @Args,'-DIBOutlet=__attribute__((iboutlet))';
187 push @Args,'-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection)))';
188 push @Args,'-DIBAction=void)__attribute__((ibaction)';
191 # Create arguments for doing regular parsing.
192 my $SyntaxArgs = GetCCArgs("-fsyntax-only", \@Args);
193 @CmdArgsSansAnalyses = @$SyntaxArgs;
195 # Create arguments for doing static analysis.
196 if (defined $ResultFile) {
197 push @Args, '-o', $ResultFile;
199 elsif (defined $HtmlDir) {
200 push @Args, '-o', $HtmlDir;
203 push @Args, "-Xclang", "-analyzer-display-progress";
206 foreach my $arg (@$AnalyzeArgs) {
207 push @Args, "-Xclang", $arg;
210 # Display Ubiviz graph?
211 if (defined $ENV{'CCC_UBI'}) {
212 push @Args, "-Xclang", "-analyzer-viz-egraph-ubigraph";
215 my $AnalysisArgs = GetCCArgs("--analyze", \@Args);
216 @CmdArgs = @$AnalysisArgs;
224 print STDERR "\n[LOCATION]: $dir\n";
225 push @PrintArgs,"'$Cmd'";
226 foreach my $arg (@CmdArgs) {
227 push @PrintArgs,"\'$arg\'";
231 # We MUST print to stderr. Some clients use the stdout output of
232 # gcc for various purposes.
233 print STDERR join(' ', @PrintArgs);
236 elsif ($Verbose == 2) {
237 print STDERR "#SHELL (cd '$dir' && @PrintArgs)\n";
240 # Capture the STDERR of clang and send it to a temporary file.
241 # Capture the STDOUT of clang and reroute it to ccc-analyzer's STDERR.
242 # We save the output file in the 'crashes' directory if clang encounters
243 # any problems with the file.
244 pipe (FROM_CHILD, TO_PARENT);
248 open(STDOUT,">&", \*TO_PARENT);
249 open(STDERR,">&", \*TO_PARENT);
254 my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);
256 while (<FROM_CHILD>) {
265 # Did the command die because of a signal?
266 if ($ReportFailures) {
267 if ($Result & 127 and $Cmd eq $Clang and defined $HtmlDir) {
268 ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
269 $HtmlDir, "Crash", $ofile);
272 if ($IncludeParserRejects && !($file =~/conftest/)) {
273 ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
274 $HtmlDir, $ParserRejects, $ofile);
276 ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
277 $HtmlDir, $OtherError, $ofile);
281 # Check if there were any unhandled attributes.
282 if (open(CHILD, $ofile)) {
283 my %attributes_not_handled;
285 # Don't flag warnings about the following attributes that we
286 # know are currently not supported by Clang.
287 $attributes_not_handled{"cdecl"} = 1;
291 next if (! /warning: '([^\']+)' attribute ignored/);
293 # Have we already spotted this unhandled attribute?
294 next if (defined $attributes_not_handled{$1});
295 $attributes_not_handled{$1} = 1;
297 # Get the name of the attribute file.
298 my $dir = "$HtmlDir/failures";
299 my $afile = "$dir/attribute_ignored_$1.txt";
301 # Only create another preprocessed file if the attribute file
305 # Add this file to the list of files that contained this attribute.
306 # Generate a preprocessed file if we haven't already.
307 if (!(defined $ppfile)) {
308 $ppfile = ProcessClangFailure($Clang, $Lang, $file,
309 \@CmdArgsSansAnalyses,
310 $HtmlDir, $AttributeIgnored, $ofile);
314 open(AFILE, ">$afile");
315 print AFILE "$ppfile\n";
326 ##----------------------------------------------------------------------------##
328 ##----------------------------------------------------------------------------##
330 my %CompileOptionMap = (
334 '-fobjc-gc-only' => 0,
336 '-ffreestanding' => 0,
344 '-iwithprefixbefore' => 1
347 my %LinkerOptionMap = (
349 '-fobjc-link-runtime' => 0
352 my %CompilerLinkerOptionMap = (
354 '-fobjc-abi-version' => 0, # This is really a 1 argument, but always has '='
360 '-fpascal-strings' => 0,
361 '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
362 '-miphoneos-version-min' => 0 # This is really a 1 argument, but always has '='
365 my %IgnoredOptionMap = (
366 '-MT' => 1, # Ignore these preprocessor options.
369 '-fsyntax-only' => 0,
371 '-install_name' => 1,
372 '-exported_symbols_list' => 1,
373 '-current_version' => 1,
374 '-compatibility_version' => 1,
378 '-bundle_loader' => 1,
379 '-multiply_defined' => 1,
383 '--serialize-diagnostics' => 1
394 'i' => 'c-cpp-output',
395 'm' => 'objective-c',
396 'mi' => 'objective-c-cpp-output',
397 'mm' => 'objective-c++'
400 my %UniqueOptions = (
404 ##----------------------------------------------------------------------------##
405 # Languages accepted.
406 ##----------------------------------------------------------------------------##
408 my %LangsAccepted = (
415 ##----------------------------------------------------------------------------##
417 ##----------------------------------------------------------------------------##
427 # Forward arguments to gcc.
428 my $Status = system($Compiler,@ARGV);
429 if (defined $ENV{'CCC_ANALYZER_LOG'}) {
430 print "$Compiler @ARGV\n";
432 if ($Status) { exit($Status >> 8); }
434 # Get the analysis options.
435 my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};
437 # Get the store model.
438 my $StoreModel = $ENV{'CCC_ANALYZER_STORE_MODEL'};
440 # Get the constraints engine.
441 my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};
443 # Get the output format.
444 my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
445 if (!defined $OutputFormat) { $OutputFormat = "html"; }
447 # Determine the level of verbosity.
449 if (defined $ENV{CCC_ANALYZER_VERBOSE}) { $Verbose = 1; }
450 if (defined $ENV{CCC_ANALYZER_LOG}) { $Verbose = 2; }
452 # Get the HTML output directory.
453 my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};
455 my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
459 # Process the arguments.
460 foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
462 my ($ArgKey) = split /=/,$Arg,2;
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; }
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; }
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]; }
488 # Options with possible arguments that should pass through to linker.
489 if (defined $LinkerOptionMap{$ArgKey}) {
490 my $Cnt = $LinkerOptionMap{$ArgKey};
492 while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
496 # Options with possible arguments that should pass through to both compiler
498 if (defined $CompilerLinkerOptionMap{$ArgKey}) {
499 my $Cnt = $CompilerLinkerOptionMap{$ArgKey};
501 # Check if this is an option that should have a unique value, and if so
502 # determine if the value was checked before.
503 if ($UniqueOptions{$Arg}) {
504 if (defined $Uniqued{$Arg}) {
511 push @CompileOpts,$Arg;
516 push @CompileOpts, $ARGV[$i];
517 push @LinkOpts, $ARGV[$i];
523 if (defined $IgnoredOptionMap{$ArgKey}) {
524 my $Cnt = $IgnoredOptionMap{$ArgKey};
531 # Compile mode flags.
532 if ($Arg =~ /^-[D,I,U](.*)$/) {
535 # FIXME: Check if we are going off the end.
537 $Tmp = $Arg . $ARGV[$i];
539 push @CompileOpts,$Tmp;
557 if ($Arg =~ /^-[l,L,O]/) {
558 if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
559 elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
560 else { push @LinkOpts,$Arg; }
564 if ($Arg =~ /^-std=/) {
565 push @CompileOpts,$Arg;
569 # if ($Arg =~ /^-f/) {
570 # # FIXME: Not sure if the remaining -fxxxx options have no arguments.
571 # push @CompileOpts,$Arg;
572 # push @LinkOpts,$Arg; # FIXME: Not sure if these are link opts.
575 # Get the compiler/link mode.
576 if ($Arg =~ /^-F(.+)$/) {
579 # FIXME: Check if we are going off the end.
581 $Tmp = $Arg . $ARGV[$i];
583 push @CompileOpts,$Tmp;
589 if ($Arg eq '-filelist') {
590 # FIXME: Make sure we aren't walking off the end.
591 open(IN, $ARGV[$i+1]);
592 while (<IN>) { s/\015?\012//; push @Files,$_; }
598 # Handle -Wno-. We don't care about extra warnings, but
599 # we should suppress ones that we don't want to see.
600 if ($Arg =~ /^-Wno-/) {
601 push @CompileOpts, $Arg;
605 if (!($Arg =~ /^-/)) {
611 if ($Action eq 'compile' or $Action eq 'link') {
612 my @Archs = keys %ArchsSeen;
613 # Skip the file if we don't support the architectures specified.
614 exit 0 if ($HadArch && scalar(@Archs) == 0);
616 foreach my $file (@Files) {
617 # Determine the language for the file.
618 my $FileLang = $Lang;
620 if (!defined($FileLang)) {
621 # Infer the language from the extension.
622 if ($file =~ /[.]([^.]+)$/) {
623 $FileLang = $LangMap{$1};
627 # FileLang still not defined? Skip the file.
628 next if (!defined $FileLang);
630 # Language not accepted?
631 next if (!defined $LangsAccepted{$FileLang});
636 if ($FileLang ne 'unknown') {
637 push @CmdArgs, '-x', $FileLang;
640 if (defined $StoreModel) {
641 push @AnalyzeArgs, "-analyzer-store=$StoreModel";
644 if (defined $ConstraintsModel) {
645 push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel";
648 if (defined $Analyses) {
649 push @AnalyzeArgs, split '\s+', $Analyses;
652 if (defined $OutputFormat) {
653 push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat;
654 if ($OutputFormat =~ /plist/) {
655 # Change "Output" to be a file.
656 my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => ".plist",
659 # If the HtmlDir is not set, we sould clean up the plist files.
660 if (!defined $HtmlDir || -z $HtmlDir) {
666 push @CmdArgs, @CompileOpts;
667 push @CmdArgs, $file;
670 foreach my $arch (@Archs) {
672 push @NewArgs, '-arch', $arch;
673 push @NewArgs, @CmdArgs;
674 Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output,
675 $Verbose, $HtmlDir, $file);
679 Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output,
680 $Verbose, $HtmlDir, $file);