ccc-analyzer 20.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
#!/usr/bin/env perl
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
##===----------------------------------------------------------------------===##
#
#  A script designed to interpose between the build system and gcc.  It invokes
#  both gcc and the static analyzer.
#
##===----------------------------------------------------------------------===##

use strict;
use warnings;
use FindBin;
use Cwd qw/ getcwd abs_path /;
use File::Temp qw/ tempfile /;
use File::Path qw / mkpath /;
use File::Basename;
use Text::ParseWords;

##===----------------------------------------------------------------------===##
# List form 'system' with STDOUT and STDERR captured.
##===----------------------------------------------------------------------===##

sub silent_system {
  my $HtmlDir = shift;
  my $Command = shift;

  # Save STDOUT and STDERR and redirect to a temporary file.
  open OLDOUT, ">&", \*STDOUT;
  open OLDERR, ">&", \*STDERR;
  my ($TmpFH, $TmpFile) = tempfile("temp_buf_XXXXXX",
                                   DIR => $HtmlDir,
                                   UNLINK => 1);
  open(STDOUT, ">$TmpFile");
  open(STDERR, ">&", \*STDOUT);

  # Invoke 'system', STDOUT and STDERR are output to a temporary file.
  system $Command, @_;

  # Restore STDOUT and STDERR.
  open STDOUT, ">&", \*OLDOUT;
  open STDERR, ">&", \*OLDERR;

  return $TmpFH;
}

##===----------------------------------------------------------------------===##
# Compiler command setup.
##===----------------------------------------------------------------------===##

# Search in the PATH if the compiler exists
sub SearchInPath {
    my $file = shift;
    foreach my $dir (split (':', $ENV{PATH})) {
        if (-x "$dir/$file") {
            return 1;
        }
    }
    return 0;
}

my $Compiler;
my $Clang;
my $DefaultCCompiler;
my $DefaultCXXCompiler;
my $IsCXX;
my $AnalyzerTarget;

# If on OSX, use xcrun to determine the SDK root.
my $UseXCRUN = 0;

if (`uname -a` =~ m/Darwin/) {
  $DefaultCCompiler = 'clang';
  $DefaultCXXCompiler = 'clang++';
  # Older versions of OSX do not have xcrun to
  # query the SDK location.
  if (-x "/usr/bin/xcrun") {
    $UseXCRUN = 1;
  }
} else {
  $DefaultCCompiler = 'gcc';
  $DefaultCXXCompiler = 'g++';
}

if ($FindBin::Script =~ /c\+\+-analyzer/) {
  $Compiler = $ENV{'CCC_CXX'};
  if (!defined $Compiler || (! -x $Compiler && ! SearchInPath($Compiler))) { $Compiler = $DefaultCXXCompiler; }

  $Clang = $ENV{'CLANG_CXX'};
  if (!defined $Clang || ! -x $Clang) { $Clang = 'clang++'; }

  $IsCXX = 1
}
else {
  $Compiler = $ENV{'CCC_CC'};
  if (!defined $Compiler || (! -x $Compiler && ! SearchInPath($Compiler))) { $Compiler = $DefaultCCompiler; }

  $Clang = $ENV{'CLANG'};
  if (!defined $Clang || ! -x $Clang) { $Clang = 'clang'; }

  $IsCXX = 0
}

$AnalyzerTarget = $ENV{'CLANG_ANALYZER_TARGET'};

##===----------------------------------------------------------------------===##
# Cleanup.
##===----------------------------------------------------------------------===##

my $ReportFailures = $ENV{'CCC_REPORT_FAILURES'};
if (!defined $ReportFailures) { $ReportFailures = 1; }

my $CleanupFile;
my $ResultFile;

# Remove any stale files at exit.
END {
  if (defined $ResultFile && -z $ResultFile) {
    unlink($ResultFile);
  }
  if (defined $CleanupFile) {
    unlink($CleanupFile);
  }
}

##----------------------------------------------------------------------------##
#  Process Clang Crashes.
##----------------------------------------------------------------------------##

sub GetPPExt {
  my $Lang = shift;
  if ($Lang =~ /objective-c\+\+/) { return ".mii" };
  if ($Lang =~ /objective-c/) { return ".mi"; }
  if ($Lang =~ /c\+\+/) { return ".ii"; }
  return ".i";
}

