#! /usr/bin/perl -w
# (C) 2004 Darren Salt <linux@youmustbejoking.demon.co.uk>
# Licensed under the GPL, v2 or later

sub doit (@)
{
  local $SIG{'CHLD'} = sub {
    wait;
    die "$0: $_[0] failed with return code $?\n" if $? && $? != -1;
  };
  local $pid = open (WRITE, '-|');
  die "$0: cannot fork: $!\n" unless defined $pid;
  if ($pid)
  {
    local @output;
    push @output, $_ while <WRITE>;
    close WRITE;
    return @output;
  }
  exec @_ or die "$0: couldn't exec $_[0]: $!\n";
}

my $recurse = grep { $_ eq '-r' } @ARGV;

foreach my $arg (@ARGV)
{
  next if $arg eq '-r';
  print $arg, ":\n";
  my @ldd = doit ('ldd', $arg);
  my @dump = grep { /^  NEEDED +(.*)\n/ and $_ = $1 } doit ('objdump', '-p', $arg);
  foreach (@ldd)
  {
    /^[[:space:]]+(.*) => (.*) \(0x[[:xdigit:]]+\)$/ or next;
    next unless grep { $_ eq $1 } @dump;
    print "	$2\n";
    push @ARGV, $2 if $recurse && !grep { $_ eq $2 } @ARGV;
  }
}
exit 0;
