xref: /illumos-gate/usr/src/tools/scripts/check_rtime.pl (revision 6e375c8351497b82ffa4f33cbf61d712999b4605)
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 2009 Sun Microsystems, Inc.  All rights reserved.
25# Use is subject to license terms.
26#
27#
28
29#
30# Check ELF information.
31#
32# This script descends a directory hierarchy inspecting ELF dynamic executables
33# and shared objects.  The general theme is to verify that common Makefile rules
34# have been used to build these objects.  Typical failures occur when Makefile
35# rules are re-invented rather than being inherited from "cmd/lib" Makefiles.
36#
37# As always, a number of components don't follow the rules, and these are
38# excluded to reduce this scripts output.  Pathnames used for this exclusion
39# assume this script is being run over a "proto" area.  The -a (all) option
40# skips any exclusions.
41#
42# By default any file that has conditions that should be reported is first
43# listed and then each condition follows.  The -o (one-line) option produces a
44# more terse output which is better for sorting/diffing with "nightly".
45#
46# NOTE: missing dependencies, symbols or versions are reported by running the
47# file through ldd(1).  As objects within a proto area are built to exist in a
48# base system, standard use of ldd(1) will bind any objects to dependencies
49# that exist in the base system.  It is frequently the case that newer objects
50# exist in the proto area that are required to satisfy other objects
51# dependencies, and without using these newer objects an ldd(1) will produce
52# misleading error messages.  To compensate for this, the -d option (or the
53# existence of the CODEMSG_WS/ROOT environment variables) cause the creation of
54# alternative dependency mappings via crle(1) configuration files that establish
55# any proto shared objects as alternatives to their base system location.  Thus
56# ldd(1) can be executed against these configuration files so that objects in a
57# proto area bind to their dependencies in the same proto area.
58
59
60# Define all global variables (required for strict)
61use vars  qw($SkipDirs $SkipFiles $SkipTextrelFiles $SkipDirectBindFiles);
62use vars  qw($SkipUndefFiles $SkipUnusedDirs);
63use vars  qw($SkipStabFiles $SkipNoExStkFiles $SkipCrleConf);
64use vars  qw($SkipUnusedSearchPath $SkipUnrefObject);
65use vars  qw($Prog $Mach $Isalist $Env $Ena64 $Tmpdir $Error $Gnuc);
66use vars  qw($UnusedPaths $LddNoU $Crle32 $Crle64 $Conf32 $Conf64);
67use vars  qw($SkipDirectBindDirs $SkipInterps $SkipSymSort $OldDeps %opt);
68
69use strict;
70
71
72# Define any directories we should skip completely.
73$SkipDirs = qr{
74	usr/lib/devfsadm |		# 4382889
75	usr/lib/libc |			# optimized libc
76	usr/lib/rcm |			# 4426119
77	usr/perl5 |			# alan's taking care of these :-)
78	usr/src				# no need to look at shipped source
79}x;
80
81# Define any files we should skip completely.
82$SkipFiles = qr{ ^(?:
83	lddstub |			# lddstub has no dependencies
84	geniconvtbl\.so |		# 4384329
85	libssagent\.so\.1 |		# 4328854
86	libpsvcplugin_psr\.so\.1 |	# 4385799
87	libpsvcpolicy_psr\.so\.1 |	#  "  "
88	libpsvcpolicy\.so\.1 |		#  "  "
89	picl_slm\.so |			#  "  "
90	mod_ipp\.so |			# Apache loadable module
91	fptest |	# USIII specific extns. cause ldd noise on USII bld. m/c
92	grub
93	)$
94}x;
95
96# Define any files that are allowed text relocations.
97$SkipTextrelFiles = qr{ ^(?:
98	unix |				# kernel models are non-pic
99	mdb				# relocations against __RTC (dbx)
100	)$
101}x;
102
103# Define any directories or files that are allowed to have no direct bound
104# symbols
105$SkipDirectBindDirs = qr{
106	usr/ucb
107}x;
108
109$SkipDirectBindFiles = qr{ ^(?:
110	unix |
111	sbcp |
112	libproc.so.1 |
113	libnisdb.so.2
114	)$
115}x;
116
117# Define any files that are allowed undefined references.
118
119$SkipUndefFiles = qr{ ^(?:
120	libsvm\.so\.1 |			# libspmicommon.so.1 lacking
121	libnisdb\.so\.2			# C++
122	)$
123}x;
124
125# Define any files that have unused dependencies.
126$SkipUnusedDirs = qr{
127	lib/picl/plugins/ |		# require devtree dependencies
128	/lib/libp			# profile libc makes libm an unused
129}x;					#	dependency of standard libc
130
131# Define any files that should contain debugging information.
132$SkipStabFiles = qr{ ^(?:
133	unix
134	)$
135}x;
136
137# Define any files that don't require a non-executable stack definition.
138$SkipNoExStkFiles = qr{ ^(?:
139	forth |
140	unix |
141	multiboot
142	)$
143}x;
144
145# Identify any files that should be skipped when building a crle(1)
146# configuration file.  As the hwcap libraries can be loop-back mounted onto
147# libc, these can confuse crle(1) because of their identical dev/inode.
148$SkipCrleConf = qr{
149	lib/libc/libc_hwcap
150}x;
151
152# Skip "unused search path=" ldd(1) diagnostics.
153$SkipUnusedSearchPath = qr{
154	/usr/lib/fs/autofs.*\ from\ .automountd |		# dlopen()
155	/etc/ppp/plugins.*\ from\ .*pppd |			# dlopen()
156	/usr/lib/inet/ppp.*\ from\ .*pppd |			# dlopen()
157	/usr/sfw/lib.*\ from\ .*libipsecutil.so.1 |		# dlopen()
158	/usr/platform/.*rsmlib.*\ from\ .*librsm.so.2 |		# dlopen()
159	\$ORIGIN.*\ from\ .*fcode.so |				# dlopen()
160	/opt/VRTSvxvm/lib.*\ from\ .*libdiskmgt\.so\.1 |	# dlopen()
161	/usr/platform/.*\ from\ .*/usr/platform |		# picl
162	/usr/lib/picl/.*\ from\ .*/usr/platform |		# picl
163	/usr/platform/.*\ from\ .*/usr/lib/picl |		# picl
164	/usr/lib/smbsrv.*\ from\ .*libsmb\.so\.1 |		# future needs
165	/usr/lib/mps/secv1.*\ from\ .*libnss3\.so |		# non-OSNet
166	/usr/lib/mps.*\ from\ .*libnss3\.so |			# non-OSNet
167	/usr/sfw/lib.*\ from\ .*libdbus-1\.so\.3 |		# non-OSNet
168	/usr/sfw/lib.*\ from\ .*libdbus-glib-1\.so\.2 |		# non-OSNet
169	/usr/sfw/lib.*\ from\ .*libglib-2\.0\.so\.0 |		# non-OSNet
170	/usr/X11/lib.*\ from\ .*libglib-2\.0\.so\.0 |		# non-OSNet
171	/usr/sfw/lib.*\ from\ .*libgobject-2\.0\.so\.0 |	# non-OSNet
172	/usr/X11/lib.*\ from\ .*libgobject-2\.0\.so\.0 |	# non-OSNet
173	/usr/sfw/lib.*\ from\ .*libcrypto\.so\.0\.9\.8 |	# non-OSNet
174	/usr/sfw/lib.*\ from\ .*libnetsnmp\.so\.5 |		# non-OSNet
175	/usr/sfw/lib.*\ from\ .*libgcc_s\.so\.1 |		# non-OSNet
176	/usr.*\ from\ .*tst\.gcc\.exe |				# gcc built
177	/usr/postgres/8.3/lib.*\ from\ .*libpq\.so\.5		# non-OSNET
178}x;
179
180# Skip "unreferenced object=" ldd(1) diagnostics.
181$SkipUnrefObject = qr{
182	/libmapmalloc\.so\.1;\ unused\ dependency\ of |		# interposer
183	/libstdc\+\+\.so\.6;\ unused\ dependency\ of |		# gcc build
184	/libm\.so\.2.*\ of\ .*libstdc\+\+\.so\.6 |		# gcc build
185	/lib.*\ of\ .*/lib/picl/plugins/ |			# picl
186	/lib.*\ of\ .*libcimapi\.so |				# non-OSNET
187	/lib.*\ of\ .*libjvm\.so |				# non-OSNET
188	/lib.*\ of\ .*libnetsnmp\.so\.5 |			# non-OSNET
189	/lib.*\ of\ .*libnetsnmpagent\.so\.5 |			# non-OSNET
190	/lib.*\ of\ .*libnetsnmpmibs\.so\.5 |			# non-OSNET
191	/lib.*\ of\ .*libnetsnmphelpers\.so\.5 |		# non-OSNET
192	/lib.*\ of\ .*libnspr4\.so |				# non-OSNET
193	/lib.*\ of\ .*libsoftokn3\.so |				# non-OSNET
194	/lib.*\ of\ .*libspmicommon\.so\.1 |			# non-OSNET
195	/lib.*\ of\ .*libspmocommon\.so\.1 |			# non-OSNET
196	/lib.*\ of\ .*libssl3\.so |				# non-OSNET
197	/lib.*\ of\ .*libxml2\.so\.2 |				# non-OSNET
198	/lib.*\ of\ .*libxslt\.so\.1 |				# non-OSNET
199	/lib.*\ of\ .*libpq\.so\.4 				# non-OSNET
200}x;
201
202# Define any files that should only have unused (ldd -u) processing.
203$UnusedPaths = qr{
204	ucb/shutdown			# libucb interposes on libc and makes
205					# dependencies on libc seem unnecessary
206}x;
207
208# Define interpreters we should ignore.
209$SkipInterps = qr{
210	misc/krtld |
211	misc/amd64/krtld |
212	misc/sparcv9/krtld
213}x;
214
215# Catch libintl and libw, although ld(1) will bind to these and thus determine
216# they're needed, their content was moved into libc as of on297 build 7.
217# libthread and libpthread were completely moved into libc as of on10 build 53.
218# libdl was moved into libc as of on10 build 49.  librt and libaio were moved
219# into libc as of Nevada build 44.
220$OldDeps = qr{ ^(?:
221	libintl\.so\.1 |
222	libw\.so\.1 |
223	libthread\.so\.1 |
224	libpthread\.so\.1 |
225	libdl\.so\.1 |
226	librt\.so\.1 |
227	libaio\.so\.1
228	)$
229}x;
230
231# Files for which we skip checking of duplicate addresses in the
232# symbol sort sections. Such exceptions should be rare --- most code will
233# not have duplicate addresses, since it takes assember or a "#pragma weak"
234# to do such aliasing in C. C++ is different: The compiler generates aliases
235# for implementation reasons, and the mangled names used to encode argument
236# and return value types are difficult to handle well in mapfiles.
237# Furthermore, the Sun compiler and gcc use different and incompatible
238# name mangling conventions. Since ON must be buildable by either, we
239# would have to maintain two sets of mapfiles for each such object.
240# C++ use is rare in ON, so this is not worth pursuing.
241#
242$SkipSymSort = qr{ ^.*(?:
243	opt/SUNWdtrt/tst/common/pid/tst.weak2.exe |	# DTrace test
244	lib/amd64/libnsl\.so\.1 |			# C++
245	lib/sparcv9/libnsl\.so\.1 |			# C++
246	lib/sparcv9/libfru\.so\.1 |			# C++
247	usr/lib/sgml/nsgmls |				# C++
248	ld\.so\.1 |					# libc_pic.a user
249	lib/libsun_fc\.so\.1 |				# C++
250	lib/amd64/libsun_fc\.so\.1 |			# C++
251	lib/sparcv9/libsun_fc\.so\.1 			# C++
252	)$
253}x;
254
255use Getopt::Std;
256
257# -----------------------------------------------------------------------------
258
259# Reliably compare two OS revisions.  Arguments are <ver1> <op> <ver2>.
260# <op> is the string form of a normal numeric comparison operator.
261sub cmp_os_ver {
262	my @ver1 = split(/\./, $_[0]);
263	my $op = $_[1];
264	my @ver2 = split(/\./, $_[2]);
265
266	push @ver2, ("0") x $#ver1 - $#ver2;
267	push @ver1, ("0") x $#ver2 - $#ver1;
268
269	my $diff = 0;
270	while (@ver1 || @ver2) {
271		if (($diff = shift(@ver1) - shift(@ver2)) != 0) {
272			last;
273		}
274	}
275	return (eval "$diff $op 0" ? 1 : 0);
276}
277
278# This script relies on ldd returning output reflecting only the binary
279# contents.  But if LD_PRELOAD* environment variables are present, libraries
280# named by them will also appear in the output, disrupting our analysis.
281# So, before we get too far, scrub the environment.
282
283delete($ENV{LD_PRELOAD});
284delete($ENV{LD_PRELOAD_32});
285delete($ENV{LD_PRELOAD_64});
286
287# Establish a program name for any error diagnostics.
288chomp($Prog = `basename $0`);
289
290# Determine what machinery is available.
291$Mach = `uname -p`;
292$Isalist = `isalist`;
293$Env = "";
294if ($Mach =~ /sparc/) {
295	if ($Isalist =~ /sparcv9/) {
296		$Ena64 = "ok";
297	}
298} elsif ($Mach =~ /i386/) {
299	if ($Isalist =~ /amd64/) {
300		$Ena64 = "ok";
301	}
302}
303
304# Check that we have arguments.
305if ((getopts('ad:imos', \%opt) == 0) || ($#ARGV == -1)) {
306	print "usage: $Prog [-a] [-d depdir] [-m] [-o] [-s] file | dir, ...\n";
307	print "\t[-a]\t\tprocess all files (ignore any exception lists)\n";
308	print "\t[-d dir]\testablish dependencies from under directory\n";
309	print "\t[-i]\t\tproduce dynamic table entry information\n";
310	print "\t[-m]\t\tprocess mcs(1) comments\n";
311	print "\t[-o]\t\tproduce one-liner output (prefixed with pathname)\n";
312	print "\t[-s]\t\tprocess .stab and .symtab entries\n";
313	exit 1;
314} else {
315	my($Proto);
316
317	if ($opt{d}) {
318		# User specified dependency directory - make sure it exists.
319		if (! -d $opt{d}) {
320			print "$Prog: $opt{d} is not a directory\n";
321			exit 1;
322		}
323		$Proto = $opt{d};
324
325	} elsif ($ENV{CODEMGR_WS}) {
326		my($Root);
327
328		# Without a user specified dependency directory see if we're
329		# part of a codemanager workspace and if a proto area exists.
330		if (($Root = $ENV{ROOT}) && (-d $Root)) {
331			$Proto = $Root;
332		}
333	}
334
335	if (!($Tmpdir = $ENV{TMPDIR}) || (! -d $Tmpdir)) {
336		$Tmpdir = "/tmp";
337	}
338
339	# Determine whether this is a __GNUC build.  If so, unused search path
340	# processing is disabled.
341	if (defined $ENV{__GNUC}) {
342		$Gnuc = 1;
343	} else {
344		$Gnuc = 0;
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, $Tex, $Stab, $Strip, $Lddopt, $SymSort);
466	my($Val, $Header, $SkipLdd, $IsX86, $RWX, $UnDep);
467	my($HasDirectBinding);
468
469	# Ignore symbolic links.
470	if (-l $FullPath) {
471		return;
472	}
473
474	$Ttl = 0;
475	@Ldd = 0;
476
477	# Determine whether we have access to inspect the file.
478	if (!(-r $FullPath)) {
479		OutMsg($Ttl++, $RelPath,
480		    "\tunable to inspect file: permission denied");
481		return;
482	}
483
484	# Determine if this is a file we don't care about.
485	if (!$opt{a}) {
486		if ($File =~ $SkipFiles) {
487			return;
488		}
489	}
490
491	# Determine whether we have a executable (static or dynamic) or a
492	# shared object.
493	@Elf = split(/\n/, `elfdump -epdicy $FullPath 2>&1`);
494
495	$Dyn = $Intp = $Dll = $Stack = $IsX86 = $RWX = 0;
496	$Interp = 1;
497	$Header = 'None';
498	foreach my $Line (@Elf) {
499		# If we have an invalid file type (which we can tell from the
500		# first line), or we're processing an archive, bail.
501		if ($Header eq 'None') {
502			if (($Line =~ /invalid file/) ||
503			    ($Line =~ /$FullPath(.*):/)) {
504				return;
505			}
506		}
507
508		if ($Line =~ /^ELF Header/) {
509			$Header = 'Ehdr';
510
511		} elsif ($Line =~ /^Program Header/) {
512			$Header = 'Phdr';
513			$RWX = 0;
514
515		} elsif ($Line =~ /^Interpreter/) {
516			$Header = 'Intp';
517
518		} elsif ($Line =~ /^Dynamic Section/) {
519			# A dynamic section indicates we're a dynamic object
520			# (this makes sure we don't check static executables).
521			$Dyn = 1;
522
523		} elsif (($Header eq 'Ehdr') && ($Line =~ /e_type:/)) {
524			# The e_type field indicates whether this file is a
525			# shared object (ET_DYN) or an executable (ET_EXEC).
526			if ($Line =~ /ET_DYN/) {
527				$Dll = 1;
528			} elsif ($Line !~ /ET_EXEC/) {
529				return;
530			}
531		} elsif (($Header eq 'Ehdr') && ($Line =~ /ei_class:/)) {
532			# If we encounter a 64-bit object, but we're not running
533			# on a 64-bit system, suppress calling ldd(1).
534			if (($Line =~ /ELFCLASS64/) && !$Ena64) {
535				$SkipLdd = 1;
536			}
537		} elsif (($Header eq 'Ehdr') && ($Line =~ /e_machine:/)) {
538			# If it's a X86 object, we need to enforce RW- data.
539			if (($Line =~ /(EM_AMD64|EM_386)/)) {
540				$IsX86 = 1;
541			}
542		} elsif (($Header eq 'Phdr') &&
543		    ($Line =~ /\[ PF_X  PF_W  PF_R \]/)) {
544			# RWX segment seen.
545			$RWX = 1;
546
547		} elsif (($Header eq 'Phdr') &&
548		    ($Line =~ /\[ PT_LOAD \]/ && $RWX && $IsX86)) {
549			# Seen an RWX PT_LOAD segment.
550			if ($File !~ $SkipNoExStkFiles) {
551				OutMsg($Ttl++, $RelPath,
552				    "\tapplication requires non-executable " .
553				    "data\t<no -Mmapfile_noexdata?>");
554			}
555
556		} elsif (($Header eq 'Phdr') &&
557		    ($Line =~ /\[ PT_SUNWSTACK \]/)) {
558			# This object defines a non-executable stack.
559			$Stack = 1;
560
561		} elsif (($Header eq 'Intp') && !$opt{a} &&
562		    ($Line =~ $SkipInterps)) {
563			# This object defines an interpretor we should skip.
564			$Interp = 0;
565		}
566	}
567
568	# Determine whether this ELF executable or shared object has a
569	# conforming mcs(1) comment section.  If the correct $(POST_PROCESS)
570	# macros are used, only a 3 or 4 line .comment section should exist
571	# containing one or two "@(#)SunOS" identifying comments (one comment
572	# for a non-debug build, and two for a debug build). The results of
573	# the following split should be three or four lines, the last empty
574	# line being discarded by the split.
575	if ($opt{m}) {
576		my(@Mcs, $Con, $Dev);
577
578		@Mcs = split(/\n/, `mcs -p $FullPath 2>&1`);
579
580		$Con = $Dev = $Val = 0;
581		foreach my $Line (@Mcs) {
582			$Val++;
583
584			if (($Val == 3) && ($Line !~ /^@\(#\)SunOS/)) {
585				$Con = 1;
586				last;
587			}
588			if (($Val == 4) && ($Line =~ /^@\(#\)SunOS/)) {
589				$Dev = 1;
590				next;
591			}
592			if (($Dev == 0) && ($Val == 4)) {
593				$Con = 1;
594				last;
595			}
596			if (($Dev == 1) && ($Val == 5)) {
597				$Con = 1;
598				last;
599			}
600		}
601		if ($opt{m} && ($Con == 1)) {
602			OutMsg($Ttl++, $RelPath,
603			    "\tnon-conforming mcs(1) comment\t<no \$(POST_PROCESS)?>");
604		}
605	}
606
607	# Applications should contain a non-executable stack definition.
608	if (($Dll == 0) && ($Stack == 0)) {
609		if (!$opt{a}) {
610			if ($File =~ $SkipNoExStkFiles) {
611				goto DYN;
612			}
613		}
614		OutMsg($Ttl++, $RelPath,
615		    "\tapplication requires non-executable stack\t<no -Mmapfile_noexstk?>");
616	}
617
618DYN:
619	# Having caught any static executables in the mcs(1) check and non-
620	# executable stack definition check, continue with dynamic objects
621	# from now on.
622	if ($Dyn eq 0) {
623		return;
624	}
625
626	# Only use ldd unless we've encountered an interpreter that should
627	# be skipped.
628	if (!$SkipLdd && $Interp) {
629		my $LDDFullPath = $FullPath;
630
631		if ($Secure) {
632			# The execution of a secure application over an nfs file
633			# system mounted nosuid will result in warning messages
634			# being sent to /var/adm/messages.  As this type of
635			# environment can occur with root builds, move the file
636			# being investigated to a safe place first.  In addition
637			# remove its secure permission so that it can be
638			# influenced by any alternative dependency mappings.
639
640			my($TmpPath) = "$Tmpdir/$File";
641
642			system('cp', $LDDFullPath, $TmpPath);
643			chmod 0777, $TmpPath;
644			$LDDFullPath = $TmpPath;
645		}
646
647		# Use ldd(1) to determine the objects relocatability and use.
648		# By default look for all unreferenced dependencies.  However,
649		# some objects have legitimate dependencies that they do not
650		# reference.
651		if ($LddNoU || ($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	$UnDep = 1;
665
666	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 ($File =~ $SkipUndefFiles) {
721						$Sym = 0;
722						next;
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 search paths.
739		if ($Line =~ /unused search path=/) {
740			# Note, skip this comparison for __GNUC builds, as the
741			# gnu compilers insert numerous unused search paths.
742			if ($Gnuc == 1) {
743				next;
744			}
745			if (!$opt{a}) {
746				if ($Line =~ $SkipUnusedSearchPath) {
747					next;
748				}
749			}
750			if ($Secure) {
751				$Line =~ s!$Tmpdir/!!;
752			}
753			$Line =~ s/^[ \t]*(.*)/\t$1\t<remove search path?>/;
754			OutMsg($Ttl++, $RelPath, $Line);
755			next;
756		}
757		# Look for unreferenced dependencies.  Note, if any unreferenced
758		# objects are ignored, then set $UnDep so as to suppress any
759		# associated unused-object messages.
760		if ($Line =~ /unreferenced object=/) {
761			if (!$opt{a}) {
762				if ($Line =~ $SkipUnrefObject) {
763					$UnDep = 0;
764					next;
765				}
766			}
767			if ($Secure) {
768				$Line =~ s!$Tmpdir/!!;
769			}
770			$Line =~ s/^[ \t]*(.*)/\t$1\t<remove lib or -zignore?>/;
771			OutMsg($Ttl++, $RelPath, $Line);
772			next;
773		}
774		# Look for any unused dependencies.
775		if ($UnDep && ($Line =~ /unused/)) {
776			if (!$opt{a}) {
777				if ($RelPath =~ $SkipUnusedDirs) {
778					$UnDep = 0;
779					next;
780				}
781			}
782			if ($Secure) {
783				$Line =~ s!$Tmpdir/!!;
784			}
785			$Line =~ s/^[ \t]*(.*)/\t$1\t<remove lib or -zignore?>/;
786			OutMsg($Ttl++, $RelPath, $Line);
787			next;
788		}
789	}
790
791	# Reuse the elfdump(1) data to investigate additional dynamic linking
792	# information.
793
794	$Sun = $Relsz = $Pltsz = $Dyn = $Stab = $SymSort = 0;
795	$Tex = $Strip = 1;
796	$HasDirectBinding = 0;
797
798	$Header = 'None';
799ELF:	foreach my $Line (@Elf) {
800		# We're only interested in the section headers and the dynamic
801		# section.
802		if ($Line =~ /^Section Header/) {
803			$Header = 'Shdr';
804
805			if (($Sun == 0) && ($Line =~ /\.SUNW_reloc/)) {
806				# This object has a combined relocation section.
807				$Sun = 1;
808
809			} elsif (($Stab == 0) && ($Line =~ /\.stab/)) {
810				# This object contain .stabs sections
811				$Stab = 1;
812			} elsif (($SymSort == 0) &&
813				 ($Line =~ /\.SUNW_dyn(sym)|(tls)sort/)) {
814				# This object contains a symbol sort section
815				$SymSort = 1;
816			}
817
818			if (($Strip == 1) && ($Line =~ /\.symtab/)) {
819				# This object contains a complete symbol table.
820				$Strip = 0;
821			}
822			next;
823
824		} elsif ($Line =~ /^Dynamic Section/) {
825			$Header = 'Dyn';
826			next;
827		} elsif ($Line =~ /^Syminfo Section/) {
828			$Header = 'Syminfo';
829			next;
830		} elsif (($Header ne 'Dyn') && ($Header ne 'Syminfo')) {
831			next;
832		}
833
834		# Look into the Syminfo section.
835		# Does this object have at least one Directly Bound symbol?
836		if (($Header eq 'Syminfo')) {
837			my(@Symword);
838
839			if ($HasDirectBinding == 1) {
840				next;
841			}
842
843			@Symword = split(' ', $Line);
844
845			if (!defined($Symword[1])) {
846				next;
847			}
848			if ($Symword[1] =~ /B/) {
849				$HasDirectBinding = 1;
850			}
851			next;
852		}
853
854		# Does this object contain text relocations.
855		if ($Tex && ($Line =~ /TEXTREL/)) {
856			# Determine if this file is allowed text relocations.
857			if (!$opt{a}) {
858				if ($File =~ $SkipTextrelFiles) {
859					$Tex = 0;
860					next ELF;
861				}
862			}
863			OutMsg($Ttl++, $RelPath,
864			    "\tTEXTREL .dynamic tag\t\t\t<no -Kpic?>");
865			$Tex = 0;
866			next;
867		}
868
869		# Does this file have any relocation sections (there are a few
870		# psr libraries with no relocations at all, thus a .SUNW_reloc
871		# section won't exist either).
872		if (($Relsz == 0) && ($Line =~ / RELA?SZ/)) {
873			$Relsz = hex((split(' ', $Line))[2]);
874			next;
875		}
876
877		# Does this file have any plt relocations.  If the plt size is
878		# equivalent to the total relocation size then we don't have
879		# any relocations suitable for combining into a .SUNW_reloc
880		# section.
881		if (($Pltsz == 0) && ($Line =~ / PLTRELSZ/)) {
882			$Pltsz = hex((split(' ', $Line))[2]);
883			next;
884		}
885
886		# Does this object have any dependencies.
887		if ($Line =~ /NEEDED/) {
888			my($Need) = (split(' ', $Line))[3];
889
890			if ($Need =~ $OldDeps) {
891				# Catch any old (unnecessary) dependencies.
892				OutMsg($Ttl++, $RelPath,
893				    "\tNEEDED=$Need\t<dependency no longer necessary>");
894			} elsif ($opt{i}) {
895				# Under the -i (information) option print out
896				# any useful dynamic entries.
897				OutMsg($Ttl++, $RelPath, "\tNEEDED=$Need");
898			}
899			next;
900		}
901
902		# Is this object built with -B direct flag on?
903		if ($Line =~ / DIRECT /) {
904			$HasDirectBinding = 1;
905		}
906
907		# Does this object specify a runpath.
908		if ($opt{i} && ($Line =~ /RPATH/)) {
909			my($Rpath) = (split(' ', $Line))[3];
910			OutMsg($Ttl++, $RelPath, "\tRPATH=$Rpath");
911			next;
912		}
913	}
914
915	# A shared object, that contains non-plt relocations, should have a
916	# combined relocation section indicating it was built with -z combreloc.
917	if ($Dll && $Relsz && ($Relsz != $Pltsz) && ($Sun == 0)) {
918		OutMsg($Ttl++, $RelPath,
919		    "\tSUNW_reloc section missing\t\t<no -zcombreloc?>");
920	}
921
922	# No objects released to a customer should have any .stabs sections
923	# remaining, they should be stripped.
924	if ($opt{s} && $Stab) {
925		if (!$opt{a}) {
926			if ($File =~ $SkipStabFiles) {
927				goto DONESTAB;
928			}
929		}
930		OutMsg($Ttl++, $RelPath,
931		    "\tdebugging sections should be deleted\t<no strip -x?>");
932	}
933
934	# Identify an object that is not built with either -B direct or
935	# -z direct.
936	if (($RelPath =~ $SkipDirectBindDirs) ||
937	    ($File =~ $SkipDirectBindFiles)) {
938		goto DONESTAB;
939	}
940	if ($Relsz && ($HasDirectBinding == 0)) {
941		OutMsg($Ttl++, $RelPath,
942		    "\tobject has no direct bindings\t<no -B direct or -z direct?>");
943	}
944
945DONESTAB:
946
947	# All objects should have a full symbol table to provide complete
948	# debugging stack traces.
949	if ($Strip) {
950		OutMsg($Ttl++, $RelPath,
951		    "\tsymbol table should not be stripped\t<remove -s?>");
952	}
953
954	# If there are symbol sort sections in this object, report on
955	# any that have duplicate addresses.
956	ProcSymSort($FullPath, $RelPath, \$Ttl) if $SymSort;
957}
958
959
960## ProcSymSortOutMsg(RefTtl, RelPath, secname, addr, names...)
961#
962# Call OutMsg for a duplicate address error in a symbol sort
963# section
964#
965sub ProcSymSortOutMsg {
966	my($RefTtl, $RelPath, $secname, $addr, @names) = @_;
967
968	OutMsg($$RefTtl++, $RelPath,
969	    "$secname: duplicate $addr: ". join(', ', @names));
970}
971
972
973## ProcSymSort(FullPath, RelPath)
974#
975# Examine the symbol sort sections for the given object and report
976# on any duplicate addresses found.  Ideally, mapfile directives
977# should be used when building objects that have multiple symbols
978# with the same address so that only one of them appears in the sort
979# section. This saves space, reduces user confusion, and ensures that
980# libproc and debuggers always display public names instead of symbols
981# that are merely implementation details.
982#
983sub ProcSymSort {
984
985	my($FullPath, $RelPath, $RefTtl) = @_;
986
987	# If this object is exempt from checking, return quietly
988	return if ($FullPath =~ $SkipSymSort);
989
990
991	open(SORT, "elfdump -S $FullPath|") ||
992	    die "$Prog: Unable to execute elfdump (symbol sort sections)\n";
993
994	my $line;
995	my $last_addr;
996	my @dups = ();
997	my $secname;
998	while ($line = <SORT>) {
999		chomp $line;
1000
1001		next if ($line eq '');
1002
1003		# If this is a header line, pick up the section name
1004		if ($line =~ /^Symbol Sort Section:\s+([^\s]+)\s+/) {
1005			$secname = $1;
1006
1007			# Every new section is followed by a column header line
1008			$line = <SORT>;		# Toss header line
1009
1010			# Flush anything left from previous section
1011			ProcSymSortOutMsg($RefTtl, $RelPath, $secname,
1012			    $last_addr, @dups) if (scalar(@dups) > 1);
1013
1014			# Reset variables for new sort section
1015			$last_addr = '';
1016			@dups = ();
1017
1018			next;
1019		}
1020
1021		# Process symbol line
1022		my @fields = split /\s+/, $line;
1023		my $new_addr = $fields[2];
1024		my $new_type = $fields[8];
1025		my $new_name = $fields[9];
1026
1027		if ($new_type eq 'UNDEF') {
1028		    OutMsg($RefTtl++, $RelPath,
1029		        "$secname: unexpected UNDEF symbol " .
1030			"(link-editor error): $new_name");
1031		    next;
1032		}
1033
1034		if ($new_addr eq $last_addr) {
1035			push @dups, $new_name;
1036		} else {
1037			ProcSymSortOutMsg($RefTtl, $RelPath, $secname,
1038			    $last_addr, @dups) if (scalar(@dups) > 1);
1039			@dups = ( $new_name );
1040			$last_addr = $new_addr;
1041		}
1042	}
1043
1044	ProcSymSortOutMsg($RefTtl, $RelPath, $secname, $last_addr, @dups)
1045		if (scalar(@dups) > 1);
1046
1047	close SORT;
1048}
1049
1050
1051sub ProcDir {
1052	my($FullDir, $RelDir) = @_;
1053	my($NewFull, $NewRel);
1054
1055	# Determine if this is a directory we don't care about.
1056	if (!$opt{a}) {
1057		if ($RelDir =~ $SkipDirs) {
1058			return;
1059		}
1060	}
1061
1062	# Open the directory and read each entry, omit files starting with "."
1063	if (opendir(DIR, $FullDir)) {
1064		foreach my $Entry (readdir(DIR)) {
1065			if ($Entry =~ /^\./) {
1066				next;
1067			}
1068			$NewFull = "$FullDir/$Entry";
1069
1070			# Ignore symlinks.
1071			if (-l $NewFull) {
1072				next;
1073			}
1074			if (!stat($NewFull)) {
1075				next;
1076			}
1077			$NewRel = "$RelDir/$Entry";
1078
1079			# Descend into and process any directories.
1080			if (-d _) {
1081				ProcDir($NewFull, $NewRel);
1082				next;
1083			}
1084
1085			# Typically dynamic objects are executable, so we can
1086			# reduce the overall cost of this script (a lot!) by
1087			# screening out non-executables here, rather than pass
1088			# them to file(1) later.  However, it has been known
1089			# for shared objects to be mistakenly left non-
1090			# executable, so with -a let all files through so that
1091			# this requirement can be verified (see ProcFile()).
1092			if (!$opt{a}) {
1093				if (! -x _) {
1094					next;
1095				}
1096			}
1097
1098			# Process any standard files.
1099			if (-f _) {
1100				my($Secure) = 0;
1101
1102				if (-u _ || -g _) {
1103					$Secure = 1;
1104				}
1105
1106				ProcFile($NewFull, $NewRel, $Entry, $Secure);
1107				next;
1108			}
1109
1110		}
1111		closedir(DIR);
1112	}
1113}
1114
1115# Create a crle(1) script for any 64-bit dependencies we locate.  A runtime
1116# configuration file will be generated to establish alternative dependency
1117# mappings for all these dependencies.
1118
1119sub Entercrle64 {
1120	my($FullDir, $RelDir, $Entry) = @_;
1121
1122	if (!$Crle64) {
1123		# Create and initialize the script if is doesn't already exit.
1124
1125		$Crle64 = "$Tmpdir/$Prog.crle64.$$";
1126		open(CRLE64, "> $Crle64") ||
1127			die "$Prog: open failed: $Crle64: $!";
1128
1129		print CRLE64 "#!/bin/sh\ncrle -64\\\n";
1130	}
1131	print CRLE64 "\t-o $FullDir -a $RelDir/$Entry \\\n";
1132}
1133
1134# Create a crle(1) script for any 32-bit dependencies we locate.  A runtime
1135# configuration file will be generated to establish alternative dependency
1136# mappings for all these dependencies.
1137
1138sub Entercrle32 {
1139	my($FullDir, $RelDir, $Entry) = @_;
1140
1141	if (!$Crle32) {
1142		# Create and initialize the script if is doesn't already exit.
1143
1144		$Crle32 = "$Tmpdir/$Prog.crle32.$$";
1145		open(CRLE32, "> $Crle32") ||
1146			die "$Prog: open failed: $Crle32: $!";
1147
1148		print CRLE32 "#!/bin/sh\ncrle \\\n";
1149	}
1150	print CRLE32 "\t-o $FullDir -a $RelDir/$Entry \\\n";
1151}
1152
1153# Having finished gathering dependencies, complete any crle(1) scripts and
1154# execute them to generate the associated runtime configuration files.  In
1155# addition establish the environment variable required to pass the configuration
1156# files to ldd(1).
1157
1158sub GenConf {
1159	if ($Crle64) {
1160		$Conf64 = "$Tmpdir/$Prog.conf64.$$";
1161		print CRLE64 "\t-c $Conf64\n";
1162
1163		chmod 0755, $Crle64;
1164		close CRLE64;
1165
1166		if (system($Crle64)) {
1167			undef $Conf64;
1168		}
1169	}
1170	if ($Crle32) {
1171		$Conf32 = "$Tmpdir/$Prog.conf32.$$";
1172		print CRLE32 "\t-c $Conf32\n";
1173
1174		chmod 0755, $Crle32;
1175		close CRLE32;
1176
1177		if (system($Crle32)) {
1178			undef $Conf32;
1179		}
1180	}
1181
1182	if ($Crle64 && $Conf64 && $Crle32 && $Conf32) {
1183		$Env = "-e LD_FLAGS=config_64=$Conf64,config_32=$Conf32";
1184	} elsif ($Crle64 && $Conf64) {
1185		$Env = "-e LD_FLAGS=config_64=$Conf64";
1186	} elsif ($Crle32 && $Conf32) {
1187		$Env = "-e LD_FLAGS=config_32=$Conf32";
1188	}
1189}
1190
1191# Recurse through a directory hierarchy looking for appropriate dependencies.
1192
1193sub GetDeps {
1194	my($FullDir, $RelDir) = @_;
1195	my($NewFull);
1196
1197	# Open the directory and read each entry, omit files starting with "."
1198	if (opendir(DIR, $FullDir)) {
1199		 foreach my $Entry (readdir(DIR)) {
1200			if ($Entry =~ /^\./) {
1201				next;
1202			}
1203			$NewFull = "$FullDir/$Entry";
1204
1205			# We need to follow links so that any dependencies
1206			# are expressed in all their available forms.
1207			# Bail on symlinks like 32 -> .
1208			if (-l $NewFull) {
1209				if (readlink($NewFull) =~ /^\.$/) {
1210					next;
1211				}
1212			}
1213			if (!stat($NewFull)) {
1214				next;
1215			}
1216
1217			if (!$opt{a}) {
1218				if ($NewFull =~ $SkipCrleConf) {
1219					next;
1220				}
1221			}
1222
1223			# If this is a directory descend into it.
1224			if (-d _) {
1225				my($NewRel);
1226
1227				if ($RelDir =~ /^\/$/) {
1228					$NewRel = "$RelDir$Entry";
1229				} else {
1230					$NewRel = "$RelDir/$Entry";
1231				}
1232
1233				GetDeps($NewFull, $NewRel);
1234				next;
1235			}
1236
1237			# If this is a regular file determine if its a
1238			# valid ELF dependency.
1239			if (-f _) {
1240				my($File);
1241
1242				# Typically shared object dependencies end with
1243				# ".so" or ".so.?", hence we can reduce the cost
1244				# of this script (a lot!) by screening out files
1245				# that don't follow this pattern.
1246				if (!$opt{a}) {
1247					if ($Entry !~ /\.so(?:\.\d+)*$/) {
1248						next;
1249					}
1250				}
1251
1252				$File = `file $NewFull`;
1253				if ($File !~ /dynamic lib/) {
1254					next;
1255				}
1256
1257				if ($File =~ /32-bit/) {
1258					Entercrle32($FullDir, $RelDir, $Entry);
1259				} elsif ($Ena64) {
1260					Entercrle64($FullDir, $RelDir, $Entry);
1261				}
1262				next;
1263			}
1264		}
1265		closedir(DIR);
1266	}
1267}
1268exit $Error
1269