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