ccc-analyzer revision 2aefcb2e8b8b37529807945b3ecedda76e75c831
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 '-iprefix' => 1, 324 '-iquote' => 1, 325 '-isystem' => 1, 326 '-iwithprefix' => 1, 327 '-iwithprefixbefore' => 1 328); 329 330my %LinkerOptionMap = ( 331 '-framework' => 1 332); 333 334my %CompilerLinkerOptionMap = ( 335 '-isysroot' => 1, 336 '-arch' => 1, 337 '-m32' => 0, 338 '-m64' => 0, 339 '-v' => 0, 340 '-fpascal-strings' => 0, 341 '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '=' 342 '-miphoneos-version-min' => 0 # This is really a 1 argument, but always has '=' 343); 344 345my %IgnoredOptionMap = ( 346 '-MT' => 1, # Ignore these preprocessor options. 347 '-MF' => 1, 348 349 '-fsyntax-only' => 0, 350 '-save-temps' => 0, 351 '-install_name' => 1, 352 '-exported_symbols_list' => 1, 353 '-current_version' => 1, 354 '-compatibility_version' => 1, 355 '-init' => 1, 356 '-e' => 1, 357 '-seg1addr' => 1, 358 '-bundle_loader' => 1, 359 '-multiply_defined' => 1, 360 '-sectorder' => 3, 361 '--param' => 1, 362 '-u' => 1 363); 364 365my %LangMap = ( 366 'c' => 'c', 367 'cpp' => 'c++', 368 'cc' => 'c++', 369 'i' => 'c-cpp-output', 370 'm' => 'objective-c', 371 'mi' => 'objective-c-cpp-output' 372); 373 374my %UniqueOptions = ( 375 '-isysroot' => 0 376); 377 378##----------------------------------------------------------------------------## 379# Languages accepted. 380##----------------------------------------------------------------------------## 381 382my %LangsAccepted = ( 383 "objective-c" => 1, 384 "c" => 1 385); 386 387if (defined $ENV{'CCC_ANALYZER_CPLUSPLUS'}) { 388 $LangsAccepted{"c++"} = 1; 389 $LangsAccepted{"objective-c++"} = 1; 390} 391 392##----------------------------------------------------------------------------## 393# Main Logic. 394##----------------------------------------------------------------------------## 395 396my $Action = 'link'; 397my @CompileOpts; 398my @LinkOpts; 399my @Files; 400my $Lang; 401my $Output; 402my %Uniqued; 403 404# Forward arguments to gcc. 405my $Status = system($Compiler,@ARGV); 406if ($Status) { exit($Status >> 8); } 407 408# Get the analysis options. 409my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'}; 410if (!defined($Analyses)) { $Analyses = '-analyzer-check-objc-mem'; } 411 412# Get the store model. 413my $StoreModel = $ENV{'CCC_ANALYZER_STORE_MODEL'}; 414if (!defined $StoreModel) { $StoreModel = "region"; } 415 416# Get the constraints engine. 417my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'}; 418if (!defined $ConstraintsModel) { $ConstraintsModel = "range"; } 419 420# Get the output format. 421my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'}; 422if (!defined $OutputFormat) { $OutputFormat = "html"; } 423 424# Determine the level of verbosity. 425my $Verbose = 0; 426if (defined $ENV{CCC_ANALYZER_VERBOSE}) { $Verbose = 1; } 427if (defined $ENV{CCC_ANALYZER_LOG}) { $Verbose = 2; } 428 429# Get the HTML output directory. 430my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'}; 431 432my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1); 433my %ArchsSeen; 434my $HadArch = 0; 435 436# Process the arguments. 437foreach (my $i = 0; $i < scalar(@ARGV); ++$i) { 438 my $Arg = $ARGV[$i]; 439 my ($ArgKey) = split /=/,$Arg,2; 440 441 # Modes ccc-analyzer supports 442 if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; } 443 elsif ($Arg eq '-c') { $Action = 'compile'; } 444 elsif ($Arg =~ /^-print-prog-name/) { exit 0; } 445 446 # Specially handle duplicate cases of -arch 447 if ($Arg eq "-arch") { 448 my $arch = $ARGV[$i+1]; 449 # We don't want to process 'ppc' because of Clang's lack of support 450 # for Altivec (also some #defines won't likely be defined correctly, etc.) 451 if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; } 452 $HadArch = 1; 453 ++$i; 454 next; 455 } 456 457 # Options with possible arguments that should pass through to compiler. 458 if (defined $CompileOptionMap{$ArgKey}) { 459 my $Cnt = $CompileOptionMap{$ArgKey}; 460 push @CompileOpts,$Arg; 461 while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; } 462 next; 463 } 464 465 # Options with possible arguments that should pass through to linker. 466 if (defined $LinkerOptionMap{$ArgKey}) { 467 my $Cnt = $LinkerOptionMap{$ArgKey}; 468 push @LinkOpts,$Arg; 469 while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; } 470 next; 471 } 472 473 # Options with possible arguments that should pass through to both compiler 474 # and the linker. 475 if (defined $CompilerLinkerOptionMap{$ArgKey}) { 476 my $Cnt = $CompilerLinkerOptionMap{$ArgKey}; 477 478 # Check if this is an option that should have a unique value, and if so 479 # determine if the value was checked before. 480 if ($UniqueOptions{$Arg}) { 481 if (defined $Uniqued{$Arg}) { 482 $i += $Cnt; 483 next; 484 } 485 $Uniqued{$Arg} = 1; 486 } 487 488 push @CompileOpts,$Arg; 489 push @LinkOpts,$Arg; 490 491 while ($Cnt > 0) { 492 ++$i; --$Cnt; 493 push @CompileOpts, $ARGV[$i]; 494 push @LinkOpts, $ARGV[$i]; 495 } 496 next; 497 } 498 499 # Ignored options. 500 if (defined $IgnoredOptionMap{$ArgKey}) { 501 my $Cnt = $IgnoredOptionMap{$ArgKey}; 502 while ($Cnt > 0) { 503 ++$i; --$Cnt; 504 } 505 next; 506 } 507 508 # Compile mode flags. 509 if ($Arg =~ /^-[D,I,U](.*)$/) { 510 my $Tmp = $Arg; 511 if ($1 eq '') { 512 # FIXME: Check if we are going off the end. 513 ++$i; 514 $Tmp = $Arg . $ARGV[$i]; 515 } 516 push @CompileOpts,$Tmp; 517 next; 518 } 519 520 # Language. 521 if ($Arg eq '-x') { 522 $Lang = $ARGV[$i+1]; 523 ++$i; next; 524 } 525 526 # Output file. 527 if ($Arg eq '-o') { 528 ++$i; 529 $Output = $ARGV[$i]; 530 next; 531 } 532 533 # Get the link mode. 534 if ($Arg =~ /^-[l,L,O]/) { 535 if ($Arg eq '-O') { push @LinkOpts,'-O1'; } 536 elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; } 537 else { push @LinkOpts,$Arg; } 538 next; 539 } 540 541 if ($Arg =~ /^-std=/) { 542 push @CompileOpts,$Arg; 543 next; 544 } 545 546# if ($Arg =~ /^-f/) { 547# # FIXME: Not sure if the remaining -fxxxx options have no arguments. 548# push @CompileOpts,$Arg; 549# push @LinkOpts,$Arg; # FIXME: Not sure if these are link opts. 550# } 551 552 # Get the compiler/link mode. 553 if ($Arg =~ /^-F(.+)$/) { 554 my $Tmp = $Arg; 555 if ($1 eq '') { 556 # FIXME: Check if we are going off the end. 557 ++$i; 558 $Tmp = $Arg . $ARGV[$i]; 559 } 560 push @CompileOpts,$Tmp; 561 push @LinkOpts,$Tmp; 562 next; 563 } 564 565 # Input files. 566 if ($Arg eq '-filelist') { 567 # FIXME: Make sure we aren't walking off the end. 568 open(IN, $ARGV[$i+1]); 569 while (<IN>) { s/\015?\012//; push @Files,$_; } 570 close(IN); 571 ++$i; 572 next; 573 } 574 575 # Handle -Wno-. We don't care about extra warnings, but 576 # we should suppress ones that we don't want to see. 577 if ($Arg =~ /^-Wno-/) { 578 push @CompileOpts, $Arg; 579 next; 580 } 581 582 if (!($Arg =~ /^-/)) { 583 push @Files, $Arg; 584 next; 585 } 586} 587 588if ($Action eq 'compile' or $Action eq 'link') { 589 my @Archs = keys %ArchsSeen; 590 # Skip the file if we don't support the architectures specified. 591 exit 0 if ($HadArch && scalar(@Archs) == 0); 592 593 foreach my $file (@Files) { 594 # Determine the language for the file. 595 my $FileLang = $Lang; 596 597 if (!defined($FileLang)) { 598 # Infer the language from the extension. 599 if ($file =~ /[.]([^.]+)$/) { 600 $FileLang = $LangMap{$1}; 601 } 602 } 603 604 # FileLang still not defined? Skip the file. 605 next if (!defined $FileLang); 606 607 # Language not accepted? 608 next if (!defined $LangsAccepted{$FileLang}); 609 610 my @CmdArgs; 611 my @AnalyzeArgs; 612 613 if ($FileLang ne 'unknown') { 614 push @CmdArgs,'-x'; 615 push @CmdArgs,$FileLang; 616 } 617 618 if (defined $StoreModel) { 619 push @AnalyzeArgs, "-analyzer-store=$StoreModel"; 620 } 621 622 if (defined $ConstraintsModel) { 623 push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel"; 624 } 625 626 if (defined $OutputFormat) { 627 push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat; 628 if ($OutputFormat =~ /plist/) { 629 # Change "Output" to be a file. 630 my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => ".plist", 631 DIR => $HtmlDir); 632 $ResultFile = $f; 633 $CleanupFile = $f; 634 } 635 } 636 637 push @CmdArgs,@CompileOpts; 638 push @CmdArgs,$file; 639 640 if (scalar @Archs) { 641 foreach my $arch (@Archs) { 642 my @NewArgs; 643 push @NewArgs, '-arch'; 644 push @NewArgs, $arch; 645 push @NewArgs, @CmdArgs; 646 Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output, 647 $Verbose, $HtmlDir, $file, $Analyses); 648 } 649 } 650 else { 651 Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output, 652 $Verbose, $HtmlDir, $file, $Analyses); 653 } 654 } 655} 656 657exit($Status >> 8); 658 659