#!/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
# ############################################################################

##############################################################################
# This script does lots of little tasks in order to build a simulator image. #
# The result of the build process is an executable called a.out, and an ARM  #
# image call armobjects.o. Major comments in this file are surrounded by a   #
# block of hashes.                                                           #
##############################################################################

##############################################################################
# First we parse the syslink.input file to see what goes into the PP image.  #
##############################################################################

my $SIM_SYSLINK_VERSION = "1.04";

# Respond to simulator_syslink -h
if ($ARGV[0] eq "-h")
{
    print <<"ENDHELP";
  Usage: simulator_syslink [-h] [-pp|-gp] [compiler [compiler options...]]
      simulator_syslink is the simulator counterpart to the syslink tool
      used in producing native ATMos images. It reads all the information 
      required to produce a simulator image form syslink.input, and takes
      no command-line arguments.
ENDHELP
    exit 0;
}
elsif ($ARGV[0] eq "-v")
{
    print $SIM_SYSLINK_VERSION . "\n";
    exit 0;
}


my $objcopy = "isos-objcopy";

# See if a -pp or -gp option has been specified.
$do_final_link = 0;
if ($ARGV[0] eq "-pp")
{
    $symbol_prefix = "_PP_";
    shift;
} elsif ($ARGV[0] eq "-gp")
{
    $symbol_prefix = "_GP_";
    shift;
} else
{
    $symbol_prefix = "_PP_";
    $do_final_link = 1;
}

# Read any remaining command line options as the compiler.
if ($#ARGV ne -1) {
    $compiler = join(' ', @ARGV);
} else {
    $compiler = "gcc";
}

open(SYSLINK, "<syslink.input") || die "Couldn't open syslink.input: $!\n";

$allobjs = "";
$allarchs = ""; # List of archive libraries - .a files
$link_warnings = "--warn-common";
$link_options = "";

unlink "syslink.symbols";
open(ALL_SYMS, ">>syslink.symbols") || die "Couldn't open :syslink.symbols $!\n";

while(<SYSLINK>)
{
    # Each line in the syslink.input file is of the following format:
    #
    # (Shared|Object) *.o (x=y)*

    # Read the *.o part and split it into directory and file components.
    chomp;
    ($type, $filename, $stuff) = split(/\s+/, $_, 3);
    $filename =~ /^(.*)\/([^\/]+)$/;
    ($dir, $file) = ($1, $2);

    if ($dir ne "./simulator") {

	if ($type eq "Shared")
	{
            # Check if this is a .a file, and add to the list of archive libraries if so
            # Otherwise, add straight onto the list of objects.
            if ($filename =~ /\.a$/)
            { $allarchs .= " $filename" }
            else
            { $allobjs .= " $filename" }
	}
	elsif ($type eq "Object")
	{
	    $prefix = "${file}_";
	    $out_file = "${dir}/prefixed_$file";
	    $allobjs .= " $out_file";

	    foreach $thing (split (/\s+/, $stuff))
	    {
		($lhs, $rhs) = split (/=/, $thing);
		$lhs =~ s/^\_//;
		$rhs =~ s/^\_//;
		$link_options .= " --defsym $rhs=${prefix}$rhs";
		print ALL_SYMS "$rhs\n";
	    }

	    $com = "$objcopy --prefix-defined-symbols $prefix $filename $out_file";
	    print "$com\n";
	    if (system($com) ne 0) { die; };
	}
	else
	{
	    print STDERR "Warning: ignoring unrecognised directive '$type'\n";
	}
    }
}

close SYSLINK;
close ALL_SYMS;

# Now, group all the archive objects together and add them to the link
# line. We need to group them because they might contain references to
# each other.
$allobjs .= " --start-group $allarchs  --end-group";

##############################################################################
# Now we begin work on the ARM assembler objects. We build up two lists of   #
# symbols that are defined and undefined symbols. Ie. symbols that are       #
# exported from the ARM objects, and symbols that are imported into the ARM  #
# objects.                                                                   #
##############################################################################

# Find all the ARM assembler objects.
my $arm_objects = `find . -name \"*_SIMREAL.o\" -print`;
my $defined_symbols = "";
$arm_objects =~ s/\n/ /g;

