xref: /titanic_41/usr/src/cmd/sgs/rtld/common/setup.c (revision cdf5ca0aa1c383eea7ce9831fea01be3999bb218)
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 2008 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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 /*
35  * Run time linker common setup.
36  *
37  * Called from _setup to get the process going at startup.
38  */
39 
40 #include	<stdlib.h>
41 #include	<fcntl.h>
42 #include	<stdio.h>
43 #include	<sys/types.h>
44 #include	<sys/stat.h>
45 #include	<sys/mman.h>
46 #include	<string.h>
47 #include	<stdio.h>
48 #include	<unistd.h>
49 #include	<dlfcn.h>
50 #include	<sys/sysconfig.h>
51 #include	<sys/auxv.h>
52 #include	<debug.h>
53 #include	<conv.h>
54 #include	"_rtld.h"
55 #include	"_audit.h"
56 #include	"_elf.h"
57 #include	"_a.out.h"
58 #include	"msg.h"
59 
60 
61 extern int	_end, _edata, _etext;
62 extern void	_init(void);
63 extern int	_brk_unlocked(void *);
64 
65 #ifndef	SGS_PRE_UNIFIED_PROCESS
66 /* needed for _brk_unlocked() */
67 void *_nd = &_end;
68 #endif
69 
70 /*
71  * Define for the executable's interpreter.
72  * Usually it is ld.so.1, but for the first release of ICL binaries
73  * it is libc.so.1.  We keep this information so that we don't end
74  * up mapping libc twice if it is the interpreter.
75  */
76 static Interp _interp;
77 
78 
79 static int
80 preload(const char *str, Rt_map *lmp)
81 {
82 	Rt_map		*clmp = lmp;
83 	char		*objs, *ptr, *next;
84 	Word		lmflags = lml_main.lm_flags;
85 	uint_t		flags;
86 
87 	DBG_CALL(Dbg_util_nl(&lml_main, DBG_NL_STD));
88 
89 	if ((objs = strdup(str)) == 0)
90 		return (0);
91 
92 	/*
93 	 * Establish the flags for loading each object.  If we're called via
94 	 * lddstub, then the first shared object is the object being inspected
95 	 * by ldd(1).  This object should not be marked as an interposer, as
96 	 * it is intended to act like the first object of the process.
97 	 */
98 	if ((lmflags & LML_FLG_TRC_ENABLE) && (FLAGS1(lmp) & FL1_RT_LDDSTUB))
99 		flags = FLG_RT_PRELOAD;
100 	else
101 		flags = (FLG_RT_PRELOAD | FLG_RT_OBJINTPO);
102 
103 	ptr = strtok_r(objs, MSG_ORIG(MSG_STR_DELIMIT), &next);
104 	do {
105 		Pnode	*pnp;
106 		Rt_map	*nlmp = 0;
107 
108 		DBG_CALL(Dbg_file_preload(&lml_main, ptr));
109 
110 		/*
111 		 * If this a secure application, then preload errors are
112 		 * reduced to warnings, as the errors are non-fatal.
113 		 */
114 		if (rtld_flags & RT_FL_SECURE)
115 			rtld_flags2 |= RT_FL2_FTL2WARN;
116 		if ((pnp = expand_paths(clmp, ptr, PN_FLG_EXTLOAD, 0)) != 0)
117 			nlmp = load_one(&lml_main, ALIST_OFF_DATA, pnp, clmp,
118 			    MODE(lmp), flags, 0, NULL);
119 		if (pnp)
120 			remove_pnode(pnp);
121 		if (rtld_flags & RT_FL_SECURE)
122 			rtld_flags2 &= ~RT_FL2_FTL2WARN;
123 		if (nlmp && (bind_one(clmp, nlmp, BND_NEEDED) == 0))
124 			nlmp = 0;
125 
126 		/*
127 		 * Establish state for the next preloadable object.  If no
128 		 * error occurred with loading this object, indicate that this
129 		 * link-map list contains an interposer.
130 		 */
131 		flags |= FLG_RT_OBJINTPO;
132 		if (nlmp == 0) {
133 			if ((lmflags & LML_FLG_TRC_ENABLE) ||
134 			    (rtld_flags & RT_FL_SECURE))
135 				continue;
136 			else
137 				return (0);
138 		}
139 		lml_main.lm_flags |= LML_FLG_INTRPOSE;
140 
141 		/*
142 		 * If we're tracing shared objects via lddstub, establish a
143 		 * binding between the initial shared object and lddstub so that
144 		 * the shared object isn't called out from unused() processing.
145 		 * After the first object is loaded increment the caller to the
146 		 * initial preloaded object to provide intuitive ldd -v and -s
147 		 * diagnostics
148 		 */
149 		if ((lmflags & LML_FLG_TRC_ENABLE) &&
150 		    (FLAGS1(lmp) & FL1_RT_LDDSTUB)) {
151 			if ((lmp == clmp) && (lmflags &
152 			    (LML_FLG_TRC_UNREF | LML_FLG_TRC_UNUSED))) {
153 				if (bind_one(clmp, nlmp, BND_REFER) == 0)
154 					continue;
155 			}
156 			clmp = (Rt_map *)NEXT(lmp);
157 		}
158 
159 	} while ((ptr = strtok_r(NULL,
160 	    MSG_ORIG(MSG_STR_DELIMIT), &next)) != NULL);
161 
162 	free(objs);
163 	return (1);
164 }
165 
166 Rt_map *
167 setup(char **envp, auxv_t *auxv, Word _flags, char *_platform, int _syspagsz,
168     char *_rtldname, Dyn *dyn_ptr, ulong_t ld_base, ulong_t interp_base, int fd,
169     Phdr *phdr, char *execname, char **argv, int dz_fd, uid_t uid,
170     uid_t euid, gid_t gid, gid_t egid, void *aoutdyn, int auxflags,
171     uint_t hwcap_1)
172 {
173 	Rt_map		*rlmp, *mlmp, **tobj = 0;
174 	Ehdr		*ehdr;
175 	struct stat	status;
176 	int		features = 0, ldsoexec = 0;
177 	size_t		eaddr, esize;
178 	char		*str, *argvname;
179 	Mmap		*mmaps;
180 	Word		lmflags;
181 
182 	/*
183 	 * Now that ld.so has relocated itself, initialize our own 'environ' so
184 	 * as to establish an address suitable for libc's hardware mul/div
185 	 * magic (libc/sparc/crt/hwmuldiv.o).
186 	 */
187 	_environ = (char **)((ulong_t)auxv - sizeof (char *));
188 	_init();
189 	_environ = envp;
190 
191 	/*
192 	 * Far the most common application execution revolves around appending
193 	 * the application name to the users PATH definition, thus a full name
194 	 * is passed to exec() which will in turn be returned via
195 	 * AT_SUN_EXECNAME.  Applications may also be invoked from the current
196 	 * working directory, or via a relative name.
197 	 *
198 	 * Determine whether the kernel has supplied a AT_SUN_EXECNAME aux
199 	 * vector.  This vector points to the full pathname, on the stack, of
200 	 * the object that started the process.  If this is null, then
201 	 * AT_SUN_EXECNAME isn't supported (if the pathname exceeded the system
202 	 * limit (PATH_MAX) the exec would have failed).  This flag is used to
203 	 * determine whether we can call resolvepath().
204 	 */
205 	if (execname)
206 		rtld_flags |= RT_FL_EXECNAME;
207 
208 	/*
209 	 * Determine how ld.so.1 has been executed.
210 	 */
211 	if ((fd == -1) && (phdr == 0)) {
212 		/*
213 		 * If we received neither the AT_EXECFD nor the AT_PHDR aux
214 		 * vector, ld.so.1 must have been invoked directly from the
215 		 * command line.
216 		 */
217 		ldsoexec = 1;
218 
219 		/*
220 		 * AT_SUN_EXECNAME provides the most precise name, if it is
221 		 * available, otherwise fall back to argv[0].  At this time,
222 		 * there is no process name.
223 		 */
224 		if (execname)
225 			rtldname = execname;
226 		else if (argv[0])
227 			rtldname = argv[0];
228 		else
229 			rtldname = (char *)MSG_INTL(MSG_STR_UNKNOWN);
230 	} else {
231 		/*
232 		 * Otherwise, we have a standard process.  AT_SUN_EXECNAME
233 		 * provides the most precise name, if it is available,
234 		 * otherwise fall back to argv[0].  Provided the application
235 		 * is already mapped, the process is the application, so
236 		 * simplify the application name for use in any diagnostics.
237 		 */
238 		if (execname)
239 			argvname = execname;
240 		else if (argv[0])
241 			argvname = execname = argv[0];
242 		else
243 			argvname = execname = (char *)MSG_INTL(MSG_STR_UNKNOWN);
244 
245 		if (fd == -1) {
246 			if ((str = strrchr(argvname, '/')) != 0)
247 				procname = ++str;
248 			else
249 				procname = argvname;
250 		}
251 
252 		/*
253 		 * At this point, we don't know the runtime linkers full path
254 		 * name.  The _rtldname passed to us is the SONAME of the
255 		 * runtime linker, which is typically /lib/ld.so.1 no matter
256 		 * what the full path is.   Use this for now, we'll reset the
257 		 * runtime linkers name once the application is analyzed.
258 		 */
259 		if (_rtldname) {
260 			if ((str = strrchr(_rtldname, '/')) != 0)
261 				rtldname = ++str;
262 			else
263 				rtldname = _rtldname;
264 		} else
265 			rtldname = (char *)MSG_INTL(MSG_STR_UNKNOWN);
266 	}
267 
268 	/*
269 	 * Initialize any global variables.
270 	 */
271 	at_flags = _flags;
272 	if (dz_fd != FD_UNAVAIL)
273 		dz_init(dz_fd);
274 	platform = _platform;
275 
276 	/*
277 	 * If pagesize is unspecified find its value.
278 	 */
279 	if ((syspagsz = _syspagsz) == 0)
280 		syspagsz = _sysconfig(_CONFIG_PAGESIZE);
281 	fmap_setup();
282 
283 	/*
284 	 * Add the unused portion of the last data page to the free space list.
285 	 * The page size must be set before doing this.  Here, _end refers to
286 	 * the end of the runtime linkers bss.  Note that we do not use the
287 	 * unused data pages from any included .so's to supplement this free
288 	 * space as badly behaved .os's may corrupt this data space, and in so
289 	 * doing ruin our data.
290 	 */
291 	eaddr = S_DROUND((size_t)&_end);
292 	esize = eaddr % syspagsz;
293 	if (esize) {
294 		esize = syspagsz - esize;
295 		addfree((void *)eaddr, esize);
296 	}
297 
298 	/*
299 	 * Establish initial link-map list flags, and link-map list alists.
300 	 */
301 	if (alist_append(&lml_main.lm_lists, 0, sizeof (Lm_cntl),
302 	    AL_CNT_LMLISTS) == 0)
303 		return (0);
304 	lml_main.lm_flags |= LML_FLG_BASELM;
305 	lml_main.lm_lmid = LM_ID_BASE;
306 	lml_main.lm_lmidstr = (char *)MSG_ORIG(MSG_LMID_BASE);
307 
308 	if (alist_append(&lml_rtld.lm_lists, 0, sizeof (Lm_cntl),
309 	    AL_CNT_LMLISTS) == 0)
310 		return (0);
311 	lml_rtld.lm_flags |= (LML_FLG_RTLDLM | LML_FLG_NOAUDIT |
312 	    LML_FLG_HOLDLOCK);
313 	lml_rtld.lm_lmid = LM_ID_LDSO;
314 	lml_rtld.lm_lmidstr = (char *)MSG_ORIG(MSG_LMID_LDSO);
315 
316 	/*
317 	 * Determine whether we have a secure executable.
318 	 */
319 	security(uid, euid, gid, egid, auxflags);
320 
321 	/*
322 	 * Initialize a hardware capability descriptor for use in comparing
323 	 * each loaded object.
324 	 */
325 #ifdef	AT_SUN_AUXFLAGS
326 	if (auxflags & AF_SUN_HWCAPVERIFY) {
327 		rtld_flags2 |= RT_FL2_HWCAP;
328 		hwcap = (ulong_t)hwcap_1;
329 	}
330 #endif
331 	/*
332 	 * Look for environment strings (allows things like LD_NOAUDIT to be
333 	 * established, although debugging isn't enabled until later).
334 	 */
335 	if ((readenv_user((const char **)envp, &(lml_main.lm_flags),
336 	    &(lml_main.lm_tflags), (aoutdyn != 0))) == 1)
337 		return (0);
338 
339 	/*
340 	 * Create a mapping descriptor for ld.so.1.  We can determine our
341 	 * two segments information from known symbols.
342 	 */
343 	if ((mmaps = calloc(3, sizeof (Mmap))) == 0)
344 		return (0);
345 	mmaps[0].m_vaddr = (caddr_t)M_PTRUNC(ld_base);
346 	mmaps[0].m_msize = (size_t)((caddr_t)&_etext - mmaps[0].m_vaddr);
347 	mmaps[0].m_fsize = mmaps[0].m_msize;
348 	mmaps[0].m_perm = (PROT_READ | PROT_EXEC);
349 	mmaps[1].m_vaddr = (caddr_t)M_PTRUNC((ulong_t)&r_debug);
350 	mmaps[1].m_msize = (size_t)((caddr_t)&_end - mmaps[1].m_vaddr);
351 	mmaps[1].m_fsize = (size_t)((caddr_t)&_edata - mmaps[1].m_vaddr);
352 	mmaps[1].m_perm = (PROT_READ | PROT_WRITE | PROT_EXEC);
353 
354 	/*
355 	 * Create a link map structure for ld.so.1.
356 	 */
357 	if ((rlmp = elf_new_lm(&lml_rtld, _rtldname, rtldname, dyn_ptr, ld_base,
358 	    (ulong_t)&_etext, ALIST_OFF_DATA, (ulong_t)(eaddr - ld_base), 0,
359 	    ld_base, (ulong_t)(eaddr - ld_base), mmaps, 2, NULL)) == 0) {
360 		return (0);
361 	}
362 
363 	MODE(rlmp) |= (RTLD_LAZY | RTLD_NODELETE | RTLD_GLOBAL | RTLD_WORLD);
364 	FLAGS(rlmp) |= (FLG_RT_ANALYZED | FLG_RT_RELOCED | FLG_RT_INITDONE |
365 	    FLG_RT_INITCLCT | FLG_RT_FINICLCT | FLG_RT_MODESET);
366 
367 	/*
368 	 * Initialize the runtime linkers information.
369 	 */
370 	interp = &_interp;
371 	interp->i_name = NAME(rlmp);
372 	interp->i_faddr = (caddr_t)ADDR(rlmp);
373 	ldso_plt_init(rlmp);
374 
375 	/*
376 	 * If ld.so.1 has been invoked directly, process its arguments.
377 	 */
378 	if (ldsoexec) {
379 		/*
380 		 * Process any arguments that are specific to ld.so.1, and
381 		 * reorganize the process stack to effectively remove ld.so.1
382 		 * from it.  Reinitialize the environment pointer, as this may
383 		 * have been shifted after skipping ld.so.1's arguments.
384 		 */
385 		if (rtld_getopt(argv, &envp, &auxv, &(lml_main.lm_flags),
386 		    &(lml_main.lm_tflags), (aoutdyn != 0)) == 1) {
387 			eprintf(&lml_main, ERR_NONE, MSG_INTL(MSG_USG_BADOPT));
388 			return (0);
389 		}
390 		_environ = envp;
391 
392 		/*
393 		 * Open the object that ld.so.1 is to execute.
394 		 */
395 		argvname = execname = argv[0];
396 
397 		if ((fd = open(argvname, O_RDONLY)) == -1) {
398 			int	err = errno;
399 			eprintf(&lml_main, ERR_FATAL, MSG_INTL(MSG_SYS_OPEN),
400 			    argvname, strerror(err));
401 			return (0);
402 		}
403 	}
404 
405 	/*
406 	 * Map in the file, if exec has not already done so.  If it has,
407 	 * simply create a new link map structure for the executable.
408 	 */
409 	if (fd != -1) {
410 		Rej_desc	rej;
411 		Fct		*ftp;
412 
413 		/*
414 		 * Find out what type of object we have.
415 		 */
416 		(void) fstat(fd, &status);
417 		if ((ftp = are_u_this(&rej, fd, &status, argvname)) == 0) {
418 			Conv_reject_desc_buf_t rej_buf;
419 
420 			eprintf(&lml_main, ERR_FATAL,
421 			    MSG_INTL(err_reject[rej.rej_type]), argvname,
422 			    conv_reject_desc(&rej, &rej_buf, M_MACH));
423 			return (0);
424 		}
425 
426 		/*
427 		 * Map in object.
428 		 */
429 		if ((mlmp = (ftp->fct_map_so)(&lml_main, ALIST_OFF_DATA,
430 		    execname, argvname, fd, NULL)) == 0)
431 			return (0);
432 
433 		/*
434 		 * We now have a process name for error diagnostics.
435 		 */
436 		if ((str = strrchr(argvname, '/')) != 0)
437 			procname = ++str;
438 		else
439 			procname = argvname;
440 
441 		if (ldsoexec) {
442 			Addr	brkbase = 0;
443 
444 			/*
445 			 * Since ld.so.1 was the primary executed object - the
446 			 * brk() base has not yet been initialized, we need to
447 			 * initialize it.  For an executable, initialize it to
448 			 * the end of the object.  For a shared object (ET_DYN)
449 			 * initialize it to the first page in memory.
450 			 */
451 			ehdr = (Ehdr *)ADDR(mlmp);
452 
453 			if ((FCT(mlmp) == &elf_fct) &&
454 			    (ehdr->e_type == ET_EXEC)) {
455 				int	i;
456 				Phdr *_phdr = (Phdr *)((uintptr_t)ADDR(mlmp) +
457 				    ehdr->e_phoff);
458 
459 				/*
460 				 * We scan the program headers to find the tail
461 				 * of the memory image.  We can't use MSIZE()
462 				 * since that's already been page aligned.
463 				 */
464 				for (i = 0; i < ehdr->e_phnum; i++, _phdr++) {
465 					if (_phdr->p_type == PT_LOAD)
466 						brkbase = _phdr->p_vaddr +
467 						    _phdr->p_memsz;
468 				}
469 			}
470 
471 			if (!brkbase)
472 				brkbase = syspagsz;
473 
474 			if (_brk_unlocked((void *)brkbase) == -1) {
475 				int	err = errno;
476 				eprintf(&lml_main, ERR_FATAL,
477 				    MSG_INTL(MSG_SYS_BRK), argvname,
478 				    strerror(err));
479 			}
480 		}
481 
482 		/*
483 		 * The object has now been mmaped, we no longer need the file
484 		 * descriptor.
485 		 */
486 		(void) close(fd);
487 
488 	} else {
489 		/*
490 		 * Set up function ptr and arguments according to the type
491 		 * of file class the executable is. (Currently only supported
492 		 * types are ELF and a.out format.)  Then create a link map
493 		 * for the executable.
494 		 */
495 		if (aoutdyn) {
496 #ifdef A_OUT
497 			if ((mlmp = aout_new_lm(&lml_main, execname, argvname,
498 			    aoutdyn, 0, 0, ALIST_OFF_DATA)) == 0)
499 				return (0);
500 
501 			/*
502 			 * Set the memory size.  Note, we only know the end of
503 			 * text, and although we could find the _end by looking
504 			 * up the symbol, this may not be present.  We should
505 			 * set ADDR to MAIN_BASE, but presently all the a.out
506 			 * relocation code assumes ADDR is 0 for the dynamic
507 			 * executable. (these data items are only used for
508 			 * dladdr(3x), and there aren't many a.out dladdr(3x)
509 			 * users to warrant spending much time on this :-).
510 			 */
511 			MSIZE(mlmp) = MAIN_BASE + ETEXT(mlmp);
512 
513 			/*
514 			 * Disable any object configuration cache (BCP apps
515 			 * bring in sbcp which can benefit from any object
516 			 * cache, but both the app and sbcp can't use the same
517 			 * objects).
518 			 */
519 			rtld_flags |= RT_FL_NOOBJALT;
520 
521 			/*
522 			 * Make sure no-direct bindings are in effect.
523 			 */
524 			lml_main.lm_tflags |= LML_TFLG_NODIRECT;
525 #else
526 			eprintf(&lml_main, ERR_FATAL,
527 			    MSG_INTL(MSG_ERR_REJ_UNKFILE), argvname);
528 			return (0);
529 #endif
530 		} else if (phdr) {
531 			Phdr		*pptr, *firstptr = 0, *lastptr;
532 			Phdr		*tlsphdr = 0, *unwindphdr = 0;
533 			Dyn		*dyn = 0;
534 			Cap		*cap = 0;
535 			Off		i_offset = 0;
536 			Addr		base = 0;
537 			ulong_t		memsize, phsize, entry, etext;
538 			uint_t		mmapcnt = 0;
539 			int		i;
540 
541 			/*
542 			 * Using the executables phdr address determine the base
543 			 * address of the input file.  NOTE, this assumes the
544 			 * program headers and elf header are part of the same
545 			 * mapped segment.  Although this has held for many
546 			 * years now, it might be more flexible if the kernel
547 			 * gave use the ELF headers start address, rather than
548 			 * the Program headers.
549 			 *
550 			 * Determine from the ELF header if we're been called
551 			 * from a shared object or dynamic executable.  If the
552 			 * latter, then any addresses within the object are used
553 			 * as is.  Addresses within shared objects must be added
554 			 * to the process's base address.
555 			 */
556 			ehdr = (Ehdr *)((Addr)phdr - phdr->p_offset);
557 			phsize = ehdr->e_phentsize;
558 			if (ehdr->e_type == ET_DYN)
559 				base = (Addr)ehdr;
560 
561 			/*
562 			 * Allocate a mapping array to retain mapped segment
563 			 * information.
564 			 */
565 			if ((mmaps = calloc(ehdr->e_phnum, sizeof (Mmap))) == 0)
566 				return (0);
567 
568 			/*
569 			 * Extract the needed information from the segment
570 			 * headers.
571 			 */
572 			for (i = 0, pptr = phdr; i < ehdr->e_phnum; i++) {
573 				if (pptr->p_type == PT_INTERP) {
574 					i_offset = pptr->p_offset;
575 					interp->i_faddr =
576 					    (caddr_t)interp_base;
577 				}
578 				if ((pptr->p_type == PT_LOAD) &&
579 				    (pptr->p_filesz || pptr->p_memsz)) {
580 					int	perm = (PROT_READ | PROT_EXEC);
581 					size_t	off;
582 
583 					if (!firstptr)
584 						firstptr = pptr;
585 					lastptr = pptr;
586 					if (i_offset && pptr->p_filesz &&
587 					    (i_offset >= pptr->p_offset) &&
588 					    (i_offset <=
589 					    (pptr->p_memsz + pptr->p_offset))) {
590 						interp->i_name = (char *)
591 						    pptr->p_vaddr + i_offset -
592 						    pptr->p_offset + base;
593 						i_offset = 0;
594 					}
595 					if ((pptr->p_flags &
596 					    (PF_R | PF_W)) == PF_R)
597 						etext = pptr->p_vaddr +
598 						    pptr->p_memsz + base;
599 					else
600 						perm |= PROT_WRITE;
601 
602 					/*
603 					 * Retain segments mapping info.  Round
604 					 * each segment to a page boundary, as
605 					 * this insures addresses are suitable
606 					 * for mprotect() if required.
607 					 */
608 					off = pptr->p_vaddr + base;
609 					mmaps[mmapcnt].m_vaddr =
610 					    (caddr_t)M_PTRUNC(off);
611 					off -= (size_t)mmaps[mmapcnt].m_vaddr;
612 					mmaps[mmapcnt].m_msize =
613 					    pptr->p_memsz + off;
614 					mmaps[mmapcnt].m_fsize =
615 					    pptr->p_filesz + off;
616 					mmaps[mmapcnt].m_perm = perm;
617 					mmapcnt++;
618 
619 				} else if (pptr->p_type == PT_DYNAMIC) {
620 					dyn = (Dyn *)(pptr->p_vaddr + base);
621 				} else if ((pptr->p_type == PT_TLS) &&
622 				    pptr->p_memsz) {
623 					tlsphdr = pptr;
624 				} else if (pptr->p_type == PT_SUNW_UNWIND) {
625 					unwindphdr = pptr;
626 				} else if (pptr->p_type == PT_SUNWCAP) {
627 					cap = (Cap *)(pptr->p_vaddr + base);
628 				}
629 				pptr = (Phdr *)((ulong_t)pptr + phsize);
630 			}
631 
632 
633 			memsize = (lastptr->p_vaddr + lastptr->p_memsz) -
634 			    S_ALIGN(firstptr->p_vaddr, syspagsz);
635 
636 			entry = ehdr->e_entry;
637 			if (ehdr->e_type == ET_DYN)
638 				entry += (ulong_t)ehdr;
639 
640 			if ((mlmp = elf_new_lm(&lml_main, execname, argvname,
641 			    dyn, (Addr)ehdr, etext, ALIST_OFF_DATA, memsize,
642 			    entry, (ulong_t)ehdr, memsize, mmaps,
643 			    mmapcnt, NULL)) == 0) {
644 				return (0);
645 			}
646 			if (tlsphdr &&
647 			    (tls_assign(&lml_main, mlmp, tlsphdr) == 0))
648 				return (0);
649 
650 			if (unwindphdr)
651 				PTUNWIND(mlmp) = unwindphdr;
652 
653 			if (cap)
654 				cap_assign(cap, mlmp);
655 		}
656 	}
657 
658 	/*
659 	 * Establish the interpretors name as that defined within the initial
660 	 * object (executable).  This provides for ORIGIN processing of ld.so.1
661 	 * dependencies.
662 	 */
663 	if (ldsoexec == 0) {
664 		size_t	len = strlen(interp->i_name);
665 		(void) expand(&interp->i_name, &len, 0, 0,
666 		    (PN_TKN_ISALIST | PN_TKN_HWCAP), rlmp);
667 	}
668 	PATHNAME(rlmp) = interp->i_name;
669 
670 	if (FLAGS1(rlmp) & FL1_RT_RELATIVE)
671 		(void) fullpath(rlmp, 0);
672 	else
673 		ORIGNAME(rlmp) = PATHNAME(rlmp) = NAME(rlmp);
674 
675 	/*
676 	 * Having established the true runtime linkers name, simplify the name
677 	 * for error diagnostics.
678 	 */
679 	if ((str = strrchr(PATHNAME(rlmp), '/')) != 0)
680 		rtldname = ++str;
681 	else
682 		rtldname = PATHNAME(rlmp);
683 
684 	/*
685 	 * Expand the fullpath name of the application.  This typically occurs
686 	 * as a part of loading an object, but as the kernel probably mapped
687 	 * it in, complete this processing now.
688 	 */
689 	if (FLAGS1(mlmp) & FL1_RT_RELATIVE)
690 		(void) fullpath(mlmp, 0);
691 
692 	/*
693 	 * Some troublesome programs will change the value of argv[0].  Dupping
694 	 * the process string protects us, and insures the string is left in
695 	 * any core files.
696 	 */
697 	if ((str = (char *)strdup(procname)) == 0)
698 		return (0);
699 	procname = str;
700 
701 	/*
702 	 * If the kernel has provided hardware capabilities information, and
703 	 * the executable contains hardware capabilities information, make
704 	 * sure it's a valid object.
705 	 */
706 	if ((rtld_flags2 & RT_FL2_HWCAP) && HWCAP(mlmp)) {
707 		ulong_t	mhwcap;
708 
709 		if ((mhwcap = (HWCAP(mlmp) & ~hwcap)) != 0) {
710 			Conv_cap_val_hw1_buf_t cap_val_hw1_buf;
711 
712 			const char *str =
713 			    conv_cap_val_hw1(mhwcap, M_MACH, 0,
714 			    &cap_val_hw1_buf);
715 
716 			if (lml_main.lm_flags & LML_FLG_TRC_ENABLE) {
717 				(void) printf(MSG_INTL(MSG_LDD_GEN_HWCAP_1),
718 				    NAME(mlmp), str);
719 			} else {
720 				eprintf(&lml_main, ERR_FATAL,
721 				    MSG_INTL(MSG_GEN_BADHWCAP_1), str);
722 				return (0);
723 			}
724 		}
725 	}
726 
727 	FLAGS(mlmp) |= (FLG_RT_ISMAIN | FLG_RT_MODESET);
728 	FLAGS1(mlmp) |= FL1_RT_USED;
729 
730 	/*
731 	 * It's the responsibility of MAIN(crt0) to call it's _init and _fini
732 	 * section, therefore null out any INIT/FINI so that this object isn't
733 	 * collected during tsort processing.  And, if the application has no
734 	 * initarray or finiarray we can economize on establishing bindings.
735 	 */
736 	INIT(mlmp) = FINI(mlmp) = 0;
737 	if ((INITARRAY(mlmp) == 0) && (FINIARRAY(mlmp) == 0))
738 		FLAGS1(mlmp) |= FL1_RT_NOINIFIN;
739 
740 	/*
741 	 * Identify lddstub if necessary.
742 	 */
743 	if (lml_main.lm_flags & LML_FLG_TRC_LDDSTUB)
744 		FLAGS1(mlmp) |= FL1_RT_LDDSTUB;
745 
746 	/*
747 	 * Retain our argument information for use in dlinfo.
748 	 */
749 	argsinfo.dla_argv = argv--;
750 	argsinfo.dla_argc = (long)*argv;
751 	argsinfo.dla_envp = envp;
752 	argsinfo.dla_auxv = auxv;
753 
754 	(void) enter(0);
755 
756 	/*
757 	 * Add our two main link-maps to the dynlm_list
758 	 */
759 	if (list_append(&dynlm_list, &lml_main) == 0)
760 		return (0);
761 
762 	if (list_append(&dynlm_list, &lml_rtld) == 0)
763 		return (0);
764 
765 	/*
766 	 * Reset the link-map counts for both lists.  The init count is used to
767 	 * track how many objects have pending init sections, this gets incre-
768 	 * mented each time an object is relocated.  Since ld.so.1 relocates
769 	 * itself, it's init count will remain zero.
770 	 * The object count is used to track how many objects have pending fini
771 	 * sections, as ld.so.1 handles its own fini we can zero its count.
772 	 */
773 	lml_main.lm_obj = 1;
774 	lml_rtld.lm_obj = 0;
775 
776 	/*
777 	 * Initialize debugger information structure.  Some parts of this
778 	 * structure were initialized statically.
779 	 */
780 	r_debug.rtd_rdebug.r_map = (Link_map *)lml_main.lm_head;
781 	r_debug.rtd_rdebug.r_ldsomap = (Link_map *)lml_rtld.lm_head;
782 	r_debug.rtd_rdebug.r_ldbase = r_debug.rtd_rdebug.r_ldsomap->l_addr;
783 	r_debug.rtd_dynlmlst = &dynlm_list;
784 
785 	if (platform)
786 		platform_sz = strlen(platform);
787 
788 	/*
789 	 * Determine the dev/inode information for the executable to complete
790 	 * load_so() checking for those who might dlopen(a.out).
791 	 */
792 	if ((FLAGS1(mlmp) & FL1_RT_RELATIVE) &&
793 	    (stat(PATHNAME(mlmp), &status) == 0)) {
794 		STDEV(mlmp) = status.st_dev;
795 		STINO(mlmp) = status.st_ino;
796 	}
797 
798 	/*
799 	 * Initialize any configuration information.
800 	 */
801 	if (!(rtld_flags & RT_FL_NOCFG)) {
802 		if ((features = elf_config(mlmp, (aoutdyn != 0))) == -1)
803 			return (0);
804 	}
805 
806 	/*
807 	 * Establish the modes of the initial object.  These modes are
808 	 * propagated to any preloaded objects and explicit shared library
809 	 * dependencies.
810 	 *
811 	 * If we're generating a configuration file using crle(1), remove
812 	 * any RTLD_NOW use, as we don't want to trigger any relocation proc-
813 	 * essing during crle(1)'s first past (this would just be unnecessary
814 	 * overhead).  Any filters are explicitly loaded, and thus RTLD_NOW is
815 	 * not required to trigger filter loading.
816 	 *
817 	 * Note, RTLD_NOW may have been established during analysis of the
818 	 * application had the application been built -z now.
819 	 */
820 	MODE(mlmp) |= (RTLD_NODELETE | RTLD_GLOBAL | RTLD_WORLD);
821 
822 	if (rtld_flags & RT_FL_CONFGEN) {
823 		MODE(mlmp) |= RTLD_CONFGEN;
824 		MODE(mlmp) &= ~RTLD_NOW;
825 		rtld_flags2 &= ~RT_FL2_BINDNOW;
826 	}
827 
828 	if ((MODE(mlmp) & RTLD_NOW) == 0) {
829 		if (rtld_flags2 & RT_FL2_BINDNOW)
830 			MODE(mlmp) |= RTLD_NOW;
831 		else
832 			MODE(mlmp) |= RTLD_LAZY;
833 	}
834 
835 	/*
836 	 * If debugging was requested initialize things now that any cache has
837 	 * been established.  A user can specify LD_DEBUG=help to discover the
838 	 * list of debugging tokens available without running the application.
839 	 * However, don't allow this setting from a configuration file.
840 	 *
841 	 * Note, to prevent recursion issues caused by loading and binding the
842 	 * debugging libraries themselves, a local debugging descriptor is
843 	 * initialized.  Once the debugging setup has completed, this local
844 	 * descriptor is copied to the global descriptor which effectively
845 	 * enables diagnostic output.
846 	 */
847 	if (rpl_debug || prm_debug) {
848 		Dbg_desc	_dbg_desc = {0, 0, 0};
849 
850 		if (rpl_debug) {
851 			uintptr_t	ret;
852 
853 			if ((ret = dbg_setup(rpl_debug, &_dbg_desc)) == S_ERROR)
854 				return (0);
855 			if (ret == 0)
856 				rtldexit(&lml_main, 0);
857 		}
858 		if (prm_debug)
859 			(void) dbg_setup(prm_debug, &_dbg_desc);
860 
861 		*dbg_desc = _dbg_desc;
862 	}
863 
864 	/*
865 	 * Now that debugging is enabled generate any diagnostics from any
866 	 * previous events.
867 	 */
868 	if (hwcap)
869 		DBG_CALL(Dbg_cap_val_hw1(&lml_main, hwcap, M_MACH));
870 	if (features)
871 		DBG_CALL(Dbg_file_config_dis(&lml_main, config->c_name,
872 		    features));
873 
874 	if (DBG_ENABLED) {
875 		DBG_CALL(Dbg_file_ldso(rlmp, envp, auxv,
876 		    LIST(rlmp)->lm_lmidstr, ALIST_OFF_DATA));
877 
878 		if (FCT(mlmp) == &elf_fct) {
879 			DBG_CALL(Dbg_file_elf(&lml_main, PATHNAME(mlmp),
880 			    (ulong_t)DYN(mlmp), ADDR(mlmp), MSIZE(mlmp),
881 			    ENTRY(mlmp), LIST(mlmp)->lm_lmidstr,
882 			    ALIST_OFF_DATA));
883 		} else {
884 			DBG_CALL(Dbg_file_aout(&lml_main, PATHNAME(mlmp),
885 			    (ulong_t)AOUTDYN(mlmp), (ulong_t)ADDR(mlmp),
886 			    (ulong_t)MSIZE(mlmp), LIST(mlmp)->lm_lmidstr,
887 			    ALIST_OFF_DATA));
888 		}
889 	}
890 
891 	/*
892 	 * Enable auditing.
893 	 */
894 	if (rpl_audit || prm_audit || profile_lib) {
895 		int		ndx;
896 		const char	*aud[3];
897 
898 		aud[0] = rpl_audit;
899 		aud[1] = prm_audit;
900 		aud[2] = profile_lib;
901 
902 		/*
903 		 * Any global auditing (set using LD_AUDIT or LD_PROFILE) that
904 		 * can't be established is non-fatal.
905 		 */
906 		if ((auditors = calloc(1, sizeof (Audit_desc))) == 0)
907 			return (0);
908 
909 		for (ndx = 0; ndx < 3; ndx++) {
910 			if (aud[ndx]) {
911 				if ((auditors->ad_name = strdup(aud[ndx])) == 0)
912 					return (0);
913 				rtld_flags2 |= RT_FL2_FTL2WARN;
914 				(void) audit_setup(mlmp, auditors,
915 				    PN_FLG_EXTLOAD, NULL);
916 				rtld_flags2 &= ~RT_FL2_FTL2WARN;
917 			}
918 		}
919 		lml_main.lm_tflags |= auditors->ad_flags;
920 	}
921 	if (AUDITORS(mlmp)) {
922 		/*
923 		 * Any object required auditing (set with a DT_DEPAUDIT dynamic
924 		 * entry) that can't be established is fatal.
925 		 */
926 		if (FLAGS1(mlmp) & FL1_RT_GLOBAUD) {
927 			/*
928 			 * If this object requires global auditing, use the
929 			 * local auditing information to set the global
930 			 * auditing descriptor.  The effect is that a
931 			 * DT_DEPAUDIT act as an LD_AUDIT.
932 			 */
933 			if ((auditors == 0) &&
934 			    ((auditors = calloc(1, sizeof (Audit_desc))) == 0))
935 				return (0);
936 
937 			auditors->ad_name = AUDITORS(mlmp)->ad_name;
938 			if (audit_setup(mlmp, auditors, 0, NULL) == 0)
939 				return (0);
940 			lml_main.lm_tflags |= auditors->ad_flags;
941 
942 			/*
943 			 * Clear the local auditor information.
944 			 */
945 			free((void *) AUDITORS(mlmp));
946 			AUDITORS(mlmp) = 0;
947 
948 		} else {
949 			/*
950 			 * Establish any local auditing.
951 			 */
952 			if (audit_setup(mlmp, AUDITORS(mlmp), 0, NULL) == 0)
953 				return (0);
954 
955 			FLAGS1(mlmp) |= AUDITORS(mlmp)->ad_flags;
956 			lml_main.lm_flags |= LML_FLG_LOCAUDIT;
957 		}
958 	}
959 
960 	/*
961 	 * Explicitly add the initial object and ld.so.1 to those objects being
962 	 * audited.  Note, although the ld.so.1 link-map isn't auditable,
963 	 * establish a cookie for ld.so.1 as this may be bound to via the
964 	 * dl*() family.
965 	 */
966 	if ((lml_main.lm_tflags | FLAGS1(mlmp)) & LML_TFLG_AUD_MASK) {
967 		if (((audit_objopen(mlmp, mlmp) == 0) ||
968 		    (audit_objopen(mlmp, rlmp) == 0)) &&
969 		    (FLAGS1(mlmp) & LML_TFLG_AUD_MASK))
970 			return (0);
971 	}
972 
973 	/*
974 	 * Map in any preloadable shared objects.  Note, it is valid to preload
975 	 * a 4.x shared object with a 5.0 executable (or visa-versa), as this
976 	 * functionality is required by ldd(1).
977 	 */
978 	if (rpl_preload && (preload(rpl_preload, mlmp) == 0))
979 		return (0);
980 	if (prm_preload && (preload(prm_preload, mlmp) == 0))
981 		return (0);
982 
983 	/*
984 	 * Load all dependent (needed) objects.
985 	 */
986 	if (analyze_lmc(&lml_main, ALIST_OFF_DATA, mlmp, NULL) == 0)
987 		return (0);
988 
989 	/*
990 	 * Relocate all the dependencies we've just added.
991 	 *
992 	 * If this process has been established via crle(1), the environment
993 	 * variable LD_CONFGEN will have been set.  crle(1) may create this
994 	 * process twice.  The first time crle only needs to gather dependency
995 	 * information.  The second time, is to dldump() the images.
996 	 *
997 	 * If we're only gathering dependencies, relocation is unnecessary.
998 	 * As crle(1) may be building an arbitrary family of objects, they may
999 	 * not fully relocate either.  Hence the relocation phase is not carried
1000 	 * out now, but will be called by crle(1) once all objects have been
1001 	 * loaded.
1002 	 */
1003 	if ((rtld_flags & RT_FL_CONFGEN) == 0) {
1004 
1005 		DBG_CALL(Dbg_util_nl(&lml_main, DBG_NL_STD));
1006 
1007 		if (relocate_lmc(&lml_main, ALIST_OFF_DATA, mlmp,
1008 		    mlmp, NULL) == 0)
1009 			return (0);
1010 
1011 		/*
1012 		 * Inform the debuggers we're here and stable.  Newer debuggers
1013 		 * can indicate their presence by setting the DT_DEBUG entry in
1014 		 * the dynamic executable (see elf_new_lm()).  In this case call
1015 		 * getpid() so the debugger can catch the system call.  This
1016 		 * handshake allows the debugger to initialize, and consequently
1017 		 * allows the user to set break points in .init code.
1018 		 */
1019 		rd_event(&lml_main, RD_DLACTIVITY, RT_CONSISTENT);
1020 		rd_event(&lml_rtld, RD_DLACTIVITY, RT_CONSISTENT);
1021 
1022 		if (rtld_flags & RT_FL_DEBUGGER) {
1023 			r_debug.rtd_rdebug.r_flags |= RD_FL_ODBG;
1024 			(void) getpid();
1025 		}
1026 	}
1027 
1028 	/*
1029 	 * Indicate preinit activity, and call any auditing routines.  These
1030 	 * routines are called before initializing any threads via libc, or
1031 	 * before collecting the complete set of .inits on the primary link-map.
1032 	 * Although most libc interfaces are encapsulated in local routines
1033 	 * within libc, they have been known to escape (ie. call a .plt).  As
1034 	 * the appcert auditor uses preinit as a trigger to establish some
1035 	 * external interfaces to the main link-maps libc, we need to activate
1036 	 * this trigger before exercising any code within libc.  Additionally,
1037 	 * I wouldn't put it past an auditor to add additional objects to the
1038 	 * primary link-map.  Hence, we collect .inits after the audit call.
1039 	 */
1040 	rd_event(&lml_main, RD_PREINIT, 0);
1041 
1042 	if ((lml_main.lm_tflags | FLAGS1(mlmp)) & LML_TFLG_AUD_ACTIVITY)
1043 		audit_activity(mlmp, LA_ACT_CONSISTENT);
1044 	if ((lml_main.lm_tflags | FLAGS1(mlmp)) & LML_TFLG_AUD_PREINIT)
1045 		audit_preinit(mlmp);
1046 
1047 	/*
1048 	 * If we're creating initial configuration information, we're done
1049 	 * now that the auditing step has been called.
1050 	 */
1051 	if (rtld_flags & RT_FL_CONFGEN) {
1052 		leave(LIST(mlmp), 0);
1053 		return (mlmp);
1054 	}
1055 
1056 	/*
1057 	 * Sort the .init sections of all objects we've added.  If we're
1058 	 * tracing we only need to execute this under ldd(1) with the -i or -u
1059 	 * options.
1060 	 */
1061 	lmflags = lml_main.lm_flags;
1062 	if (((lmflags & LML_FLG_TRC_ENABLE) == 0) ||
1063 	    (lmflags & (LML_FLG_TRC_INIT | LML_FLG_TRC_UNREF))) {
1064 		if ((tobj = tsort(mlmp, LIST(mlmp)->lm_init,
1065 		    RT_SORT_REV)) == (Rt_map **)S_ERROR)
1066 			return (0);
1067 	}
1068 
1069 	/*
1070 	 * If we are tracing we're done.  This is the one legitimate use of a
1071 	 * direct call to rtldexit() rather than return, as we don't want to
1072 	 * return and jump to the application.
1073 	 */
1074 	if (lmflags & LML_FLG_TRC_ENABLE) {
1075 		unused(&lml_main);
1076 		rtldexit(&lml_main, 0);
1077 	}
1078 
1079 #ifdef	AT_SUN_AUXFLAGS
1080 	/*
1081 	 * Check if this instance of the linker should have a primary link
1082 	 * map.  This flag allows multiple copies of the -same- -version-
1083 	 * of the linker (and libc) to run in the same address space.
1084 	 *
1085 	 * Without this flag we only support one copy of the linker in a
1086 	 * process because by default the linker will always try to
1087 	 * initialize at one primary link map  The copy of libc which is
1088 	 * initialized on a primary link map will initalize global TLS
1089 	 * data which can be shared with other copies of libc in the
1090 	 * process.  The problem is that if there is more than one copy
1091 	 * of the linker, only one copy should link libc onto a primary
1092 	 * link map, otherwise libc will attempt to re-initialize global
1093 	 * TLS data.  So when a copy of the linker is loaded with this
1094 	 * flag set, it will not initialize any primary link maps since
1095 	 * persumably another copy of the linker will do this.
1096 	 *
1097 	 * Note that this flag only allows multiple copies of the -same-
1098 	 * -version- of the linker (and libc) to coexist.  This approach
1099 	 * will not work if we are trying to load different versions of
1100 	 * the linker and libc into the same process.  The reason for
1101 	 * this is that the format of the global TLS data may not be
1102 	 * the same for different versions of libc.  In this case each
1103 	 * different version of libc must have it's own primary link map
1104 	 * and be able to maintain it's own TLS data.  The only way this
1105 	 * can be done is by carefully managing TLS pointers on transitions
1106 	 * between code associated with each of the different linkers.
1107 	 * Note that this is actually what is done for processes in lx
1108 	 * branded zones.  Although in the lx branded zone case, the
1109 	 * other linker and libc are actually gld and glibc.  But the
1110 	 * same general TLS management mechanism used by the lx brand
1111 	 * would apply to any attempts to run multiple versions of the
1112 	 * solaris linker and libc in a single process.
1113 	 */
1114 	if (auxflags & AF_SUN_NOPLM)
1115 		rtld_flags2 |= RT_FL2_NOPLM;
1116 #endif
1117 	/*
1118 	 * Establish any static TLS for this primary link-map.  Note, regardless
1119 	 * of whether TLS is available, an initial handshake occurs with libc to
1120 	 * indicate we're processing the primary link-map.  Having identified
1121 	 * the primary link-map, initialize threads.
1122 	 */
1123 	if (rt_get_extern(&lml_main, mlmp) == 0)
1124 		return (0);
1125 
1126 	if ((rtld_flags2 & RT_FL2_NOPLM) == 0) {
1127 		if (tls_statmod(&lml_main, mlmp) == 0)
1128 			return (0);
1129 		rt_thr_init(&lml_main);
1130 		rtld_flags2 |= RT_FL2_PLMSETUP;
1131 	} else {
1132 		rt_thr_init(&lml_main);
1133 	}
1134 
1135 	rtld_flags |= RT_FL_APPLIC;
1136 
1137 	/*
1138 	 * Fire all dependencies .init sections.  Identify any unused
1139 	 * dependencies, and leave the runtime linker - effectively calling
1140 	 * the dynamic executables entry point.
1141 	 */
1142 	call_array(PREINITARRAY(mlmp), (uint_t)PREINITARRAYSZ(mlmp), mlmp,
1143 	    SHT_PREINIT_ARRAY);
1144 
1145 	if (tobj)
1146 		call_init(tobj, DBG_INIT_SORT);
1147 
1148 	rd_event(&lml_main, RD_POSTINIT, 0);
1149 
1150 	unused(&lml_main);
1151 
1152 	DBG_CALL(Dbg_util_call_main(mlmp));
1153 
1154 	rtld_flags |= RT_FL_OPERATION;
1155 	leave(LIST(mlmp), 0);
1156 
1157 	return (mlmp);
1158 }
1159