#! /usr/bin/perl
use Getopt::Long;
#%opts = ();
@opt_library = ();
$result = GetOptions("noinit", "library=s@", "libname=s", "majorversion=i");

#print "$opt_noinit, $opt_libname\n";
#foreach $foo (@opt_library) {
#  print $foo;
  print "\n";
#}
#
#foreach (@ARGV) {
#  print;
#  print "asdf\n";
#}
#print "\n";
#print @ARGV;
#print len($opt_library);
#exit 0;
		     

$libname = $opt_libname;
$libname ne "" || die "bad library name";

$majorversion = int($opt_majorversion);

while (<STDIN>) {
  next if (/^$/);
  next if (/file format elf32-/);
  next if (/^SYMBOL TABLE/);
  next if (/^00000000([0-9a-f]+) l/); # locals
  next if (/\*ABS\*/); # symbols we got from elsewhere
  #next if (/^00000000([0-9a-f]+)  w/); # weak symbols
  # if (/^00000000([0-9a-f]+) [g ][ w]\W+[FO]\W+([.A-Za-z0-9_]+)\W+[0-9a-f]+\W+(0xf0)?\W*([a-zA-Z_0-9]+)/) { 
  if (/^00000000([0-9a-f]+) [g ][ w]\W+[FO ]\W+([.A-Za-z0-9_]+)\W+[0-9a-f]+\W+(0xf0)?\W*([a-zA-Z_0-9]+)/) {
    $symbol = $4;
    $address = $1;
    
    if ($symbol eq "_init" || $symbol eq "_fini") {
      $symbol = "__LIBRARY_$libname\_$symbol";
    }
    if ($3 eq "0xf0") {
      # OK, we have a mips16 symbol.  We must emit a nop for it to show
      # up as a function definition rather than an absolute address
      
      print " .set mips16\n";
      print " .global $symbol\n";
      print "$symbol:\n";
      print "  $symbol = 0x$address\n";
    print " nop\n";
      print " .set nomips16\n";
      print " .weak $symbol\n";
      print "\n";
    } else {
      print " .global $symbol\n";
      print "  $symbol = 0x$address\n";
      print " .weak $symbol\n";
      print "\n";
    }
  } else {
    warn "couldn't parse $_";
  }
}

if (0 && !$opt_noinit) {
print <<EOF

 .section .init
 jal __LIBRARY_$libname\__init

 .section .fini
 jal __LIBRARY_$libname\__fini
EOF
}

if ($opt_noinit) {
  $lib_init_addr = "0";
  $lib_fini_addr = "0";
} else {
  $lib_init_addr = "__LIBRARY_$libname\__init";
  $lib_fini_addr = "__LIBRARY_$libname\__fini";
}

#$needsym = "__NEEDS_SHRLIB_$libname\_$majorversion";
$needsym = "__NEEDS_SHRLIB_$libname";

print <<EOF;

 .section .rodata
 .globl $needsym
 $needsym = 0

libname:
 .asciiz "$libname.$majorversion.sso"

libinfo:
 .word libname
 .word $lib_init_addr
 .word $lib_fini_addr

 .section .library_list
 .word libinfo
EOF

foreach (@opt_library) {
  print <<EOF;
 .section .rodata
 .word __NEEDS_SHRLIB_$_
EOF
}

    
