head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.9
	netbsd-11-0-RC3:1.1.1.9
	netbsd-11-0-RC2:1.1.1.9
	netbsd-11-0-RC1:1.1.1.9
	perseant-exfatfs-base-20250801:1.1.1.9
	netbsd-11:1.1.1.9.0.24
	netbsd-11-base:1.1.1.9
	netbsd-10-1-RELEASE:1.1.1.9
	perseant-exfatfs-base-20240630:1.1.1.9
	perseant-exfatfs:1.1.1.9.0.22
	perseant-exfatfs-base:1.1.1.9
	netbsd-8-3-RELEASE:1.1.1.9
	netbsd-9-4-RELEASE:1.1.1.9
	netbsd-10-0-RELEASE:1.1.1.9
	netbsd-10-0-RC6:1.1.1.9
	netbsd-10-0-RC5:1.1.1.9
	netbsd-10-0-RC4:1.1.1.9
	netbsd-10-0-RC3:1.1.1.9
	netbsd-10-0-RC2:1.1.1.9
	netbsd-10-0-RC1:1.1.1.9
	netbsd-10:1.1.1.9.0.20
	netbsd-10-base:1.1.1.9
	netbsd-9-3-RELEASE:1.1.1.9
	cjep_sun2x:1.1.1.9.0.18
	cjep_sun2x-base:1.1.1.9
	cjep_staticlib_x-base1:1.1.1.9
	netbsd-9-2-RELEASE:1.1.1.9
	cjep_staticlib_x:1.1.1.9.0.16
	cjep_staticlib_x-base:1.1.1.9
	netbsd-9-1-RELEASE:1.1.1.9
	phil-wifi-20200421:1.1.1.9
	phil-wifi-20200411:1.1.1.9
	phil-wifi-20200406:1.1.1.9
	netbsd-8-2-RELEASE:1.1.1.9
	netbsd-9-0-RELEASE:1.1.1.9
	netbsd-9-0-RC2:1.1.1.9
	netbsd-9-0-RC1:1.1.1.9
	netbsd-9:1.1.1.9.0.14
	netbsd-9-base:1.1.1.9
	netbsd-8-1-RELEASE:1.1.1.9
	netbsd-8-1-RC1:1.1.1.9
	pgoyette-compat-merge-20190127:1.1.1.9
	pgoyette-compat-20190127:1.1.1.9
	pgoyette-compat-20190118:1.1.1.9
	pgoyette-compat-1226:1.1.1.9
	pgoyette-compat-1126:1.1.1.9
	pgoyette-compat-1020:1.1.1.9
	pgoyette-compat-0930:1.1.1.9
	pgoyette-compat-0906:1.1.1.9
	netbsd-7-2-RELEASE:1.1.1.7.2.1
	pgoyette-compat-0728:1.1.1.9
	netbsd-8-0-RELEASE:1.1.1.9
	pgoyette-compat-0625:1.1.1.9
	netbsd-8-0-RC2:1.1.1.9
	pgoyette-compat-0521:1.1.1.9
	pgoyette-compat-0502:1.1.1.9
	pgoyette-compat-0422:1.1.1.9
	netbsd-8-0-RC1:1.1.1.9
	pgoyette-compat-0415:1.1.1.9
	pgoyette-compat-0407:1.1.1.9
	pgoyette-compat-0330:1.1.1.9
	pgoyette-compat-0322:1.1.1.9
	pgoyette-compat-0315:1.1.1.9
	netbsd-7-1-2-RELEASE:1.1.1.7.2.1
	pgoyette-compat:1.1.1.9.0.12
	pgoyette-compat-base:1.1.1.9
	netbsd-7-1-1-RELEASE:1.1.1.7.2.1
	perseant-stdc-iso10646:1.1.1.9.0.10
	perseant-stdc-iso10646-base:1.1.1.9
	netbsd-8:1.1.1.9.0.8
	netbsd-8-base:1.1.1.9
	prg-localcount2-base3:1.1.1.9
	prg-localcount2-base2:1.1.1.9
	prg-localcount2-base1:1.1.1.9
	prg-localcount2:1.1.1.9.0.6
	prg-localcount2-base:1.1.1.9
	pgoyette-localcount-20170426:1.1.1.9
	bouyer-socketcan-base1:1.1.1.9
	pgoyette-localcount-20170320:1.1.1.9
	netbsd-7-1:1.1.1.7.2.1.0.6
	netbsd-7-1-RELEASE:1.1.1.7.2.1
	netbsd-7-1-RC2:1.1.1.7.2.1
	netbsd-7-nhusb-base-20170116:1.1.1.7.2.1
	bouyer-socketcan:1.1.1.9.0.4
	bouyer-socketcan-base:1.1.1.9
	pgoyette-localcount-20170107:1.1.1.9
	netbsd-7-1-RC1:1.1.1.7.2.1
	pgoyette-localcount-20161104:1.1.1.9
	netbsd-7-0-2-RELEASE:1.1.1.7.2.1
	localcount-20160914:1.1.1.9
	netbsd-7-nhusb:1.1.1.7.2.1.0.4
	netbsd-7-nhusb-base:1.1.1.7.2.1
	pgoyette-localcount-20160806:1.1.1.9
	pgoyette-localcount-20160726:1.1.1.9
	pgoyette-localcount:1.1.1.9.0.2
	pgoyette-localcount-base:1.1.1.9
	netbsd-7-0-1-RELEASE:1.1.1.7.2.1
	netbsd-7-0:1.1.1.7.2.1.0.2
	netbsd-7-0-RELEASE:1.1.1.7.2.1
	netbsd-7-0-RC3:1.1.1.7.2.1
	netbsd-7-0-RC2:1.1.1.7.2.1
	netbsd-7-0-RC1:1.1.1.7.2.1
	clang-237755:1.1.1.8
	clang-232565:1.1.1.8
	clang-227398:1.1.1.8
	tls-maxphys-base:1.1.1.7
	tls-maxphys:1.1.1.7.0.4
	netbsd-7:1.1.1.7.0.2
	netbsd-7-base:1.1.1.7
	clang-215315:1.1.1.7
	clang-209886:1.1.1.6
	yamt-pagecache:1.1.1.5.0.4
	yamt-pagecache-base9:1.1.1.5
	tls-earlyentropy:1.1.1.5.0.2
	tls-earlyentropy-base:1.1.1.6
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.5
	riastradh-drm2-base3:1.1.1.5
	clang-202566:1.1.1.5
	clang-201163:1.1.1.4
	clang-199312:1.1.1.3
	clang-198450:1.1.1.2
	clang-196603:1.1.1.1
	clang-195771:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@# @;


