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