#!/usr/bin/perl -w
my $running_under_some_shell;  # never true
eval 'exec perl -S $0 "$@"'
    if $running_under_some_shell;
			# this emulates #! processing on NIH machines.
			# (remove #! line above if indigestible)

use File::Basename;
use strict;



#######################################################################
#
# Configuration
#
#######################################################################

my $version = "1.01";
my $progName = basename $0;

my $stdin_filename = '-';
my $default_mapfile = 'debug.map';
my $default_image_format = "elf";
my $default_elf_imagefile = 'image.elf';
my $default_aout_imagefile = 'image.aout';
my $default_elf_addr2line = 'isos-addr2line';
my $default_aout_addr2line = 'arm-aout-addr2line';


#######################################################################
#
# Command line argument handling
#
#######################################################################


my $use_map = 0;
my $mapfile = '';
my $imagefile = '';
my $imageformat = '';
my $stackfile = $stdin_filename;
my $ask_help = 0;
my $addr2line = '';


sub showhelp {
    print("Syntax: $progName [-s <stackfile>] [-m | -i] [-a <addr2line>] [<mapfile>|<imagefile>]\n");
    print("        -i          - get function names from image file (default)\n");
    print("        -m          - get function names from map file\n");
    print("        <stackfile> - file containing captured Quantum backtrace\n");
    print("                      (standard input used by default)\n");
    print("        <mapfile>   - .map file generated my mkproduct/aconfig\n");
    print("                      (\"$default_mapfile\" used by default)\n");
    print("        <imagefile> - image file generated my mkproduct/aconfig\n");
    print("                      (\"$default_aout_imagefile\" or \"$default_elf_imagefile\" used by default)\n");
    print("        <addr2line> - path to addr2line command used if -i given\n");
    print("\n");
    print("This command decodes the Quantum backtrace captured in the <stackfile>.\n");
    
}



sub argv_parse {
    my $arg = $ARGV[0];
    my $ok = 1;

    while (defined $arg && $arg =~ /^\-/) {
	shift @ARGV;
	if ($arg eq '-h' or $arg eq '-help' or
	    $arg eq '--help' or $arg eq '-?') {
	    $ask_help = 1;
	} elsif ($arg eq '-s' or $arg eq '--stack') {
	    $stackfile = shift @ARGV;
	} elsif ($arg eq '-m' or $arg eq '--map') {
	    $use_map = 1;
	} elsif ($arg eq '-i' or $arg eq '--image') {
	    $use_map = 0;
	} elsif ($arg eq '-b' or $arg eq '--format') {
	    $imageformat = shift @ARGV;
	} else {
	    $ok = 0;
	}
	$arg = $ARGV[0];
    }

    if (defined $arg) {
	if ($use_map) {
	    $mapfile = shift @ARGV;
	} else {
	    $imagefile = shift @ARGV;
	}
	$ok = 0 if defined $ARGV[0];
    } else {
	$ok = 0;
    }

    if ($ok) {
	if ($imageformat eq '') {
	    if (basename($addr2line) eq $default_elf_addr2line) {
		$imageformat="elf";
	    } elsif (basename($addr2line) eq $default_aout_addr2line) {
		$imageformat="aout";
	    } elsif (basename($imagefile) eq $default_elf_imagefile) {
		$imageformat="elf";
	    } elsif (basename($imagefile) eq $default_aout_imagefile) {
		$imageformat="aout";
	    } elsif (-r $default_elf_imagefile) {
		$imageformat="elf";
	    } elsif (-r $default_aout_imagefile) {
		$imageformat="aout";
	    }
	}

	if ($mapfile eq '') {
            $mapfile = $default_mapfile;
        }
	
	if ($imagefile eq '') {
	    if ($imageformat eq "aout") {
		$imagefile=$default_aout_imagefile;
	    } elsif ($imageformat eq "elf") {
		$imagefile=$default_elf_imagefile;
	    } elsif (not $use_map and -r $mapfile) {
		print("Can't find image file - using map file \"$mapfile\" instead\n");
		$use_map=1;
	    }
	}

	if ($addr2line eq '') {
	    if ($imageformat eq "aout") {
		$addr2line=$default_aout_addr2line;
	    } elsif ($imageformat eq "elf") {
		$addr2line=$default_elf_addr2line;
	    }
	}

	if (not $use_map and ($imagefile eq '' or $addr2line eq '')) {
	    $ok=0;
	}
    }

    if (not $ok) {
        $ask_help = 1;
    }

    
    return $ok;
}