if ($arm_objects !~ /^( )*$/) {
    # Find './simulator/sim_as_SIMREAL.o' and move it to the beginning of the list.
    my $driver = "";
    my $tmp = "";
    
    print STDERR "Linking Assembler objects: $arm_objects\n";
    foreach $file (split / /, $arm_objects) {
        if ($file ne "./simulator/sim_as_SIMREAL.o") {
            $tmp .= " $file";
        } else {
            $driver = $file;
        }
    }
    
    if ( $driver eq "" ) {
        $arm_objects = $tmp;
        print STDERR "Warning: assembler objects have been found but assembly code support has not\n";
    } else {
        $arm_objects = $driver." ".$tmp;
    }

    # Do a trial link to discover which symbols are undefined and are needed from the C world.
    my $com = "isos-ld -A arm -r -N -Ttext 0x00100020 -oarm_objects.o $arm_objects";
    print "$com\n";
    if (system($com) ne 0) { die; };

    # Find undefined symbols and get into a perl array.
    $com = "isos-nm arm_objects.o | grep \" U \"";
    print "$com\n";
    my $undefined_symbols = `$com`;
    my @undefined_symbol = split /\n/, $undefined_symbols;
    my %undefined_symbol_value;

    # Remove the ".. U " prefix left by 'nm' and create NULL value in value array.
    for (my $count = 0; $count <= $#undefined_symbol; $count += 1) {
        $undefined_symbol[$count] =~ s/\s+U //;
        $undefined_symbol_value{$undefined_symbol[$count]} = 0;
    }

    # Now do a more complete link to get the value of the exported symbols from the ARM assembler.
    $com = "isos-ld -N -Ttext 0x00100020 -oarm_objects.o $arm_objects";
    for (my $count = 0; $count <= $#undefined_symbol; $count += 1) {
        my $symbol = $undefined_symbol[$count];
        $com .= " --defsym $symbol=0x$undefined_symbol_value{$symbol}";
    }
    print "$com\n";
    if (system($com) ne 0) { die; };
    
    # Now get a list of exported symbols (and their values) from the assembler object.
    $com = "isos-nm arm_objects.o | grep \" [B-TV-Z] \"";
    print "$com\n";
    $defined_symbols = `$com`;

} else {
    $defined_symbols = "\n";
    # print STDERR "No assembler objects in the code\n";
}

my @defined_symbol = split /\n/, $defined_symbols;
my %defined_symbol_value;

# Remove the ".. [B-Z] " prefix left by 'nm' and create value in value array.
for (my $count = 0; $count <= $#defined_symbol; $count += 1) {
    $defined_symbol[$count] =~ s/([0-9a-zA-Z]+)\s+[B-Z] //;
    $defined_symbol_value{$defined_symbol[$count]} = $1;
}

##############################################################################
# At this point, we don't have an ARM object file that we can use, but we do #
# have arrays of defined and undefined symbols that the ARM assembler        #
# exports and requires respectively.                                         #
#                                                                            #
# Now we go on and build the main simulator image (to a.out).                #
##############################################################################

# Link all bits of ATMOS together in one lump.
if (-f "intermediate.o") { unlink "intermediate.o"; }
$com = "ld $link_warnings $link_options -r --retain-symbols-file syslink.symbols -ointermediate.o ctortab.o $allobjs";
print "$com\n";
if (system($com) ne 0) { die; }

# Prefix ATMOS object file with _ATMOS_.
if (-f "prefixed_intermediate.o") { unlink "prefixed_intermediate.o"; }
$com = "$objcopy --prefix-defined-symbols _ATMOS_ intermediate.o prefixed_intermediate.o";
print "$com\n";
if (system($com) ne 0) { die; }

# Check that the dangerous line which subsequently follows is not dangerous.
undef $/;    # undefine line separator
open(PI_FILE, "<prefixed_intermediate.o") || die "Couldn't open prefixed_intermediate.o.\n";
$file = <PI_FILE>;  # sucks whole file as line separator is undefined
close(PI_FILE);
$count = 0;
while ($file =~ m/\.[cd]tors\000/g) { $count++ };
if ($count gt 2) { die "Too many occurences of .[cd]tors in prefixed_intermediate.o.\n"; }

# This dangerous line rename the constructor and destructor sections in the object file.
$com = "perl -pi -e \"s/\\.ctors\\000/\.Xtors\\000/g\" \'prefixed_intermediate.o\'";
print "$com\n";
system($com);

$com = "perl -pi -e \"s/\\.dtors\\000/\.Ytors\\000/g\" \'prefixed_intermediate.o\'";
print "$com\n";
system($com);

# Link ATMOS image with simulator kernel support.
if (-f "intermediate2.o") { unlink "intermediate2.o"; }
$com = "ld $link_warnings -r -ointermediate2.o prefixed_intermediate.o ./simulator/sim_atmos.o";
print "$com\n";
$retval = system($com);
if ($retval eq 0) {
    unlink "prefixed_intermediate.o";
} else { exit(1); }

# Check none of the symbols clash with those exported from the NP assembler.
# First get list of exported symbols.
$com = "nm intermediate2.o | grep \" [A-TV-Z] \"";
print "$com\n";
my $sim_defined_symbols = `$com`;
my @sim_defined_symbol = split /\n/, $sim_defined_symbols;