1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	ow8OybrawrB1f3fx;

1.1.1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches;
next	1.1.1.2;
commitid	ow8OybrawrB1f3fx;

1.1.1.2
date	2014.01.05.15.37.58;	author joerg;	state Exp;
branches;
next	1.1.1.3;
commitid	wh3aCSIWykURqWjx;

1.1.1.3
date	2014.01.15.21.26.17;	author joerg;	state Exp;
branches;
next	1.1.1.4;
commitid	NQXlzzA0SPkc5glx;

1.1.1.4
date	2014.02.14.20.07.02;	author joerg;	state Exp;
branches;
next	1.1.1.5;
commitid	annVkZ1sc17rF6px;

1.1.1.5
date	2014.03.04.19.53.21;	author joerg;	state Exp;
branches
	1.1.1.5.2.1
	1.1.1.5.4.1;
next	1.1.1.6;
commitid	29z1hJonZISIXprx;

1.1.1.6
date	2014.05.30.18.14.49;	author joerg;	state Exp;
branches;
next	1.1.1.7;
commitid	8q0kdlBlCn09GACx;

1.1.1.7
date	2014.08.10.17.08.24;	author joerg;	state Exp;
branches
	1.1.1.7.2.1
	1.1.1.7.4.1;
next	1.1.1.8;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.8
date	2015.01.29.19.57.27;	author joerg;	state Exp;
branches;
next	1.1.1.9;
commitid	mlISSizlPKvepX7y;

1.1.1.9
date	2016.02.27.22.23.00;	author joerg;	state dead;
branches;
next	;
commitid	DKbhbwSVAW5DxBWy;

1.1.1.5.2.1
date	2014.08.10.07.08.25;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.5.4.1
date	2014.03.04.19.53.21;	author yamt;	state dead;
branches;
next	1.1.1.5.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.5.4.2
date	2014.05.22.16.19.48;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.7.2.1
date	2015.06.04.20.04.46;	author snj;	state Exp;
branches;
next	;
commitid	yRnjq9fueSo6n9oy;

