# Print unused global symbols in a bunch of object files
# Copyright (C) 2013 Alexander Cherepanov <cherepan at mccme.ru>
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted.

# Usage:
# build your project with generating debugging information and run:
# $ nm -olgp *.o | perl unused-globals.pl | sort -k1.49

# Examples of nm output:
#
# DES_std.o:0000000000020000 C DES_KS_table
# common.o:0000000000000000 D itoa64	/home/user/john/john/master/src/common.c:11
# trip_fmt.o:                 U fmt_default_reset
# wordlist.o:                 U error     /home/user/john/john/master/src/wordlist.c:80

# Examples of this script's output:
#
# DES_KS_table                    DES_std.o
# itoa64                          common.o <- common.c:11

use strict;
use warnings;

my (%used, %defined);

while (<>) {
    chomp;
    my ($obj, $type, $symbol, $where) = /^(.*?):[0-9A-Fa-f]*\s+(\S) (\S+)\s?(.*)/;
    if ($type eq 'U') {
        $used{$symbol}++;
    } else {
        $where =~ s!.*/!!;
        $defined{$symbol} = $obj . ($where ? " <- $where" : "");
    }
}

for (sort keys %defined) {
    if (!$used{$_}) {
        printf "%-47s %s\n", $_, $defined{$_};
    }
}