# Remove the ".. [B-Z] " prefix left by 'nm'.
for (my $count = 0; $count <= $#sim_defined_symbol; $count += 1) { $sim_defined_symbol[$count] =~ s/([0-9a-zA-Z]+)\s+[A-Z] //; }

# Compare the sim_defined_symbol array against the defined_symbol from the ARM.
my $symbol_clash = 0;
foreach $symbol (@sim_defined_symbol) {
    my @search = grep /^_$symbol$/, @defined_symbol;
    if ($#search ne -1) {
	print "Error: Symbol '$symbol' is defined in both the ARM assembler image, and the C simulator image.\n";
	$symbol_clash = 1;
    }
}
if ($symbol_clash) { exit(1); }

# Create the dummy functions in the simulator for accessing assembler functions.
my $program = "
#include <stdarg.h>
extern void* simulator_call_assembler_routine(void* routine, void* first, va_list ap);
";

foreach $symbol (@defined_symbol) {
    my $c_symbol = $symbol;
    $c_symbol =~ s/^\_//;
    $program .= "
extern void* $c_symbol(void* first, ...);
extern void* _PP__$symbol(void* first, ...);
void* $c_symbol(void* first, ...)
{
  va_list ap;
  void* result;
  va_start(ap, first);

  result = simulator_call_assembler_routine(_PP__$symbol, first, ap);
  va_end(ap);
  return result;
}
";
}

open OUT, ">assembler_functions.c" or die "$!";
print OUT $program;
close OUT;

$com = "gcc -g -O2 -Wall -c assembler_functions.c -oassembler_functions.o";
print "$com\n";
$retval = system($com);
if ($retval ne 0) { exit(1); }

# Now "link" C image to assembler image.
if (-f "intermediate3.o") { unlink "intermediate3.o"; }
$com = "ld $link_warnings -r -ointermediate3.o intermediate2.o assembler_functions.o";
foreach $symbol (@defined_symbol) { $com .= " --defsym _$symbol=0x$defined_symbol_value{$symbol}"; }
print "$com\n";
$retval = system($com);
if ($retval eq 0) {
    unlink "intermediate2.o";
} else { exit(1); }

# Prefix this (near complete!) image with _PP_ or _GP_ or whatever.
if (-f "prefixed_intermediate3.o") { unlink "prefixed_intermediate3.o"; }
$com = "$objcopy --prefix-defined-symbols $symbol_prefix intermediate3.o prefixed_intermediate3.o";
print "$com\n";
$retval = system($com);
if ($retval eq 0) {
    unlink "intermediate3.o";
} else { exit(1); }

##############################################################################
# Final link of C image, producing a.out.                                    #
##############################################################################

if ($do_final_link)
{
    # Link ATMOS world with simulator world.
    if (-f "a.out") { unlink "a.out"; }
    $com = "$compiler -g -D_REENTRANT -lpthread -oa.out prefixed_intermediate3.o ./simulator/sim_ctrl.o ./simulator/sim_devices.o";

    # Move library arguments to end.
    my $libraries = "";
    while (1) {
	if (!($com =~ s/( -l\S+)//)) { last; }
	$libraries .= $1;
    }
    $com .= $libraries;

    print "$com\n";
    $retval = system($com);
    if ($retval eq 0) {
	unlink "prefixed_intermediate3.o";
    } else { exit(1); }
}

##############################################################################
# Final link of ARM assembler objects. We define symbols that are exported   #
# from the C image.                                                          #
##############################################################################

$com = "nm a.out | grep \" [A-TV-Z] \"";
print "$com\n";
my $c_defined_symbols = `$com`;
my @c_defined_symbol = split /\n/, $c_defined_symbols;
my %c_defined_symbol_value;

# Remove the ".. [B-Z] " prefix left by 'nm' and create value in value array.
for (my $count = 0; $count <= $#c_defined_symbol; $count += 1) {
    $c_defined_symbol[$count] =~ s/([0-9a-zA-Z]+)\s+[A-Z] //;
    $c_defined_symbol_value{$c_defined_symbol[$count]} = $1;
}

if ($arm_objects !~ /^( )*$/) {
    # Link.
    # print STDERR "ARM objects: $arm_objects\n";
    $com = "isos-ld -N -Ttext 0x00100020 -oarm_objects.o $arm_objects";
    for (my $count = 0; $count <= $#undefined_symbol; $count += 1) {
        my $symbol = $undefined_symbol[$count];
        $com .= " --defsym $symbol=0x$c_defined_symbol_value{$symbol}";
    }
    print "$com\n";
    if (system($com) ne 0) { die; };
}

exit $retval;