# Set this to 1 if we want to include 'parser rejects' files.
my $IncludeParserRejects = 0;
my $ParserRejects = "Parser Rejects";
my $AttributeIgnored = "Attribute Ignored";
my $OtherError = "Other Error";

sub ProcessClangFailure {
  my ($Clang, $Lang, $file, $Args, $HtmlDir, $ErrorType, $ofile) = @_;
  my $Dir = "$HtmlDir/failures";
  mkpath $Dir;

  my $prefix = "clang_crash";
  if ($ErrorType eq $ParserRejects) {
    $prefix = "clang_parser_rejects";
  }
  elsif ($ErrorType eq $AttributeIgnored) {
    $prefix = "clang_attribute_ignored";
  }
  elsif ($ErrorType eq $OtherError) {
    $prefix = "clang_other_error";
  }

  # Generate the preprocessed file with Clang.
  my ($PPH, $PPFile) = tempfile( $prefix . "_XXXXXX",
                                 SUFFIX => GetPPExt($Lang),
                                 DIR => $Dir);
  close ($PPH);
  system $Clang, @$Args, "-E", "-o", $PPFile;

  # Create the info file.
  open (OUT, ">", "$PPFile.info.txt") or die "Cannot open $PPFile.info.txt\n";
  print OUT abs_path($file), "\n";
  print OUT "$ErrorType\n";
  print OUT "@$Args\n";
  close OUT;
  `uname -a >> $PPFile.info.txt 2>&1`;
  `"$Compiler" -v >> $PPFile.info.txt 2>&1`;
  rename($ofile, "$PPFile.stderr.txt");
  return (basename $PPFile);
}

##----------------------------------------------------------------------------##
#  Running the analyzer.
##----------------------------------------------------------------------------##

sub GetCCArgs {
  my $HtmlDir = shift;
  my $mode = shift;
  my $Args = shift;
  my $line;
  my $OutputStream = silent_system($HtmlDir, $Clang, "-###", $mode, @$Args);
  while (<$OutputStream>) {
    next if (!/\s"?-cc1"?\s/);
    $line = $_;
  }
  die "could not find clang line\n" if (!defined $line);
  # Strip leading and trailing whitespace characters.
  $line =~ s/^\s+|\s+$//g;
  my @items = quotewords('\s+', 0, $line);
  my $cmd = shift @items;
  die "cannot find 'clang' in 'clang' command\n" if (!($cmd =~ /clang/));
  return \@items;
}

