#!/usr/bin/perl -w
#################################################################
#
# 	(c) Copyright GlobespanVirata 2002
#
#	Filename: 	catobj
#	Version:	1.05
# 	Author:		Luke Diamnond
# 	Created: 	1999
#
#	Purpose:	Fix-up symbols names and partially link objects
#	Process Overview:
#		Decide if real or simulator build
#
#
#
#	Bugs:
#
#
#
#
#	Notes:
#		bintils 1.10 significantly changed objcopy syntax
#		Are -no-warn-shared and -no-prefix-tors useful?
#
#
##################################################################

use strict;
use File::Basename;
use Getopt::Long;
use Cwd;
use lib dirname $0;
use syslink;
use atmos_utils;
use bytes;

BEGIN
{
    eval ("use bytes;");
}


my $ver = "1.08";

my $progname = basename $0;

# which programs to use depends on the name of the program
my $linker;             # command to use for linking
my $objcopy;            # GNU command to use for mangling objects
my $objdump;            # GNU command to use for dumping objects
my $armtools;           # Set if using ARM toolchain
my $exclude_from_prefix = "";
my ( $destination_file, $opt_help, $opt_nowarn_shared, $opt_no_prefix_tors,
     $opt_ver );
my $syslink = new syslink;
$syslink->open( "../syslink.input" );
my $base_dir = basename( cwd() );
my $type;                # what type of object is this (Shared/Object)
my $defsyms = "";
my $relocatable = "-r";  # option to give to linker to get relocatable objects
my $link_warnings = "";
my $final_command = "";
my $needs_prefix = 0;    # do we need to prefix all the defined symbols in this object?
my $objectfile;          # full path to object file.
my %entrypoints;
my $no_leading_underscore;



#
# Print out a usage message.
#
sub usage
{
    print <<EOF;
$progname Version $ver
usage: $progname [-no-warn-shared] [-no-prefix-tors] [-o] dest obj1 obj2 ...
$progname concatenates a number of object files into a single object.
-o  destination    - specify destination
-l  linker         - specify linker to use
-c  objcopy        - DEPRICATED use -y
-y  objcopy        - specify objcopy to use
-d  objdump        - specify objdump to use
-no-warn-shared    - do not warn about questionable use of shared libraries
-no-prefix-tors    - do not prefix contructor/destructor symbols
-v                 - print version and exit
--armtools         - support ARM toolchain instead of GNU
--no-leading-underscore
EOF
    exit 1;
}