1.1.1.7.4.1
date	2014.08.10.17.08.24;	author tls;	state dead;
branches;
next	1.1.1.7.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.7.4.2
date	2014.08.19.23.49.27;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;


desc
@@


1.1
log
@Initial revision
@
text
@#!/usr/bin/env perl
#
#                     The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
#
#  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;

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

my $Compiler;
my $Clang;
my $DefaultCCompiler;
my $DefaultCXXCompiler;

if (`uname -a` =~ m/Darwin/) { 
  $DefaultCCompiler = 'clang';
  $DefaultCXXCompiler = 'clang++';
} else {
  $DefaultCCompiler = 'gcc';
  $DefaultCXXCompiler = 'g++';
}

if ($FindBin::Script =~ /c\+\+-analyzer/) {
  $Compiler = $ENV{'CCC_CXX'};
  if (!defined $Compiler) { $Compiler = $DefaultCXXCompiler; }
  
  $Clang = $ENV{'CLANG_CXX'};
  if (!defined $Clang) { $Clang = 'clang++'; }
}
else {
  $Compiler = $ENV{'CCC_CC'};
  if (!defined $Compiler) { $Compiler = $DefaultCCompiler; }

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

##===----------------------------------------------------------------------===##
# 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) {
    `rm -f $ResultFile`;
  }
  if (defined $CleanupFile) {
    `rm -f $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);
  system $Clang, @@$Args, "-E", "-o", $PPFile;
  close ($PPH);
  
  # 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`;
  system 'mv',$ofile,"$PPFile.stderr.txt";
  return (basename $PPFile);
}

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

sub GetCCArgs {
  my $mode = shift;
  my $Args = shift;
  
  pipe (FROM_CHILD, TO_PARENT);
  my $pid = fork();
  if ($pid == 0) {
    close FROM_CHILD;
    open(STDOUT,">&", \*TO_PARENT);
    open(STDERR,">&", \*TO_PARENT);
    exec $Clang, "-###", $mode, @@$Args;
  }  
  close(TO_PARENT);
  my $line;
  while (<FROM_CHILD>) {
    next if (!/-cc1/);
    $line = $_;
  }

  waitpid($pid,0);
  close(FROM_CHILD);
  
  die "could not find clang line\n" if (!defined $line);
  # Strip the newline and initial whitspace
  chomp $line;
  $line =~ s/^\s+//;
  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("-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;
    }

    # Display Ubiviz graph?
    if (defined $ENV{'CCC_UBI'}) {   
      push @@Args, "-Xclang", "-analyzer-viz-egraph-ubigraph";
    }

    my $AnalysisArgs = GetCCArgs("--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";
  }

  # Capture the STDERR of clang and send it to a temporary file.
  # Capture the STDOUT of clang and reroute it to ccc-analyzer's STDERR.
  # We save the output file in the 'crashes' directory if clang encounters
  # any problems with the file.  
  pipe (FROM_CHILD, TO_PARENT);
  my $pid = fork();
  if ($pid == 0) {
    close FROM_CHILD;
    open(STDOUT,">&", \*TO_PARENT);
    open(STDERR,">&", \*TO_PARENT);
    exec $Cmd, @@CmdArgs;
  }

  close TO_PARENT;
  my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);
  
  while (<FROM_CHILD>) {
    print $ofh $_;
    print STDERR $_;
  }
  close $ofh;

  waitpid($pid,0);
  close(FROM_CHILD);
  my $Result = $?;

  # 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,
  '-isystem' => 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 '='
  '-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 '='
);

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'   => 'c',
  'cp'  => 'c++',
  'cpp' => 'c++',
  'cxx' => 'c++',
  'txx' => 'c++',
  'cc'  => 'c++',
  'C'   => 'c++',
  'ii'  => 'c++',
  'i'   => 'c-cpp-output',
  'm'   => 'objective-c',
  'mi'  => 'objective-c-cpp-output',
  'mm'  => 'objective-c++'
);

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

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