#######################################################################
#
# Error handling
#
#######################################################################



sub errmsg {
    my ($msg) = @_;
    printf("Error: $msg\n");
}



#######################################################################
#
# Symbol table
#
#######################################################################

my %symbols;
my %objcode;
my @sortedaddrs;
my %codenameid;
my @codename;



sub symbol_new {
    my ($symb, $addr, $objname) = @_;
    my $objid;

    if (!defined $codenameid{$objname}) {
	$objid = push(@codename,$objname)-1;
	$codenameid{$objname} = $objid;
    } else {
	$objid = $codenameid{$objname};
    }
    
    $symbols{$addr} = $symb;
    $objcode{$symb} = $objid;

    # print p('New symbol ',$symb,' at ',$addr);
}



sub symbols_sort {
    @sortedaddrs = sort {$a <=> $b} keys %symbols;
}



sub symbols_loweraddr {
    my ($sought, $mini, $maxi) = @_;
    my $min=$sortedaddrs[$mini];
    my $max=$sortedaddrs[$maxi];
    
    if ($sought < $min) {
	# print "In $mini-$maxi $sought<$min\n";
	return $mini-1;
    } elsif ($sought >= $max) {
	# print "In $mini-$maxi $sought>=$max\n";
	return $maxi;
    } elsif ($mini == $maxi) {
	# print "In $mini-$maxi same\n";
	return $mini;
    } else {
	my $testi = $mini + int(($sought - $min)*($maxi-$mini)/($max-$min));
	my $test = $sortedaddrs[$testi];
	# print "In $mini-$maxi for $sought test $testi=$test\n";

	if ($sought == $test) {
	    return $testi;
	} elsif ($sought < $test) {
	    return symbols_loweraddr($sought, $mini, $testi-1);
	} else {
	    return symbols_loweraddr($sought, $testi+1, $maxi);
	}
    }
}




sub symbols_findaddr {
    my ($addr) = @_;
    my ($symb, $offset, $obj);

    if (defined $symbols{$addr}) {
	$offset = 0;
	$symb = $symbols{$addr};
    } else {
	my $symi = symbols_loweraddr($addr, 0, scalar @sortedaddrs-1);
	if ($symi >= 0) {
	    my $loweraddr = $sortedaddrs[$symi];
	    $symb=$symbols{$loweraddr};
	    $offset=$addr-$loweraddr;
	}
    }
    if (defined $symb) {
        $obj = $codename[$objcode{$symb}];
    }

    return ($symb, $offset, $obj);
}
	    
    

    
    
sub symbols_list {
    my ($key, $val);
    
    foreach $key (@sortedaddrs) {
	$val=$symbols{$key};
	printf("%08x: %-40s %s\n", $key, $val, @codename[$objcode{$val}]);
    }
}





#######################################################################
#
# Parse map file
#
#######################################################################



sub map_parse {
    my ($map) = @_;

    if (!open(MAP, "<".$map)) {
	errmsg("Can't open '$map' to read");
	return 0;
    } else {
	my $in;
	my ($empty, $sectype, $startaddr, $len, $objname, $rubbish);
	my ($currentsection, $currentsectiontype);
	
	# skip to start of the symbols
	while (($in = <MAP>) !~ /^\.text/) { };
	while (! eof MAP) {
	    # print "========================== $in";
	    # go to start of .text/bss/data section:
	    $currentsection='';
	    $currentsectiontype='';
	    while (<MAP> !~ /^ \*\(.*\)/) { };
	    while (($in = <MAP>) =~ /^\s/) {
		if ($in =~ /^ \S/) {
		    ($empty, $sectype, $startaddr, $len, $objname, $rubbish) =
			split(/\s+/, $in);
		    if (defined $objname) {
		        # print("$sectype $startaddr '$objname'\n");
			$currentsection=$objname;
			$currentsectiontype=$sectype;
		    }
		} else {
		    # print $in;
		    ($empty, $startaddr, $objname, $rubbish) =
			split(/\s+/, $in);
		    # printf("%08x: %-40s %s\n",
		    #	   oct($startaddr), $objname, $currentsection);
		    if (defined $objname) {
                        symbol_new($objname, oct($startaddr), $currentsection);
		    }
		}
	    };
	}
	close(MAP);
	return 1;
    }
}


