xref: /illumos-gate/usr/src/cmd/sgs/rtld/common/elf.c (revision 481bba9e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  *	Copyright (c) 1988 AT&T
29  *	  All Rights Reserved
30  */
31 
32 /*
33  * Object file dependent support for ELF objects.
34  */
35 
36 #include	<stdio.h>
37 #include	<sys/procfs.h>
38 #include	<sys/mman.h>
39 #include	<sys/debug.h>
40 #include	<string.h>
41 #include	<limits.h>
42 #include	<dlfcn.h>
43 #include	<debug.h>
44 #include	<conv.h>
45 #include	"_rtld.h"
46 #include	"_audit.h"
47 #include	"_elf.h"
48 #include	"_inline.h"
49 #include	"msg.h"
50 
51 /*
52  * Default and secure dependency search paths.
53  */
54 static Spath_defn _elf_def_dirs[] = {
55 #if	defined(_ELF64)
56 	{ MSG_ORIG(MSG_PTH_LIB_64),		MSG_PTH_LIB_64_SIZE },
57 	{ MSG_ORIG(MSG_PTH_USRLIB_64),		MSG_PTH_USRLIB_64_SIZE },
58 #else
59 	{ MSG_ORIG(MSG_PTH_LIB),		MSG_PTH_LIB_SIZE },
60 	{ MSG_ORIG(MSG_PTH_USRLIB),		MSG_PTH_USRLIB_SIZE },
61 #endif
62 	{ 0, 0 }
63 };
64 
65 static Spath_defn _elf_sec_dirs[] = {
66 #if	defined(_ELF64)
67 	{ MSG_ORIG(MSG_PTH_LIBSE_64),		MSG_PTH_LIBSE_64_SIZE },
68 	{ MSG_ORIG(MSG_PTH_USRLIBSE_64),	MSG_PTH_USRLIBSE_64_SIZE },
69 #else
70 	{ MSG_ORIG(MSG_PTH_LIBSE),		MSG_PTH_LIBSE_SIZE },
71 	{ MSG_ORIG(MSG_PTH_USRLIBSE),		MSG_PTH_USRLIBSE_SIZE },
72 #endif
73 	{ 0, 0 }
74 };
75 
76 Alist	*elf_def_dirs = NULL;
77 Alist	*elf_sec_dirs = NULL;
78 
79 /*
80  * Defines for local functions.
81  */
82 static void	elf_dladdr(ulong_t, Rt_map *, Dl_info *, void **, int);
83 static Addr	elf_entry_point(void);
84 static int	elf_fix_name(const char *, Rt_map *, Alist **, Aliste, uint_t);
85 static Alist	**elf_get_def_dirs(void);
86 static Alist	**elf_get_sec_dirs(void);
87 static char	*elf_get_so(const char *, const char *, size_t, size_t);
88 static int	elf_needed(Lm_list *, Aliste, Rt_map *, int *);
89 
90 /*
91  * Functions and data accessed through indirect pointers.
92  */
93 Fct elf_fct = {
94 	elf_verify,
95 	elf_new_lmp,
96 	elf_entry_point,
97 	elf_needed,
98 	lookup_sym,
99 	elf_reloc,
100 	elf_get_def_dirs,
101 	elf_get_sec_dirs,
102 	elf_fix_name,
103 	elf_get_so,
104 	elf_dladdr,
105 	dlsym_handle
106 };
107 
108 /*
109  * Default and secure dependency search paths.
110  */
111 static Alist **
112 elf_get_def_dirs()
113 {
114 	if (elf_def_dirs == NULL)
115 		set_dirs(&elf_def_dirs, _elf_def_dirs, LA_SER_DEFAULT);
116 	return (&elf_def_dirs);
117 }
118 
119 static Alist **
120 elf_get_sec_dirs()
121 {
122 	if (elf_sec_dirs == NULL)
123 		set_dirs(&elf_sec_dirs, _elf_sec_dirs, LA_SER_SECURE);
124 	return (&elf_sec_dirs);
125 }
126 
127 /*
128  * Redefine NEEDED name if necessary.
129  */
130 static int
131 elf_fix_name(const char *name, Rt_map *clmp, Alist **alpp, Aliste alni,
132     uint_t orig)
133 {
134 	/*
135 	 * For ABI compliance, if we are asked for ld.so.1, then really give
136 	 * them libsys.so.1 (the SONAME of libsys.so.1 is ld.so.1).
137 	 */
138 	if (((*name == '/') &&
139 	/* BEGIN CSTYLED */
140 #if	defined(_ELF64)
141 	    (strcmp(name, MSG_ORIG(MSG_PTH_RTLD_64)) == 0)) ||
142 #else
143 	    (strcmp(name, MSG_ORIG(MSG_PTH_RTLD)) == 0)) ||
144 #endif
145 	    (strcmp(name, MSG_ORIG(MSG_FIL_RTLD)) == 0)) {
146 		/* END CSTYLED */
147 		Pdesc	*pdp;
148 
149 		DBG_CALL(Dbg_file_fixname(LIST(clmp), name,
150 		    MSG_ORIG(MSG_PTH_LIBSYS)));
151 		if ((pdp = alist_append(alpp, 0, sizeof (Pdesc), alni)) == NULL)
152 			return (0);
153 
154 		pdp->pd_pname = (char *)MSG_ORIG(MSG_PTH_LIBSYS);
155 		pdp->pd_plen = MSG_PTH_LIBSYS_SIZE;
156 		pdp->pd_flags = PD_FLG_PNSLASH;
157 
158 		return (1);
159 	}
160 
161 	return (expand_paths(clmp, name, alpp, alni, orig, 0));
162 }
163 
164 /*
165  * Determine whether this object requires any hardware or software capabilities.
166  */
167 static int
168 elf_cap_check(Fdesc *fdp, Ehdr *ehdr, Rej_desc *rej)
169 {
170 	Phdr	*phdr;
171 	int	cnt;
172 
173 	/* LINTED */
174 	phdr = (Phdr *)((char *)ehdr + ehdr->e_phoff);
175 	for (cnt = 0; cnt < ehdr->e_phnum; cnt++, phdr++) {
176 		Cap	*cptr;
177 
178 		if (phdr->p_type != PT_SUNWCAP)
179 			continue;
180 
181 		/* LINTED */
182 		cptr = (Cap *)((char *)ehdr + phdr->p_offset);
183 		while (cptr->c_tag != CA_SUNW_NULL) {
184 			if (cptr->c_tag == CA_SUNW_HW_1) {
185 				/*
186 				 * Verify the hardware capabilities.
187 				 */
188 				if (hwcap_check(cptr->c_un.c_val, rej) == 0)
189 					return (0);
190 
191 				/*
192 				 * Retain this hardware capabilities value for
193 				 * possible later inspection should this object
194 				 * be processed as a filtee.
195 				 */
196 				fdp->fd_hwcap = cptr->c_un.c_val;
197 			}
198 			if (cptr->c_tag == CA_SUNW_SF_1) {
199 				/*
200 				 * Verify the software capabilities.
201 				 */
202 				if (sfcap_check(cptr->c_un.c_val, rej) == 0)
203 					return (0);
204 			}
205 			cptr++;
206 		}
207 	}
208 	return (1);
209 }
210 
211 /*
212  * Determine if we have been given an ELF file and if so determine if the file
213  * is compatible.  Returns 1 if true, else 0 and sets the reject descriptor
214  * with associated error information.
215  */
216 Fct *
217 elf_verify(caddr_t addr, size_t size, Fdesc *fdp, const char *name,
218     Rej_desc *rej)
219 {
220 	Ehdr	*ehdr;
221 	char	*caddr = (char *)addr;
222 
223 	/*
224 	 * Determine if we're an elf file.  If not simply return, we don't set
225 	 * any rejection information as this test allows use to scroll through
226 	 * the objects we support (ELF, AOUT).
227 	 */
228 	if (size < sizeof (Ehdr) ||
229 	    caddr[EI_MAG0] != ELFMAG0 ||
230 	    caddr[EI_MAG1] != ELFMAG1 ||
231 	    caddr[EI_MAG2] != ELFMAG2 ||
232 	    caddr[EI_MAG3] != ELFMAG3) {
233 		return (NULL);
234 	}
235 
236 	/*
237 	 * Check class and encoding.
238 	 */
239 	/* LINTED */
240 	ehdr = (Ehdr *)addr;
241 	if (ehdr->e_ident[EI_CLASS] != M_CLASS) {
242 		rej->rej_type = SGS_REJ_CLASS;
243 		rej->rej_info = (uint_t)ehdr->e_ident[EI_CLASS];
244 		return (NULL);
245 	}
246 	if (ehdr->e_ident[EI_DATA] != M_DATA) {
247 		rej->rej_type = SGS_REJ_DATA;
248 		rej->rej_info = (uint_t)ehdr->e_ident[EI_DATA];
249 		return (NULL);
250 	}
251 	if ((ehdr->e_type != ET_REL) && (ehdr->e_type != ET_EXEC) &&
252 	    (ehdr->e_type != ET_DYN)) {
253 		rej->rej_type = SGS_REJ_TYPE;
254 		rej->rej_info = (uint_t)ehdr->e_type;
255 		return (NULL);
256 	}
257 
258 	/*
259 	 * Verify ELF version.
260 	 */
261 	if (ehdr->e_version > EV_CURRENT) {
262 		rej->rej_type = SGS_REJ_VERSION;
263 		rej->rej_info = (uint_t)ehdr->e_version;
264 		return (NULL);
265 	}
266 
267 	/*
268 	 * Verify machine specific flags.
269 	 */
270 	if (elf_mach_flags_check(rej, ehdr) == 0)
271 		return (NULL);
272 
273 	/*
274 	 * Verify any hardware/software capability requirements.  Note, if this
275 	 * object is an explicitly defined shared object under inspection by
276 	 * ldd(1), and contains an incompatible hardware capabilities
277 	 * requirement, then inform the user, but continue processing.
278 	 */
279 	if (elf_cap_check(fdp, ehdr, rej) == 0) {
280 		Rt_map	*lmp = lml_main.lm_head;
281 
282 		if ((lml_main.lm_flags & LML_FLG_TRC_LDDSTUB) &&
283 		    (lmp != NULL) && (FLAGS1(lmp) & FL1_RT_LDDSTUB) &&
284 		    (NEXT(lmp) == NULL)) {
285 			const char	*fmt;
286 
287 			if (rej->rej_type == SGS_REJ_HWCAP_1)
288 				fmt = MSG_INTL(MSG_LDD_GEN_HWCAP_1);
289 			else
290 				fmt = MSG_INTL(MSG_LDD_GEN_SFCAP_1);
291 			(void) printf(fmt, name, rej->rej_str);
292 			return (&elf_fct);
293 		}
294 		return (NULL);
295 	}
296 	return (&elf_fct);
297 }
298 
299 /*
300  * The runtime linker employs lazy loading to provide the libraries needed for
301  * debugging, preloading .o's and dldump().  As these are seldom used, the
302  * standard startup of ld.so.1 doesn't initialize all the information necessary
303  * to perform plt relocation on ld.so.1's link-map.  The first time lazy loading
304  * is called we get here to perform these initializations:
305  *
306  *  o	elf_needed() is called to set up the DYNINFO() indexes for each lazy
307  *	dependency.  Typically, for all other objects, this is called during
308  *	analyze_so(), but as ld.so.1 is set-contained we skip this processing.
309  *
310  *  o	For intel, ld.so.1's JMPSLOT relocations need relative updates. These
311  *	are by default skipped thus delaying all relative relocation processing
312  * 	on every invocation of ld.so.1.
313  */
314 int
315 elf_rtld_load()
316 {
317 	Lm_list	*lml = &lml_rtld;
318 	Rt_map	*lmp = lml->lm_head;
319 
320 	if (lml->lm_flags & LML_FLG_PLTREL)
321 		return (1);
322 
323 	/*
324 	 * As we need to refer to the DYNINFO() information, insure that it has
325 	 * been initialized.
326 	 */
327 	if (elf_needed(lml, ALIST_OFF_DATA, lmp, NULL) == 0)
328 		return (0);
329 
330 #if	defined(__i386)
331 	/*
332 	 * This is a kludge to give ld.so.1 a performance benefit on i386.
333 	 * It's based around two factors.
334 	 *
335 	 *  o	JMPSLOT relocations (PLT's) actually need a relative relocation
336 	 *	applied to the GOT entry so that they can find PLT0.
337 	 *
338 	 *  o	ld.so.1 does not exercise *any* PLT's before it has made a call
339 	 *	to elf_lazy_load().  This is because all dynamic dependencies
340 	 * 	are recorded as lazy dependencies.
341 	 */
342 	(void) elf_reloc_relative_count((ulong_t)JMPREL(lmp),
343 	    (ulong_t)(PLTRELSZ(lmp) / RELENT(lmp)), (ulong_t)RELENT(lmp),
344 	    (ulong_t)ADDR(lmp), lmp, NULL);
345 #endif
346 
347 	lml->lm_flags |= LML_FLG_PLTREL;
348 	return (1);
349 }
350 
351 /*
352  * Lazy load an object.
353  */
354 Rt_map *
355 elf_lazy_load(Rt_map *clmp, Slookup *slp, uint_t ndx, const char *sym,
356     int *in_nfavl)
357 {
358 	Alist		*palp = NULL;
359 	Rt_map		*nlmp, *hlmp;
360 	Dyninfo		*dip = &DYNINFO(clmp)[ndx], *pdip;
361 	uint_t		flags = 0;
362 	const char	*name;
363 	Lm_list		*lml = LIST(clmp);
364 	Aliste		lmco;
365 
366 	/*
367 	 * If this dependency has already been processed, we're done.
368 	 */
369 	if (((nlmp = (Rt_map *)dip->di_info) != NULL) ||
370 	    (dip->di_flags & FLG_DI_LDD_DONE))
371 		return (nlmp);
372 
373 	/*
374 	 * If we're running under ldd(1), indicate that this dependency has been
375 	 * processed (see test above).  It doesn't matter whether the object is
376 	 * successfully loaded or not, this flag simply ensures that we don't
377 	 * repeatedly attempt to load an object that has already failed to load.
378 	 * To do so would create multiple failure diagnostics for the same
379 	 * object under ldd(1).
380 	 */
381 	if (lml->lm_flags & LML_FLG_TRC_ENABLE)
382 		dip->di_flags |= FLG_DI_LDD_DONE;
383 
384 	/*
385 	 * Determine the initial dependency name.
386 	 */
387 	name = STRTAB(clmp) + DYN(clmp)[ndx].d_un.d_val;
388 	DBG_CALL(Dbg_file_lazyload(clmp, name, sym));
389 
390 	/*
391 	 * If this object needs to establish its own group, make sure a handle
392 	 * is created.
393 	 */
394 	if (dip->di_flags & FLG_DI_GROUP)
395 		flags |= (FLG_RT_SETGROUP | FLG_RT_HANDLE);
396 
397 	/*
398 	 * Lazy dependencies are identified as DT_NEEDED entries with a
399 	 * DF_P1_LAZYLOAD flag in the previous DT_POSFLAG_1 element.  The
400 	 * dynamic information element that corresponds to the DT_POSFLAG_1
401 	 * entry is free, and thus used to store the present entrance
402 	 * identifier.  This identifier is used to prevent multiple attempts to
403 	 * load a failed lazy loadable dependency within the same runtime linker
404 	 * operation.  However, future attempts to reload this dependency are
405 	 * still possible.
406 	 */
407 	if (ndx && (pdip = dip - 1) && (pdip->di_flags & FLG_DI_POSFLAG1))
408 		pdip->di_info = (void *)slp->sl_id;
409 
410 	/*
411 	 * Expand the requested name if necessary.
412 	 */
413 	if (elf_fix_name(name, clmp, &palp, AL_CNT_NEEDED, 0) == 0)
414 		return (NULL);
415 
416 	/*
417 	 * Provided the object on the head of the link-map has completed its
418 	 * relocation, create a new link-map control list for this request.
419 	 */
420 	hlmp = lml->lm_head;
421 	if (FLAGS(hlmp) & FLG_RT_RELOCED) {
422 		Lm_cntl	*lmc;
423 
424 		if ((lmc = alist_append(&lml->lm_lists, 0, sizeof (Lm_cntl),
425 		    AL_CNT_LMLISTS)) == NULL) {
426 			remove_plist(&palp, 1);
427 			return (NULL);
428 		}
429 		lmco = (Aliste)((char *)lmc - (char *)lml->lm_lists);
430 	} else
431 		lmco = ALIST_OFF_DATA;
432 
433 	/*
434 	 * Load the associated object.
435 	 */
436 	dip->di_info = nlmp =
437 	    load_one(lml, lmco, palp, clmp, MODE(clmp), flags, 0, in_nfavl);
438 
439 	/*
440 	 * Remove any expanded pathname infrastructure.  Reduce the pending lazy
441 	 * dependency count of the caller, together with the link-map lists
442 	 * count of objects that still have lazy dependencies pending.
443 	 */
444 	remove_plist(&palp, 1);
445 	if (--LAZY(clmp) == 0)
446 		LIST(clmp)->lm_lazy--;
447 
448 	/*
449 	 * Finish processing the objects associated with this request, and
450 	 * create an association between the caller and this dependency.
451 	 */
452 	if (nlmp && ((bind_one(clmp, nlmp, BND_NEEDED) == 0) ||
453 	    ((nlmp = analyze_lmc(lml, lmco, nlmp, in_nfavl)) == NULL) ||
454 	    (relocate_lmc(lml, lmco, clmp, nlmp, in_nfavl) == 0)))
455 		dip->di_info = nlmp = NULL;
456 
457 	/*
458 	 * If this lazyload has failed, and we've created a new link-map
459 	 * control list to which this request has added objects, then remove
460 	 * all the objects that have been associated to this request.
461 	 */
462 	if ((nlmp == NULL) && (lmco != ALIST_OFF_DATA))
463 		remove_lmc(lml, clmp, lmco, name);
464 
465 	/*
466 	 * Finally, remove any link-map control list that was created.
467 	 */
468 	if (lmco != ALIST_OFF_DATA)
469 		remove_cntl(lml, lmco);
470 
471 	/*
472 	 * If this lazy loading failed, record the fact, and bump the lazy
473 	 * counts.
474 	 */
475 	if (nlmp == NULL) {
476 		dip->di_flags |= FLG_DI_LAZYFAIL;
477 		if (LAZY(clmp)++ == 0)
478 			LIST(clmp)->lm_lazy++;
479 	}
480 
481 	return (nlmp);
482 }
483 
484 /*
485  * Return the entry point of the ELF executable.
486  */
487 static Addr
488 elf_entry_point(void)
489 {
490 	Rt_map	*lmp = lml_main.lm_head;
491 	Ehdr	*ehdr = (Ehdr *)ADDR(lmp);
492 	Addr	addr = (Addr)(ehdr->e_entry);
493 
494 	if ((FLAGS(lmp) & FLG_RT_FIXED) == 0)
495 		addr += ADDR(lmp);
496 
497 	return (addr);
498 }
499 
500 /*
501  * Determine if a dependency requires a particular version and if so verify
502  * that the version exists in the dependency.
503  */
504 int
505 elf_verify_vers(const char *name, Rt_map *clmp, Rt_map *nlmp)
506 {
507 	Verneed		*vnd = VERNEED(clmp);
508 	int		_num, num = VERNEEDNUM(clmp);
509 	char		*cstrs = (char *)STRTAB(clmp);
510 	Lm_list		*lml = LIST(clmp);
511 
512 	/*
513 	 * Traverse the callers version needed information and determine if any
514 	 * specific versions are required from the dependency.
515 	 */
516 	DBG_CALL(Dbg_ver_need_title(LIST(clmp), NAME(clmp)));
517 	for (_num = 1; _num <= num; _num++,
518 	    vnd = (Verneed *)((Xword)vnd + vnd->vn_next)) {
519 		Half		cnt = vnd->vn_cnt;
520 		Vernaux		*vnap;
521 		char		*nstrs, *need;
522 
523 		/*
524 		 * Determine if a needed entry matches this dependency.
525 		 */
526 		need = (char *)(cstrs + vnd->vn_file);
527 		if (strcmp(name, need) != 0)
528 			continue;
529 
530 		if ((lml->lm_flags & LML_FLG_TRC_VERBOSE) &&
531 		    ((FLAGS1(clmp) & FL1_RT_LDDSTUB) == 0))
532 			(void) printf(MSG_INTL(MSG_LDD_VER_FIND), name);
533 
534 		/*
535 		 * Validate that each version required actually exists in the
536 		 * dependency.
537 		 */
538 		nstrs = (char *)STRTAB(nlmp);
539 
540 		for (vnap = (Vernaux *)((Xword)vnd + vnd->vn_aux); cnt;
541 		    cnt--, vnap = (Vernaux *)((Xword)vnap + vnap->vna_next)) {
542 			char		*version, *define;
543 			Verdef		*vdf = VERDEF(nlmp);
544 			ulong_t		_num, num = VERDEFNUM(nlmp);
545 			int		found = 0;
546 
547 			/*
548 			 * Skip validation of versions that are marked
549 			 * INFO. This optimization is used for versions
550 			 * that are inherited by another version. Verification
551 			 * of the inheriting version is sufficient.
552 			 *
553 			 * Such versions are recorded in the object for the
554 			 * benefit of VERSYM entries that refer to them. This
555 			 * provides a purely diagnositic benefit.
556 			 */
557 			if (vnap->vna_flags & VER_FLG_INFO)
558 				continue;
559 
560 			version = (char *)(cstrs + vnap->vna_name);
561 			DBG_CALL(Dbg_ver_need_entry(lml, 0, need, version));
562 
563 			for (_num = 1; _num <= num; _num++,
564 			    vdf = (Verdef *)((Xword)vdf + vdf->vd_next)) {
565 				Verdaux		*vdap;
566 
567 				if (vnap->vna_hash != vdf->vd_hash)
568 					continue;
569 
570 				vdap = (Verdaux *)((Xword)vdf + vdf->vd_aux);
571 				define = (char *)(nstrs + vdap->vda_name);
572 				if (strcmp(version, define) != 0)
573 					continue;
574 
575 				found++;
576 				break;
577 			}
578 
579 			/*
580 			 * If we're being traced print out any matched version
581 			 * when the verbose (-v) option is in effect.  Always
582 			 * print any unmatched versions.
583 			 */
584 			if (lml->lm_flags & LML_FLG_TRC_ENABLE) {
585 				/* BEGIN CSTYLED */
586 				if (found) {
587 				    if (!(lml->lm_flags & LML_FLG_TRC_VERBOSE))
588 					continue;
589 
590 				    (void) printf(MSG_ORIG(MSG_LDD_VER_FOUND),
591 					need, version, NAME(nlmp));
592 				} else {
593 				    if (rtld_flags & RT_FL_SILENCERR)
594 					continue;
595 
596 				    (void) printf(MSG_INTL(MSG_LDD_VER_NFOUND),
597 					need, version);
598 				}
599 				/* END CSTYLED */
600 				continue;
601 			}
602 
603 			/*
604 			 * If the version hasn't been found then this is a
605 			 * candidate for a fatal error condition.  Weak
606 			 * version definition requirements are silently
607 			 * ignored.  Also, if the image inspected for a version
608 			 * definition has no versioning recorded at all then
609 			 * silently ignore this (this provides better backward
610 			 * compatibility to old images created prior to
611 			 * versioning being available).  Both of these skipped
612 			 * diagnostics are available under tracing (see above).
613 			 */
614 			if ((found == 0) && (num != 0) &&
615 			    (!(vnap->vna_flags & VER_FLG_WEAK))) {
616 				eprintf(lml, ERR_FATAL,
617 				    MSG_INTL(MSG_VER_NFOUND), need, version,
618 				    NAME(clmp));
619 				return (0);
620 			}
621 		}
622 	}
623 	DBG_CALL(Dbg_util_nl(lml, DBG_NL_STD));
624 	return (1);
625 }
626 
627 /*
628  * Search through the dynamic section for DT_NEEDED entries and perform one
629  * of two functions.  If only the first argument is specified then load the
630  * defined shared object, otherwise add the link map representing the defined
631  * link map the the dlopen list.
632  */
633 static int
634 elf_needed(Lm_list *lml, Aliste lmco, Rt_map *clmp, int *in_nfavl)
635 {
636 	Alist		*palp = NULL;
637 	Dyn		*dyn, *pdyn;
638 	ulong_t		ndx = 0;
639 	uint_t		lazy, flags;
640 	Word		lmflags = lml->lm_flags;
641 	Word		lmtflags = lml->lm_tflags;
642 
643 	/*
644 	 * Process each shared object on needed list.
645 	 */
646 	if (DYN(clmp) == NULL)
647 		return (1);
648 
649 	for (dyn = (Dyn *)DYN(clmp), pdyn = NULL; dyn->d_tag != DT_NULL;
650 	    pdyn = dyn++, ndx++) {
651 		Dyninfo	*dip = &DYNINFO(clmp)[ndx];
652 		Rt_map	*nlmp = NULL;
653 		char	*name;
654 		int	silent = 0;
655 
656 		switch (dyn->d_tag) {
657 		case DT_POSFLAG_1:
658 			dip->di_flags |= FLG_DI_POSFLAG1;
659 			continue;
660 		case DT_NEEDED:
661 		case DT_USED:
662 			lazy = flags = 0;
663 			dip->di_flags |= FLG_DI_NEEDED;
664 
665 			if (pdyn && (pdyn->d_tag == DT_POSFLAG_1)) {
666 				if ((pdyn->d_un.d_val & DF_P1_LAZYLOAD) &&
667 				    ((lmtflags & LML_TFLG_NOLAZYLD) == 0)) {
668 					dip->di_flags |= FLG_DI_LAZY;
669 					lazy = 1;
670 				}
671 				if (pdyn->d_un.d_val & DF_P1_GROUPPERM) {
672 					dip->di_flags |= FLG_DI_GROUP;
673 					flags =
674 					    (FLG_RT_SETGROUP | FLG_RT_HANDLE);
675 				}
676 			}
677 
678 			name = (char *)STRTAB(clmp) + dyn->d_un.d_val;
679 
680 			/*
681 			 * NOTE, libc.so.1 can't be lazy loaded.  Although a
682 			 * lazy position flag won't be produced when a RTLDINFO
683 			 * .dynamic entry is found (introduced with the UPM in
684 			 * Solaris 10), it was possible to mark libc for lazy
685 			 * loading on previous releases.  To reduce the overhead
686 			 * of testing for this occurrence, only carry out this
687 			 * check for the first object on the link-map list
688 			 * (there aren't many applications built without libc).
689 			 */
690 			if (lazy && (lml->lm_head == clmp) &&
691 			    (strcmp(name, MSG_ORIG(MSG_FIL_LIBC)) == 0))
692 				lazy = 0;
693 
694 			/*
695 			 * Don't bring in lazy loaded objects yet unless we've
696 			 * been asked to attempt to load all available objects
697 			 * (crle(1) sets LD_FLAGS=loadavail).  Even under
698 			 * RTLD_NOW we don't process this - RTLD_NOW will cause
699 			 * relocation processing which in turn might trigger
700 			 * lazy loading, but its possible that the object has a
701 			 * lazy loaded file with no bindings (i.e., it should
702 			 * never have been a dependency in the first place).
703 			 */
704 			if (lazy) {
705 				if ((lmflags & LML_FLG_LOADAVAIL) == 0) {
706 					LAZY(clmp)++;
707 					lazy = flags = 0;
708 					continue;
709 				}
710 
711 				/*
712 				 * Silence any error messages - see description
713 				 * under elf_lookup_filtee().
714 				 */
715 				if ((rtld_flags & RT_FL_SILENCERR) == 0) {
716 					rtld_flags |= RT_FL_SILENCERR;
717 					silent = 1;
718 				}
719 			}
720 			break;
721 		case DT_AUXILIARY:
722 			dip->di_flags |= FLG_DI_AUXFLTR;
723 			continue;
724 		case DT_SUNW_AUXILIARY:
725 			dip->di_flags |= (FLG_DI_AUXFLTR | FLG_DI_SYMFLTR);
726 			continue;
727 		case DT_FILTER:
728 			dip->di_flags |= FLG_DI_STDFLTR;
729 			continue;
730 		case DT_SUNW_FILTER:
731 			dip->di_flags |= (FLG_DI_STDFLTR | FLG_DI_SYMFLTR);
732 			continue;
733 		default:
734 			continue;
735 		}
736 
737 		DBG_CALL(Dbg_file_needed(clmp, name));
738 
739 		/*
740 		 * If we're running under ldd(1), indicate that this dependency
741 		 * has been processed.  It doesn't matter whether the object is
742 		 * successfully loaded or not, this flag simply ensures that we
743 		 * don't repeatedly attempt to load an object that has already
744 		 * failed to load.  To do so would create multiple failure
745 		 * diagnostics for the same object under ldd(1).
746 		 */
747 		if (lml->lm_flags & LML_FLG_TRC_ENABLE)
748 			dip->di_flags |= FLG_DI_LDD_DONE;
749 
750 		/*
751 		 * Establish the objects name, load it and establish a binding
752 		 * with the caller.
753 		 */
754 		if ((elf_fix_name(name, clmp, &palp, AL_CNT_NEEDED, 0) == 0) ||
755 		    ((nlmp = load_one(lml, lmco, palp, clmp, MODE(clmp),
756 		    flags, 0, in_nfavl)) == NULL) ||
757 		    (bind_one(clmp, nlmp, BND_NEEDED) == 0))
758 			nlmp = NULL;
759 
760 		/*
761 		 * Clean up any infrastructure, including the removal of the
762 		 * error suppression state, if it had been previously set in
763 		 * this routine.
764 		 */
765 		remove_plist(&palp, 0);
766 
767 		if (silent)
768 			rtld_flags &= ~RT_FL_SILENCERR;
769 
770 		if ((dip->di_info = (void *)nlmp) == NULL) {
771 			/*
772 			 * If the object could not be mapped, continue if error
773 			 * suppression is established or we're here with ldd(1).
774 			 */
775 			if ((MODE(clmp) & RTLD_CONFGEN) || (lmflags &
776 			    (LML_FLG_LOADAVAIL | LML_FLG_TRC_ENABLE)))
777 				continue;
778 			else {
779 				remove_plist(&palp, 1);
780 				return (0);
781 			}
782 		}
783 	}
784 
785 	if (LAZY(clmp))
786 		lml->lm_lazy++;
787 
788 	remove_plist(&palp, 1);
789 	return (1);
790 }
791 
792 /*
793  * A null symbol interpretor.  Used if a filter has no associated filtees.
794  */
795 /* ARGSUSED0 */
796 static Sym *
797 elf_null_find_sym(Slookup *slp, Rt_map **dlmp, uint_t *binfo, int *in_nfavl)
798 {
799 	return (NULL);
800 }
801 
802 /*
803  * Disable filtee use.
804  */
805 static void
806 elf_disable_filtee(Rt_map *lmp, Dyninfo *dip)
807 {
808 	if ((dip->di_flags & FLG_DI_SYMFLTR) == 0) {
809 		/*
810 		 * If this is an object filter, null out the reference name.
811 		 */
812 		if (OBJFLTRNDX(lmp) != FLTR_DISABLED) {
813 			REFNAME(lmp) = NULL;
814 			OBJFLTRNDX(lmp) = FLTR_DISABLED;
815 
816 			/*
817 			 * Indicate that this filtee is no longer available.
818 			 */
819 			if (dip->di_flags & FLG_DI_STDFLTR)
820 				SYMINTP(lmp) = elf_null_find_sym;
821 
822 		}
823 	} else if (dip->di_flags & FLG_DI_STDFLTR) {
824 		/*
825 		 * Indicate that this standard filtee is no longer available.
826 		 */
827 		if (SYMSFLTRCNT(lmp))
828 			SYMSFLTRCNT(lmp)--;
829 	} else {
830 		/*
831 		 * Indicate that this auxiliary filtee is no longer available.
832 		 */
833 		if (SYMAFLTRCNT(lmp))
834 			SYMAFLTRCNT(lmp)--;
835 	}
836 	dip->di_flags &= ~MSK_DI_FILTER;
837 }
838 
839 /*
840  * Find symbol interpreter - filters.
841  * This function is called when the symbols from a shared object should
842  * be resolved from the shared objects filtees instead of from within itself.
843  *
844  * A symbol name of 0 is used to trigger filtee loading.
845  */
846 static Sym *
847 _elf_lookup_filtee(Slookup *slp, Rt_map **dlmp, uint_t *binfo, uint_t ndx,
848     int *in_nfavl)
849 {
850 	const char	*name = slp->sl_name, *filtees;
851 	Rt_map		*clmp = slp->sl_cmap;
852 	Rt_map		*ilmp = slp->sl_imap;
853 	Pdesc		*pdp;
854 	int		any;
855 	Dyninfo		*dip = &DYNINFO(ilmp)[ndx];
856 	Lm_list		*lml = LIST(ilmp);
857 	Aliste		idx;
858 
859 	/*
860 	 * Indicate that the filter has been used.  If a binding already exists
861 	 * to the caller, indicate that this object is referenced.  This insures
862 	 * we don't generate false unreferenced diagnostics from ldd -u/U or
863 	 * debugging.  Don't create a binding regardless, as this filter may
864 	 * have been dlopen()'ed.
865 	 */
866 	if (name && (ilmp != clmp)) {
867 		Word	tracing = (LIST(clmp)->lm_flags &
868 		    (LML_FLG_TRC_UNREF | LML_FLG_TRC_UNUSED));
869 
870 		if (tracing || DBG_ENABLED) {
871 			Bnd_desc 	*bdp;
872 			Aliste		idx;
873 
874 			FLAGS1(ilmp) |= FL1_RT_USED;
875 
876 			if ((tracing & LML_FLG_TRC_UNREF) || DBG_ENABLED) {
877 				for (APLIST_TRAVERSE(CALLERS(ilmp), idx, bdp)) {
878 					if (bdp->b_caller == clmp) {
879 						bdp->b_flags |= BND_REFER;
880 						break;
881 					}
882 				}
883 			}
884 		}
885 	}
886 
887 	/*
888 	 * If this is the first call to process this filter, establish the
889 	 * filtee list.  If a configuration file exists, determine if any
890 	 * filtee associations for this filter, and its filtee reference, are
891 	 * defined.  Otherwise, process the filtee reference.  Any token
892 	 * expansion is also completed at this point (i.e., $PLATFORM).
893 	 */
894 	filtees = (char *)STRTAB(ilmp) + DYN(ilmp)[ndx].d_un.d_val;
895 	if (dip->di_info == NULL) {
896 		if (rtld_flags2 & RT_FL2_FLTCFG)
897 			elf_config_flt(lml, PATHNAME(ilmp), filtees,
898 			    (Alist **)&dip->di_info, AL_CNT_FILTEES);
899 
900 		if (dip->di_info == NULL) {
901 			DBG_CALL(Dbg_file_filter(lml, NAME(ilmp), filtees, 0));
902 			if ((lml->lm_flags &
903 			    (LML_FLG_TRC_VERBOSE | LML_FLG_TRC_SEARCH)) &&
904 			    ((FLAGS1(ilmp) & FL1_RT_LDDSTUB) == 0))
905 				(void) printf(MSG_INTL(MSG_LDD_FIL_FILTER),
906 				    NAME(ilmp), filtees);
907 
908 			if (expand_paths(ilmp, filtees, (Alist **)&dip->di_info,
909 			    AL_CNT_FILTEES, 0, 0) == 0) {
910 				elf_disable_filtee(ilmp, dip);
911 				return (NULL);
912 			}
913 		}
914 	}
915 
916 	/*
917 	 * Traverse the filtee list, dlopen()'ing any objects specified and
918 	 * using their group handle to lookup the symbol.
919 	 */
920 	any = 0;
921 	for (ALIST_TRAVERSE((Alist *)dip->di_info, idx, pdp)) {
922 		int	mode;
923 		Grp_hdl	*ghp;
924 		Rt_map	*nlmp = NULL;
925 
926 		if (pdp->pd_plen == 0)
927 			continue;
928 
929 		/*
930 		 * Establish the mode of the filtee from the filter.  As filtees
931 		 * are loaded via a dlopen(), make sure that RTLD_GROUP is set
932 		 * and the filtees aren't global.  It would be nice to have
933 		 * RTLD_FIRST used here also, but as filters got out long before
934 		 * RTLD_FIRST was introduced it's a little too late now.
935 		 */
936 		mode = MODE(ilmp) | RTLD_GROUP;
937 		mode &= ~RTLD_GLOBAL;
938 
939 		/*
940 		 * Insure that any auxiliary filter can locate symbols from its
941 		 * caller.
942 		 */
943 		if (dip->di_flags & FLG_DI_AUXFLTR)
944 			mode |= RTLD_PARENT;
945 
946 		/*
947 		 * Process any hardware capability directory.  Establish a new
948 		 * link-map control list from which to analyze any newly added
949 		 * objects.
950 		 */
951 		if ((pdp->pd_info == NULL) && (pdp->pd_flags & PD_TKN_HWCAP)) {
952 			const char	*dir = pdp->pd_pname;
953 			Aliste		lmco;
954 
955 			if (FLAGS(lml->lm_head) & FLG_RT_RELOCED) {
956 				Lm_cntl	*lmc;
957 
958 				if ((lmc = alist_append(&lml->lm_lists, 0,
959 				    sizeof (Lm_cntl), AL_CNT_LMLISTS)) == NULL)
960 					return (NULL);
961 				lmco = (Aliste)((char *)lmc -
962 				    (char *)lml->lm_lists);
963 			} else
964 				lmco = ALIST_OFF_DATA;
965 
966 			/*
967 			 * Determine the hardware capability filtees.  If none
968 			 * can be found, provide suitable diagnostics.
969 			 */
970 			DBG_CALL(Dbg_cap_hw_filter(lml, dir, ilmp));
971 			if (hwcap_filtees((Alist **)&dip->di_info, idx, dir,
972 			    lmco, ilmp, filtees, mode,
973 			    (FLG_RT_HANDLE | FLG_RT_HWCAP), in_nfavl) == 0) {
974 				if ((lml->lm_flags & LML_FLG_TRC_ENABLE) &&
975 				    (dip->di_flags & FLG_DI_AUXFLTR) &&
976 				    (rtld_flags & RT_FL_WARNFLTR)) {
977 					(void) printf(
978 					    MSG_INTL(MSG_LDD_HWCAP_NFOUND),
979 					    dir);
980 				}
981 				DBG_CALL(Dbg_cap_hw_filter(lml, dir, 0));
982 			}
983 
984 			/*
985 			 * Re-establish the originating path name descriptor, as
986 			 * the expansion of hardware capabilities filtees may
987 			 * have re-allocated the controlling Alist.  Mark this
988 			 * original pathname descriptor as unused so that the
989 			 * descriptor isn't revisited for processing.  Any real
990 			 * hardware capabilities filtees have been added as new
991 			 * pathname descriptors following this descriptor.
992 			 */
993 			pdp = alist_item((Alist *)dip->di_info, idx);
994 			pdp->pd_flags &= ~PD_TKN_HWCAP;
995 			pdp->pd_plen = 0;
996 
997 			/*
998 			 * Now that any hardware capability objects have been
999 			 * processed, remove any link-map control list.
1000 			 */
1001 			if (lmco != ALIST_OFF_DATA)
1002 				remove_cntl(lml, lmco);
1003 		}
1004 
1005 		if (pdp->pd_plen == 0)
1006 			continue;
1007 
1008 		/*
1009 		 * Process an individual filtee.
1010 		 */
1011 		if (pdp->pd_info == NULL) {
1012 			const char	*filtee = pdp->pd_pname;
1013 			int		audit = 0;
1014 
1015 			DBG_CALL(Dbg_file_filtee(lml, NAME(ilmp), filtee, 0));
1016 
1017 			ghp = NULL;
1018 
1019 			/*
1020 			 * Determine if the reference link map is already
1021 			 * loaded.  As an optimization compare the filtee with
1022 			 * our interpretor.  The most common filter is
1023 			 * libdl.so.1, which is a filter on ld.so.1.
1024 			 */
1025 #if	defined(_ELF64)
1026 			if (strcmp(filtee, MSG_ORIG(MSG_PTH_RTLD_64)) == 0) {
1027 #else
1028 			if (strcmp(filtee, MSG_ORIG(MSG_PTH_RTLD)) == 0) {
1029 #endif
1030 				/*
1031 				 * Create an association between ld.so.1 and the
1032 				 * filter.  As an optimization, a handle for
1033 				 * ld.so.1 itself (required for the dlopen()
1034 				 * family filtering mechanism) shouldn't search
1035 				 * any dependencies of ld.so.1.  Omitting
1036 				 * GPD_ADDEPS prevents the addition of any
1037 				 * ld.so.1 dependencies to this handle.
1038 				 */
1039 				nlmp = lml_rtld.lm_head;
1040 				if ((ghp = hdl_create(&lml_rtld, nlmp, ilmp,
1041 				    (GPH_LDSO | GPH_FIRST | GPH_FILTEE),
1042 				    (GPD_DLSYM | GPD_RELOC), GPD_PARENT)) ==
1043 				    NULL)
1044 					nlmp = NULL;
1045 
1046 				/*
1047 				 * Establish the filter handle to prevent any
1048 				 * recursion.
1049 				 */
1050 				if (nlmp && ghp)
1051 					pdp->pd_info = (void *)ghp;
1052 
1053 				/*
1054 				 * Audit the filter/filtee established.  Ignore
1055 				 * any return from the auditor, as we can't
1056 				 * allow ignore filtering to ld.so.1, otherwise
1057 				 * nothing is going to work.
1058 				 */
1059 				if (nlmp && ((lml->lm_tflags | AFLAGS(ilmp)) &
1060 				    LML_TFLG_AUD_OBJFILTER))
1061 					(void) audit_objfilter(ilmp, filtees,
1062 					    nlmp, 0);
1063 
1064 			} else {
1065 				Rej_desc	rej = { 0 };
1066 				Fdesc		fd = { 0 };
1067 				Aliste		lmco;
1068 
1069 				/*
1070 				 * Trace the inspection of this file, determine
1071 				 * any auditor substitution, and seed the file
1072 				 * descriptor with the originating name.
1073 				 */
1074 				if (load_trace(lml, pdp, clmp, &fd) == NULL)
1075 					continue;
1076 
1077 				/*
1078 				 * Establish a new link-map control list from
1079 				 * which to analyze any newly added objects.
1080 				 */
1081 				if (FLAGS(lml->lm_head) & FLG_RT_RELOCED) {
1082 					Lm_cntl	*lmc;
1083 
1084 					if ((lmc =
1085 					    alist_append(&lml->lm_lists, 0,
1086 					    sizeof (Lm_cntl),
1087 					    AL_CNT_LMLISTS)) == NULL)
1088 						return (NULL);
1089 					lmco = (Aliste)((char *)lmc -
1090 					    (char *)lml->lm_lists);
1091 				} else
1092 					lmco = ALIST_OFF_DATA;
1093 
1094 				/*
1095 				 * Locate and load the filtee.
1096 				 */
1097 				if ((nlmp = load_path(lml, lmco, ilmp, mode,
1098 				    FLG_RT_HANDLE, &ghp, &fd, &rej,
1099 				    in_nfavl)) == NULL)
1100 					file_notfound(LIST(ilmp), filtee, ilmp,
1101 					    FLG_RT_HANDLE, &rej);
1102 
1103 				filtee = pdp->pd_pname;
1104 
1105 				/*
1106 				 * Establish the filter handle to prevent any
1107 				 * recursion.
1108 				 */
1109 				if (nlmp && ghp) {
1110 					ghp->gh_flags |= GPH_FILTEE;
1111 					pdp->pd_info = (void *)ghp;
1112 
1113 					FLAGS1(nlmp) |= FL1_RT_USED;
1114 				}
1115 
1116 				/*
1117 				 * Audit the filter/filtee established.  A
1118 				 * return of 0 indicates the auditor wishes to
1119 				 * ignore this filtee.
1120 				 */
1121 				if (nlmp && ((lml->lm_tflags | FLAGS1(ilmp)) &
1122 				    LML_TFLG_AUD_OBJFILTER)) {
1123 					if (audit_objfilter(ilmp, filtees,
1124 					    nlmp, 0) == 0) {
1125 						audit = 1;
1126 						nlmp = NULL;
1127 					}
1128 				}
1129 
1130 				/*
1131 				 * Finish processing the objects associated with
1132 				 * this request.  Create an association between
1133 				 * this object and the originating filter to
1134 				 * provide sufficient information to tear down
1135 				 * this filtee if necessary.
1136 				 */
1137 				if (nlmp && ghp && (((nlmp = analyze_lmc(lml,
1138 				    lmco, nlmp, in_nfavl)) == NULL) ||
1139 				    (relocate_lmc(lml, lmco, ilmp, nlmp,
1140 				    in_nfavl) == 0)))
1141 					nlmp = NULL;
1142 
1143 				/*
1144 				 * If the filtee has been successfully
1145 				 * processed, then create an association
1146 				 * between the filter and filtee.  This
1147 				 * association provides sufficient information
1148 				 * to tear down the filter and filtee if
1149 				 * necessary.
1150 				 */
1151 				DBG_CALL(Dbg_file_hdl_title(DBG_HDL_ADD));
1152 				if (nlmp && ghp &&
1153 				    (hdl_add(ghp, ilmp, GPD_FILTER) == 0))
1154 					nlmp = NULL;
1155 
1156 				/*
1157 				 * Generate a diagnostic if the filtee couldn't
1158 				 * be loaded.
1159 				 */
1160 				if (nlmp == NULL)
1161 					DBG_CALL(Dbg_file_filtee(lml, 0, filtee,
1162 					    audit));
1163 
1164 				/*
1165 				 * If this filtee loading has failed, and we've
1166 				 * created a new link-map control list to which
1167 				 * this request has added objects, then remove
1168 				 * all the objects that have been associated to
1169 				 * this request.
1170 				 */
1171 				if ((nlmp == NULL) && (lmco != ALIST_OFF_DATA))
1172 					remove_lmc(lml, clmp, lmco, name);
1173 
1174 				/*
1175 				 * Remove any link-map control list that was
1176 				 * created.
1177 				 */
1178 				if (lmco != ALIST_OFF_DATA)
1179 					remove_cntl(lml, lmco);
1180 			}
1181 
1182 			/*
1183 			 * If the filtee couldn't be loaded, null out the
1184 			 * path name descriptor entry, and continue the search.
1185 			 * Otherwise, the group handle is retained for future
1186 			 * symbol searches.
1187 			 */
1188 			if (nlmp == NULL) {
1189 				pdp->pd_info = NULL;
1190 				pdp->pd_plen = 0;
1191 				continue;
1192 			}
1193 		}
1194 
1195 		ghp = (Grp_hdl *)pdp->pd_info;
1196 
1197 		/*
1198 		 * If we're just here to trigger filtee loading skip the symbol
1199 		 * lookup so we'll continue looking for additional filtees.
1200 		 */
1201 		if (name) {
1202 			Grp_desc	*gdp;
1203 			Sym		*sym = NULL;
1204 			Aliste		idx;
1205 			Slookup		sl = *slp;
1206 
1207 			sl.sl_flags |= LKUP_FIRST;
1208 			any++;
1209 
1210 			/*
1211 			 * Look for the symbol in the handles dependencies.
1212 			 */
1213 			for (ALIST_TRAVERSE(ghp->gh_depends, idx, gdp)) {
1214 				if ((gdp->gd_flags & GPD_DLSYM) == 0)
1215 					continue;
1216 
1217 				/*
1218 				 * If our parent is a dependency don't look at
1219 				 * it (otherwise we are in a recursive loop).
1220 				 * This situation can occur with auxiliary
1221 				 * filters if the filtee has a dependency on the
1222 				 * filter.  This dependency isn't necessary as
1223 				 * auxiliary filters are opened RTLD_PARENT, but
1224 				 * users may still unknowingly add an explicit
1225 				 * dependency to the parent.
1226 				 */
1227 				if ((sl.sl_imap = gdp->gd_depend) == ilmp)
1228 					continue;
1229 
1230 				if (((sym = SYMINTP(sl.sl_imap)(&sl, dlmp,
1231 				    binfo, in_nfavl)) != NULL) ||
1232 				    (ghp->gh_flags & GPH_FIRST))
1233 					break;
1234 			}
1235 
1236 			/*
1237 			 * If a symbol has been found, indicate the binding
1238 			 * and return the symbol.
1239 			 */
1240 			if (sym) {
1241 				*binfo |= DBG_BINFO_FILTEE;
1242 				return (sym);
1243 			}
1244 		}
1245 
1246 		/*
1247 		 * If this object is tagged to terminate filtee processing we're
1248 		 * done.
1249 		 */
1250 		if (FLAGS1(ghp->gh_ownlmp) & FL1_RT_ENDFILTE)
1251 			break;
1252 	}
1253 
1254 	/*
1255 	 * If we're just here to trigger filtee loading then we're done.
1256 	 */
1257 	if (name == NULL)
1258 		return (NULL);
1259 
1260 	/*
1261 	 * If no filtees have been found for a filter, clean up any path name
1262 	 * descriptors and disable their search completely.  For auxiliary
1263 	 * filters we can reselect the symbol search function so that we never
1264 	 * enter this routine again for this object.  For standard filters we
1265 	 * use the null symbol routine.
1266 	 */
1267 	if (any == 0) {
1268 		remove_plist((Alist **)&(dip->di_info), 1);
1269 		elf_disable_filtee(ilmp, dip);
1270 		return (NULL);
1271 	}
1272 
1273 	return (NULL);
1274 }
1275 
1276 /*
1277  * Focal point for disabling error messages for auxiliary filters.  As an
1278  * auxiliary filter allows for filtee use, but provides a fallback should a
1279  * filtee not exist (or fail to load), any errors generated as a consequence of
1280  * trying to load the filtees are typically suppressed.  Setting RT_FL_SILENCERR
1281  * suppresses errors generated by eprint(), but insures a debug diagnostic is
1282  * produced.  ldd(1) employs printf(), and here, the selection of whether to
1283  * print a diagnostic in regards to auxiliary filters is a little more complex.
1284  *
1285  *   .	The determination of whether to produce an ldd message, or a fatal
1286  *	error message is driven by LML_FLG_TRC_ENABLE.
1287  *   .	More detailed ldd messages may also be driven off of LML_FLG_TRC_WARN,
1288  *	(ldd -d/-r), LML_FLG_TRC_VERBOSE (ldd -v), LML_FLG_TRC_SEARCH (ldd -s),
1289  *	and LML_FLG_TRC_UNREF/LML_FLG_TRC_UNUSED (ldd -U/-u).
1290  *
1291  *   .	If the calling object is lddstub, then several classes of message are
1292  *	suppressed.  The user isn't trying to diagnose lddstub, this is simply
1293  *	a stub executable employed to preload a user specified library against.
1294  *
1295  *   .	If RT_FL_SILENCERR is in effect then any generic ldd() messages should
1296  *	be suppressed.  All detailed ldd messages should still be produced.
1297  */
1298 Sym *
1299 elf_lookup_filtee(Slookup *slp, Rt_map **dlmp, uint_t *binfo, uint_t ndx,
1300     int *in_nfavl)
1301 {
1302 	Sym	*sym;
1303 	Dyninfo	*dip = &DYNINFO(slp->sl_imap)[ndx];
1304 	int	silent = 0;
1305 
1306 	/*
1307 	 * Make sure this entry is still acting as a filter.  We may have tried
1308 	 * to process this previously, and disabled it if the filtee couldn't
1309 	 * be processed.  However, other entries may provide different filtees
1310 	 * that are yet to be completed.
1311 	 */
1312 	if (dip->di_flags == 0)
1313 		return (NULL);
1314 
1315 	/*
1316 	 * Indicate whether an error message is required should this filtee not
1317 	 * be found, based on the type of filter.
1318 	 */
1319 	if ((dip->di_flags & FLG_DI_AUXFLTR) &&
1320 	    ((rtld_flags & (RT_FL_WARNFLTR | RT_FL_SILENCERR)) == 0)) {
1321 		rtld_flags |= RT_FL_SILENCERR;
1322 		silent = 1;
1323 	}
1324 
1325 	sym = _elf_lookup_filtee(slp, dlmp, binfo, ndx, in_nfavl);
1326 
1327 	if (silent)
1328 		rtld_flags &= ~RT_FL_SILENCERR;
1329 
1330 	return (sym);
1331 }
1332 
1333 /*
1334  * Compute the elf hash value (as defined in the ELF access library).
1335  * The form of the hash table is:
1336  *
1337  *	|--------------|
1338  *	| # of buckets |
1339  *	|--------------|
1340  *	| # of chains  |
1341  *	|--------------|
1342  *	|   bucket[]   |
1343  *	|--------------|
1344  *	|   chain[]    |
1345  *	|--------------|
1346  */
1347 ulong_t
1348 elf_hash(const char *name)
1349 {
1350 	uint_t	hval = 0;
1351 
1352 	while (*name) {
1353 		uint_t	g;
1354 		hval = (hval << 4) + *name++;
1355 		if ((g = (hval & 0xf0000000)) != 0)
1356 			hval ^= g >> 24;
1357 		hval &= ~g;
1358 	}
1359 	return ((ulong_t)hval);
1360 }
1361 
1362 /*
1363  * If flag argument has LKUP_SPEC set, we treat undefined symbols of type
1364  * function specially in the executable - if they have a value, even though
1365  * undefined, we use that value.  This allows us to associate all references
1366  * to a function's address to a single place in the process: the plt entry
1367  * for that function in the executable.  Calls to lookup from plt binding
1368  * routines do NOT set LKUP_SPEC in the flag.
1369  */
1370 Sym *
1371 elf_find_sym(Slookup *slp, Rt_map **dlmp, uint_t *binfo, int *in_nfavl)
1372 {
1373 	const char	*name = slp->sl_name;
1374 	Rt_map		*ilmp = slp->sl_imap;
1375 	ulong_t		hash = slp->sl_hash;
1376 	uint_t		ndx, htmp, buckets, *chainptr;
1377 	Sym		*sym, *symtabptr;
1378 	char		*strtabptr, *strtabname;
1379 	uint_t		flags1;
1380 	Syminfo		*sip;
1381 
1382 	/*
1383 	 * If we're only here to establish a symbols index, skip the diagnostic
1384 	 * used to trace a symbol search.
1385 	 */
1386 	if ((slp->sl_flags & LKUP_SYMNDX) == 0)
1387 		DBG_CALL(Dbg_syms_lookup(ilmp, name, MSG_ORIG(MSG_STR_ELF)));
1388 
1389 	if (HASH(ilmp) == NULL)
1390 		return (NULL);
1391 
1392 	buckets = HASH(ilmp)[0];
1393 	/* LINTED */
1394 	htmp = (uint_t)hash % buckets;
1395 
1396 	/*
1397 	 * Get the first symbol on hash chain and initialize the string
1398 	 * and symbol table pointers.
1399 	 */
1400 	if ((ndx = HASH(ilmp)[htmp + 2]) == 0)
1401 		return (NULL);
1402 
1403 	chainptr = HASH(ilmp) + 2 + buckets;
1404 	strtabptr = STRTAB(ilmp);
1405 	symtabptr = SYMTAB(ilmp);
1406 
1407 	while (ndx) {
1408 		sym = symtabptr + ndx;
1409 		strtabname = strtabptr + sym->st_name;
1410 
1411 		/*
1412 		 * Compare the symbol found with the name required.  If the
1413 		 * names don't match continue with the next hash entry.
1414 		 */
1415 		if ((*strtabname++ != *name) || strcmp(strtabname, &name[1])) {
1416 			if ((ndx = chainptr[ndx]) != 0)
1417 				continue;
1418 			return (NULL);
1419 		}
1420 
1421 		/*
1422 		 * The Solaris ld does not put DT_VERSYM in the dynamic
1423 		 * section, but the GNU ld does. The GNU runtime linker
1424 		 * interprets the top bit of the 16-bit Versym value
1425 		 * (0x8000) as the "hidden" bit. If this bit is set,
1426 		 * the linker is supposed to act as if that symbol does
1427 		 * not exist. The hidden bit supports their versioning
1428 		 * scheme, which allows multiple incompatible functions
1429 		 * with the same name to exist at different versions
1430 		 * within an object. The Solaris linker does not support this
1431 		 * mechanism, or the model of interface evolution that
1432 		 * it allows, but we honor the hidden bit in GNU ld
1433 		 * produced objects in order to interoperate with them.
1434 		 */
1435 		if ((VERSYM(ilmp) != NULL) &&
1436 		    ((VERSYM(ilmp)[ndx] & 0x8000) != 0)) {
1437 			DBG_CALL(Dbg_syms_ignore_gnuver(ilmp, name,
1438 			    ndx, VERSYM(ilmp)[ndx]));
1439 			if ((ndx = chainptr[ndx]) != 0)
1440 				continue;
1441 			return (NULL);
1442 		}
1443 
1444 		/*
1445 		 * If we're only here to establish a symbols index, we're done.
1446 		 */
1447 		if (slp->sl_flags & LKUP_SYMNDX)
1448 			return (sym);
1449 
1450 		/*
1451 		 * If we find a match and the symbol is defined, return the
1452 		 * symbol pointer and the link map in which it was found.
1453 		 */
1454 		if (sym->st_shndx != SHN_UNDEF) {
1455 			*dlmp = ilmp;
1456 			*binfo |= DBG_BINFO_FOUND;
1457 			if ((FLAGS(ilmp) & FLG_RT_OBJINTPO) ||
1458 			    ((FLAGS(ilmp) & FLG_RT_SYMINTPO) &&
1459 			    is_sym_interposer(ilmp, sym)))
1460 				*binfo |= DBG_BINFO_INTERPOSE;
1461 			break;
1462 
1463 		/*
1464 		 * If we find a match and the symbol is undefined, the
1465 		 * symbol type is a function, and the value of the symbol
1466 		 * is non zero, then this is a special case.  This allows
1467 		 * the resolution of a function address to the plt[] entry.
1468 		 * See SPARC ABI, Dynamic Linking, Function Addresses for
1469 		 * more details.
1470 		 */
1471 		} else if ((slp->sl_flags & LKUP_SPEC) &&
1472 		    (FLAGS(ilmp) & FLG_RT_ISMAIN) && (sym->st_value != 0) &&
1473 		    (ELF_ST_TYPE(sym->st_info) == STT_FUNC)) {
1474 			*dlmp = ilmp;
1475 			*binfo |= (DBG_BINFO_FOUND | DBG_BINFO_PLTADDR);
1476 			if ((FLAGS(ilmp) & FLG_RT_OBJINTPO) ||
1477 			    ((FLAGS(ilmp) & FLG_RT_SYMINTPO) &&
1478 			    is_sym_interposer(ilmp, sym)))
1479 				*binfo |= DBG_BINFO_INTERPOSE;
1480 			return (sym);
1481 		}
1482 
1483 		/*
1484 		 * Undefined symbol.
1485 		 */
1486 		return (NULL);
1487 	}
1488 
1489 	/*
1490 	 * We've found a match.  Determine if the defining object contains
1491 	 * symbol binding information.
1492 	 */
1493 	if ((sip = SYMINFO(ilmp)) != NULL)
1494 		sip += ndx;
1495 
1496 	/*
1497 	 * If this definition is a singleton, and we haven't followed a default
1498 	 * symbol search knowing that we're looking for a singleton (presumably
1499 	 * because the symbol definition has been changed since the referring
1500 	 * object was built), then reject this binding so that the caller can
1501 	 * fall back to a standard symbol search.
1502 	 */
1503 	if ((ELF_ST_VISIBILITY(sym->st_other) == STV_SINGLETON) &&
1504 	    (((slp->sl_flags & LKUP_STANDARD) == 0) ||
1505 	    (((slp->sl_flags & LKUP_SINGLETON) == 0) &&
1506 	    (LIST(ilmp)->lm_flags & LML_FLG_GROUPSEXIST)))) {
1507 		DBG_CALL(Dbg_bind_reject(slp->sl_cmap, ilmp, name,
1508 		    DBG_BNDREJ_SINGLE));
1509 		*binfo |= BINFO_REJSINGLE;
1510 		*binfo &= ~DBG_BINFO_MSK;
1511 		return (NULL);
1512 	}
1513 
1514 	/*
1515 	 * If this is a direct binding request, but the symbol definition has
1516 	 * disabled directly binding to it (presumably because the symbol
1517 	 * definition has been changed since the referring object was built),
1518 	 * reject this binding so that the caller can fall back to a standard
1519 	 * symbol search.
1520 	 */
1521 	if (sip && (slp->sl_flags & LKUP_DIRECT) &&
1522 	    (sip->si_flags & SYMINFO_FLG_NOEXTDIRECT)) {
1523 		DBG_CALL(Dbg_bind_reject(slp->sl_cmap, ilmp, name,
1524 		    DBG_BNDREJ_DIRECT));
1525 		*binfo |= BINFO_REJDIRECT;
1526 		*binfo &= ~DBG_BINFO_MSK;
1527 		return (NULL);
1528 	}
1529 
1530 	/*
1531 	 * If this is a binding request within an RTLD_GROUP family, and the
1532 	 * symbol has disabled directly binding to it, reject this binding so
1533 	 * that the caller can fall back to a standard symbol search.
1534 	 *
1535 	 * Effectively, an RTLD_GROUP family achieves what can now be
1536 	 * established with direct bindings.  However, various symbols have
1537 	 * been tagged as inappropriate for direct binding to (ie. libc:malloc).
1538 	 *
1539 	 * A symbol marked as no-direct cannot be used within a group without
1540 	 * first ensuring that the symbol has not been interposed upon outside
1541 	 * of the group.  A common example occurs when users implement their own
1542 	 * version of malloc() in the executable.  Such a malloc() interposes on
1543 	 * the libc:malloc, and this interposition must be honored within the
1544 	 * group as well.
1545 	 *
1546 	 * Following any rejection, LKUP_WORLD is established as a means of
1547 	 * overriding this test as we return to a standard search.
1548 	 */
1549 	if (sip && (sip->si_flags & SYMINFO_FLG_NOEXTDIRECT) &&
1550 	    ((MODE(slp->sl_cmap) & (RTLD_GROUP | RTLD_WORLD)) == RTLD_GROUP) &&
1551 	    ((slp->sl_flags & LKUP_WORLD) == 0)) {
1552 		DBG_CALL(Dbg_bind_reject(slp->sl_cmap, ilmp, name,
1553 		    DBG_BNDREJ_GROUP));
1554 		*binfo |= BINFO_REJGROUP;
1555 		*binfo &= ~DBG_BINFO_MSK;
1556 		return (NULL);
1557 	}
1558 
1559 	/*
1560 	 * Determine whether this object is acting as a filter.
1561 	 */
1562 	if (((flags1 = FLAGS1(ilmp)) & MSK_RT_FILTER) == 0)
1563 		return (sym);
1564 
1565 	/*
1566 	 * Determine if this object offers per-symbol filtering, and if so,
1567 	 * whether this symbol references a filtee.
1568 	 */
1569 	if (sip && (flags1 & (FL1_RT_SYMSFLTR | FL1_RT_SYMAFLTR))) {
1570 		/*
1571 		 * If this is a standard filter reference, and no standard
1572 		 * filtees remain to be inspected, we're done.  If this is an
1573 		 * auxiliary filter reference, and no auxiliary filtees remain,
1574 		 * we'll fall through in case any object filtering is available.
1575 		 */
1576 		if ((sip->si_flags & SYMINFO_FLG_FILTER) &&
1577 		    (SYMSFLTRCNT(ilmp) == 0))
1578 			return (NULL);
1579 
1580 		if ((sip->si_flags & SYMINFO_FLG_FILTER) ||
1581 		    ((sip->si_flags & SYMINFO_FLG_AUXILIARY) &&
1582 		    SYMAFLTRCNT(ilmp))) {
1583 			Sym	*fsym;
1584 
1585 			/*
1586 			 * This symbol has an associated filtee.  Lookup the
1587 			 * symbol in the filtee, and if it is found return it.
1588 			 * If the symbol doesn't exist, and this is a standard
1589 			 * filter, return an error, otherwise fall through to
1590 			 * catch any object filtering that may be available.
1591 			 */
1592 			if ((fsym = elf_lookup_filtee(slp, dlmp, binfo,
1593 			    sip->si_boundto, in_nfavl)) != NULL)
1594 				return (fsym);
1595 			if (sip->si_flags & SYMINFO_FLG_FILTER)
1596 				return (NULL);
1597 		}
1598 	}
1599 
1600 	/*
1601 	 * Determine if this object provides global filtering.
1602 	 */
1603 	if (flags1 & (FL1_RT_OBJSFLTR | FL1_RT_OBJAFLTR)) {
1604 		Sym	*fsym;
1605 
1606 		if (OBJFLTRNDX(ilmp) != FLTR_DISABLED) {
1607 			/*
1608 			 * This object has an associated filtee.  Lookup the
1609 			 * symbol in the filtee, and if it is found return it.
1610 			 * If the symbol doesn't exist, and this is a standard
1611 			 * filter, return and error, otherwise return the symbol
1612 			 * within the filter itself.
1613 			 */
1614 			if ((fsym = elf_lookup_filtee(slp, dlmp, binfo,
1615 			    OBJFLTRNDX(ilmp), in_nfavl)) != NULL)
1616 				return (fsym);
1617 		}
1618 
1619 		if (flags1 & FL1_RT_OBJSFLTR)
1620 			return (NULL);
1621 	}
1622 	return (sym);
1623 }
1624 
1625 /*
1626  * Create a new Rt_map structure for an ELF object and initialize
1627  * all values.
1628  */
1629 Rt_map *
1630 elf_new_lmp(Lm_list *lml, Aliste lmco, Fdesc *fdp, Addr addr, size_t msize,
1631     void *odyn, int *in_nfavl)
1632 {
1633 	const char	*name = fdp->fd_nname;
1634 	Rt_map		*lmp;
1635 	Ehdr		*ehdr = (Ehdr *)addr;
1636 	Phdr		*phdr, *tphdr = NULL, *dphdr = NULL, *uphdr = NULL;
1637 	Dyn		*dyn = (Dyn *)odyn;
1638 	Cap		*cap = NULL;
1639 	int		ndx;
1640 	Addr		base, fltr = 0, audit = 0, cfile = 0, crle = 0;
1641 	Xword		rpath = 0;
1642 	size_t		lmsz, rtsz, epsz, dynsz = 0;
1643 	uint_t		dyncnt = 0;
1644 
1645 	DBG_CALL(Dbg_file_elf(lml, name, addr, msize, lml->lm_lmidstr, lmco));
1646 
1647 	/*
1648 	 * If this is a shared object, the base address of the shared object is
1649 	 * added to all address values defined within the object.  Otherwise, if
1650 	 * this is an executable, all object addresses are used as is.
1651 	 */
1652 	if (ehdr->e_type == ET_EXEC)
1653 		base = 0;
1654 	else
1655 		base = addr;
1656 
1657 	/*
1658 	 * Traverse the program header table, picking off required items.  This
1659 	 * traversal also provides for the sizing of the PT_DYNAMIC section.
1660 	 */
1661 	phdr = (Phdr *)((uintptr_t)ehdr + ehdr->e_phoff);
1662 	for (ndx = 0; ndx < (int)ehdr->e_phnum; ndx++,
1663 	    phdr = (Phdr *)((uintptr_t)phdr + ehdr->e_phentsize)) {
1664 		switch (phdr->p_type) {
1665 		case PT_DYNAMIC:
1666 			dphdr = phdr;
1667 			dyn = (Dyn *)((uintptr_t)phdr->p_vaddr + base);
1668 			break;
1669 		case PT_TLS:
1670 			tphdr = phdr;
1671 			break;
1672 		case PT_SUNWCAP:
1673 			cap = (Cap *)((uintptr_t)phdr->p_vaddr + base);
1674 			break;
1675 		case PT_SUNW_UNWIND:
1676 			uphdr = phdr;
1677 			break;
1678 		default:
1679 			break;
1680 		}
1681 	}
1682 
1683 	/*
1684 	 * Determine the number of PT_DYNAMIC entries for the DYNINFO()
1685 	 * allocation.  Sadly, this is a little larger than we really need,
1686 	 * as there are typically padding DT_NULL entries.  However, adding
1687 	 * this data to the initial link-map allocation is a win.
1688 	 */
1689 	if (dyn) {
1690 		dyncnt = dphdr->p_filesz / sizeof (Dyn);
1691 		dynsz = dyncnt * sizeof (Dyninfo);
1692 	}
1693 
1694 	/*
1695 	 * Allocate space for the link-map, private elf information, and
1696 	 * DYNINFO() data.  Once these are allocated and initialized,
1697 	 * remove_so(0, lmp) can be used to tear down the link-map allocation
1698 	 * should any failures occur.
1699 	 */
1700 	rtsz = S_DROUND(sizeof (Rt_map));
1701 	epsz = S_DROUND(sizeof (Rt_elfp));
1702 	lmsz = rtsz + epsz + dynsz;
1703 	if ((lmp = calloc(lmsz, 1)) == NULL)
1704 		return (NULL);
1705 	ELFPRV(lmp) = (void *)((uintptr_t)lmp + rtsz);
1706 	DYNINFO(lmp) = (Dyninfo *)((uintptr_t)lmp + rtsz + epsz);
1707 	LMSIZE(lmp) = lmsz;
1708 
1709 	/*
1710 	 * All fields not filled in were set to 0 by calloc.
1711 	 */
1712 	NAME(lmp) = (char *)name;
1713 	ADDR(lmp) = addr;
1714 	MSIZE(lmp) = msize;
1715 	SYMINTP(lmp) = elf_find_sym;
1716 	FCT(lmp) = &elf_fct;
1717 	LIST(lmp) = lml;
1718 	OBJFLTRNDX(lmp) = FLTR_DISABLED;
1719 	SORTVAL(lmp) = -1;
1720 	DYN(lmp) = dyn;
1721 	DYNINFOCNT(lmp) = dyncnt;
1722 	PTUNWIND(lmp) = uphdr;
1723 
1724 	if (ehdr->e_type == ET_EXEC)
1725 		FLAGS(lmp) |= FLG_RT_FIXED;
1726 
1727 	/*
1728 	 * Fill in rest of the link map entries with information from the file's
1729 	 * dynamic structure.
1730 	 */
1731 	if (dyn) {
1732 		uint_t		dynndx = 0;
1733 		Xword		pltpadsz = 0;
1734 		Rti_desc	*rti;
1735 
1736 		/* CSTYLED */
1737 		for ( ; dyn->d_tag != DT_NULL; ++dyn, dynndx++) {
1738 			switch ((Xword)dyn->d_tag) {
1739 			case DT_SYMTAB:
1740 				SYMTAB(lmp) = (void *)(dyn->d_un.d_ptr + base);
1741 				break;
1742 			case DT_SUNW_SYMTAB:
1743 				SUNWSYMTAB(lmp) =
1744 				    (void *)(dyn->d_un.d_ptr + base);
1745 				break;
1746 			case DT_SUNW_SYMSZ:
1747 				SUNWSYMSZ(lmp) = dyn->d_un.d_val;
1748 				break;
1749 			case DT_STRTAB:
1750 				STRTAB(lmp) = (void *)(dyn->d_un.d_ptr + base);
1751 				break;
1752 			case DT_SYMENT:
1753 				SYMENT(lmp) = dyn->d_un.d_val;
1754 				break;
1755 			case DT_FEATURE_1:
1756 				dyn->d_un.d_val |= DTF_1_PARINIT;
1757 				if (dyn->d_un.d_val & DTF_1_CONFEXP)
1758 					crle = 1;
1759 				break;
1760 			case DT_MOVESZ:
1761 				MOVESZ(lmp) = dyn->d_un.d_val;
1762 				FLAGS(lmp) |= FLG_RT_MOVE;
1763 				break;
1764 			case DT_MOVEENT:
1765 				MOVEENT(lmp) = dyn->d_un.d_val;
1766 				break;
1767 			case DT_MOVETAB:
1768 				MOVETAB(lmp) = (void *)(dyn->d_un.d_ptr + base);
1769 				break;
1770 			case DT_REL:
1771 			case DT_RELA:
1772 				/*
1773 				 * At this time, ld.so. can only handle one
1774 				 * type of relocation per object.
1775 				 */
1776 				REL(lmp) = (void *)(dyn->d_un.d_ptr + base);
1777 				break;
1778 			case DT_RELSZ:
1779 			case DT_RELASZ:
1780 				RELSZ(lmp) = dyn->d_un.d_val;
1781 				break;
1782 			case DT_RELENT:
1783 			case DT_RELAENT:
1784 				RELENT(lmp) = dyn->d_un.d_val;
1785 				break;
1786 			case DT_RELCOUNT:
1787 			case DT_RELACOUNT:
1788 				RELACOUNT(lmp) = (uint_t)dyn->d_un.d_val;
1789 				break;
1790 			case DT_HASH:
1791 				HASH(lmp) = (uint_t *)(dyn->d_un.d_ptr + base);
1792 				break;
1793 			case DT_PLTGOT:
1794 				PLTGOT(lmp) =
1795 				    (uint_t *)(dyn->d_un.d_ptr + base);
1796 				break;
1797 			case DT_PLTRELSZ:
1798 				PLTRELSZ(lmp) = dyn->d_un.d_val;
1799 				break;
1800 			case DT_JMPREL:
1801 				JMPREL(lmp) = (void *)(dyn->d_un.d_ptr + base);
1802 				break;
1803 			case DT_INIT:
1804 				if (dyn->d_un.d_ptr != NULL)
1805 					INIT(lmp) =
1806 					    (void (*)())(dyn->d_un.d_ptr +
1807 					    base);
1808 				break;
1809 			case DT_FINI:
1810 				if (dyn->d_un.d_ptr != NULL)
1811 					FINI(lmp) =
1812 					    (void (*)())(dyn->d_un.d_ptr +
1813 					    base);
1814 				break;
1815 			case DT_INIT_ARRAY:
1816 				INITARRAY(lmp) = (Addr *)(dyn->d_un.d_ptr +
1817 				    base);
1818 				break;
1819 			case DT_INIT_ARRAYSZ:
1820 				INITARRAYSZ(lmp) = (uint_t)dyn->d_un.d_val;
1821 				break;
1822 			case DT_FINI_ARRAY:
1823 				FINIARRAY(lmp) = (Addr *)(dyn->d_un.d_ptr +
1824 				    base);
1825 				break;
1826 			case DT_FINI_ARRAYSZ:
1827 				FINIARRAYSZ(lmp) = (uint_t)dyn->d_un.d_val;
1828 				break;
1829 			case DT_PREINIT_ARRAY:
1830 				PREINITARRAY(lmp) = (Addr *)(dyn->d_un.d_ptr +
1831 				    base);
1832 				break;
1833 			case DT_PREINIT_ARRAYSZ:
1834 				PREINITARRAYSZ(lmp) = (uint_t)dyn->d_un.d_val;
1835 				break;
1836 			case DT_RPATH:
1837 			case DT_RUNPATH:
1838 				rpath = dyn->d_un.d_val;
1839 				break;
1840 			case DT_FILTER:
1841 				fltr = dyn->d_un.d_val;
1842 				OBJFLTRNDX(lmp) = dynndx;
1843 				FLAGS1(lmp) |= FL1_RT_OBJSFLTR;
1844 				break;
1845 			case DT_AUXILIARY:
1846 				if (!(rtld_flags & RT_FL_NOAUXFLTR)) {
1847 					fltr = dyn->d_un.d_val;
1848 					OBJFLTRNDX(lmp) = dynndx;
1849 				}
1850 				FLAGS1(lmp) |= FL1_RT_OBJAFLTR;
1851 				break;
1852 			case DT_SUNW_FILTER:
1853 				SYMSFLTRCNT(lmp)++;
1854 				FLAGS1(lmp) |= FL1_RT_SYMSFLTR;
1855 				break;
1856 			case DT_SUNW_AUXILIARY:
1857 				if (!(rtld_flags & RT_FL_NOAUXFLTR)) {
1858 					SYMAFLTRCNT(lmp)++;
1859 				}
1860 				FLAGS1(lmp) |= FL1_RT_SYMAFLTR;
1861 				break;
1862 			case DT_DEPAUDIT:
1863 				if (!(rtld_flags & RT_FL_NOAUDIT))
1864 					audit = dyn->d_un.d_val;
1865 				break;
1866 			case DT_CONFIG:
1867 				cfile = dyn->d_un.d_val;
1868 				break;
1869 			case DT_DEBUG:
1870 				/*
1871 				 * DT_DEBUG entries are only created in
1872 				 * dynamic objects that require an interpretor
1873 				 * (ie. all dynamic executables and some shared
1874 				 * objects), and provide for a hand-shake with
1875 				 * debuggers.  This entry is initialized to
1876 				 * zero by the link-editor.  If a debugger has
1877 				 * us and updated this entry set the debugger
1878 				 * flag, and finish initializing the debugging
1879 				 * structure (see setup() also).  Switch off any
1880 				 * configuration object use as most debuggers
1881 				 * can't handle fixed dynamic executables as
1882 				 * dependencies, and we can't handle requests
1883 				 * like object padding for alternative objects.
1884 				 */
1885 				if (dyn->d_un.d_ptr)
1886 					rtld_flags |=
1887 					    (RT_FL_DEBUGGER | RT_FL_NOOBJALT);
1888 				dyn->d_un.d_ptr = (Addr)&r_debug;
1889 				break;
1890 			case DT_VERNEED:
1891 				VERNEED(lmp) = (Verneed *)(dyn->d_un.d_ptr +
1892 				    base);
1893 				break;
1894 			case DT_VERNEEDNUM:
1895 				/* LINTED */
1896 				VERNEEDNUM(lmp) = (int)dyn->d_un.d_val;
1897 				break;
1898 			case DT_VERDEF:
1899 				VERDEF(lmp) = (Verdef *)(dyn->d_un.d_ptr +
1900 				    base);
1901 				break;
1902 			case DT_VERDEFNUM:
1903 				/* LINTED */
1904 				VERDEFNUM(lmp) = (int)dyn->d_un.d_val;
1905 				break;
1906 			case DT_VERSYM:
1907 				/*
1908 				 * The Solaris ld does not produce DT_VERSYM,
1909 				 * but the GNU ld does, in order to support
1910 				 * their style of versioning, which differs
1911 				 * from ours in some ways, while using the
1912 				 * same data structures. The presence of
1913 				 * DT_VERSYM therefore means that GNU
1914 				 * versioning rules apply to the given file.
1915 				 * If DT_VERSYM is not present, then Solaris
1916 				 * versioning rules apply.
1917 				 */
1918 				VERSYM(lmp) = (Versym *)(dyn->d_un.d_ptr +
1919 				    base);
1920 				break;
1921 			case DT_BIND_NOW:
1922 				if ((dyn->d_un.d_val & DF_BIND_NOW) &&
1923 				    ((rtld_flags2 & RT_FL2_BINDLAZY) == 0)) {
1924 					MODE(lmp) |= RTLD_NOW;
1925 					MODE(lmp) &= ~RTLD_LAZY;
1926 				}
1927 				break;
1928 			case DT_FLAGS:
1929 				FLAGS1(lmp) |= FL1_RT_DTFLAGS;
1930 				if (dyn->d_un.d_val & DF_SYMBOLIC)
1931 					FLAGS1(lmp) |= FL1_RT_SYMBOLIC;
1932 				if ((dyn->d_un.d_val & DF_BIND_NOW) &&
1933 				    ((rtld_flags2 & RT_FL2_BINDLAZY) == 0)) {
1934 					MODE(lmp) |= RTLD_NOW;
1935 					MODE(lmp) &= ~RTLD_LAZY;
1936 				}
1937 				/*
1938 				 * Capture any static TLS use, and enforce that
1939 				 * this object be non-deletable.
1940 				 */
1941 				if (dyn->d_un.d_val & DF_STATIC_TLS) {
1942 					FLAGS1(lmp) |= FL1_RT_TLSSTAT;
1943 					MODE(lmp) |= RTLD_NODELETE;
1944 				}
1945 				break;
1946 			case DT_FLAGS_1:
1947 				if (dyn->d_un.d_val & DF_1_DISPRELPND)
1948 					FLAGS1(lmp) |= FL1_RT_DISPREL;
1949 				if (dyn->d_un.d_val & DF_1_GROUP)
1950 					FLAGS(lmp) |=
1951 					    (FLG_RT_SETGROUP | FLG_RT_HANDLE);
1952 				if ((dyn->d_un.d_val & DF_1_NOW) &&
1953 				    ((rtld_flags2 & RT_FL2_BINDLAZY) == 0)) {
1954 					MODE(lmp) |= RTLD_NOW;
1955 					MODE(lmp) &= ~RTLD_LAZY;
1956 				}
1957 				if (dyn->d_un.d_val & DF_1_NODELETE)
1958 					MODE(lmp) |= RTLD_NODELETE;
1959 				if (dyn->d_un.d_val & DF_1_INITFIRST)
1960 					FLAGS(lmp) |= FLG_RT_INITFRST;
1961 				if (dyn->d_un.d_val & DF_1_NOOPEN)
1962 					FLAGS(lmp) |= FLG_RT_NOOPEN;
1963 				if (dyn->d_un.d_val & DF_1_LOADFLTR)
1964 					FLAGS(lmp) |= FLG_RT_LOADFLTR;
1965 				if (dyn->d_un.d_val & DF_1_NODUMP)
1966 					FLAGS(lmp) |= FLG_RT_NODUMP;
1967 				if (dyn->d_un.d_val & DF_1_CONFALT)
1968 					crle = 1;
1969 				if (dyn->d_un.d_val & DF_1_DIRECT)
1970 					FLAGS1(lmp) |= FL1_RT_DIRECT;
1971 				if (dyn->d_un.d_val & DF_1_NODEFLIB)
1972 					FLAGS1(lmp) |= FL1_RT_NODEFLIB;
1973 				if (dyn->d_un.d_val & DF_1_ENDFILTEE)
1974 					FLAGS1(lmp) |= FL1_RT_ENDFILTE;
1975 				if (dyn->d_un.d_val & DF_1_TRANS)
1976 					FLAGS(lmp) |= FLG_RT_TRANS;
1977 
1978 				/*
1979 				 * Global auditing is only meaningful when
1980 				 * specified by the initiating object of the
1981 				 * process - typically the dynamic executable.
1982 				 * If this is the initiaiting object, its link-
1983 				 * map will not yet have been added to the
1984 				 * link-map list, and consequently the link-map
1985 				 * list is empty.  (see setup()).
1986 				 */
1987 				if (dyn->d_un.d_val & DF_1_GLOBAUDIT) {
1988 					if (lml_main.lm_head == NULL)
1989 						FLAGS1(lmp) |= FL1_RT_GLOBAUD;
1990 					else
1991 						DBG_CALL(Dbg_audit_ignore(lmp));
1992 				}
1993 
1994 				/*
1995 				 * If this object identifies itself as an
1996 				 * interposer, but relocation processing has
1997 				 * already started, then demote it.  It's too
1998 				 * late to guarantee complete interposition.
1999 				 */
2000 				/* BEGIN CSTYLED */
2001 				if (dyn->d_un.d_val &
2002 				    (DF_1_INTERPOSE | DF_1_SYMINTPOSE)) {
2003 				    if (lml->lm_flags & LML_FLG_STARTREL) {
2004 					DBG_CALL(Dbg_util_intoolate(lmp));
2005 					if (lml->lm_flags & LML_FLG_TRC_ENABLE)
2006 					    (void) printf(
2007 						MSG_INTL(MSG_LDD_REL_ERR2),
2008 						NAME(lmp));
2009 				    } else if (dyn->d_un.d_val & DF_1_INTERPOSE)
2010 					FLAGS(lmp) |= FLG_RT_OBJINTPO;
2011 				    else
2012 					FLAGS(lmp) |= FLG_RT_SYMINTPO;
2013 				}
2014 				/* END CSTYLED */
2015 				break;
2016 			case DT_SYMINFO:
2017 				SYMINFO(lmp) = (Syminfo *)(dyn->d_un.d_ptr +
2018 				    base);
2019 				break;
2020 			case DT_SYMINENT:
2021 				SYMINENT(lmp) = dyn->d_un.d_val;
2022 				break;
2023 			case DT_PLTPAD:
2024 				PLTPAD(lmp) = (void *)(dyn->d_un.d_ptr + base);
2025 				break;
2026 			case DT_PLTPADSZ:
2027 				pltpadsz = dyn->d_un.d_val;
2028 				break;
2029 			case DT_SUNW_RTLDINF:
2030 				/*
2031 				 * Maintain a list of RTLDINFO structures.
2032 				 * Typically, libc is the only supplier, and
2033 				 * only one structure is provided.  However,
2034 				 * multiple suppliers and multiple structures
2035 				 * are supported.  For example, one structure
2036 				 * may provide thread_init, and another
2037 				 * structure may provide atexit reservations.
2038 				 */
2039 				if ((rti = alist_append(&lml->lm_rti, 0,
2040 				    sizeof (Rti_desc),
2041 				    AL_CNT_RTLDINFO)) == NULL) {
2042 					remove_so(0, lmp);
2043 					return (NULL);
2044 				}
2045 				rti->rti_lmp = lmp;
2046 				rti->rti_info = (void *)(dyn->d_un.d_ptr +
2047 				    base);
2048 				break;
2049 			case DT_SUNW_SORTENT:
2050 				SUNWSORTENT(lmp) = dyn->d_un.d_val;
2051 				break;
2052 			case DT_SUNW_SYMSORT:
2053 				SUNWSYMSORT(lmp) =
2054 				    (void *)(dyn->d_un.d_ptr + base);
2055 				break;
2056 			case DT_SUNW_SYMSORTSZ:
2057 				SUNWSYMSORTSZ(lmp) = dyn->d_un.d_val;
2058 				break;
2059 			case DT_DEPRECATED_SPARC_REGISTER:
2060 			case M_DT_REGISTER:
2061 				FLAGS(lmp) |= FLG_RT_REGSYMS;
2062 				break;
2063 			}
2064 		}
2065 
2066 		if (PLTPAD(lmp)) {
2067 			if (pltpadsz == (Xword)0)
2068 				PLTPAD(lmp) = NULL;
2069 			else
2070 				PLTPADEND(lmp) = (void *)((Addr)PLTPAD(lmp) +
2071 				    pltpadsz);
2072 		}
2073 	}
2074 
2075 	/*
2076 	 * A dynsym contains only global functions. We want to have
2077 	 * a version of it that also includes local functions, so that
2078 	 * dladdr() will be able to report names for local functions
2079 	 * when used to generate a stack trace for a stripped file.
2080 	 * This version of the dynsym is provided via DT_SUNW_SYMTAB.
2081 	 *
2082 	 * In producing DT_SUNW_SYMTAB, ld uses a non-obvious trick
2083 	 * in order to avoid having to have two copies of the global
2084 	 * symbols held in DT_SYMTAB: The local symbols are placed in
2085 	 * a separate section than the globals in the dynsym, but the
2086 	 * linker conspires to put the data for these two sections adjacent
2087 	 * to each other. DT_SUNW_SYMTAB points at the top of the local
2088 	 * symbols, and DT_SUNW_SYMSZ is the combined length of both tables.
2089 	 *
2090 	 * If the two sections are not adjacent, then something went wrong
2091 	 * at link time. We use ASSERT to kill the process if this is
2092 	 * a debug build. In a production build, we will silently ignore
2093 	 * the presence of the .ldynsym and proceed. We can detect this
2094 	 * situation by checking to see that DT_SYMTAB lies in
2095 	 * the range given by DT_SUNW_SYMTAB/DT_SUNW_SYMSZ.
2096 	 */
2097 	if ((SUNWSYMTAB(lmp) != NULL) &&
2098 	    (((char *)SYMTAB(lmp) <= (char *)SUNWSYMTAB(lmp)) ||
2099 	    (((char *)SYMTAB(lmp) >=
2100 	    (SUNWSYMSZ(lmp) + (char *)SUNWSYMTAB(lmp)))))) {
2101 		ASSERT(0);
2102 		SUNWSYMTAB(lmp) = NULL;
2103 		SUNWSYMSZ(lmp) = 0;
2104 	}
2105 
2106 	/*
2107 	 * If configuration file use hasn't been disabled, and a configuration
2108 	 * file hasn't already been set via an environment variable, see if any
2109 	 * application specific configuration file is specified.  An LD_CONFIG
2110 	 * setting is used first, but if this image was generated via crle(1)
2111 	 * then a default configuration file is a fall-back.
2112 	 */
2113 	if ((!(rtld_flags & RT_FL_NOCFG)) && (config->c_name == NULL)) {
2114 		if (cfile)
2115 			config->c_name = (const char *)(cfile +
2116 			    (char *)STRTAB(lmp));
2117 		else if (crle)
2118 			rtld_flags |= RT_FL_CONFAPP;
2119 	}
2120 
2121 	if (rpath)
2122 		RPATH(lmp) = (char *)(rpath + (char *)STRTAB(lmp));
2123 	if (fltr)
2124 		REFNAME(lmp) = (char *)(fltr + (char *)STRTAB(lmp));
2125 
2126 	/*
2127 	 * For Intel ABI compatibility.  It's possible that a JMPREL can be
2128 	 * specified without any other relocations (e.g. a dynamic executable
2129 	 * normally only contains .plt relocations).  If this is the case then
2130 	 * no REL, RELSZ or RELENT will have been created.  For us to be able
2131 	 * to traverse the .plt relocations under LD_BIND_NOW we need to know
2132 	 * the RELENT for these relocations.  Refer to elf_reloc() for more
2133 	 * details.
2134 	 */
2135 	if (!RELENT(lmp) && JMPREL(lmp))
2136 		RELENT(lmp) = sizeof (M_RELOC);
2137 
2138 	/*
2139 	 * Establish any per-object auditing.  If we're establishing `main's
2140 	 * link-map its too early to go searching for audit objects so just
2141 	 * hold the object name for later (see setup()).
2142 	 */
2143 	if (audit) {
2144 		char	*cp = audit + (char *)STRTAB(lmp);
2145 
2146 		if (*cp) {
2147 			if (((AUDITORS(lmp) =
2148 			    calloc(1, sizeof (Audit_desc))) == NULL) ||
2149 			    ((AUDITORS(lmp)->ad_name = strdup(cp)) == NULL)) {
2150 				remove_so(0, lmp);
2151 				return (NULL);
2152 			}
2153 			if (lml_main.lm_head) {
2154 				if (audit_setup(lmp, AUDITORS(lmp), 0,
2155 				    in_nfavl) == 0) {
2156 					remove_so(0, lmp);
2157 					return (NULL);
2158 				}
2159 				AFLAGS(lmp) |= AUDITORS(lmp)->ad_flags;
2160 				lml->lm_flags |= LML_FLG_LOCAUDIT;
2161 			}
2162 		}
2163 	}
2164 
2165 	if (tphdr && (tls_assign(lml, lmp, tphdr) == 0)) {
2166 		remove_so(0, lmp);
2167 		return (NULL);
2168 	}
2169 
2170 	if (cap)
2171 		cap_assign(cap, lmp);
2172 
2173 	/*
2174 	 * Add the mapped object to the end of the link map list.
2175 	 */
2176 	lm_append(lml, lmco, lmp);
2177 
2178 	/*
2179 	 * Start the system loading in the ELF information we'll be processing.
2180 	 */
2181 	if (REL(lmp)) {
2182 		(void) madvise((void *)ADDR(lmp), (uintptr_t)REL(lmp) +
2183 		    (uintptr_t)RELSZ(lmp) - (uintptr_t)ADDR(lmp),
2184 		    MADV_WILLNEED);
2185 	}
2186 	return (lmp);
2187 }
2188 
2189 /*
2190  * Assign hardware/software capabilities.
2191  */
2192 void
2193 cap_assign(Cap *cap, Rt_map *lmp)
2194 {
2195 	while (cap->c_tag != CA_SUNW_NULL) {
2196 		switch (cap->c_tag) {
2197 		case CA_SUNW_HW_1:
2198 			HWCAP(lmp) = cap->c_un.c_val;
2199 			break;
2200 		case CA_SUNW_SF_1:
2201 			SFCAP(lmp) = cap->c_un.c_val;
2202 		}
2203 		cap++;
2204 	}
2205 }
2206 
2207 /*
2208  * Build full pathname of shared object from given directory name and filename.
2209  */
2210 static char *
2211 elf_get_so(const char *dir, const char *file, size_t dlen, size_t flen)
2212 {
2213 	static char	pname[PATH_MAX];
2214 
2215 	(void) strncpy(pname, dir, dlen);
2216 	pname[dlen++] = '/';
2217 	(void) strncpy(&pname[dlen], file, flen + 1);
2218 	return (pname);
2219 }
2220 
2221 /*
2222  * The copy relocation is recorded in a copy structure which will be applied
2223  * after all other relocations are carried out.  This provides for copying data
2224  * that must be relocated itself (ie. pointers in shared objects).  This
2225  * structure also provides a means of binding RTLD_GROUP dependencies to any
2226  * copy relocations that have been taken from any group members.
2227  *
2228  * If the size of the .bss area available for the copy information is not the
2229  * same as the source of the data inform the user if we're under ldd(1) control
2230  * (this checking was only established in 5.3, so by only issuing an error via
2231  * ldd(1) we maintain the standard set by previous releases).
2232  */
2233 int
2234 elf_copy_reloc(char *name, Sym *rsym, Rt_map *rlmp, void *radd, Sym *dsym,
2235     Rt_map *dlmp, const void *dadd)
2236 {
2237 	Rel_copy	rc;
2238 	Lm_list		*lml = LIST(rlmp);
2239 
2240 	rc.r_name = name;
2241 	rc.r_rsym = rsym;		/* the new reference symbol and its */
2242 	rc.r_rlmp = rlmp;		/*	associated link-map */
2243 	rc.r_dlmp = dlmp;		/* the defining link-map */
2244 	rc.r_dsym = dsym;		/* the original definition */
2245 	rc.r_radd = radd;
2246 	rc.r_dadd = dadd;
2247 
2248 	if (rsym->st_size > dsym->st_size)
2249 		rc.r_size = (size_t)dsym->st_size;
2250 	else
2251 		rc.r_size = (size_t)rsym->st_size;
2252 
2253 	if (alist_append(&COPY_R(dlmp), &rc, sizeof (Rel_copy),
2254 	    AL_CNT_COPYREL) == NULL) {
2255 		if (!(lml->lm_flags & LML_FLG_TRC_WARN))
2256 			return (0);
2257 		else
2258 			return (1);
2259 	}
2260 	if (!(FLAGS1(dlmp) & FL1_RT_COPYTOOK)) {
2261 		if (aplist_append(&COPY_S(rlmp), dlmp,
2262 		    AL_CNT_COPYREL) == NULL) {
2263 			if (!(lml->lm_flags & LML_FLG_TRC_WARN))
2264 				return (0);
2265 			else
2266 				return (1);
2267 		}
2268 		FLAGS1(dlmp) |= FL1_RT_COPYTOOK;
2269 	}
2270 
2271 	/*
2272 	 * If we are tracing (ldd), warn the user if
2273 	 *	1) the size from the reference symbol differs from the
2274 	 *	   copy definition. We can only copy as much data as the
2275 	 *	   reference (dynamic executables) entry allows.
2276 	 *	2) the copy definition has STV_PROTECTED visibility.
2277 	 */
2278 	if (lml->lm_flags & LML_FLG_TRC_WARN) {
2279 		if (rsym->st_size != dsym->st_size) {
2280 			(void) printf(MSG_INTL(MSG_LDD_CPY_SIZDIF),
2281 			    _conv_reloc_type(M_R_COPY), demangle(name),
2282 			    NAME(rlmp), EC_XWORD(rsym->st_size),
2283 			    NAME(dlmp), EC_XWORD(dsym->st_size));
2284 			if (rsym->st_size > dsym->st_size)
2285 				(void) printf(MSG_INTL(MSG_LDD_CPY_INSDATA),
2286 				    NAME(dlmp));
2287 			else
2288 				(void) printf(MSG_INTL(MSG_LDD_CPY_DATRUNC),
2289 				    NAME(rlmp));
2290 		}
2291 
2292 		if (ELF_ST_VISIBILITY(dsym->st_other) == STV_PROTECTED) {
2293 			(void) printf(MSG_INTL(MSG_LDD_CPY_PROT),
2294 			    _conv_reloc_type(M_R_COPY), demangle(name),
2295 			    NAME(dlmp));
2296 		}
2297 	}
2298 
2299 	DBG_CALL(Dbg_reloc_apply_val(lml, ELF_DBG_RTLD, (Xword)radd,
2300 	    (Xword)rc.r_size));
2301 	return (1);
2302 }
2303 
2304 /*
2305  * Determine the symbol location of an address within a link-map.  Look for
2306  * the nearest symbol (whose value is less than or equal to the required
2307  * address).  This is the object specific part of dladdr().
2308  */
2309 static void
2310 elf_dladdr(ulong_t addr, Rt_map *lmp, Dl_info *dlip, void **info, int flags)
2311 {
2312 	ulong_t		ndx, cnt, base, _value;
2313 	Sym		*sym, *_sym = NULL;
2314 	const char	*str;
2315 	int		_flags;
2316 	uint_t		*dynaddr_ndx;
2317 	uint_t		dynaddr_n = 0;
2318 	ulong_t		value;
2319 
2320 	/*
2321 	 * If SUNWSYMTAB() is non-NULL, then it sees a special version of
2322 	 * the dynsym that starts with any local function symbols that exist in
2323 	 * the library and then moves to the data held in SYMTAB(). In this
2324 	 * case, SUNWSYMSZ tells us how long the symbol table is. The
2325 	 * availability of local function symbols will enhance the results
2326 	 * we can provide.
2327 	 *
2328 	 * If SUNWSYMTAB() is non-NULL, then there might also be a
2329 	 * SUNWSYMSORT() vector associated with it. SUNWSYMSORT() contains
2330 	 * an array of indices into SUNWSYMTAB, sorted by increasing
2331 	 * address. We can use this to do an O(log N) search instead of a
2332 	 * brute force search.
2333 	 *
2334 	 * If SUNWSYMTAB() is NULL, then SYMTAB() references a dynsym that
2335 	 * contains only global symbols. In that case, the length of
2336 	 * the symbol table comes from the nchain field of the related
2337 	 * symbol lookup hash table.
2338 	 */
2339 	str = STRTAB(lmp);
2340 	if (SUNWSYMSZ(lmp) == NULL) {
2341 		sym = SYMTAB(lmp);
2342 		/*
2343 		 * If we don't have a .hash table there are no symbols
2344 		 * to look at.
2345 		 */
2346 		if (HASH(lmp) == NULL)
2347 			return;
2348 		cnt = HASH(lmp)[1];
2349 	} else {
2350 		sym = SUNWSYMTAB(lmp);
2351 		cnt = SUNWSYMSZ(lmp) / SYMENT(lmp);
2352 		dynaddr_ndx = SUNWSYMSORT(lmp);
2353 		if (dynaddr_ndx != NULL)
2354 			dynaddr_n = SUNWSYMSORTSZ(lmp) / SUNWSORTENT(lmp);
2355 	}
2356 
2357 	if (FLAGS(lmp) & FLG_RT_FIXED)
2358 		base = 0;
2359 	else
2360 		base = ADDR(lmp);
2361 
2362 	if (dynaddr_n > 0) {		/* Binary search */
2363 		long	low = 0, low_bnd;
2364 		long	high = dynaddr_n - 1, high_bnd;
2365 		long	mid;
2366 		Sym	*mid_sym;
2367 
2368 		/*
2369 		 * Note that SUNWSYMSORT only contains symbols types that
2370 		 * supply memory addresses, so there's no need to check and
2371 		 * filter out any other types.
2372 		 */
2373 		low_bnd = low;
2374 		high_bnd = high;
2375 		while (low <= high) {
2376 			mid = (low + high) / 2;
2377 			mid_sym = &sym[dynaddr_ndx[mid]];
2378 			value = mid_sym->st_value + base;
2379 			if (addr < value) {
2380 				if ((sym[dynaddr_ndx[high]].st_value + base) >=
2381 				    addr)
2382 					high_bnd = high;
2383 				high = mid - 1;
2384 			} else if (addr > value) {
2385 				if ((sym[dynaddr_ndx[low]].st_value + base) <=
2386 				    addr)
2387 					low_bnd = low;
2388 				low = mid + 1;
2389 			} else {
2390 				_sym = mid_sym;
2391 				_value = value;
2392 				break;
2393 			}
2394 		}
2395 		/*
2396 		 * If the above didn't find it exactly, then we must
2397 		 * return the closest symbol with a value that doesn't
2398 		 * exceed the one we are looking for. If that symbol exists,
2399 		 * it will lie in the range bounded by low_bnd and
2400 		 * high_bnd. This is a linear search, but a short one.
2401 		 */
2402 		if (_sym == NULL) {
2403 			for (mid = low_bnd; mid <= high_bnd; mid++) {
2404 				mid_sym = &sym[dynaddr_ndx[mid]];
2405 				value = mid_sym->st_value + base;
2406 				if (addr >= value) {
2407 					_sym = mid_sym;
2408 					_value = value;
2409 				} else {
2410 					break;
2411 				}
2412 			}
2413 		}
2414 	} else {			/* Linear search */
2415 		for (_value = 0, sym++, ndx = 1; ndx < cnt; ndx++, sym++) {
2416 			/*
2417 			 * Skip expected symbol types that are not functions
2418 			 * or data:
2419 			 *	- A symbol table starts with an undefined symbol
2420 			 *		in slot 0. If we are using SUNWSYMTAB(),
2421 			 *		there will be a second undefined symbol
2422 			 *		right before the globals.
2423 			 *	- The local part of SUNWSYMTAB() contains a
2424 			 *		series of function symbols. Each section
2425 			 *		starts with an initial STT_FILE symbol.
2426 			 */
2427 			if ((sym->st_shndx == SHN_UNDEF) ||
2428 			    (ELF_ST_TYPE(sym->st_info) == STT_FILE))
2429 				continue;
2430 
2431 			value = sym->st_value + base;
2432 			if (value > addr)
2433 				continue;
2434 			if (value < _value)
2435 				continue;
2436 
2437 			_sym = sym;
2438 			_value = value;
2439 
2440 			/*
2441 			 * Note, because we accept local and global symbols
2442 			 * we could find a section symbol that matches the
2443 			 * associated address, which means that the symbol
2444 			 * name will be null.  In this case continue the
2445 			 * search in case we can find a global symbol of
2446 			 * the same value.
2447 			 */
2448 			if ((value == addr) &&
2449 			    (ELF_ST_TYPE(sym->st_info) != STT_SECTION))
2450 				break;
2451 		}
2452 	}
2453 
2454 	_flags = flags & RTLD_DL_MASK;
2455 	if (_sym) {
2456 		if (_flags == RTLD_DL_SYMENT)
2457 			*info = (void *)_sym;
2458 		else if (_flags == RTLD_DL_LINKMAP)
2459 			*info = (void *)lmp;
2460 
2461 		dlip->dli_sname = str + _sym->st_name;
2462 		dlip->dli_saddr = (void *)_value;
2463 	} else {
2464 		/*
2465 		 * addr lies between the beginning of the mapped segment and
2466 		 * the first global symbol. We have no symbol to return
2467 		 * and the caller requires one. We use _START_, the base
2468 		 * address of the mapping.
2469 		 */
2470 
2471 		if (_flags == RTLD_DL_SYMENT) {
2472 			/*
2473 			 * An actual symbol struct is needed, so we
2474 			 * construct one for _START_. To do this in a
2475 			 * fully accurate way requires a different symbol
2476 			 * for each mapped segment. This requires the
2477 			 * use of dynamic memory and a mutex. That's too much
2478 			 * plumbing for a fringe case of limited importance.
2479 			 *
2480 			 * Fortunately, we can simplify:
2481 			 *    - Only the st_size and st_info fields are useful
2482 			 *	outside of the linker internals. The others
2483 			 *	reference things that outside code cannot see,
2484 			 *	and can be set to 0.
2485 			 *    - It's just a label and there is no size
2486 			 *	to report. So, the size should be 0.
2487 			 * This means that only st_info needs a non-zero
2488 			 * (constant) value. A static struct will suffice.
2489 			 * It must be const (readonly) so the caller can't
2490 			 * change its meaning for subsequent callers.
2491 			 */
2492 			static const Sym fsym = { 0, 0, 0,
2493 			    ELF_ST_INFO(STB_LOCAL, STT_OBJECT) };
2494 			*info = (void *) &fsym;
2495 		}
2496 
2497 		dlip->dli_sname = MSG_ORIG(MSG_SYM_START);
2498 		dlip->dli_saddr = (void *) ADDR(lmp);
2499 	}
2500 }
2501 
2502 static void
2503 elf_lazy_cleanup(APlist *alp)
2504 {
2505 	Rt_map	*lmp;
2506 	Aliste	idx;
2507 
2508 	/*
2509 	 * Cleanup any link-maps added to this dynamic list and free it.
2510 	 */
2511 	for (APLIST_TRAVERSE(alp, idx, lmp))
2512 		FLAGS(lmp) &= ~FLG_RT_TMPLIST;
2513 	free(alp);
2514 }
2515 
2516 /*
2517  * This routine is called as a last fall-back to search for a symbol from a
2518  * standard relocation.  To maintain lazy loadings goal of reducing the number
2519  * of objects mapped, any symbol search is first carried out using the objects
2520  * that already exist in the process (either on a link-map list or handle).
2521  * If a symbol can't be found, and lazy dependencies are still pending, this
2522  * routine loads the dependencies in an attempt to locate the symbol.
2523  *
2524  * Only new objects are inspected as we will have already inspected presently
2525  * loaded objects before calling this routine.  However, a new object may not
2526  * be new - although the di_lmp might be zero, the object may have been mapped
2527  * as someone elses dependency.  Thus there's a possibility of some symbol
2528  * search duplication.
2529  */
2530 Sym *
2531 elf_lazy_find_sym(Slookup *slp, Rt_map **_lmp, uint_t *binfo, int *in_nfavl)
2532 {
2533 	Sym		*sym = NULL;
2534 	APlist		*alist = NULL;
2535 	Aliste		idx;
2536 	Rt_map		*lmp1, *lmp = slp->sl_imap;
2537 	const char	*name = slp->sl_name;
2538 
2539 	/*
2540 	 * Generate a local list of new objects to process.  This list can grow
2541 	 * as each object supplies its own lazy dependencies.
2542 	 */
2543 	if (aplist_append(&alist, lmp, AL_CNT_LAZYFIND) == NULL)
2544 		return (NULL);
2545 	FLAGS(lmp) |= FLG_RT_TMPLIST;
2546 
2547 	for (APLIST_TRAVERSE(alist, idx, lmp1)) {
2548 		uint_t	cnt = 0;
2549 		Slookup	sl = *slp;
2550 		Dyninfo	*dip, *pdip;
2551 
2552 		/*
2553 		 * Discard any relocation index from further symbol searches.
2554 		 * This index will have already been used to trigger any
2555 		 * necessary lazy-loads, and it might be because one of these
2556 		 * lazy loads have failed that we're here performing this
2557 		 * fallback.  By removing the relocation index we don't try
2558 		 * and perform the same failed lazy loading activity again.
2559 		 */
2560 		sl.sl_rsymndx = 0;
2561 
2562 		/*
2563 		 * Loop through the lazy DT_NEEDED entries examining each object
2564 		 * for the required symbol.  If the symbol is not found, the
2565 		 * object is in turn added to the local alist, so that the
2566 		 * objects lazy DT_NEEDED entries can be examined.
2567 		 */
2568 		lmp = lmp1;
2569 		for (dip = DYNINFO(lmp), pdip = NULL; cnt < DYNINFOCNT(lmp);
2570 		    cnt++, pdip = dip++) {
2571 			Rt_map *nlmp;
2572 
2573 			if (((dip->di_flags & FLG_DI_LAZY) == 0) ||
2574 			    dip->di_info)
2575 				continue;
2576 
2577 			/*
2578 			 * If this object has already failed to lazy load, and
2579 			 * we're still processing the same runtime linker
2580 			 * operation that produced the failure, don't bother
2581 			 * to try and load the object again.
2582 			 */
2583 			if ((dip->di_flags & FLG_DI_LAZYFAIL) && pdip &&
2584 			    (pdip->di_flags & FLG_DI_POSFLAG1)) {
2585 				if (pdip->di_info == (void *)ld_entry_cnt)
2586 					continue;
2587 
2588 				dip->di_flags &= ~FLG_DI_LAZYFAIL;
2589 				pdip->di_info = NULL;
2590 			}
2591 
2592 			/*
2593 			 * Try loading this lazy dependency.  If the object
2594 			 * can't be loaded, consider this non-fatal and continue
2595 			 * the search.  Lazy loaded dependencies need not exist
2596 			 * and their loading should only turn out to be fatal
2597 			 * if they are required to satisfy a relocation.
2598 			 *
2599 			 * If the file is already loaded and relocated we must
2600 			 * still inspect it for symbols, even though it might
2601 			 * have already been searched.  This lazy load operation
2602 			 * might have promoted the permissions of the object,
2603 			 * and thus made the object applicable for this symbol
2604 			 * search, whereas before the object might have been
2605 			 * skipped.
2606 			 */
2607 			if ((nlmp = elf_lazy_load(lmp, &sl, cnt,
2608 			    name, in_nfavl)) == NULL)
2609 				continue;
2610 
2611 			/*
2612 			 * If this object isn't yet a part of the dynamic list
2613 			 * then inspect it for the symbol.  If the symbol isn't
2614 			 * found add the object to the dynamic list so that we
2615 			 * can inspect its dependencies.
2616 			 */
2617 			if (FLAGS(nlmp) & FLG_RT_TMPLIST)
2618 				continue;
2619 
2620 			sl.sl_imap = nlmp;
2621 			if (sym = LM_LOOKUP_SYM(sl.sl_cmap)(&sl, _lmp,
2622 			    binfo, in_nfavl))
2623 				break;
2624 
2625 			/*
2626 			 * Some dlsym() operations are already traversing a
2627 			 * link-map (dlopen(0)), and thus there's no need to
2628 			 * build our own dynamic dependency list.
2629 			 */
2630 			if ((sl.sl_flags & LKUP_NODESCENT) == 0) {
2631 				if (aplist_append(&alist, nlmp,
2632 				    AL_CNT_LAZYFIND) == NULL) {
2633 					elf_lazy_cleanup(alist);
2634 					return (NULL);
2635 				}
2636 				FLAGS(nlmp) |= FLG_RT_TMPLIST;
2637 			}
2638 		}
2639 		if (sym)
2640 			break;
2641 	}
2642 
2643 	elf_lazy_cleanup(alist);
2644 	return (sym);
2645 }
2646 
2647 /*
2648  * Warning message for bad r_offset.
2649  */
2650 void
2651 elf_reloc_bad(Rt_map *lmp, void *rel, uchar_t rtype, ulong_t roffset,
2652     ulong_t rsymndx)
2653 {
2654 	const char	*name = NULL;
2655 	Lm_list		*lml = LIST(lmp);
2656 	int		trace;
2657 
2658 	if ((lml->lm_flags & LML_FLG_TRC_ENABLE) &&
2659 	    (((rtld_flags & RT_FL_SILENCERR) == 0) ||
2660 	    (lml->lm_flags & LML_FLG_TRC_VERBOSE)))
2661 		trace = 1;
2662 	else
2663 		trace = 0;
2664 
2665 	if ((trace == 0) && (DBG_ENABLED == 0))
2666 		return;
2667 
2668 	if (rsymndx) {
2669 		Sym	*symref = (Sym *)((ulong_t)SYMTAB(lmp) +
2670 		    (rsymndx * SYMENT(lmp)));
2671 
2672 		if (ELF_ST_BIND(symref->st_info) != STB_LOCAL)
2673 			name = (char *)(STRTAB(lmp) + symref->st_name);
2674 	}
2675 
2676 	if (name == NULL)
2677 		name = MSG_INTL(MSG_STR_UNKNOWN);
2678 
2679 	if (trace) {
2680 		const char *rstr;
2681 
2682 		rstr = _conv_reloc_type((uint_t)rtype);
2683 		(void) printf(MSG_INTL(MSG_LDD_REL_ERR1), rstr, name,
2684 		    EC_ADDR(roffset));
2685 		return;
2686 	}
2687 
2688 	Dbg_reloc_error(lml, ELF_DBG_RTLD, M_MACH, M_REL_SHT_TYPE, rel, name);
2689 }
2690 
2691 /*
2692  * Resolve a static TLS relocation.
2693  */
2694 long
2695 elf_static_tls(Rt_map *lmp, Sym *sym, void *rel, uchar_t rtype, char *name,
2696     ulong_t roffset, long value)
2697 {
2698 	Lm_list	*lml = LIST(lmp);
2699 
2700 	/*
2701 	 * Relocations against a static TLS block have limited support once
2702 	 * process initialization has completed.  Any error condition should be
2703 	 * discovered by testing for DF_STATIC_TLS as part of loading an object,
2704 	 * however individual relocations are tested in case the dynamic flag
2705 	 * had not been set when this object was built.
2706 	 */
2707 	if (PTTLS(lmp) == NULL) {
2708 		DBG_CALL(Dbg_reloc_in(lml, ELF_DBG_RTLD, M_MACH,
2709 		    M_REL_SHT_TYPE, rel, NULL, name));
2710 		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_REL_BADTLS),
2711 		    _conv_reloc_type((uint_t)rtype), NAME(lmp),
2712 		    name ? demangle(name) : MSG_INTL(MSG_STR_UNKNOWN));
2713 		return (0);
2714 	}
2715 
2716 	/*
2717 	 * If no static TLS has been set aside for this object, determine if
2718 	 * any can be obtained.  Enforce that any object using static TLS is
2719 	 * non-deletable.
2720 	 */
2721 	if (TLSSTATOFF(lmp) == 0) {
2722 		FLAGS1(lmp) |= FL1_RT_TLSSTAT;
2723 		MODE(lmp) |= RTLD_NODELETE;
2724 
2725 		if (tls_assign(lml, lmp, PTTLS(lmp)) == 0) {
2726 			DBG_CALL(Dbg_reloc_in(lml, ELF_DBG_RTLD, M_MACH,
2727 			    M_REL_SHT_TYPE, rel, NULL, name));
2728 			eprintf(lml, ERR_FATAL, MSG_INTL(MSG_REL_BADTLS),
2729 			    _conv_reloc_type((uint_t)rtype), NAME(lmp),
2730 			    name ? demangle(name) : MSG_INTL(MSG_STR_UNKNOWN));
2731 			return (0);
2732 		}
2733 	}
2734 
2735 	/*
2736 	 * Typically, a static TLS offset is maintained as a symbols value.
2737 	 * For local symbols that are not apart of the dynamic symbol table,
2738 	 * the TLS relocation points to a section symbol, and the static TLS
2739 	 * offset was deposited in the associated GOT table.  Make sure the GOT
2740 	 * is cleared, so that the value isn't reused in do_reloc().
2741 	 */
2742 	if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) {
2743 		if ((ELF_ST_TYPE(sym->st_info) == STT_SECTION)) {
2744 			value = *(long *)roffset;
2745 			*(long *)roffset = 0;
2746 		} else {
2747 			value = sym->st_value;
2748 		}
2749 	}
2750 	return (-(TLSSTATOFF(lmp) - value));
2751 }
2752 
2753 /*
2754  * If the symbol is not found and the reference was not to a weak symbol, report
2755  * an error.  Weak references may be unresolved.
2756  */
2757 int
2758 elf_reloc_error(Rt_map *lmp, const char *name, void *rel, uint_t binfo)
2759 {
2760 	Lm_list	*lml = LIST(lmp);
2761 
2762 	/*
2763 	 * Under crle(1), relocation failures are ignored.
2764 	 */
2765 	if (lml->lm_flags & LML_FLG_IGNRELERR)
2766 		return (1);
2767 
2768 	/*
2769 	 * Under ldd(1), unresolved references are reported.  However, if the
2770 	 * original reference is EXTERN or PARENT these references are ignored
2771 	 * unless ldd's -p option is in effect.
2772 	 */
2773 	if (lml->lm_flags & LML_FLG_TRC_WARN) {
2774 		if (((binfo & DBG_BINFO_REF_MSK) == 0) ||
2775 		    ((lml->lm_flags & LML_FLG_TRC_NOPAREXT) != 0)) {
2776 			(void) printf(MSG_INTL(MSG_LDD_SYM_NFOUND),
2777 			    demangle(name), NAME(lmp));
2778 		}
2779 		return (1);
2780 	}
2781 
2782 	/*
2783 	 * Otherwise, the unresolved references is fatal.
2784 	 */
2785 	DBG_CALL(Dbg_reloc_in(lml, ELF_DBG_RTLD, M_MACH, M_REL_SHT_TYPE, rel,
2786 	    NULL, name));
2787 	eprintf(lml, ERR_FATAL, MSG_INTL(MSG_REL_NOSYM), NAME(lmp),
2788 	    demangle(name));
2789 
2790 	return (0);
2791 }
2792 
2793 /*
2794  * Generic relative relocation function.
2795  */
2796 inline static ulong_t
2797 _elf_reloc_relative(ulong_t rbgn, ulong_t base, Rt_map *lmp, APlist **textrel)
2798 {
2799 	mmapobj_result_t	*mpp;
2800 	ulong_t			roffset;
2801 
2802 	roffset = ((M_RELOC *)rbgn)->r_offset;
2803 	roffset += base;
2804 
2805 	/*
2806 	 * If this relocation is against an address that is not associated with
2807 	 * a mapped segment, fall back to the generic relocation loop to
2808 	 * collect the associated error.
2809 	 */
2810 	if ((mpp = find_segment((caddr_t)roffset, lmp)) == NULL)
2811 		return (0);
2812 
2813 	/*
2814 	 * If this relocation is against a segment that does not provide write
2815 	 * access, set the write permission for all non-writable mappings.
2816 	 */
2817 	if (((mpp->mr_prot & PROT_WRITE) == 0) && textrel &&
2818 	    ((set_prot(lmp, mpp, 1) == 0) ||
2819 	    (aplist_append(textrel, mpp, AL_CNT_TEXTREL) == NULL)))
2820 		return (0);
2821 
2822 	/*
2823 	 * Perform the actual relocation.  Note, for backward compatibility,
2824 	 * SPARC relocations are added to the offset contents (there was a time
2825 	 * when the offset was used to contain the addend, rather than using
2826 	 * the addend itself).
2827 	 */
2828 #if	defined(__sparc)
2829 	*((ulong_t *)roffset) += base + ((M_RELOC *)rbgn)->r_addend;
2830 #elif	defined(__amd64)
2831 	*((ulong_t *)roffset) = base + ((M_RELOC *)rbgn)->r_addend;
2832 #else
2833 	*((ulong_t *)roffset) += base;
2834 #endif
2835 	return (1);
2836 }
2837 
2838 /*
2839  * When a generic relocation loop realizes that it's dealing with relative
2840  * relocations, but no DT_RELCOUNT .dynamic tag is present, this tighter loop
2841  * is entered as an optimization.
2842  */
2843 ulong_t
2844 elf_reloc_relative(ulong_t rbgn, ulong_t rend, ulong_t rsize, ulong_t base,
2845     Rt_map *lmp, APlist **textrel)
2846 {
2847 	char	rtype;
2848 
2849 	do {
2850 		if (_elf_reloc_relative(rbgn, base, lmp, textrel) == 0)
2851 			break;
2852 
2853 		rbgn += rsize;
2854 		if (rbgn >= rend)
2855 			break;
2856 
2857 		/*
2858 		 * Make sure the next type is a relative relocation.
2859 		 */
2860 		rtype = ELF_R_TYPE(((M_RELOC *)rbgn)->r_info, M_MACH);
2861 
2862 	} while (rtype == M_R_RELATIVE);
2863 
2864 	return (rbgn);
2865 }
2866 
2867 /*
2868  * This is the tightest loop for RELATIVE relocations for those objects built
2869  * with the DT_RELACOUNT .dynamic entry.
2870  */
2871 ulong_t
2872 elf_reloc_relative_count(ulong_t rbgn, ulong_t rcount, ulong_t rsize,
2873     ulong_t base, Rt_map *lmp, APlist **textrel)
2874 {
2875 	for (; rcount; rcount--) {
2876 		if (_elf_reloc_relative(rbgn, base, lmp, textrel) == 0)
2877 			break;
2878 
2879 		rbgn += rsize;
2880 	}
2881 	return (rbgn);
2882 }
2883