sub Analyze {
  my ($Clang, $OriginalArgs, $AnalyzeArgs, $Lang, $Output, $Verbose, $HtmlDir,
      $file) = @_;

  my @Args = @$OriginalArgs;
  my $Cmd;
  my @CmdArgs;
  my @CmdArgsSansAnalyses;

  if ($Lang =~ /header/) {
    exit 0 if (!defined ($Output));
    $Cmd = 'cp';
    push @CmdArgs, $file;
    # Remove the PCH extension.
    $Output =~ s/[.]gch$//;
    push @CmdArgs, $Output;
    @CmdArgsSansAnalyses = @CmdArgs;
  }
  else {
    $Cmd = $Clang;

    # Create arguments for doing regular parsing.
    my $SyntaxArgs = GetCCArgs($HtmlDir, "-fsyntax-only", \@Args);
    @CmdArgsSansAnalyses = @$SyntaxArgs;

    # Create arguments for doing static analysis.
    if (defined $ResultFile) {
      push @Args, '-o', $ResultFile;
    }
    elsif (defined $HtmlDir) {
      push @Args, '-o', $HtmlDir;
    }
    if ($Verbose) {
      push @Args, "-Xclang", "-analyzer-display-progress";
    }

    foreach my $arg (@$AnalyzeArgs) {
      push @Args, "-Xclang", $arg;
    }

    if (defined $AnalyzerTarget) {
      push @Args, "-target", $AnalyzerTarget;
    }

    my $AnalysisArgs = GetCCArgs($HtmlDir, "--analyze", \@Args);
    @CmdArgs = @$AnalysisArgs;
  }

  my @PrintArgs;
  my $dir;

  if ($Verbose) {
    $dir = getcwd();
    print STDERR "\n[LOCATION]: $dir\n";
    push @PrintArgs,"'$Cmd'";
    foreach my $arg (@CmdArgs) {
        push @PrintArgs,"\'$arg\'";
    }
  }
  if ($Verbose == 1) {
    # We MUST print to stderr.  Some clients use the stdout output of
    # gcc for various purposes.
    print STDERR join(' ', @PrintArgs);
    print STDERR "\n";
  }
  elsif ($Verbose == 2) {
    print STDERR "#SHELL (cd '$dir' && @PrintArgs)\n";
  }

  # Save STDOUT and STDERR of clang to a temporary file and reroute
  # all clang output to ccc-analyzer's STDERR.
  # We save the output file in the 'crashes' directory if clang encounters
  # any problems with the file.
  my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);

  my $OutputStream = silent_system($HtmlDir, $Cmd, @CmdArgs);
  while ( <$OutputStream> ) {
    print $ofh $_;
    print STDERR $_;
  }
  my $Result = $?;
  close $ofh;

  # Did the command die because of a signal?
  if ($ReportFailures) {
    if ($Result & 127 and $Cmd eq $Clang and defined $HtmlDir) {
      ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
                          $HtmlDir, "Crash", $ofile);
    }
    elsif ($Result) {
      if ($IncludeParserRejects && !($file =~/conftest/)) {
        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
                            $HtmlDir, $ParserRejects, $ofile);
      } else {
        ProcessClangFailure($Clang, $Lang, $file, \@CmdArgsSansAnalyses,
                            $HtmlDir, $OtherError, $ofile);
      }
    }
    else {
      # Check if there were any unhandled attributes.
      if (open(CHILD, $ofile)) {
        my %attributes_not_handled;

        # Don't flag warnings about the following attributes that we
        # know are currently not supported by Clang.
        $attributes_not_handled{"cdecl"} = 1;

        my $ppfile;
        while (<CHILD>) {
          next if (! /warning: '([^\']+)' attribute ignored/);

          # Have we already spotted this unhandled attribute?
          next if (defined $attributes_not_handled{$1});
          $attributes_not_handled{$1} = 1;

          # Get the name of the attribute file.
          my $dir = "$HtmlDir/failures";
          my $afile = "$dir/attribute_ignored_$1.txt";

          # Only create another preprocessed file if the attribute file
          # doesn't exist yet.
          next if (-e $afile);

          # Add this file to the list of files that contained this attribute.
          # Generate a preprocessed file if we haven't already.
          if (!(defined $ppfile)) {
            $ppfile = ProcessClangFailure($Clang, $Lang, $file,
                                          \@CmdArgsSansAnalyses,
                                          $HtmlDir, $AttributeIgnored, $ofile);
          }

          mkpath $dir;
          open(AFILE, ">$afile");
          print AFILE "$ppfile\n";
          close(AFILE);
        }
        close CHILD;
      }
    }
  }

  unlink($ofile);
}

##----------------------------------------------------------------------------##
#  Lookup tables.
##----------------------------------------------------------------------------##

my %CompileOptionMap = (
  '-nostdinc' => 0,
  '-include' => 1,
  '-idirafter' => 1,
  '-imacros' => 1,
  '-iprefix' => 1,
  '-iquote' => 1,
  '-iwithprefix' => 1,
  '-iwithprefixbefore' => 1
);

my %LinkerOptionMap = (
  '-framework' => 1,
  '-fobjc-link-runtime' => 0
);

my %CompilerLinkerOptionMap = (
  '-Wwrite-strings' => 0,
  '-ftrapv-handler' => 1, # specifically call out separated -f flag
  '-mios-simulator-version-min' => 0, # This really has 1 argument, but always has '='
  '-isysroot' => 1,
  '-arch' => 1,
  '-m32' => 0,
  '-m64' => 0,
  '-stdlib' => 0, # This is really a 1 argument, but always has '='
  '--sysroot' => 1,
  '-target' => 1,
  '-v' => 0,
  '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
  '-miphoneos-version-min' => 0, # This is really a 1 argument, but always has '='
  '--target' => 0
);