sub map_load {
    if (&map_parse) {
        symbols_sort();
        # symbols_list();
	return 1;
    } else {
	return 0;
    }
}



#######################################################################
#
# Parse stack trace file
#
#######################################################################



my @stackat;
my @stackin;



sub trace_parse {
    my ($trace) = @_;

    if (!open(TRACE, "<".$trace)) {
	errmsg("Can't open '$trace' to read");
	return 0;
    } else {
	my $in;
	my ($empty, $sectype, $startaddr, $len, $objname, $rubbish);
	
	while (<TRACE>) {
	    if (/^\d+:\s+([a-f0-9]+)\s+(in function|after entry)\s+([a-f0-9]+),/) {
		# printf("%08x in %08x (hf)\n", hex($1), hex($3));
		push @stackat, hex($1);
		push @stackin, hex($3);
	    } elsif (/^\d+:\s+([a-f0-9]+)/) {
		# printf("%08x (hf)\n", hex($1));
		push @stackat, hex($1);
		push @stackin, -1;
	    } elsif (/^\s+([a-f0-9]+)/ and not /\(\)/) {
		# printf("%08x (tj)\n", hex($1));
		push @stackat, hex($1);
		push @stackin, -1;
	    }
	}
	close(TRACE);
	return 1;
    }
}




sub trace_mapshow {
    my $i;
    my ($sy, $off, $cd);
    my $place;

    for ($i=0; $i<scalar @stackat; $i++) {
	printf("%08x: ", $stackat[$i]);
	($sy, $off, $cd) = symbols_findaddr($stackat[$i]);
	if (defined $sy) {
	    $place = sprintf("%s + 0x%x", $sy, $off);
	    printf("%-40s %s ", $place, $cd);
	} 
	printf("\n");
        if ($stackin[$i] != -1) {
	    printf("%8s     ", " ");
	    ($sy, $off, $cd) = symbols_findaddr($stackin[$i]);
	    if (defined $sy) {
		if ($off == 0) {
		    $place = sprintf("%s [= %08x]", $sy, $stackin[$i]);
		} else {
		    $place = sprintf("[%s+0x%x = %08x]",
				     $sy, $off, $stackin[$i]);
		}
		printf("%-37s %s", $place, $cd);
	    } 
	    printf("\n");
	}
    }
}



    
#######################################################################
#
# Debug output using addr2line
#
#######################################################################





sub shortsourcefile {
    my ($file) = @_;
    if ($file =~ /^.*atmos.source.(.*)$/) {
	return $1;
    } else {
	return $file;
    }
}




sub addr2line_findaddr {
    my ($addr) = @_;
    my $cmd=sprintf("$addr2line -e $imagefile -C -f %08X", $addr);
    # print("cmd: '$cmd' ");
    my $cmdout = `$cmd`;

    if (defined $cmdout) {
	# printf("%08X->'$cmdout'\n", $addr);
	my $sy;
	my $line;

	if ($cmdout =~ s/^(.*)\n(.*)\n$//) {
	    $line = $2;
	    $sy = $1;
	}

	if (not defined($sy)) {
	    $sy = "(unknown symbol)";
	}
	if (not defined($line)) {
	    $line = "(unknown line)";
	}
	return ($sy, $line);
    } else {
	return ("(unknown symbol)", "(unknown line)");
    }
}





