Debian Codegraph @

local/minimalist/find-unused-code

raw
1 #!/usr/bin/perl
2
3 # searches for .o files in the current directory and examines each for
4 # defined functions (T) and undefined references (U) and lists
5 # anything that isn't required by something else or itself
6
7 # useful calling sorted by file:
8 # perl minimal/find-unused-code | sort
9
10 use File::Find;
11 use Data::Dumper;
12 use strict;
13 use Getopt::GUI::Long;
14
15 my %opts;
16
17 LocalGetOptions(\%opts,
18 ['g|grep', "run find/grep to look for string usages"],
19 );
20
21 my (@files, %defined, %lookingfor);
22
23 find(\&dot_os, ".");
24
25 foreach my $file (@files) {
26 collect_from_file($file);
27 }
28
29
30 if ($#ARGV > -1) {
31 print "Dumping found symbol usages:\n\n";
32 foreach my $arg (@ARGV) {
33 print "$arg:\n";
34 print " ", join("\n ", @{$defined{$arg}{'usages'}}),"\n\n";
35 }
36 exit;
37 }
38
39 foreach my $function (sort { $defined{$a}{'source'} cmp $defined{$b}{'source'} } keys(%defined)) {
40 if (exists($defined{$function}{'source'}) &&
41 !exists($defined{$function}{'usages'})) {
42 if (check_for_once_only($defined{$function}{'source'}, $function)) {
43 printf("%-38s %-38s\n", $defined{$function}{'source'}, $function);
44 if ($opts{'g'}) {
45 open(P,"find . -regex '.*.\\(c\\|xs\\)' | xargs grep -n $function|");
46 while(<P>) {
47 print " $_";
48 }
49 close(P);
50 print "\n";
51 }
52 }
53 }
54 }
55
56 sub dot_os {
57 return if (!/\.o$/);
58 return if ($File::Find::name =~ /\/.libs\//);
59 # return if ($File::Find::name =~ /\/(perl|python)\//);
60 push @files, $File::Find::name;
61 }
62
63 sub collect_from_file {
64 my $file = shift;
65 # print "searching $file\n";
66 open(I,"nm $file|");
67 while(<I>) {
68 $defined{$1}{'source'} = $file if (/ T (.*)/);
69 push @{$defined{$1}{'usages'}}, $file if (/ U (.*)/);
70 }
71 close(I);
72 }
73
74 sub check_for_once_only {
75 my ($file, $function) = @_;
76 $file =~ s/\.o/.c/;
77 open(I, $file);
78 my $usages = 0;
79 while(<I>) {
80 if (/$function/) {
81 $usages++;
82 }
83 if ($usages > 1) {
84 close(I);
85 return 0;
86 }
87 }
88 return 1;
89 }
90
91
92 sub LocalGetOptions {
93 if (eval {require Getopt::GUI::Long;}) {
94 import Getopt::GUI::Long;
95 # optional configure call
96 Getopt::GUI::Long::Configure(qw(display_help no_ignore_case capture_output no_gui allow_zero));
97 return GetOptions(@_);
98 }
99 require Getopt::Long;
100 import Getopt::Long;
101 # optional configure call
102 Getopt::Long::Configure(qw(display_help no_ignore_case capture_output));
103 GetOptions(LocalOptionsMap(@_));
104 }
105
106 sub LocalOptionsMap {
107 my ($st, $cb, @opts) = ((ref($_[0]) eq 'HASH')
108 ? (1, 1, $_[0]) : (0, 2));
109 for (my $i = $st; $i <= $#_; $i += $cb) {
110 if ($_[$i]) {
111 next if (ref($_[$i]) eq 'ARRAY' && $_[$i][0] =~ /^GUI:/);
112 push @opts, ((ref($_[$i]) eq 'ARRAY') ? $_[$i][0] : $_[$i]);
113 push @opts, $_[$i+1] if ($cb == 2);
114 }
115 }
116 return @opts;
117 }