my %LangsAccepted = (
  "objective-c" => 1,
  "c" => 1,
  "c++" => 1,
  "objective-c++" => 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"; }

# 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'};

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

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

  # 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;
  }

  # 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;

    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 =~ /^-[D,I,U](.*)$/) {
    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;
  }

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

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/) {
        # Change "Output" to be a file.
        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => ".plist",
                               DIR => $HtmlDir);
        $ResultFile = $f;
        # If the HtmlDir is not set, we sould clean up the plist files.
        if (!defined $HtmlDir || -z $HtmlDir) {
          $CleanupFile = $f;
        }
      }
    }

    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);
    }
  }
}

exit($Status >> 8);

@


1.1.1.1
log
@Import Clang 3.4rc1 r195771.
@
text
@@


1.1.1.2
log
@Import clang 3.5svn r198450.
@
text
@a446 3
# Get the config options.
my $ConfigOptions = $ENV{'CCC_ANALYZER_CONFIG'};

d680 1
a680 1
        # If the HtmlDir is not set, we should clean up the plist files.
a685 3
    if (defined $ConfigOptions) {
      push @@AnalyzeArgs, split '\s+', $ConfigOptions;
    }
@


1.1.1.3
log
@Import Clang 3.5svn r199312
@
text
@a31 1
my $IsCXX;
a46 2

  $IsCXX = 1
a53 2

  $IsCXX = 0
d380 1
a380 1
  'c'   => $IsCXX ? 'c++' : 'c',
d387 2
a388 2
  'ii'  => 'c++-cpp-output',
  'i'   => $IsCXX ? 'c++-cpp-output' : 'c-cpp-output',
d391 1
a391 2
  'mm'  => 'objective-c++',
  'mii' => 'objective-c++-cpp-output',
@


1.1.1.4
log
@Import Clang 3.5svn r201163.
@
text
@d161 3
a163 2
  # Strip leading and trailing whitespace characters.
  $line =~ s/^\s+|\s+$//g;
@


