#!/usr/bin/perl
#===-- test_bcc_debuginfo.pl - Debugger integration test driver script ---===#
#
#                     The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===----------------------------------------------------------------------===#
#
# This script tests debugging information generated by a compiler.
# Input arguments
#   - Path to FileCheck tool.
#   - Input source program. Usually this source file is decorated using
#     special comments (//DEBUGGER:, //CHECK:)to communicate debugger commands.
#   - Executable file. This file is generated by the compiler.
#
# This perl script extracts debugger commands from input source program
# comments in a script. A debugger is used to load the executable file
# and run the script generated from source program comments. Finally,
# the debugger output is checked, using FileCheck, to validate
# debugging information.
#
#===----------------------------------------------------------------------===#

use File::Basename;

my $filecheck_tool = $ARGV[0];
my $testcase_file = $ARGV[1];
my $testcase_output = $ARGV[2];

my $input_filename = basename $testcase_file;
my $output_dir = dirname $testcase_output;

my $debugger_script_file = "$output_dir/$input_filename.debugger.script";
my $output_file = "$output_dir/$input_filename.gdb.output";

open(OUTPUT, ">$debugger_script_file");

# Enable extra verbosity in GDB
print OUTPUT "set verbose on\n";

# Extract debugger commands from testcase. They are marked with DEBUGGER:
# at the beginning of a comment line.
open(INPUT, $testcase_file);
while(<INPUT>) {
    my($line) = $_;
    $i = index($line, "DEBUGGER:");
    if ( $i >= 0) {
        $l = length("DEBUGGER:");
        $s = substr($line, $i + $l);
        $s =~ s/\%s/$input_filename/g;
        $s =~ s/\%t/$testcase_output/g;
        print OUTPUT  "$s";
    }
}
print OUTPUT "\n";
print OUTPUT "quit\n";
close(INPUT);
close(OUTPUT);

# setup debugger and debugger options to run a script.
my $debugger = $ENV{'DEBUGGER'};
my $debugger_options = $ENV{'DEBUGGER_ARGS'};
if (!$debugger) {
    print "Please set DEBUGGER prior to using this script";
    exit 1;
}
$debugger_options = "-x $debugger_script_file $debugger_options $testcase_output";

# run debugger and capture output.
system("$debugger $debugger_options > $output_file 2>&1") ;
if ($?>>8 != 0) {
  print "Error during debugger invocation. Command used was: \n";
  print("$debugger $debugger_options > $output_file 2>&1\n") ;
  exit 1;
}

# validate output.
system("$filecheck_tool", "-input-file", "$output_file", "$testcase_file");
if ($?>>8 != 0) {
    print "Error during verification. Debugger command used was: \n";
    print("$debugger $debugger_options > $output_file 2>&1\n") ;
    print "Verification command used was: \n";
    print "$filecheck_tool -input-file $output_file $testcase_file\n";
    exit 1;
}
else {
    exit 0;
}
