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