1.1.1.5
log
@Import Clang 3.5svn r202566.
@
text
@d34 1
a34 1
if (`uname -a` =~ m/Darwin/) {
d44 2
a45 2
  if (!defined $Compiler || ! -x $Compiler) { $Compiler = $DefaultCXXCompiler; }

d47 1
a47 1
  if (!defined $Clang || ! -x $Clang) { $Clang = 'clang++'; }
d53 1
a53 1
  if (!defined $Compiler || ! -x $Compiler) { $Compiler = $DefaultCCompiler; }
d56 1
a56 1
  if (!defined $Clang || ! -x $Clang) { $Clang = 'clang'; }
d72 1
a72 1
END {
d103 1
a103 1

d121 1
a121 1

d141 1
a141 1

d149 1
a149 1
  }
d159 1
a159 1

d210 1
a210 1
    if (defined $ENV{'CCC_UBI'}) {
d231 1
a231 1
    # gcc for various purposes.
d242 1
a242 1
  # any problems with the file.
d254 1
a254 1

d296 1
a296 1

d300 1
a300 1

d304 1
a304 1

d322 1
a322 1

d400 1
a400 1
  '-isysroot' => 0
d411 1
a411 4
  "objective-c++" => 1,
  "c-cpp-output" => 1,
  "objective-c-cpp-output" => 1,
  "c++-cpp-output" => 1
d469 1
a469 1
  my $Arg = $ARGV[$i];
d513 1
a513 1

d523 2
a524 2

    push @@CompileOpts,$Arg;
d534 1
a534 1

d543 1
a543 1

d546 1
a546 1
    my $Tmp = $Arg;
d555 1
a555 1

d560 1
a560 1

d573 1
a573 1

d584 1
a584 1

d589 1
a589 1

d612 1
a612 1

d618 1
a618 1

d647 1
a647 1

d655 2
a656 2
    my @@AnalyzeArgs;

d672 1
a672 1

d718 1
@


1.1.1.5.2.1
log
@Rebase.
@
text
@d74 1
a74 1
    unlink($ResultFile);
d77 1
a77 1
    unlink($CleanupFile);
d130 1
a130 1
  rename($ofile, "$PPFile.stderr.txt");
d153 1
a153 1
    next if (!/\s"?-cc1"?\s/);
a355 1
  '--sysroot' => 1,
d499 1
a499 1
  if ($Arg =~ /^-iquote.*/) {
d559 1
a559 1
  if ($Arg =~ /^-m.*/) {
@


1.1.1.6
log
@Import Clang 3.5svn r209886.
@
text
@d74 1
a74 1
    unlink($ResultFile);
d77 1
a77 1
    unlink($CleanupFile);
d130 1
a130 1
  rename($ofile, "$PPFile.stderr.txt");
d153 1
a153 1
    next if (!/\s"?-cc1"?\s/);
a355 1
  '--sysroot' => 1,
d499 1
a499 1
  if ($Arg =~ /^-iquote.*/) {
d559 1
a559 1
  if ($Arg =~ /^-m.*/) {
@


1.1.1.7
log
@Import clang 3.6svn r215315.
@
text
@a27 11
# 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;
}

d44 1
a44 1
  if (!defined $Compiler || (! -x $Compiler && ! SearchInPath($Compiler))) { $Compiler = $DefaultCXXCompiler; }
d53 1
a53 1
  if (!defined $Compiler || (! -x $Compiler && ! SearchInPath($Compiler))) { $Compiler = $DefaultCCompiler; }
@


1.1.1.7.2.1
log
@Update LLVM to 3.6.1, requested by joerg in ticket 824.
@
text
@a44 3
# If on OSX, use xcrun to determine the SDK root.
my $UseXCRUN = 0;

a47 5
  # Older versions of OSX do not have xcrun to
  # query the SDK location.
  if (-x "/usr/bin/xcrun") {
    $UseXCRUN = 1;
  }
a480 1
my $HasSDK = 0;
a502 6
  # 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;
  }

a646 9
# 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;
}

@


1.1.1.8
log
@Import Clang 3.6RC1 r227398.
@
text
@a44 3
# If on OSX, use xcrun to determine the SDK root.
my $UseXCRUN = 0;

a47 5
  # Older versions of OSX do not have xcrun to
  # query the SDK location.
  if (-x "/usr/bin/xcrun") {
    $UseXCRUN = 1;
  }
a480 1
my $HasSDK = 0;
a502 6
  # 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;
  }

a646 9
# 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;
}

@


1.1.1.9
log
@Mark files without clang-261930 as dead.
@
text
@@


1.1.1.7.4.1
log
@file ccc-analyzer was added on branch tls-maxphys on 2014-08-19 23:49:27 +0000
@
text
@d1 732
@


1.1.1.7.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 732
#!/usr/bin/env perl
#
#                     The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
#
#  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;

##===----------------------------------------------------------------------===##
# 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;

if (`uname -a` =~ m/Darwin/) {
  $DefaultCCompiler = 'clang';
  $DefaultCXXCompiler = 'clang++';
} 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
}

##===----------------------------------------------------------------------===##
# 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);
  system $Clang, @@$Args, "-E", "-o", $PPFile;
  close ($PPH);

  # 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 $mode = shift;
  my $Args = shift;

  pipe (FROM_CHILD, TO_PARENT);
  my $pid = fork();
  if ($pid == 0) {
    close FROM_CHILD;
    open(STDOUT,">&", \*TO_PARENT);
    open(STDERR,">&", \*TO_PARENT);
    exec $Clang, "-###", $mode, @@$Args;
  }
  close(TO_PARENT);
  my $line;
  while (<FROM_CHILD>) {
    next if (!/\s"?-cc1"?\s/);
    $line = $_;
  }

  waitpid($pid,0);
  close(FROM_CHILD);

  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("-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;
    }

    # Display Ubiviz graph?
    if (defined $ENV{'CCC_UBI'}) {
      push @@Args, "-Xclang", "-analyzer-viz-egraph-ubigraph";
    }

    my $AnalysisArgs = GetCCArgs("--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";
  }

  # Capture the STDERR of clang and send it to a temporary file.
  # Capture the STDOUT of clang and reroute it to ccc-analyzer's STDERR.
  # We save the output file in the 'crashes' directory if clang encounters
  # any problems with the file.
  pipe (FROM_CHILD, TO_PARENT);
  my $pid = fork();
  if ($pid == 0) {
    close FROM_CHILD;
    open(STDOUT,">&", \*TO_PARENT);
    open(STDERR,">&", \*TO_PARENT);
    exec $Cmd, @@CmdArgs;
  }

  close TO_PARENT;
  my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);

  while (<FROM_CHILD>) {
    print $ofh $_;
    print STDERR $_;
  }
  close $ofh;

  waitpid($pid,0);
  close(FROM_CHILD);
  my $Result = $?;

  # 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,
  '-isystem' => 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 '='
);

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' : 'c-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,
  "c-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'};

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

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

  # 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;
  }

  # 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;

    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 =~ /^-[D,I,U](.*)$/) {
    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;
  }

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

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/) {
        # Change "Output" to be a file.
        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => ".plist",
                               DIR => $HtmlDir);
        $ResultFile = $f;
        # If the HtmlDir is not set, we should clean up the plist files.
        if (!defined $HtmlDir || -z $HtmlDir) {
          $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);
    }
  }
}

