#!/local/bin/perl

sub uniqify {
    local ($list) = @_;
    local ($_, %set);
    foreach (split(" ", $list)) {
	$set{$_} = 1;
    }
    return join(" ", keys %set);
}

foreach $objfile (@ARGV) {
    print "processing $objfile\n";
    open(PIPE, "nm $objfile|");

    local(@Usymbols, @Dsymbols);
    while ($_=<PIPE>) {
	next unless /^[0-9a-f ]{8} (.) /i;
	local($code, $symbol) = ($1, $');
	chop $symbol;
	if ($code eq "U") {
	    #print "$symbol undefined\n";
	    push(@Usymbols, $symbol);
	} elsif ($code eq "T" || $code eq "D") {
	    push(@Dsymbols, $symbol);
	    if (defined($HOMEOF{$symbol})) {
		warn "Warning: $symbol defined twice, in $HOMEOF{$symbol} and $objfile\n";
	    } else {
		$HOMEOF{$symbol} = $objfile;
	    }
	} elsif (!$OLDUNKNOWN{$code}) {
	    print "Unknown code $code\n";
	    $OLDUNKNOWN{$code} = 1;
	}
    }
    close(PIPE);

    printf "has %d defineds, %d undefineds\n",
    int(@Dsymbols), int(@Usymbols);

    $Dsymbols{$objfile} = join(" ", @Dsymbols);
    $Usymbols{$objfile} = join(" ", @Usymbols);
}

foreach $objfile (@ARGV) {
    local($symbol);
    print "processing $objfile\n";
    foreach $symbol (split(" ", $Usymbols{$objfile})) {
	if (!defined($HOMEOF{$symbol})) {
	    if (!defined($MISSING{$symbol})) {
		warn "Undefined symbol: $symbol\n";
		$MISSING{$symbol}=1;
	    }
	    next;
	}
	local ($source) = $HOMEOF{$symbol};
	$needfrom{$source} .= " " if (defined($needfrom{$source}));
	$needfrom{$source} .= $objfile;
	#print "$objfile got $symbol from $source\n";
    }
}

foreach $objfile  (keys %needfrom) {
    $needfrom{$objfile} = &uniqify($needfrom{$objfile});
}

foreach $objfile (@ARGV) {
    local (@_) = split(" ", $needfrom{$objfile});
    print "$objfile needed by ", int(@_), " others\n";
}