sub trace_addr2lineshow {
    my $i;
    my ($sy, $cd);
    my $place;

    for ($i=0; $i<scalar @stackat; $i++) {
	printf("%08x: ", $stackat[$i]);
	($sy, $cd) = addr2line_findaddr($stackat[$i]);
	if (defined $sy) {
	    printf("%-40s %s ", $sy, shortsourcefile($cd));
	} 
	printf("\n");
        if ($stackin[$i] != -1) {
	    printf("%8s     ", " ");
	    ($sy, $cd) = addr2line_findaddr($stackin[$i]);
	    if (defined $sy) {
		if ($sy eq "(unknown symbol)") {
		    $place=sprintf("%08x", $stackin[$i]);
		} else {
		    $place=sprintf("$sy [%08x]", $stackin[$i]);
		}
		printf("%-37s %s", $place, shortsourcefile($cd));
	    } 
	    printf("\n");
	}
    }
	
}



#######################################################################
#
# Testing
#
#######################################################################





my $test;

$test = "symbols";
$test = "file";
$test = "trace";
$test = "args";
$test = "none";


if ($test eq 'symbols') {

    symbol_new("symb1", 0x122222, 'one.o');
    symbol_new("symb2", 0x788, 'one.o');
    symbol_new("symb3", 0x92288, 'one.o');
    symbol_new("symb4", 0xabc99, 'three.o');
    symbol_new("symb5", 0x99822, 'two.o');

    symbols_sort();
    symbols_list();

    my @test=(2,45,1);
    printf("%d addresses: ", scalar @sortedaddrs);
    print(join (" ", @sortedaddrs));
    printf("\n");

    my $i;
    for ($i=0; $i<scalar @sortedaddrs; $i++) {
	printf("Addr %d: %x\n", $i, $sortedaddrs[$i]);
    }

    my $try=0xb00000;
    my $tryi=symbols_loweraddr($try, 0, scalar @sortedaddrs-1);
    printf("Lower %x is [%d]\n", $try, $tryi);

    my ($sy, $off, $cd) = symbols_findaddr($try);
    if (defined $sy) {
	printf("%x = %s+%x, code %s\n", $try, $sy, $off, $cd);
    } else {
	printf("%x is before 1st symbol\n");
    }

} elsif ($test eq 'file') {

    my $mapfile = '/home/ggirling/tree/clean/atmos/build/'.
               'bd6000-eth-gateway.debug/debug.map';
    map_load("rubbish-map--");
    print "Loading symbols\n";
    print "Got symbols\n" if map_load($mapfile);
 
} elsif ($test eq 'trace') {

    my $mapfile = '/home/ggirling/tree/clean/atmos/build/'.
                  'bd6000-eth-gateway.debug/debug.map';
    my $tracefile = "1";
    print "Symbols loaded\n" if map_load($mapfile);

    trace_parse("--rubbish-trace");
    print("Loading $tracefile\n");
    if (trace_parse($tracefile)) {
	print("Backtrace:\n");
	trace_mapshow();
    } else {
	print("Load failed\n");
    }
    
} elsif ($test eq 'args') {

    my $i;
    my $rc;

    for ($i=0; $i<scalar @ARGV; $i++) {
	printf("Arg %d: '%s'\n", $i, $ARGV[$i]);
    }

    showhelp();

    $rc = argv_parse();

    print("ok=$rc, help=$ask_help, format=$imageformat,\n".
	  "mapfile='$mapfile',\nimagefile='$imagefile',\n".
	  "stackfile='$stackfile', use_map=$use_map, addr2line=$addr2line\n");
} else {

    my $rc = argv_parse();

    errmsg("syntax error") if (not $rc);
    showhelp() if ($ask_help);
    if ($rc) {
	if (not $use_map or map_load($mapfile)) {
	    
	    # Flush immediately to stdout
            $| = 1;

	    print "Please type the backtrace:\n" if ($stackfile eq '-');
	    if (trace_parse($stackfile)) {
		print("Backtrace:\n");
		if ($use_map) {
		    trace_mapshow();
		} else {
		    trace_addr2lineshow();
		}
	    }
	}
    }
}