#
# Rename symbols in order to create separate namespace for ATMOS
# processes. Use ARM toolchain.
#
# Parameters:
#   $object_file - object file to mangle
#
sub rename_armtools($)
{
    my $object_file = shift @_;
    my $tmpfile = "$$.o";
    my $editfile = "$$.edit";
    rename $object_file, $tmpfile || die "could not rename $object_file to $tmpfile: $!\n";

    # work out the names of the symbols we want to rename - this is all the
    # public exported syms.

    open( EDIT, ">$editfile") or die "could not write to $editfile: $!\n";
    open( SYMS, "readelf --wide -s $tmpfile|") or die "could not read symbols in $tmpfile\n";
    while (<SYMS>) {
        chomp;
        my @words = split(/\s+/);
        next if ( $#words < 6 );
        my $sym = $words[8];
        next if $words[7] eq 'UND';
        next unless $words[5] eq 'GLOBAL';
        print "skip $sym\n" if defined $entrypoints{$sym};
        next if defined $entrypoints{$sym};
        print EDIT "RENAME $sym AS ${needs_prefix}${sym}\n";
    }
    print EDIT "# entry points\n";
    print EDIT $defsyms;
    close EDIT;
    my $cmd = "armlink --partial --noscanlib --edit $editfile $tmpfile -o $object_file";
    print "$cmd\n";
    my $rc = system($cmd);
    if ( $rc != 0 ) {
        die "failed to rename symbols\n";
    }
    unlink $editfile;
    unlink $tmpfile;
}

#
# Rename symbols in order to create separate namespace for ATMOS
# processes. Use GNU-derived tools.
#
# Parameters:
#   $object_file - object file to mangle
#
sub rename_gnu($)
{
    my $object_file = shift @_;

    my $tmpout = atmos_utils::tmpfile();
    my $template_functions = "";

    # Find templated functions that need to be excluded from prefix.
    $template_functions = `$objdump -h $object_file`;
    my @objdump_output = split (/\n/, $template_functions);
# .gnu.linkonce.r._ZTIN4isos16VMITempAllocatorE
    my @template_functions = grep {s/^.*?gnu.linkonce.t.([^\s]*).*$/$1/} @objdump_output;
    my @template_functions2 = grep {s/^.*?gnu.linkonce.d.([^\s]*).*$/$1/} @objdump_output;
    my @template_functions3 = grep {s/^.*?gnu.linkonce.r.([^\s]*).*$/$1/} @objdump_output;
    
    # Extract unique lines from template_functions;
    my %template_functions;
    foreach my $function (@template_functions, @template_functions2, @template_functions3)
    { $template_functions{$function} = 1 }
    
    # Print the now unique arguments in a space separated list
    my $excluded_templates = "";
    foreach my $function (keys %template_functions) {
	$excluded_templates .= " --exclude-from-prefix $function";
    }

    # Prefix and link.
    atmos_utils::system( "$objcopy --prefix-defined-symbols ${needs_prefix} $exclude_from_prefix $excluded_templates $object_file $tmpout" );

    atmos_utils::system( "$linker $defsyms $relocatable -o$object_file $tmpout" );
}

#
# Main program starts ....
#

if ( $progname =~ m/simulator/ ) {
    $linker = 'ld';
    $objcopy = 'atmos-objcopy';
    $objdump = 'objdump';
} else {
    $linker = 'isos-ld';
    $objcopy = 'isos-objcopy';
    $objdump = 'isos-objdump';
}


GetOptions( "o=s", 	\$destination_file,
            "h", 	\$opt_help,
	    	"v", 	\$opt_ver,
            "l=s", 	\$linker,
            "c=s", 	\$objcopy,
            "y=s", 	\$objcopy,
	    "d=s",      \$objdump,
            "armtools" => \$armtools,
            "no-leading-underscore" => \$no_leading_underscore,
            "no-warn-shared", \$opt_nowarn_shared,
            "no-prefix-tors", \$opt_no_prefix_tors ) or usage;

die "catobj version $ver\n" if $opt_ver;

if ( $opt_no_prefix_tors ) {
    $exclude_from_prefix = "--exclude-from-prefix __GLOBAL_";
}

usage if $opt_help;
usage unless defined $destination_file;

# Check command line and read off arguments.
if ($#ARGV lt 0)
{
    die "Incorrect number of arguments supplied at command line.\n";
}

$objectfile = "$base_dir/$destination_file";
$type = $syslink->type( $objectfile );


if ( $armtools ) {
    $relocatable = '--partial';
    $linker = 'armlink';
}

# Now see if which category the file is in and do different actions
# based on this:
#
# (a) In syslink.input and Shared:
#       ld -r $link_warnings -o$destination_file $component_files
# (b) In syslink.input and Object:
#       ld -r $link_warnings [--defsym <blah>] --retain-symbols-file <blah> -o$destination_file $component_files
# (c) Otherwise:
#       Same as (a)

# work out our list of files to concatenate together ...
my $component_files = '';
foreach my $f (@ARGV) {

    if ( $syslink->is_shared( $f ) ) {
        print STDERR <<EOF;
Warning: input "$f" to catobj is a shared library.
This is almost certainly a mistake, since you will get 2 copies
of the code in your image. (Use -no-warn-shared to suppress this warning).
EOF
    }

    $component_files .= " $f";
}

# Work out final command.
$final_command .= "$linker $relocatable $link_warnings";

if ( !defined $type or $syslink->is_shared( $objectfile ) )
{
    # Just do an ordinary link.
    $final_command .= " -o$destination_file $component_files";
}
elsif ( $syslink->is_object( $objectfile ) )
{
    my $prefix;

    my %renames = $syslink->renames( $objectfile );
    foreach my $lhs ( keys %renames )
    {
        my $rhs = $renames{$lhs};

	# Have to fiddle __main because aconfig writes things thinking there's
        # one more underscore than there really is.
        if ( $armtools || $no_leading_underscore ) {
                if ($lhs eq "__main") { $lhs = "_main"; }
                $lhs =~ s/^_//;
        }

        # now we can better infer the prefix to use
        my $rhs_s = $rhs; $rhs_s =~ s/^_//;
        my $lhs_s = $lhs; $lhs_s =~ s/^_//;
        $rhs_s =~ m/(.*)$lhs_s/;
        $prefix = $1 unless $prefix;

        if ( $no_leading_underscore ) {
            $rhs =~ s/^_//;
            $prefix =~ s/_$//;
	
            # Have to fiddle __main because aconfig writes things 
            # thinking there's one more underscore than there really is.
            # That's because for 'main' only, the *real* entrypoint
            # is the llibc wrapper function _main(), that does
            # process stdio initialization.
	    if ($lhs eq "main") { $lhs = "_main"; }
        }
	
        # arrange to add a fake symbol pointing at the real entrypoint
        if ( $armtools ) {
            $rhs =~ s/^_//;
            my $rename = "RENAME $lhs AS $rhs\n";
            $defsyms .= $rename;
        } else {
            $defsyms .= " --defsym $rhs=${prefix}$lhs";
        }
        $entrypoints{$lhs} = $rhs;
        
    }
    $prefix = "_$base_dir" unless $prefix;

    $final_command .= " -o $destination_file $component_files";

    $needs_prefix = $prefix;
}

if ($final_command eq "")
{
    $final_command =
        "$linker $relocatable $link_warnings -o $destination_file $component_files";
}

atmos_utils::system($final_command);

# now prefix all symbols if required

if ( $needs_prefix )
{
    if ( $armtools ) {
        rename_armtools($destination_file);
    } else {
        rename_gnu($destination_file);
    }
}

exit 0;