my %IgnoredOptionMap = (
  '-MT' => 1,  # Ignore these preprocessor options.
  '-MF' => 1,

  '-fsyntax-only' => 0,
  '-save-temps' => 0,
  '-install_name' => 1,
  '-exported_symbols_list' => 1,
  '-current_version' => 1,
  '-compatibility_version' => 1,
  '-init' => 1,
  '-e' => 1,
  '-seg1addr' => 1,
  '-bundle_loader' => 1,
  '-multiply_defined' => 1,
  '-sectorder' => 3,
  '--param' => 1,
  '-u' => 1,
  '--serialize-diagnostics' => 1
);

my %LangMap = (
  'c'   => $IsCXX ? 'c++' : 'c',
  'cp'  => 'c++',
  'cpp' => 'c++',
  'cxx' => 'c++',
  'txx' => 'c++',
  'cc'  => 'c++',
  'C'   => 'c++',
  'ii'  => 'c++-cpp-output',
  'i'   => $IsCXX ? 'c++-cpp-output' : 'cpp-output',
  'm'   => 'objective-c',
  'mi'  => 'objective-c-cpp-output',
  'mm'  => 'objective-c++',
  'mii' => 'objective-c++-cpp-output',
);

my %UniqueOptions = (
  '-isysroot' => 0
);

##----------------------------------------------------------------------------##
# Languages accepted.
##----------------------------------------------------------------------------##

my %LangsAccepted = (
  "objective-c" => 1,
  "c" => 1,
  "c++" => 1,
  "objective-c++" => 1,
  "cpp-output" => 1,
  "objective-c-cpp-output" => 1,
  "c++-cpp-output" => 1
);

##----------------------------------------------------------------------------##
#  Main Logic.
##----------------------------------------------------------------------------##

my $Action = 'link';
my @CompileOpts;
my @LinkOpts;
my @Files;
my $Lang;
my $Output;
my %Uniqued;

# Forward arguments to gcc.
my $Status = system($Compiler,@ARGV);
if (defined $ENV{'CCC_ANALYZER_LOG'}) {
  print STDERR "$Compiler @ARGV\n";
}
if ($Status) { exit($Status >> 8); }

# Get the analysis options.
my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};

# Get the plugins to load.
my $Plugins = $ENV{'CCC_ANALYZER_PLUGINS'};

# Get the store model.
my $StoreModel = $ENV{'CCC_ANALYZER_STORE_MODEL'};

# Get the constraints engine.
my $ConstraintsModel = $ENV{'CCC_ANALYZER_CONSTRAINTS_MODEL'};

#Get the internal stats setting.
my $InternalStats = $ENV{'CCC_ANALYZER_INTERNAL_STATS'};

# Get the output format.
my $OutputFormat = $ENV{'CCC_ANALYZER_OUTPUT_FORMAT'};
if (!defined $OutputFormat) { $OutputFormat = "html"; }

# Get the config options.
my $ConfigOptions = $ENV{'CCC_ANALYZER_CONFIG'};

# Determine the level of verbosity.
my $Verbose = 0;
if (defined $ENV{'CCC_ANALYZER_VERBOSE'}) { $Verbose = 1; }
if (defined $ENV{'CCC_ANALYZER_LOG'}) { $Verbose = 2; }

# Get the HTML output directory.
my $HtmlDir = $ENV{'CCC_ANALYZER_HTML'};

# Get force-analyze-debug-code option.
my $ForceAnalyzeDebugCode = $ENV{'CCC_ANALYZER_FORCE_ANALYZE_DEBUG_CODE'};

my %DisabledArchs = ('ppc' => 1, 'ppc64' => 1);
my %ArchsSeen;
my $HadArch = 0;
my $HasSDK = 0;

