#!/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 Cwd;
use File::Temp qw/ tempfile /;
use File::Path qw / mkpath /;
 
##----------------------------------------------------------------------------##
#  Process Clang Crashes.
##----------------------------------------------------------------------------##

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

sub ProcessClangFailure {
  my ($Lang, $file, $Args, $HtmlDir, $ErrorType) = @_;
  my $Dir = "$HtmlDir/crashes";
  mkpath $Dir;
  my ($PPH, $PPFile) = tempfile("clang_crash_XXXXXX",
                                  SUFFIX => GetPPExt($Lang),
                                  DIR => $Dir);

  system "gcc", @$Args, "-E", "-o", $PPFile;  
  close ($PPH);
  open (OUT, ">", "$PPFile.info") or die "Cannot open $PPFile.info\n";
  print OUT "$file\n";
  print OUT "$ErrorType\n";
  print OUT "@$Args\n";
  close OUT;
}

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

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

  # Skip anything related to C++.
  return if ($Lang =~ /c[+][+]/);

  my $RunAnalyzer = 0;
  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;
    push @CmdArgs,'-DIBOutlet=__attribute__((iboutlet))';
    push @CmdArgs,@$Args;
    @CmdArgsSansAnalyses = @CmdArgs;
    push @CmdArgs,(split /\s/,$Analyses);
    $RunAnalyzer = 1;
  }
  
  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";
  }
  
  if ($RunAnalyzer and defined($HtmlDir)) {
    push @CmdArgs,'-o';
    push @CmdArgs,$HtmlDir;
  }

   system $Cmd,@CmdArgs;

   # Did the command die because of a signal?
   if ($? & 127 and $Cmd eq $Clang and defined $HtmlDir) {
     ProcessClangFailure($Lang, $file, \@CmdArgsSansAnalyses, $HtmlDir,
                          "Crash");
   }
   elsif ($?) {
     ProcessClangFailure($Lang, $file, \@CmdArgsSansAnalyses, $HtmlDir,
                          "Parser Rejects");
   }
}

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

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

my %LinkerOptionMap = (
  '-framework' => 1
);

my %CompilerLinkerOptionMap = (
  '-isysroot' => 1,
  '-arch' => 1,
  '-v' => 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
);

my %LangMap = (
  'c'   => 'c',
  'cpp' => 'c++',
  'cc'  => 'c++',
  'i'   => 'c-cpp-output',
  'm'   => 'objective-c',
  'mi'  => 'objective-c-cpp-output'
);

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

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

# Forward arguments to gcc.
my $Status = system("gcc",@ARGV);
if ($Status) { exit($Status); }

# Get the analysis options.
my $Analyses = $ENV{'CCC_ANALYZER_ANALYSIS'};
if (!defined($Analyses)) { $Analyses = '-checker-cfref'; }

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

# Determine what clang executable to use.
my $Clang = $ENV{'CLANG'};
if (!defined $Clang) { $Clang = 'clang'; }

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


# Process the arguments.
foreach (my $i = 0; $i < scalar(@ARGV); ++$i) {
  my $Arg = $ARGV[$i];
  
  # Modes ccc-analyzer supports
  if ($Arg eq '-E') { $Action = 'preprocess'; }
  elsif ($Arg eq '-c') { $Action = 'compile'; }
  elsif ($Arg =~ /^-print-prog-name/) { exit 0; }
    
  # Options with possible arguments that should pass through to compiler.
  if (defined $CompileOptionMap{$Arg}) {
    my $Cnt = $CompileOptionMap{$Arg};
    push @CompileOpts,$Arg;
    while ($Cnt > 0) { ++$i; --$Cnt; push @CompileOpts, $ARGV[$i]; }
    next;
  }

  # Options with possible arguments that should pass through to linker.
  if (defined $LinkerOptionMap{$Arg}) {
    my $Cnt = $LinkerOptionMap{$Arg};
    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{$Arg}) {
    my $Cnt = $CompilerLinkerOptionMap{$Arg};
    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{$Arg}) {
    my $Cnt = $IgnoredOptionMap{$Arg};
    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;
  }
  
  # 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; }
    next;
  }
  
  if ($Arg =~ /^-std=/) {
    push @CompileOpts,$Arg;
    next;
  }
  
#  if ($Arg =~ /^-f/) {
#    # FIXME: Not sure if the remaining -fxxxx options have no arguments.
#    push @CompileOpts,$Arg;
#    push @LinkOpts,$Arg;  # FIXME: Not sure if these are link opts.
#  }
  
  # 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 =~ /^-/)) {
    push @Files,$Arg; next;
  }
}

if ($Action eq 'compile' or $Action eq 'link') {
  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};
      }
    }
    
    next if (!defined $FileLang);
    
    my @AnalyzeArgs;
    
    if ($FileLang ne 'unknown') {
      push @AnalyzeArgs,'-x';
      push @AnalyzeArgs,$FileLang;
    }

    push @AnalyzeArgs,@CompileOpts;
    push @AnalyzeArgs,$file;
    
    Analyze($Clang, \@AnalyzeArgs, $FileLang, $Output,
            $Verbose, $HtmlDir, $file, $Analyses);
  }
}