exit($Status >> 8);
@


1.1.1.5.4.1
log
@file ccc-analyzer was added on branch yamt-pagecache on 2014-05-22 16:19:48 +0000
@
text
@d1 720
@


1.1.1.5.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 720
#!/usr/bin/env perl
#
#                     The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
#
#  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;

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

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

if (`uname -a` =~ m/Darwin/) {
  $DefaultCCompiler = 'clang';
  $DefaultCXXCompiler = 'clang++';
} else {
  $DefaultCCompiler = 'gcc';
  $DefaultCXXCompiler = 'g++';
}

if ($FindBin::Script =~ /c\+\+-analyzer/) {
  $Compiler = $ENV{'CCC_CXX'};
  if (!defined $Compiler || ! -x $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) { $Compiler = $DefaultCCompiler; }

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

  $IsCXX = 0
}

##===----------------------------------------------------------------------===##
# 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) {
    `rm -f $ResultFile`;
  }
  if (defined $CleanupFile) {
    `rm -f $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);
  system $Clang, @@$Args, "-E", "-o", $PPFile;
  close ($PPH);

  # 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`;
  system 'mv',$ofile,"$PPFile.stderr.txt";
  return (basename $PPFile);
}

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

sub GetCCArgs {
  my $mode = shift;
  my $Args = shift;

  pipe (FROM_CHILD, TO_PARENT);
  my $pid = fork();
  if ($pid == 0) {
    close FROM_CHILD;
    open(STDOUT,">&", \*TO_PARENT);
    open(STDERR,">&", \*TO_PARENT);
    exec $Clang, "-###", $mode, @@$Args;
  }
  close(TO_PARENT);
  my $line;
  while (<FROM_CHILD>) {
    next if (!/-cc1/);
    $line = $_;
  }

  waitpid($pid,0);
  close(FROM_CHILD);

  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("-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;
    }

    # Display Ubiviz graph?
    if (defined $ENV{'CCC_UBI'}) {
      push @@Args, "-Xclang", "-analyzer-viz-egraph-ubigraph";
    }

    my $AnalysisArgs = GetCCArgs("--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";
  }

  # Capture the STDERR of clang and send it to a temporary file.
  # Capture the STDOUT of clang and reroute it to ccc-analyzer's STDERR.
  # We save the output file in the 'crashes' directory if clang encounters
  # any problems with the file.
  pipe (FROM_CHILD, TO_PARENT);
  my $pid = fork();
  if ($pid == 0) {
    close FROM_CHILD;
    open(STDOUT,">&", \*TO_PARENT);
    open(STDERR,">&", \*TO_PARENT);
    exec $Cmd, @@CmdArgs;
  }

  close TO_PARENT;
  my ($ofh, $ofile) = tempfile("clang_output_XXXXXX", DIR => $HtmlDir);

  while (<FROM_CHILD>) {
    print $ofh $_;
    print STDERR $_;
  }
  close $ofh;

  waitpid($pid,0);
  close(FROM_CHILD);
  my $Result = $?;

  # 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,
  '-isystem' => 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 '='
  '-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 '='
);

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' : 'c-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,
  "c-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'};

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

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

  # 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;
  }

  # 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;

    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 =~ /^-[D,I,U](.*)$/) {
    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;
  }

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

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/) {
        # Change "Output" to be a file.
        my ($h, $f) = tempfile("report-XXXXXX", SUFFIX => ".plist",
                               DIR => $HtmlDir);
        $ResultFile = $f;
        # If the HtmlDir is not set, we should clean up the plist files.
        if (!defined $HtmlDir || -z $HtmlDir) {
          $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);
    }
  }
}

exit($Status >> 8);
@