# Process the arguments.
foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
  my $Arg = $ARGV[$i];
  my @ArgParts = split /=/,$Arg,2;
  my $ArgKey = $ArgParts[0];

  # Be friendly to "" in the argument list.
  if (!defined($ArgKey)) {
    next;
  }

  # Modes ccc-analyzer supports
  if ($Arg =~ /^-(E|MM?)$/) { $Action = 'preprocess'; }
  elsif ($Arg eq '-c') { $Action = 'compile'; }
  elsif ($Arg =~ /^-print-prog-name/) { exit 0; }

  # Specially handle duplicate cases of -arch
  if ($Arg eq "-arch") {
    my $arch = $ARGV[$i+1];
    # We don't want to process 'ppc' because of Clang's lack of support
    # for Altivec (also some #defines won't likely be defined correctly, etc.)
    if (!(defined $DisabledArchs{$arch})) { $ArchsSeen{$arch} = 1; }
    $HadArch = 1;
    ++$i;
    next;
  }

  # On OSX/iOS, record if an SDK path was specified.  This
  # is innocuous for other platforms, so the check just happens.
  if ($Arg =~ /^-isysroot/) {
    $HasSDK = 1;
  }

  # Options with possible arguments that should pass through to compiler.
  if (defined $CompileOptionMap{$ArgKey}) {
    my $Cnt = $CompileOptionMap{$ArgKey};
    push @CompileOpts,$Arg;
    while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
    next;
  }
  # Handle the case where there isn't a space after -iquote
  if ($Arg =~ /^-iquote.*/) {
    push @CompileOpts,$Arg;
    next;
  }

  # Options with possible arguments that should pass through to linker.
  if (defined $LinkerOptionMap{$ArgKey}) {
    my $Cnt = $LinkerOptionMap{$ArgKey};
    push @LinkOpts,$Arg;
    while ($Cnt > 0) { ++$i; --$Cnt; push @LinkOpts, $ARGV[$i]; }
    next;
  }

  # Options with possible arguments that should pass through to both compiler
  # and the linker.
  if (defined $CompilerLinkerOptionMap{$ArgKey}) {
    my $Cnt = $CompilerLinkerOptionMap{$ArgKey};

    # Check if this is an option that should have a unique value, and if so
    # determine if the value was checked before.
    if ($UniqueOptions{$Arg}) {
      if (defined $Uniqued{$Arg}) {
        $i += $Cnt;
        next;
      }
      $Uniqued{$Arg} = 1;
    }

    push @CompileOpts,$Arg;
    push @LinkOpts,$Arg;

    if (scalar @ArgParts == 1) {
      while ($Cnt > 0) {
        ++$i; --$Cnt;
        push @CompileOpts, $ARGV[$i];
        push @LinkOpts, $ARGV[$i];
      }
    }
    next;
  }

  # Ignored options.
  if (defined $IgnoredOptionMap{$ArgKey}) {
    my $Cnt = $IgnoredOptionMap{$ArgKey};
    while ($Cnt > 0) {
      ++$i; --$Cnt;
    }
    next;
  }

  # Compile mode flags.
  if ($Arg =~ /^-(?:[DIU]|isystem)(.*)$/) {
    my $Tmp = $Arg;
    if ($1 eq '') {
      # FIXME: Check if we are going off the end.
      ++$i;
      $Tmp = $Arg . $ARGV[$i];
    }
    push @CompileOpts,$Tmp;
    next;
  }

  if ($Arg =~ /^-m.*/) {
    push @CompileOpts,$Arg;
    next;
  }

  # Language.
  if ($Arg eq '-x') {
    $Lang = $ARGV[$i+1];
    ++$i; next;
  }

  # Output file.
  if ($Arg eq '-o') {
    ++$i;
    $Output = $ARGV[$i];
    next;
  }

  # Get the link mode.
  if ($Arg =~ /^-[l,L,O]/) {
    if ($Arg eq '-O') { push @LinkOpts,'-O1'; }
    elsif ($Arg eq '-Os') { push @LinkOpts,'-O2'; }
    else { push @LinkOpts,$Arg; }

    # Must pass this along for the __OPTIMIZE__ macro
    if ($Arg =~ /^-O/) { push @CompileOpts,$Arg; }
    next;
  }

  if ($Arg =~ /^-std=/) {
    push @CompileOpts,$Arg;
    next;
  }

  # Get the compiler/link mode.
  if ($Arg =~ /^-F(.+)$/) {
    my $Tmp = $Arg;
    if ($1 eq '') {
      # FIXME: Check if we are going off the end.
      ++$i;
      $Tmp = $Arg . $ARGV[$i];
    }
    push @CompileOpts,$Tmp;
    push @LinkOpts,$Tmp;
    next;
  }

  # Input files.
  if ($Arg eq '-filelist') {
    # FIXME: Make sure we aren't walking off the end.
    open(IN, $ARGV[$i+1]);
    while (<IN>) { s/\015?\012//; push @Files,$_; }
    close(IN);
    ++$i;
    next;
  }

  if ($Arg =~ /^-f/) {
    push @CompileOpts,$Arg;
    push @LinkOpts,$Arg;
    next;
  }

  # Handle -Wno-.  We don't care about extra warnings, but
  # we should suppress ones that we don't want to see.
  if ($Arg =~ /^-Wno-/) {
    push @CompileOpts, $Arg;
    next;
  }

  # Handle -Xclang some-arg. Add both arguments to the compiler options.
  if ($Arg =~ /^-Xclang$/) {
    # FIXME: Check if we are going off the end.
    ++$i;
    push @CompileOpts, $Arg;
    push @CompileOpts, $ARGV[$i];
    next;
  }

  if (!($Arg =~ /^-/)) {
    push @Files, $Arg;
    next;
  }
}

