xref: /onnv-gate/usr/src/tools/scripts/check_rtime.pl (revision 4292:d7beef35913b)
1#!/usr/perl5/bin/perl -w
2#
3# CDDL HEADER START
4#
5# The contents of this file are subject to the terms of the
6# Common Development and Distribution License (the "License").
7# You may not use this file except in compliance with the License.
8#
9# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10# or http://www.opensolaris.org/os/licensing.
11# See the License for the specific language governing permissions
12# and limitations under the License.
13#
14# When distributing Covered Code, include this CDDL HEADER in each
15# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16# If applicable, add the following below this CDDL HEADER, with the
17# fields enclosed by brackets "[]" replaced with your own identifying
18# information: Portions Copyright [yyyy] [name of copyright owner]
19#
20# CDDL HEADER END
21#
22
23#
24# Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
25# Use is subject to license terms.
26#
27# ident	"%Z%%M%	%I%	%E% SMI"
28#
29
30#
31# Check ELF information.
32#
33# This script descends a directory hierarchy inspecting ELF dynamic executables
34# and shared objects.  The general theme is to verify that common Makefile rules
35# have been used to build these objects.  Typical failures occur when Makefile
36# rules are re-invented rather than being inherited from "cmd/lib" Makefiles.
37#
38# As always, a number of components don't follow the rules, and these are
39# excluded to reduce this scripts output.  Pathnames used for this exclusion
40# assume this script is being run over a "proto" area.  The -a (all) option
41# skips any exclusions.
42#
43# By default any file that has conditions that should be reported is first
44# listed and then each condition follows.  The -o (one-line) option produces a
45# more terse output which is better for sorting/diffing with "nightly".
46#
47# NOTE: missing dependencies, symbols or versions are reported by running the
48# file through ldd(1).  As objects within a proto area are built to exist in a
49# base system, standard use of ldd(1) will bind any objects to dependencies
50# that exist in the base system.  It is frequently the case that newer objects
51# exist in the proto area that are required to satisfy other objects
52# dependencies, and without using these newer objects an ldd(1) will produce
53# misleading error messages.  To compensate for this, the -d option (or the
54# existence of the CODEMSG_WS/ROOT environment variables) cause the creation of
55# alternative dependency mappings via crle(1) configuration files that establish
56# any proto shared objects as alternatives to their base system location.  Thus
57# ldd(1) can be executed against these configuration files so that objects in a
58# proto area bind to their dependencies in the same proto area.
59
60
61# Define all global variables (required for strict)
62use vars  qw($SkipDirs $SkipFiles $SkipTextrelFiles);
63use vars  qw($SkipUndefDirs $SkipUndefFiles $SkipUnusedDirs $SkipUnusedFiles);
64use vars  qw($SkipStabFiles $SkipNoExStkFiles $SkipCrleConf);
65use vars  qw($UnusedNoise $Prog $Mach $Isalist $Env $Ena64 $Tmpdir $Error);
66use vars  qw($UnusedFiles $UnusedPaths $LddNoU $Crle32 $Crle64 $Conf32 $Conf64);
67use vars  qw($SkipInterps $SkipSymSort $OldDeps %opt);
68
69use strict;
70
71
72# Define any directories we should skip completely.
73$SkipDirs = qr{
74	etc/lib |			# special - used for partial statics
75	usr/lib/devfsadm |		# 4382889
76	usr/lib/libc |			# optimized libc
77	usr/lib/rcm |			# 4426119
78	usr/perl5 |			# alan's taking care of these :-)
79	usr/src				# no need to look at shipped source
80}x;
81
82# Define any files we should skip completely.
83$SkipFiles = qr{ ^(?:
84	ld\.so\.1 |			# confusing but correct dependencies
85	lddstub |			# lddstub has no dependencies
86	libmakestate\.so\.1 |		# temporary; delivered by compiler group
87	libm\.so\.1 |			# temporary; delivered by compiler group
88	libm\.so\.2 |			# temporary; delivered by compiler group
89	geniconvtbl\.so |		# 4384329
90	libssagent\.so\.1 |		# 4328854
91	libpsvcplugin_psr\.so\.1 |	# 4385799
92	libpsvcpolicy_psr\.so\.1 |	#  "  "
93	libpsvcpolicy\.so\.1 |		#  "  "
94	picl_slm\.so |			#  "  "
95	libcrypto_extra\.so\.0\.9\.8 |	# OpenSSL SUNWcry filter lib
96	libssl_extra\.so\.0\.9\.8 |	# OpenSSL SUNWcry filter lib
97	fcpackage\.so |			# circular dependency on fcthread.so
98	mod_ipp\.so |			# Apache loadable module
99	grub
100	)$
101}x;
102
103# Define any files that are allowed text relocations.
104$SkipTextrelFiles = qr{ ^(?:
105	unix |				# kernel models are non-pic
106	mdb				# relocations against __RTC (dbx)
107	)$
108}x;
109
110# Define any files that are allowed undefined references.
111$SkipUndefDirs = qr{
112	usr/lib/inet/ppp/ |		# pppd plugins have callbacks
113	usr/lib/libp/ |			# libc.so.1 requires _mcount
114	/lib/mdb/ |			# mdb modules have callbacks
115	/lib/fm/fmd/plugins/ |		# fmd modules have callbacks
116	/lib/fm/fmd/schemes/ |		# fmd schemes have callbacks
117	/i86pc/lib/mtst/		# mtst modules have callbacks
118}x;
119
120$SkipUndefFiles = qr{ ^(?:
121	libthread_db\.so\.0 |		# callbacks to proc service interface
122	libthread_db\.so\.1 |		#  "	"	"	"
123	librtld_db\.so\.1 |		#  "	"	"	"
124	libc_db\.so\.1 |		#  "	"	"	"
125	libldstab\.so\.1 |		# link-edit support libraries have
126	libld\.so\.[2-4] |			# callback to the link-editors
127	liblddbg\.so\.4 |		#  "	"	"	"
128	librtld\.so\.1 |		#  "	"	"	"
129	libnisdb\.so\.2 |		# C++
130	libsvm\.so\.1 |			# libspmicommon.so.1 lacking
131	libwanboot\.so\.1 |		# libcrypto.a and libssl.a
132	libwrap\.so\.1\.0 |		# uses symbols provided by application
133	fcthread\.so |			# uses symbols provided by application
134	fn\.so\.2 |			# callback to automount
135	preen_md\.so\.1 |		# callback to driver
136	libike\.so\.1 |			# callbacks to in.iked for IKE policy
137	devfsadmd_mod\.so |		# sysevent module callback to syseventd
138	sysevent_conf_mod\.so |		# sysevent module callback to syseventd
139	sysevent_reg_mod\.so		# sysevent module callback to syseventd
140	)$
141}x;
142
143# Define any files that have unused dependencies.
144$SkipUnusedDirs = qr{
145	lib/picl/plugins/ |		# require devtree dependencies
146	/lib/libp			# profile libc makes libm an unused
147}x;					#	dependency of standard libc
148
149$SkipUnusedFiles = qr{ ^(?:
150	devfsadm |			# 4382889
151	disks |				#  "  "
152	tapes |				#  "  "
153	ports |				#  "  "
154	audlinks |			#  "  "
155	devlinks |			#  "  "
156	drvconfig |			#  "  "
157	ntptrace |			# on intel doesn't need libmd5
158	ocfserv |			# libsched unreference by libjvm,
159	poold |				#	see 4952319.
160	libc\.so\.1\.9 |		# 4lib/libc versions have private
161	libc\.so\.2\.9			#	copies of stuff from libc.
162	)$
163}x;
164
165# Define any files that should contain debugging information.
166$SkipStabFiles = qr{ ^(?:
167	abi_.* |
168	interceptors\.so\.1 |
169	unix
170	)$
171}x;
172
173# Define any files that don't require a non-executable stack definition.
174$SkipNoExStkFiles = qr{ ^(?:
175	forth |
176	unix |
177	multiboot
178	)$
179}x;
180
181# Identify any files that should be skipped when building a crle(1)
182# configuration file.  As the hwcap libraries can be loop-back mounted onto
183# libc, these can confuse crle(1) because of their identical dev/inode.
184$SkipCrleConf = qr{
185	lib/libc/libc_hwcap
186}x;
187
188# Define any files that should only have unused (ldd -u) processing.
189$UnusedPaths = qr{
190	ucb/shutdown			# libucb interposes on libc and makes
191					# dependencies on libc seem unnecessary
192}x;
193
194$UnusedFiles = qr{ ^(?:
195	rpc\.nisd			# CCNEEDED makes pthread unreferenced
196	)$
197}x;
198
199# Define unused dependencies we should ignore.
200# libCrun has a unnecessary dependency on libw, and libmapmalloc is often
201# defined to interpose on libc but isn't used by the application itself.
202# Threads dependencies look unused if libc is bound first.
203$UnusedNoise = qr{
204	libw\.so\.1;\ unused |
205	unused\ object=.*libw\.so\.1 |
206	libthread\.so\.1;\ unused |
207	libpthread\.so\.1;\ unused |
208	unused\ object=.*libpthread\.so\.1 |
209	libnsl\.so\.1;\ unused\ dependency\ of\ .*libxslt\.so\.1 |
210	libdl\.so\.1;\ unused\ dependency\ of\ .*libspmicommon\.so\.1 |
211	libdl\.so\.1;\ unused\ dependency\ of\ .*libCrun\.so\.1 |
212	libfru\.so\.1;\ unused\ object=.*libdl\.so\.1 |
213	libfrupicl\.so\.1;\ unused\ object=.*libdl\.so\.1 |
214	libmapmalloc\.so\.1;\ unused |
215	unused\ dependency\ of\ .*libstdc\+\+\.so\.6 |
216	unreferenced\ object=.*libstdc\+\+\.so\.6 |
217	unused\ dependency\ of\ .*libnetsnmphelpers\.so\.5 |
218	unused\ dependency\ of\ .*libnetsnmpmibs\.so\.5 |
219	unused\ dependency\ of\ .*libnetsnmpagent\.so\.5
220}x;
221
222# Define interpreters we should ignore.
223$SkipInterps = qr{
224	misc/krtld |
225	misc/amd64/krtld |
226	misc/sparcv9/krtld
227}x;
228
229# Catch libintl and libw, although ld(1) will bind to these and thus determine
230# they're needed, their content was moved into libc as of on297 build 7.
231# libthread and libpthread were completely moved into libc as of on10 build 53.
232# Also, catch libdl, whose content was moved into libc as of on10 build 49.
233$OldDeps = qr{ ^(?:
234	libintl\.so\.1 |
235	libw\.so\.1 |
236	libthread\.so\.1 |
237	libpthread\.so\.1 |
238	libdl\.so\.1
239	)$
240}x;
241
242# Files for which we skip checking of duplicate addresses in the
243# symbol sort sections. Such exceptions should be rare --- most code will
244# not have duplicate addresses, since it takes assember or a "#pragma weak"
245# to do such aliasing in C. C++ is different: The compiler generates aliases
246# for implementation reasons, and the mangled names used to encode argument
247# and return value types are difficult to handle well in mapfiles.
248# Furthermore, the Sun compiler and gcc use different and incompatible
249# name mangling conventions. Since ON must be buildable by either, we
250# would have to maintain two sets of mapfiles for each such object.
251# C++ use is rare in ON, so this is not worth pursuing.
252#
253$SkipSymSort = qr{ ^.*(?:
254	opt/SUNWdtrt/tst/common/pid/tst.weak2.exe |	# DTrace test
255	lib/amd64/libnsl\.so\.1 |			# C++
256	lib/sparcv9/libnsl\.so\.1 |			# C++
257	lib/sparcv9/libfru\.so\.1			# C++
258	)$
259}x;
260
261use Getopt::Std;
262
263# -----------------------------------------------------------------------------
264
265# Reliably compare two OS revisions.  Arguments are <ver1> <op> <ver2>.
266# <op> is the string form of a normal numeric comparison operator.
267sub cmp_os_ver {
268	my @ver1 = split(/\./, $_[0]);
269	my $op = $_[1];
270	my @ver2 = split(/\./, $_[2]);
271
272	push @ver2, ("0") x $#ver1 - $#ver2;
273	push @ver1, ("0") x $#ver2 - $#ver1;
274
275	my $diff = 0;
276	while (@ver1 || @ver2) {
277		if (($diff = shift(@ver1) - shift(@ver2)) != 0) {
278			last;
279		}
280	}
281	return (eval "$diff $op 0" ? 1 : 0);
282}
283
284# This script relies on ldd returning output reflecting only the binary
285# contents.  But if LD_PRELOAD* environment variables are present, libraries
286# named by them will also appear in the output, disrupting our analysis.
287# So, before we get too far, scrub the environment.
288
289delete($ENV{LD_PRELOAD});
290delete($ENV{LD_PRELOAD_32});
291delete($ENV{LD_PRELOAD_64});
292
293# Establish a program name for any error diagnostics.
294chomp($Prog = `basename $0`);
295
296# Determine what machinery is available.
297$Mach = `uname -p`;
298$Isalist = `isalist`;
299$Env = "";
300if ($Mach =~ /sparc/) {
301	if ($Isalist =~ /sparcv9/) {
302		$Ena64 = "ok";
303	}
304} elsif ($Mach =~ /i386/) {
305	if ($Isalist =~ /amd64/) {
306		$Ena64 = "ok";
307	}
308}
309
310# Check that we have arguments.
311if ((getopts('ad:imos', \%opt) == 0) || ($#ARGV == -1)) {
312	print "usage: $Prog [-a] [-d depdir] [-m] [-o] [-s] file | dir, ...\n";
313	print "\t[-a]\t\tprocess all files (ignore any exception lists)\n";
314	print "\t[-d dir]\testablish dependencies from under directory\n";
315	print "\t[-i]\t\tproduce dynamic table entry information\n";
316	print "\t[-m]\t\tprocess mcs(1) comments\n";
317	print "\t[-o]\t\tproduce one-liner output (prefixed with pathname)\n";
318	print "\t[-s]\t\tprocess .stab and .symtab entries\n";
319	exit 1;
320} else {
321	my($Proto);
322
323	if ($opt{d}) {
324		# User specified dependency directory - make sure it exists.
325		if (! -d $opt{d}) {
326			print "$Prog: $opt{d} is not a directory\n";
327			exit 1;
328		}
329		$Proto = $opt{d};
330
331	} elsif ($ENV{CODEMGR_WS}) {
332		my($Root);
333
334		# Without a user specified dependency directory see if we're
335		# part of a codemanager workspace and if a proto area exists.
336		if (($Root = $ENV{ROOT}) && (-d $Root)) {
337			$Proto = $Root;
338		}
339	}
340
341	if (!($Tmpdir = $ENV{TMPDIR}) || (! -d $Tmpdir)) {
342		$Tmpdir = "/tmp";
343	}
344
345	# Look for dependencies under $Proto.
346	if ($Proto) {
347		# To support alternative dependency mapping we'll need ldd(1)'s
348		# -e option.  This is relatively new (s81_30), so make sure
349		# ldd(1) is capable before gathering any dependency information.
350		if (system('ldd -e /usr/lib/lddstub 2> /dev/null')) {
351			print "ldd: does not support -e, unable to ";
352			print "create alternative dependency mappingings.\n";
353			print "ldd: option added under 4390308 (s81_30).\n\n";
354		} else {
355			# Gather dependencies and construct a alternative
356			# dependency mapping via a crle(1) configuration file.
357			GetDeps($Proto, "/");
358			GenConf();
359		}
360	}
361
362	# To support unreferenced dependency detection we'll need ldd(1)'s -U
363	# option.  This is relatively new (4638070), and if not available we
364	# can still fall back to -u.  Even with this option, don't use -U with
365	# releases prior to 5.10 as the cleanup for -U use only got integrated
366	# into 5.10 under 4642023.  Note, that nightly doesn't typically set a
367	# RELEASE from the standard <env> files.  Users who wish to disable use
368	# of ldd(1)'s -U should set (or uncomment) RELEASE in their <env> file
369	# if using nightly, or otherwise establish it in their environment.
370	if (system('ldd -U /usr/lib/lddstub 2> /dev/null')) {
371		$LddNoU = 1;
372	} else {
373		my($Release);
374
375		if (($Release = $ENV{RELEASE}) &&
376		    (cmp_os_ver($Release, "<", "5.10"))) {
377			$LddNoU = 1;
378		} else {
379			$LddNoU = 0;
380		}
381	}
382
383	# For each argument determine if we're dealing with a file or directory.
384	foreach my $Arg (@ARGV) {
385		# Ignore symbolic links.
386		if (-l $Arg) {
387			next;
388		}
389
390		if (!stat($Arg)) {
391			next;
392		}
393
394		# Process simple files.
395		if (-f _) {
396			my($RelPath) = $Arg;
397			my($File) = $Arg;
398			my($Secure) = 0;
399
400			$RelPath =~ s!^.*/!./!;
401			$File =~ s!^.*/!!;
402
403			if (-u _ || -g _) {
404				$Secure = 1;
405			}
406
407			ProcFile($Arg, $RelPath, $File, $Secure);
408			next;
409		}
410		# Process directories.
411		if (-d _) {
412			ProcDir($Arg, ".");
413			next;
414		}
415
416		print "$Arg is not a file or directory\n";
417		$Error = 1;
418	}
419
420	# Cleanup
421	CleanUp();
422}
423
424$Error = 0;
425
426# Clean up any temporary files.
427sub CleanUp {
428	if ($Crle64) {
429		unlink $Crle64;
430	}
431	if ($Conf64) {
432		unlink $Conf64;
433	}
434	if ($Crle32) {
435		unlink $Crle32;
436	}
437	if ($Conf32) {
438		unlink $Conf32;
439	}
440}
441
442# Create an output message, either a one-liner (under -o) or preceded by the
443# files relative pathname as a title.
444sub OutMsg {
445	my($Ttl, $Path, $Msg) = @_;
446
447	if ($opt{o}) {
448		$Msg =~ s/^[ \t]*//;
449		print "$Path: $Msg\n";
450	} else {
451		if ($Ttl eq 0) {
452			print "==== $Path ====\n";
453		}
454		print "$Msg\n";
455	}
456}
457
458# Determine whether this a ELF dynamic object and if so investigate its runtime
459# attributes.
460sub ProcFile {
461	my($FullPath, $RelPath, $File, $Secure) = @_;
462	my(@Elf, @Ldd, $Dyn, $Intp, $Dll, $Ttl, $Sym, $Interp, $Stack);
463	my($Sun, $Relsz, $Pltsz, $Uns, $Tex, $Stab, $Strip, $Lddopt, $SymSort);
464	my($Val, $Header, $SkipLdd, $IsX86, $RWX);
465
466	# Ignore symbolic links.
467	if (-l $FullPath) {
468		return;
469	}
470
471	$Ttl = 0;
472	@Ldd = 0;
473
474	# Determine whether we have access to inspect the file.
475	if (!(-r $FullPath)) {
476		OutMsg($Ttl++, $RelPath,
477		    "\tunable to inspect file: permission denied");
478		return;
479	}
480
481	# Determine if this is a file we don't care about.
482	if (!$opt{a}) {
483		if ($File =~ $SkipFiles) {
484			return;
485		}
486	}
487
488	# Determine whether we have a executable (static or dynamic) or a
489	# shared object.
490	@Elf = split(/\n/, `elfdump -epdic $FullPath 2>&1`);
491
492	$Dyn = $Intp = $Dll = $Stack = $IsX86 = $RWX = 0;
493	$Interp = 1;
494	$Header = 'None';
495	foreach my $Line (@Elf) {
496		# If we have an invalid file type (which we can tell from the
497		# first line), or we're processing an archive, bail.
498		if ($Header eq 'None') {
499			if (($Line =~ /invalid file/) ||
500			    ($Line =~ /$FullPath(.*):/)) {
501				return;
502			}
503		}
504
505		if ($Line =~ /^ELF Header/) {
506			$Header = 'Ehdr';
507
508		} elsif ($Line =~ /^Program Header/) {
509			$Header = 'Phdr';
510			$RWX = 0;
511
512		} elsif ($Line =~ /^Interpreter/) {
513			$Header = 'Intp';
514
515		} elsif ($Line =~ /^Dynamic Section/) {
516			# A dynamic section indicates we're a dynamic object
517			# (this makes sure we don't check static executables).
518			$Dyn = 1;
519
520		} elsif (($Header eq 'Ehdr') && ($Line =~ /e_type:/)) {
521			# The e_type field indicates whether this file is a
522			# shared object (ET_DYN) or an executable (ET_EXEC).
523			if ($Line =~ /ET_DYN/) {
524				$Dll = 1;
525			} elsif ($Line !~ /ET_EXEC/) {
526				return;
527			}
528		} elsif (($Header eq 'Ehdr') && ($Line =~ /ei_class:/)) {
529			# If we encounter a 64-bit object, but we're not running
530			# on a 64-bit system, suppress calling ldd(1).
531			if (($Line =~ /ELFCLASS64/) && !$Ena64) {
532				$SkipLdd = 1;
533			}
534		} elsif (($Header eq 'Ehdr') && ($Line =~ /e_machine:/)) {
535			# If it's a X86 object, we need to enforce RW- data.
536			if (($Line =~ /(EM_AMD64|EM_386)/)) {
537				$IsX86 = 1;
538			}
539		} elsif (($Header eq 'Phdr') &&
540		    ($Line =~ /\[ PF_X  PF_W  PF_R \]/)) {
541			# RWX segment seen.
542			$RWX = 1;
543
544		} elsif (($Header eq 'Phdr') &&
545		    ($Line =~ /\[ PT_LOAD \]/ && $RWX && $IsX86)) {
546			# Seen an RWX PT_LOAD segment.
547			if ($File !~ $SkipNoExStkFiles) {
548				OutMsg($Ttl++, $RelPath,
549				    "\tapplication requires non-executable " .
550				    "data\t<no -Mmapfile_noexdata?>");
551			}
552
553		} elsif (($Header eq 'Phdr') &&
554		    ($Line =~ /\[ PT_SUNWSTACK \]/)) {
555			# This object defines a non-executable stack.
556			$Stack = 1;
557
558		} elsif (($Header eq 'Intp') && !$opt{a} &&
559		    ($Line =~ $SkipInterps)) {
560			# This object defines an interpretor we should skip.
561			$Interp = 0;
562		}
563	}
564
565	# Determine whether this ELF executable or shared object has a
566	# conforming mcs(1) comment section.  If the correct $(POST_PROCESS)
567	# macros are used, only a 3 or 4 line .comment section should exist
568	# containing one or two "@(#)SunOS" identifying comments (one comment
569	# for a non-debug build, and two for a debug build). The results of
570	# the following split should be three or four lines, the last empty
571	# line being discarded by the split.
572	if ($opt{m}) {
573		my(@Mcs, $Con, $Dev);
574
575		@Mcs = split(/\n/, `mcs -p $FullPath 2>&1`);
576
577		$Con = $Dev = $Val = 0;
578		foreach my $Line (@Mcs) {
579			$Val++;
580
581			if (($Val == 3) && ($Line !~ /^@\(#\)SunOS/)) {
582				$Con = 1;
583				last;
584			}
585			if (($Val == 4) && ($Line =~ /^@\(#\)SunOS/)) {
586				$Dev = 1;
587				next;
588			}
589			if (($Dev == 0) && ($Val == 4)) {
590				$Con = 1;
591				last;
592			}
593			if (($Dev == 1) && ($Val == 5)) {
594				$Con = 1;
595				last;
596			}
597		}
598		if ($opt{m} && ($Con == 1)) {
599			OutMsg($Ttl++, $RelPath,
600			    "\tnon-conforming mcs(1) comment\t<no \$(POST_PROCESS)?>");
601		}
602	}
603
604	# Applications should contain a non-executable stack definition.
605	if (($Dll == 0) && ($Stack == 0)) {
606		if (!$opt{a}) {
607			if ($File =~ $SkipNoExStkFiles) {
608				goto DYN;
609			}
610		}
611		OutMsg($Ttl++, $RelPath,
612		    "\tapplication requires non-executable stack\t<no -Mmapfile_noexstk?>");
613	}
614
615DYN:
616	# Having caught any static executables in the mcs(1) check and non-
617	# executable stack definition check, continue with dynamic objects
618	# from now on.
619	if ($Dyn eq 0) {
620		return;
621	}
622
623	# Only use ldd unless we've encountered an interpreter that should
624	# be skipped.
625	if (!$SkipLdd && $Interp) {
626		if ($Secure) {
627			# The execution of a secure application over an nfs file
628			# system mounted nosuid will result in warning messages
629			# being sent to /var/adm/messages.  As this type of
630			# environment can occur with root builds, move the file
631			# being investigated to a safe place first.  In addition
632			# remove its secure permission so that it can be
633			# influenced by any alternative dependency mappings.
634
635			my($TmpPath) = "$Tmpdir/$File";
636
637			system('cp', $FullPath, $TmpPath);
638			chmod 0777, $TmpPath;
639			$FullPath = $TmpPath;
640		}
641
642		# Use ldd(1) to determine the objects relocatability and use.
643		# By default look for all unreferenced dependencies.  However,
644		# some objects have legitimate dependencies that they do not
645		# reference.
646		if ($LddNoU || ($File =~ $UnusedFiles) ||
647		    ($RelPath =~ $UnusedPaths)) {
648			$Lddopt = "-ru";
649		} else {
650			$Lddopt = "-rU";
651		}
652		@Ldd = split(/\n/, `ldd $Lddopt $Env $FullPath 2>&1`);
653		if ($Secure) {
654			unlink $FullPath;
655		}
656	}
657
658	$Val = 0;
659	$Sym = 5;
660	$Uns = 1;
661
662LDD:	foreach my $Line (@Ldd) {
663
664		if ($Val == 0) {
665			$Val = 1;
666			# Make sure ldd(1) worked.  One possible failure is that
667			# this is an old ldd(1) prior to -e addition (4390308).
668			if ($Line =~ /usage:/) {
669				$Line =~ s/$/\t<old ldd(1)?>/;
670				OutMsg($Ttl++, $RelPath, $Line);
671				last;
672			} elsif ($Line =~ /execution failed/) {
673				OutMsg($Ttl++, $RelPath, $Line);
674				last;
675			}
676
677			# It's possible this binary can't be executed, ie. we've
678			# found a sparc binary while running on an intel system,
679			# or a sparcv9 binary on a sparcv7/8 system.
680			if ($Line =~ /wrong class/) {
681				OutMsg($Ttl++, $RelPath,
682				    "\thas wrong class or data encoding");
683				next;
684			}
685
686			# Historically, ldd(1) likes executable objects to have
687			# their execute bit set.  Note that this test isn't
688			# applied unless the -a option is in effect, as any
689			# non-executable files are skipped by default to reduce
690			# the cost of running this script.
691			if ($Line =~ /not executable/) {
692				OutMsg($Ttl++, $RelPath,
693				    "\tis not executable");
694				next;
695			}
696		}
697
698		# Look for "file" or "versions" that aren't found.  Note that
699		# these lines will occur before we find any symbol referencing
700		# errors.
701		if (($Sym == 5) && ($Line =~ /not found\)/)) {
702			if ($Line =~ /file not found\)/) {
703				$Line =~ s/$/\t<no -zdefs?>/;
704			}
705			OutMsg($Ttl++, $RelPath, $Line);
706			next;
707		}
708		# Look for relocations whose symbols can't be found.  Note, we
709		# only print out the first 5 relocations for any file as this
710		# output can be excessive.
711		if ($Sym && ($Line =~ /symbol not found/)) {
712			# Determine if this file is allowed undefined
713			# references.
714			if ($Sym == 5) {
715				if (!$opt{a}) {
716					if ($RelPath =~ $SkipUndefDirs) {
717						$Sym = 0;
718						next LDD;
719					}
720					if ($File =~ $SkipUndefFiles) {
721						$Sym = 0;
722						next LDD;
723					}
724				}
725			}
726			if ($Sym-- == 1) {
727				if (!$opt{o}) {
728					OutMsg($Ttl++, $RelPath,
729					    "\tcontinued ...");
730				}
731				next;
732			}
733			# Just print the symbol name.
734			$Line =~ s/$/\t<no -zdefs?>/;
735			OutMsg($Ttl++, $RelPath, $Line);
736			next;
737		}
738		# Look for any unused dependencies.
739		if ($Uns && ($Line =~ /unused/)) {
740			if (!$opt{a}) {
741				if ($RelPath =~ $SkipUnusedDirs) {
742					$Uns = 0;
743					next LDD;
744				}
745				if ($File =~ $SkipUnusedFiles) {
746					$Uns = 0;
747					next LDD;
748				}
749
750				# Remove any noise.
751				if ($Line =~ $UnusedNoise) {
752					$Uns = 0;
753					next LDD;
754				}
755			}
756			if ($Secure) {
757				$Line =~ s!$Tmpdir/!!;
758			}
759			$Line =~ s/^[ \t]*(.*)/\t$1\t<remove lib or -zignore?>/;
760			OutMsg($Ttl++, $RelPath, $Line);
761			next;
762		}
763	}
764
765	# Reuse the elfdump(1) data to investigate additional dynamic linking
766	# information.
767
768	$Sun = $Relsz = $Pltsz = $Dyn = $Stab = $SymSort = 0;
769	$Tex = $Strip = 1;
770
771	$Header = 'None';
772ELF:	foreach my $Line (@Elf) {
773		# We're only interested in the section headers and the dynamic
774		# section.
775		if ($Line =~ /^Section Header/) {
776			$Header = 'Shdr';
777
778			if (($Sun == 0) && ($Line =~ /\.SUNW_reloc/)) {
779				# This object has a combined relocation section.
780				$Sun = 1;
781
782			} elsif (($Stab == 0) && ($Line =~ /\.stab/)) {
783				# This object contain .stabs sections
784				$Stab = 1;
785			} elsif (($SymSort == 0) &&
786				 ($Line =~ /\.SUNW_dyn(sym)|(tls)sort/)) {
787				# This object contains a symbol sort section
788				$SymSort = 1;
789			}
790
791			if (($Strip == 1) && ($Line =~ /\.symtab/)) {
792				# This object contains a complete symbol table.
793				$Strip = 0;
794			}
795			next;
796
797		} elsif ($Line =~ /^Dynamic Section/) {
798			$Header = 'Dyn';
799			next;
800		} elsif ($Header ne 'Dyn') {
801			next;
802		}
803
804		# Does this object contain text relocations.
805		if ($Tex && ($Line =~ /TEXTREL/)) {
806			# Determine if this file is allowed text relocations.
807			if (!$opt{a}) {
808				if ($File =~ $SkipTextrelFiles) {
809					$Tex = 0;
810					next ELF;
811				}
812			}
813			OutMsg($Ttl++, $RelPath,
814			    "\tTEXTREL .dynamic tag\t\t\t<no -Kpic?>");
815			$Tex = 0;
816			next;
817		}
818
819		# Does this file have any relocation sections (there are a few
820		# psr libraries with no relocations at all, thus a .SUNW_reloc
821		# section won't exist either).
822		if (($Relsz == 0) && ($Line =~ / RELA?SZ/)) {
823			$Relsz = hex((split(' ', $Line))[2]);
824			next;
825		}
826
827		# Does this file have any plt relocations.  If the plt size is
828		# equivalent to the total relocation size then we don't have
829		# any relocations suitable for combining into a .SUNW_reloc
830		# section.
831		if (($Pltsz == 0) && ($Line =~ / PLTRELSZ/)) {
832			$Pltsz = hex((split(' ', $Line))[2]);
833			next;
834		}
835
836		# Under the -i (information) option print out any useful dynamic
837		# entries.
838		# Does this object have any dependencies.
839		if ($opt{i} && ($Line =~ /NEEDED/)) {
840			my($Need) = (split(' ', $Line))[3];
841
842			# Catch any old (unnecessary) dependencies.
843			if ($Need =~ $OldDeps) {
844				OutMsg($Ttl++, $RelPath,
845				    "\tNEEDED=$Need\t<dependency no longer necessary>");
846			} else {
847				OutMsg($Ttl++, $RelPath, "\tNEEDED=$Need");
848			}
849			next;
850		}
851
852		# Does this object specify a runpath.
853		if ($opt{i} && ($Line =~ /RPATH/)) {
854			my($Rpath) = (split(' ', $Line))[3];
855			OutMsg($Ttl++, $RelPath, "\tRPATH=$Rpath");
856			next;
857		}
858	}
859
860	# A shared object, that contains non-plt relocations, should have a
861	# combined relocation section indicating it was built with -z combreloc.
862	if ($Dll && $Relsz && ($Relsz != $Pltsz) && ($Sun == 0)) {
863		OutMsg($Ttl++, $RelPath,
864		    "\tSUNW_reloc section missing\t\t<no -zcombreloc?>");
865	}
866
867	# No objects released to a customer should have any .stabs sections
868	# remaining, they should be stripped.
869	if ($opt{s} && $Stab) {
870		if (!$opt{a}) {
871			if ($File =~ $SkipStabFiles) {
872				goto DONESTAB;
873			}
874		}
875		OutMsg($Ttl++, $RelPath,
876		    "\tdebugging sections should be deleted\t<no strip -x?>");
877	}
878
879DONESTAB:
880
881	# All objects should have a full symbol table to provide complete
882	# debugging stack traces.
883	if ($Strip) {
884		OutMsg($Ttl++, $RelPath,
885		    "\tsymbol table should not be stripped\t<remove -s?>");
886	}
887
888	# If there are symbol sort sections in this object, report on
889	# any that have duplicate addresses.
890	ProcSymSort($FullPath, $RelPath, \$Ttl) if $SymSort;
891}
892
893
894## ProcSymSortOutMsg(RefTtl, RelPath, secname, addr, names...)
895#
896# Call OutMsg for a duplicate address error in a symbol sort
897# section
898#
899sub ProcSymSortOutMsg {
900	my($RefTtl, $RelPath, $secname, $addr, @names) = @_;
901
902	OutMsg($$RefTtl++, $RelPath,
903	    "$secname: duplicate $addr: ". join(', ', @names));
904}
905
906
907
908## ProcSymSort(FullPath, RelPath)
909#
910# Examine the symbol sort sections for the given object and report
911# on any duplicate addresses found.  Ideally, mapfile directives
912# should be used when building objects that have multiple symbols
913# with the same address so that only one of them appears in the sort
914# section. This saves space, reduces user confusion, and ensures that
915# libproc and debuggers always display public names instead of symbols
916# that are merely implementation details.
917#
918sub ProcSymSort {
919
920	my($FullPath, $RelPath, $RefTtl) = @_;
921
922	# If this object is exempt from checking, return quietly
923	return if ($FullPath =~ $SkipSymSort);
924
925
926	open(SORT, "elfdump -S $FullPath|") ||
927	    die "$Prog: Unable to execute elfdump (symbol sort sections)\n";
928
929	my $line;
930	my $last_addr;
931	my @dups = ();
932	my $secname;
933	while ($line = <SORT>) {
934		chomp $line;
935
936		next if ($line eq '');
937
938		# If this is a header line, pick up the section name
939		if ($line =~ /^Symbol Sort Section:\s+([^\s]+)\s+/) {
940			$secname = $1;
941
942			# Every new section is followed by a column header line
943			$line = <SORT>;		# Toss header line
944
945			# Flush anything left from previous section
946			ProcSymSortOutMsg($RefTtl, $RelPath, $secname,
947			    $last_addr, @dups) if (scalar(@dups) > 1);
948
949			# Reset variables for new sort section
950			$last_addr = '';
951			@dups = ();
952
953			next;
954		}
955
956		# Process symbol line
957		my @fields = split /\s+/, $line;
958		my $new_addr = $fields[2];
959		my $new_name = $fields[9];
960		if ($new_addr eq $last_addr) {
961			push @dups, $new_name;
962		} else {
963			ProcSymSortOutMsg($RefTtl, $RelPath, $secname,
964			    $last_addr, @dups) if (scalar(@dups) > 1);
965			@dups = ( $new_name );
966			$last_addr = $new_addr;
967		}
968	}
969
970	ProcSymSortOutMsg($RefTtl, $RelPath, $secname, $last_addr, @dups)
971		if (scalar(@dups) > 1);
972
973	close SORT;
974}
975
976
977sub ProcDir {
978	my($FullDir, $RelDir) = @_;
979	my($NewFull, $NewRel);
980
981	# Determine if this is a directory we don't care about.
982	if (!$opt{a}) {
983		if ($RelDir =~ $SkipDirs) {
984			return;
985		}
986	}
987
988	# Open the directory and read each entry, omit files starting with "."
989	if (opendir(DIR, $FullDir)) {
990		foreach my $Entry (readdir(DIR)) {
991			if ($Entry =~ /^\./) {
992				next;
993			}
994			$NewFull = "$FullDir/$Entry";
995
996			# Ignore symlinks.
997			if (-l $NewFull) {
998				next;
999			}
1000			if (!stat($NewFull)) {
1001				next;
1002			}
1003			$NewRel = "$RelDir/$Entry";
1004
1005			# Descend into and process any directories.
1006			if (-d _) {
1007				ProcDir($NewFull, $NewRel);
1008				next;
1009			}
1010
1011			# Typically dynamic objects are executable, so we can
1012			# reduce the overall cost of this script (a lot!) by
1013			# screening out non-executables here, rather than pass
1014			# them to file(1) later.  However, it has been known
1015			# for shared objects to be mistakenly left non-
1016			# executable, so with -a let all files through so that
1017			# this requirement can be verified (see ProcFile()).
1018			if (!$opt{a}) {
1019				if (! -x _) {
1020					next;
1021				}
1022			}
1023
1024			# Process any standard files.
1025			if (-f _) {
1026				my($Secure) = 0;
1027
1028				if (-u _ || -g _) {
1029					$Secure = 1;
1030				}
1031
1032				ProcFile($NewFull, $NewRel, $Entry, $Secure);
1033				next;
1034			}
1035
1036		}
1037		closedir(DIR);
1038	}
1039}
1040
1041# Create a crle(1) script for any 64-bit dependencies we locate.  A runtime
1042# configuration file will be generated to establish alternative dependency
1043# mappings for all these dependencies.
1044
1045sub Entercrle64 {
1046	my($FullDir, $RelDir, $Entry) = @_;
1047
1048	if (!$Crle64) {
1049		# Create and initialize the script if is doesn't already exit.
1050
1051		$Crle64 = "$Tmpdir/$Prog.crle64.$$";
1052		open(CRLE64, "> $Crle64") ||
1053			die "$Prog: open failed: $Crle64: $!";
1054
1055		print CRLE64 "#!/bin/sh\ncrle -64\\\n";
1056	}
1057	print CRLE64 "\t-o $FullDir -a $RelDir/$Entry \\\n";
1058}
1059
1060# Create a crle(1) script for any 32-bit dependencies we locate.  A runtime
1061# configuration file will be generated to establish alternative dependency
1062# mappings for all these dependencies.
1063
1064sub Entercrle32 {
1065	my($FullDir, $RelDir, $Entry) = @_;
1066
1067	if (!$Crle32) {
1068		# Create and initialize the script if is doesn't already exit.
1069
1070		$Crle32 = "$Tmpdir/$Prog.crle32.$$";
1071		open(CRLE32, "> $Crle32") ||
1072			die "$Prog: open failed: $Crle32: $!";
1073
1074		print CRLE32 "#!/bin/sh\ncrle \\\n";
1075	}
1076	print CRLE32 "\t-o $FullDir -a $RelDir/$Entry \\\n";
1077}
1078
1079# Having finished gathering dependencies, complete any crle(1) scripts and
1080# execute them to generate the associated runtime configuration files.  In
1081# addition establish the environment variable required to pass the configuration
1082# files to ldd(1).
1083
1084sub GenConf {
1085	if ($Crle64) {
1086		$Conf64 = "$Tmpdir/$Prog.conf64.$$";
1087		print CRLE64 "\t-c $Conf64\n";
1088
1089		chmod 0755, $Crle64;
1090		close CRLE64;
1091
1092		if (system($Crle64)) {
1093			undef $Conf64;
1094		}
1095	}
1096	if ($Crle32) {
1097		$Conf32 = "$Tmpdir/$Prog.conf32.$$";
1098		print CRLE32 "\t-c $Conf32\n";
1099
1100		chmod 0755, $Crle32;
1101		close CRLE32;
1102
1103		if (system($Crle32)) {
1104			undef $Conf32;
1105		}
1106	}
1107
1108	if ($Crle64 && $Conf64 && $Crle32 && $Conf32) {
1109		$Env = "-e LD_FLAGS=config_64=$Conf64,config_32=$Conf32";
1110	} elsif ($Crle64 && $Conf64) {
1111		$Env = "-e LD_FLAGS=config_64=$Conf64";
1112	} elsif ($Crle32 && $Conf32) {
1113		$Env = "-e LD_FLAGS=config_32=$Conf32";
1114	}
1115}
1116
1117# Recurse through a directory hierarchy looking for appropriate dependencies.
1118
1119sub GetDeps {
1120	my($FullDir, $RelDir) = @_;
1121	my($NewFull);
1122
1123	# Open the directory and read each entry, omit files starting with "."
1124	if (opendir(DIR, $FullDir)) {
1125		 foreach my $Entry (readdir(DIR)) {
1126			if ($Entry =~ /^\./) {
1127				next;
1128			}
1129			$NewFull = "$FullDir/$Entry";
1130
1131			# We need to follow links so that any dependencies
1132			# are expressed in all their available forms.
1133			# Bail on symlinks like 32 -> .
1134			if (-l $NewFull) {
1135				if (readlink($NewFull) =~ /^\.$/) {
1136					next;
1137				}
1138			}
1139			if (!stat($NewFull)) {
1140				next;
1141			}
1142
1143			if (!$opt{a}) {
1144				if ($NewFull =~ $SkipCrleConf) {
1145					next;
1146				}
1147			}
1148
1149			# If this is a directory descend into it.
1150			if (-d _) {
1151				my($NewRel);
1152
1153				if ($RelDir =~ /^\/$/) {
1154					$NewRel = "$RelDir$Entry";
1155				} else {
1156					$NewRel = "$RelDir/$Entry";
1157				}
1158
1159				GetDeps($NewFull, $NewRel);
1160				next;
1161			}
1162
1163			# If this is a regular file determine if its a
1164			# valid ELF dependency.
1165			if (-f _) {
1166				my($File);
1167
1168				# Typically shared object dependencies end with
1169				# ".so" or ".so.?", hence we can reduce the cost
1170				# of this script (a lot!) by screening out files
1171				# that don't follow this pattern.
1172				if (!$opt{a}) {
1173					if ($Entry !~ /\.so(?:\.\d+)*$/) {
1174						next;
1175					}
1176				}
1177
1178				$File = `file $NewFull`;
1179				if ($File !~ /dynamic lib/) {
1180					next;
1181				}
1182
1183				if ($File =~ /32-bit/) {
1184					Entercrle32($FullDir, $RelDir, $Entry);
1185				} elsif ($Ena64) {
1186					Entercrle64($FullDir, $RelDir, $Entry);
1187				}
1188				next;
1189			}
1190		}
1191		closedir(DIR);
1192	}
1193}
1194exit $Error
1195