#!/usr/bin/perl -w
# ############################################################################
# (c) Copyright Virata Limited 1998
#
# Virata Limited Confidential and Proprietary
#
# The following software shell script ("Software") is strictly confidential and
# is proprietary to Virata Limited ("Virata").  It may only be read, used,
# copied, adapted, modified or otherwise dealt with by you if you have
# entered into a confidentiality agreement with Virata and then subject to the
# terms of that confidentiality agreement and any other applicable agreement
# between you and Virata.  If you are in any doubt as to whether you are
# entitled to access, read, use, copy, adapt, modify or otherwise deal with
# the Software or whether you are entitled to disclose the Software to any
# other person you should contact Virata.  If you have not entered into a
# confidentiality agreement with Virata granting access to this Software you
# should forthwith return all media, copies and printed listings containing
# the Software to Virata.
#
# Virata reserves the right to take legal action against you should you breach
# the above provisions.
#
# If you are unsure, or to report violations, please contact
# support@virata.com
# ############################################################################


use 5.004;
use strict;
use File::stat;
use File::Basename;
use Fcntl;
use lib dirname $0;
use syslink;
use atmos_utils;
use bytes;

# cope with missing O_BINARY on some platforms
my $x = eval "O_BINARY";
if ( ! defined $x ) {
	eval "sub O_BINARY { 0 }";
}

my $ver = '1.12';

my $progname = basename $0;
my $install_dir = dirname $0;

# where we put our objects when we've done with them
my $prefixdir = '.prefixed';

my $objcopy = 'isos-objcopy';
my $ld = 'isos-ld';
my $usage = <<EOF;
usage: $progname [-h] -T<textaddr> -o<outputfile> [-M<map>] <syslink.input>

    -h    - give this help
    -T    - set the start address of the text segment (data follows on
            immediately afterwards)
    -D    - set the start address of the data segment (if data does not
            follow the text segment)
    -S    - pass the link script to the linker
    -o    - set the outputfile
    -M    - write a map file
    -r    - generate romable image
    --elf - generate elf image only, no aout image
    -Wopt - pass opt through to ld

Note that this version of syslink is merely a wrapper around isos-ld.
The map file produced is _not_ compatible with the mapfile format used by
earlier versions of syslink.
EOF

sub ver
{
    print STDERR "$progname $ver\n";
    system( "$ld -v" );
}

sub usage
{
    print STDERR $usage;
    exit 1;
}

# parse command line args - can't use GetOpt due to non-GNU standard
# option syntax

my ( $opt_help, $opt_script, $opt_textbase, $opt_database, $opt_map, $opt_output, $opt_rom, $opt_ver, $elf_image);
my $opt_passthrough = '';

my %opts = (
            '-h' => \$opt_help,
            '-S' => \$opt_script,
            '-T' => \$opt_textbase,
            '-D' => \$opt_database,
            '-r' => \$opt_rom,
            '-v' => \$opt_ver,
            '-M' => \$opt_map,
            '-l' => \$ld,
            '-c' => \$objcopy,
            '-o' => \$opt_output,
            "--elf" => \$elf_image );

my @args;

# Parse arguments.
while (@ARGV)
{
    my $opt = shift @ARGV;
    if ( $opt =~ m/-W(.+)/ ) {
        $opt_passthrough .= $1;
        $opt_passthrough .= ' ';
    }
    elsif ( $opt =~ m/(^-[A-Za-z])=?(.*)/ ) {
	# First look for single letter arguments.
        my $opt_key = $1;
        my $opt_val = $2;
        $opt_val = 1 if ($opt_val eq "");

        my $opt_arg = $opts{$opt_key};
        if ( defined $opt_arg ) {
            $$opt_arg = $opt_val;
        } else {
	    # Add the option to the list we are passing to the linker.
	    push @args, $opt;
	}
    } elsif ( $opt =~ m/(^--([A-Za-z]+))/ ) {
	# Second, look for multiple letter arguments.
	my $opt_key = $1;
	my $opt_arg = $opts{$opt_key};
	if ( defined $opt_arg ) {
		$$opt_arg = 1;
	    } else {
                # Add the option to the list we are passing to the linker.
		push @args, $opt;
	    }
    } else {
	# Add the option to the list we are passing to the linker.
	push @args, $opt;
    }
}

usage if $opt_help;
ver if $opt_ver;
usage unless $opt_output;

$opt_script = "$install_dir/isos.link" if !defined($opt_script);
# now build up the link line
my $link_options = "-N -warn-once $opt_passthrough -T $opt_script ";
$link_options .= "-Ttext $opt_textbase --defsym _start=$opt_textbase " if defined($opt_textbase);
$link_options .= "-Tdata $opt_database " if defined($opt_database);
$link_options .= "-Map $opt_map " if $opt_map;

my $syslink = new syslink;
$syslink->open;

# rename all the symbols in the unshared objects to give each of them
# their own private name space

mkdir( $prefixdir, 0777 );

my $inputs = '';

$inputs .= join( " ", $syslink->filtered_objects('\.o$') );
$inputs .= ' --start-group ';
$inputs .= join( " ", $syslink->filtered_objects('\.a$') );
$inputs .= ' --end-group ';

shift @args;
my $extra_args = join(" ", @args);

# Work out the part of the filename without the extension, ie. 'image'.out.
my $base_file 	= '';
my $extension 	= '';
if ($opt_output =~ m/(.*)(\..*)/) {
    $base_file = $1;
    $extension = $2;
} else {
    $base_file = $opt_output;
    $extension = "";
}

# work out the strip command to use ...
$ld =~ m/(.*)ld(.*)/;
#my ( $prefix, $postfix ) = ($1,$2);
my $strip = "isos-strip";

# Now do different things depending on whether or not we need to convert
# ELF to AOUT.
if ($elf_image) {
  # ELF build.
  atmos_utils::system("$ld $link_options -o${base_file}${extension} $inputs $extra_args") && die;
    
  if ($opt_rom) {
    # Strip the image.
    atmos_utils::system("$strip ${base_file}${extension}") && die;
  }
} else {
  # AOUT build.
  my $elf_extension = ".elf";

  # Prevent possible filename clash at elf2aout stage.
  if ("${base_file}${elf_extension}" eq "$opt_output") { $elf_extension = "2.elf"; }

  # Do initial link.
  atmos_utils::system("$ld $link_options -o${base_file}${elf_extension} $inputs $extra_args") && die;
 
  if ($opt_rom) {
    # Strip the image.
    atmos_utils::system("$strip ${base_file}${elf_extension}") && die;
    
    # Convert to AOUT without symbols.
    atmos_utils::system("elf2aout ${base_file}${elf_extension} $opt_output") && die;
  } else {
    # Convert to AOUT leaving symbols in.
    atmos_utils::system("elf2aout ${base_file}${elf_extension} $opt_output") && die;      
  }
}