# Forcedly enable debugging if requested by user.
if ($ForceAnalyzeDebugCode) {
  push @CompileOpts, '-UNDEBUG';
}

# If we are on OSX and have an installation where the
# default SDK is inferred by xcrun use xcrun to infer
# the SDK.
if (not $HasSDK and $UseXCRUN) {
  my $sdk = `/usr/bin/xcrun --show-sdk-path -sdk macosx`;
  chomp $sdk;
  push @CompileOpts, "-isysroot", $sdk;
}

if ($Action eq 'compile' or $Action eq 'link') {
  my @Archs = keys %ArchsSeen;
  # Skip the file if we don't support the architectures specified.
  exit 0 if ($HadArch && scalar(@Archs) == 0);

  foreach my $file (@Files) {
    # Determine the language for the file.
    my $FileLang = $Lang;

    if (!defined($FileLang)) {
      # Infer the language from the extension.
      if ($file =~ /[.]([^.]+)$/) {
        $FileLang = $LangMap{$1};
      }
    }

    # FileLang still not defined?  Skip the file.
    next if (!defined $FileLang);

    # Language not accepted?
    next if (!defined $LangsAccepted{$FileLang});

    my @CmdArgs;
    my @AnalyzeArgs;

    if ($FileLang ne 'unknown') {
      push @CmdArgs, '-x', $FileLang;
    }

    if (defined $StoreModel) {
      push @AnalyzeArgs, "-analyzer-store=$StoreModel";
    }

    if (defined $ConstraintsModel) {
      push @AnalyzeArgs, "-analyzer-constraints=$ConstraintsModel";
    }

    if (defined $InternalStats) {
      push @AnalyzeArgs, "-analyzer-stats";
    }

    if (defined $Analyses) {
      push @AnalyzeArgs, split '\s+', $Analyses;
    }

    if (defined $Plugins) {
      push @AnalyzeArgs, split '\s+', $Plugins;
    }

    if (defined $OutputFormat) {
      push @AnalyzeArgs, "-analyzer-output=" . $OutputFormat;
      if ($OutputFormat =~ /plist/ || $OutputFormat =~ /sarif/) {
        # Change "Output" to be a file.
        my $Suffix = $OutputFormat =~ /plist/ ? ".plist" : ".sarif";
        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => $Suffix,
                               DIR => $HtmlDir);
        $ResultFile = $f;
        # If the HtmlDir is not set, we should clean up the plist files.
        if (!defined $HtmlDir || $HtmlDir eq "") {
          $CleanupFile = $f;
        }
      }
    }
    if (defined $ConfigOptions) {
      push @AnalyzeArgs, split '\s+', $ConfigOptions;
    }

    push @CmdArgs, @CompileOpts;
    push @CmdArgs, $file;

    if (scalar @Archs) {
      foreach my $arch (@Archs) {
        my @NewArgs;
        push @NewArgs, '-arch', $arch;
        push @NewArgs, @CmdArgs;
        Analyze($Clang, \@NewArgs, \@AnalyzeArgs, $FileLang, $Output,
                $Verbose, $HtmlDir, $file);
      }
    }
    else {
      Analyze($Clang, \@CmdArgs, \@AnalyzeArgs, $FileLang, $Output,
              $Verbose, $HtmlDir, $file);
    }
  }
}