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 (c) 1989, 2010, Oracle and/or its affiliates. All rights reserved.
27  */
28 
29 /*
30  * Module sections. Initialize special sections
31  */
32 
33 #define	ELF_TARGET_AMD64
34 
35 #include	<string.h>
36 #include	<strings.h>
37 #include	<stdio.h>
38 #include	<link.h>
39 #include	<debug.h>
40 #include	"msg.h"
41 #include	"_libld.h"
42 
43 inline static void
44 remove_local(Ofl_desc *ofl, Sym_desc *sdp, int allow_ldynsym)
45 {
46 	Sym	*sym = sdp->sd_sym;
47 	uchar_t	type = ELF_ST_TYPE(sym->st_info);
48 	/* LINTED - only used for assert() */
49 	int	err;
50 
51 	if ((ofl->ofl_flags & FLG_OF_REDLSYM) == 0) {
52 		ofl->ofl_locscnt--;
53 
54 		err = st_delstring(ofl->ofl_strtab, sdp->sd_name);
55 		assert(err != -1);
56 
57 		if (allow_ldynsym && ldynsym_symtype[type]) {
58 			ofl->ofl_dynlocscnt--;
59 
60 			err = st_delstring(ofl->ofl_dynstrtab, sdp->sd_name);
61 			assert(err != -1);
62 			/* Remove from sort section? */
63 			DYNSORT_COUNT(sdp, sym, type, --);
64 		}
65 	}
66 	sdp->sd_flags |= FLG_SY_ISDISC;
67 }
68 
69 inline static void
70 remove_scoped(Ofl_desc *ofl, Sym_desc *sdp, int allow_ldynsym)
71 {
72 	Sym	*sym = sdp->sd_sym;
73 	uchar_t	type = ELF_ST_TYPE(sym->st_info);
74 	/* LINTED - only used for assert() */
75 	int	err;
76 
77 	ofl->ofl_scopecnt--;
78 	ofl->ofl_elimcnt++;
79 
80 	err = st_delstring(ofl->ofl_strtab, sdp->sd_name);
81 	assert(err != -1);
82 
83 	if (allow_ldynsym && ldynsym_symtype[type]) {
84 		ofl->ofl_dynscopecnt--;
85 
86 		err = st_delstring(ofl->ofl_dynstrtab, sdp->sd_name);
87 		assert(err != -1);
88 		/* Remove from sort section? */
89 		DYNSORT_COUNT(sdp, sym, type, --);
90 	}
91 	sdp->sd_flags |= FLG_SY_ELIM;
92 }
93 
94 inline static void
95 ignore_sym(Ofl_desc *ofl, Ifl_desc *ifl, Sym_desc *sdp, int allow_ldynsym)
96 {
97 	Os_desc	*osp;
98 	Is_desc	*isp = sdp->sd_isc;
99 	uchar_t	bind = ELF_ST_BIND(sdp->sd_sym->st_info);
100 
101 	if (bind == STB_LOCAL) {
102 		uchar_t	type = ELF_ST_TYPE(sdp->sd_sym->st_info);
103 
104 		/*
105 		 * Skip section symbols, these were never collected in the
106 		 * first place.
107 		 */
108 		if (type == STT_SECTION)
109 			return;
110 
111 		/*
112 		 * Determine if the whole file is being removed.  Remove any
113 		 * file symbol, and any symbol that is not associated with a
114 		 * section, provided the symbol has not been identified as
115 		 * (update) required.
116 		 */
117 		if (((ifl->ifl_flags & FLG_IF_FILEREF) == 0) &&
118 		    ((type == STT_FILE) || ((isp == NULL) &&
119 		    ((sdp->sd_flags & FLG_SY_UPREQD) == 0)))) {
120 			DBG_CALL(Dbg_syms_discarded(ofl->ofl_lml, sdp));
121 			if (ifl->ifl_flags & FLG_IF_IGNORE)
122 				remove_local(ofl, sdp, allow_ldynsym);
123 			return;
124 		}
125 
126 	} else {
127 		/*
128 		 * Global symbols can only be eliminated when the interfaces of
129 		 * an object have been defined via versioning/scoping.
130 		 */
131 		if (!SYM_IS_HIDDEN(sdp))
132 			return;
133 
134 		/*
135 		 * Remove any unreferenced symbols that are not associated with
136 		 * a section.
137 		 */
138 		if ((isp == NULL) && ((sdp->sd_flags & FLG_SY_UPREQD) == 0)) {
139 			DBG_CALL(Dbg_syms_discarded(ofl->ofl_lml, sdp));
140 			if (ifl->ifl_flags & FLG_IF_IGNORE)
141 				remove_scoped(ofl, sdp, allow_ldynsym);
142 			return;
143 		}
144 	}
145 
146 	/*
147 	 * Do not discard any symbols that are associated with non-allocable
148 	 * segments.
149 	 */
150 	if (isp && ((isp->is_flags & FLG_IS_SECTREF) == 0) &&
151 	    ((osp = isp->is_osdesc) != 0) &&
152 	    (osp->os_sgdesc->sg_phdr.p_type == PT_LOAD)) {
153 		DBG_CALL(Dbg_syms_discarded(ofl->ofl_lml, sdp));
154 		if (ifl->ifl_flags & FLG_IF_IGNORE) {
155 			if (bind == STB_LOCAL)
156 				remove_local(ofl, sdp, allow_ldynsym);
157 			else
158 				remove_scoped(ofl, sdp, allow_ldynsym);
159 		}
160 	}
161 }
162 
163 /*
164  * There are situations where we may count output sections (ofl_shdrcnt)
165  * that are subsequently eliminated from the output object. Whether or
166  * not this happens cannot be known until all input has been seen and
167  * section elimination code has run. However, the situations where this
168  * outcome is possible are known, and are flagged by setting FLG_OF_ADJOSCNT.
169  *
170  * If FLG_OF_ADJOSCNT is set, this routine makes a pass over the output
171  * sections. If an unused output section is encountered, we decrement
172  * ofl->ofl_shdrcnt and remove the section name from the .shstrtab string
173  * table (ofl->ofl_shdrsttab).
174  *
175  * This code must be kept in sync with the similar code
176  * found in outfile.c:ld_create_outfile().
177  */
178 static void
179 adjust_os_count(Ofl_desc *ofl)
180 {
181 	Sg_desc		*sgp;
182 	Is_desc		*isp;
183 	Os_desc		*osp;
184 	Ifl_desc	*ifl;
185 	Aliste		idx1;
186 
187 	if ((ofl->ofl_flags & FLG_OF_ADJOSCNT) == 0)
188 		return;
189 
190 	/*
191 	 * For each output section, look at the input sections to find at least
192 	 * one input section that has not been eliminated. If none are found,
193 	 * the -z ignore processing above has eliminated that output section.
194 	 */
195 	for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp)) {
196 		Aliste	idx2;
197 		Word	ptype = sgp->sg_phdr.p_type;
198 
199 		for (APLIST_TRAVERSE(sgp->sg_osdescs, idx2, osp)) {
200 			Aliste	idx3;
201 			int	keep = 0, os_isdescs_idx;
202 
203 			OS_ISDESCS_TRAVERSE(os_isdescs_idx, osp, idx3, isp) {
204 				ifl = isp->is_file;
205 
206 				/* Input section is tagged for discard? */
207 				if (isp->is_flags & FLG_IS_DISCARD)
208 					continue;
209 
210 				/*
211 				 * If the file is discarded, it will take
212 				 * the section with it.
213 				 */
214 				if (ifl &&
215 				    (((ifl->ifl_flags & FLG_IF_FILEREF) == 0) ||
216 				    ((ptype == PT_LOAD) &&
217 				    ((isp->is_flags & FLG_IS_SECTREF) == 0) &&
218 				    (isp->is_shdr->sh_size > 0))) &&
219 				    (ifl->ifl_flags & FLG_IF_IGNORE))
220 					continue;
221 
222 				/*
223 				 * We have found a kept input section,
224 				 * so the output section will be created.
225 				 */
226 				keep = 1;
227 				break;
228 			}
229 			/*
230 			 * If no section of this name was kept, decrement
231 			 * the count and remove the name from .shstrtab.
232 			 */
233 			if (keep == 0) {
234 				/* LINTED - only used for assert() */
235 				int err;
236 
237 				ofl->ofl_shdrcnt--;
238 				err = st_delstring(ofl->ofl_shdrsttab,
239 				    osp->os_name);
240 				assert(err != -1);
241 			}
242 		}
243 	}
244 }
245 
246 /*
247  * If -zignore has been in effect, scan all input files to determine if the
248  * file, or sections from the file, have been referenced.  If not, the file or
249  * some of the files sections can be discarded. If sections are to be
250  * discarded, rescan the output relocations and the symbol table and remove
251  * the relocations and symbol entries that are no longer required.
252  *
253  * Note:  It's possible that a section which is being discarded has contributed
254  *	  to the GOT table or the PLT table.  However, we can't at this point
255  *	  eliminate the corresponding entries.  This is because there could well
256  *	  be other sections referencing those same entries, but we don't have
257  *	  the infrastructure to determine this.  So, keep the PLT and GOT
258  *	  entries in the table in case someone wants them.
259  * Note:  The section to be affected needs to be allocatable.
260  *	  So even if -zignore is in effect, if the section is not allocatable,
261  *	  we do not eliminate it.
262  */
263 static uintptr_t
264 ignore_section_processing(Ofl_desc *ofl)
265 {
266 	Sg_desc		*sgp;
267 	Is_desc		*isp;
268 	Os_desc		*osp;
269 	Ifl_desc	*ifl;
270 	Rel_cachebuf	*rcbp;
271 	Rel_desc	*rsp;
272 	int		allow_ldynsym = OFL_ALLOW_LDYNSYM(ofl);
273 	Aliste		idx1;
274 
275 	for (APLIST_TRAVERSE(ofl->ofl_objs, idx1, ifl)) {
276 		uint_t	num, discard;
277 
278 		/*
279 		 * Diagnose (-D unused) a completely unreferenced file.
280 		 */
281 		if ((ifl->ifl_flags & FLG_IF_FILEREF) == 0)
282 			DBG_CALL(Dbg_unused_file(ofl->ofl_lml,
283 			    ifl->ifl_name, 0, 0));
284 		if (((ofl->ofl_flags1 & FLG_OF1_IGNPRC) == 0) ||
285 		    ((ifl->ifl_flags & FLG_IF_IGNORE) == 0))
286 			continue;
287 
288 		/*
289 		 * Before scanning the whole symbol table to determine if
290 		 * symbols should be discard - quickly (relatively) scan the
291 		 * sections to determine if any are to be discarded.
292 		 */
293 		discard = 0;
294 		if (ifl->ifl_flags & FLG_IF_FILEREF) {
295 			for (num = 1; num < ifl->ifl_shnum; num++) {
296 				if (((isp = ifl->ifl_isdesc[num]) != NULL) &&
297 				    ((isp->is_flags & FLG_IS_SECTREF) == 0) &&
298 				    ((osp = isp->is_osdesc) != NULL) &&
299 				    ((sgp = osp->os_sgdesc) != NULL) &&
300 				    (sgp->sg_phdr.p_type == PT_LOAD)) {
301 					discard++;
302 					break;
303 				}
304 			}
305 		}
306 
307 		/*
308 		 * No sections are to be 'ignored'
309 		 */
310 		if ((discard == 0) && (ifl->ifl_flags & FLG_IF_FILEREF))
311 			continue;
312 
313 		/*
314 		 * We know that we have discarded sections.  Scan the symbol
315 		 * table for this file to determine if symbols need to be
316 		 * discarded that are associated with the 'ignored' sections.
317 		 */
318 		for (num = 1; num < ifl->ifl_symscnt; num++) {
319 			Sym_desc	*sdp;
320 
321 			/*
322 			 * If the symbol definition has been resolved to another
323 			 * file, or the symbol has already been discarded or
324 			 * eliminated, skip it.
325 			 */
326 			sdp = ifl->ifl_oldndx[num];
327 			if ((sdp->sd_file != ifl) ||
328 			    (sdp->sd_flags &
329 			    (FLG_SY_ISDISC | FLG_SY_INVALID | FLG_SY_ELIM)))
330 				continue;
331 
332 			/*
333 			 * Complete the investigation of the symbol.
334 			 */
335 			ignore_sym(ofl, ifl, sdp, allow_ldynsym);
336 		}
337 	}
338 
339 	/*
340 	 * If we were only here to solicit debugging diagnostics, we're done.
341 	 */
342 	if ((ofl->ofl_flags1 & FLG_OF1_IGNPRC) == 0)
343 		return (1);
344 
345 	/*
346 	 * Scan all output relocations searching for those against discarded or
347 	 * ignored sections.  If one is found, decrement the total outrel count.
348 	 */
349 	REL_CACHE_TRAVERSE(&ofl->ofl_outrels, idx1, rcbp, rsp) {
350 		Is_desc		*isc = rsp->rel_isdesc;
351 		uint_t		flags, entsize;
352 		Shdr		*shdr;
353 
354 		if ((isc == NULL) || ((isc->is_flags & (FLG_IS_SECTREF))) ||
355 		    ((ifl = isc->is_file) == NULL) ||
356 		    ((ifl->ifl_flags & FLG_IF_IGNORE) == 0) ||
357 		    ((shdr = isc->is_shdr) == NULL) ||
358 		    ((shdr->sh_flags & SHF_ALLOC) == 0))
359 			continue;
360 
361 		flags = rsp->rel_flags;
362 
363 		if (flags & (FLG_REL_GOT | FLG_REL_BSS |
364 		    FLG_REL_NOINFO | FLG_REL_PLT))
365 			continue;
366 
367 		osp = RELAUX_GET_OSDESC(rsp);
368 
369 		if (rsp->rel_flags & FLG_REL_RELA)
370 			entsize = sizeof (Rela);
371 		else
372 			entsize = sizeof (Rel);
373 
374 		assert(osp->os_szoutrels > 0);
375 		osp->os_szoutrels -= entsize;
376 
377 		if (!(flags & FLG_REL_PLT))
378 			ofl->ofl_reloccntsub++;
379 
380 		if (rsp->rel_rtype == ld_targ.t_m.m_r_relative)
381 			ofl->ofl_relocrelcnt--;
382 	}
383 
384 	/*
385 	 * As a result of our work here, the number of output sections may
386 	 * have decreased. Trigger a call to adjust_os_count().
387 	 */
388 	ofl->ofl_flags |= FLG_OF_ADJOSCNT;
389 
390 	return (1);
391 }
392 
393 /*
394  * Allocate Elf_Data, Shdr, and Is_desc structures for a new
395  * section.
396  *
397  * entry:
398  *	ofl - Output file descriptor
399  *	shtype - SHT_ type code for section.
400  *	shname - String giving the name for the new section.
401  *	entcnt - # of items contained in the data part of the new section.
402  *		This value is multiplied against the known element size
403  *		for the section type to determine the size of the data
404  *		area for the section. It is only meaningful in cases where
405  *		the section type has a non-zero element size. In other cases,
406  *		the caller must set the size fields in the *ret_data and
407  *		*ret_shdr structs manually.
408  *	ret_isec, ret_shdr, ret_data - Address of pointers to
409  *		receive address of newly allocated structs.
410  *
411  * exit:
412  *	On error, returns S_ERROR. On success, returns (1), and the
413  *	ret_ pointers have been updated to point at the new structures,
414  *	which have been filled in. To finish the task, the caller must
415  *	update any fields within the supplied descriptors that differ
416  *	from its needs, and then call ld_place_section().
417  */
418 static uintptr_t
419 new_section(Ofl_desc *ofl, Word shtype, const char *shname, Xword entcnt,
420 	Is_desc **ret_isec, Shdr **ret_shdr, Elf_Data **ret_data)
421 {
422 	typedef struct sec_info {
423 		Word d_type;
424 		Word align;	/* Used in both data and section header */
425 		Word sh_flags;
426 		Word sh_entsize;
427 	} SEC_INFO_T;
428 
429 	const SEC_INFO_T	*sec_info;
430 
431 	Shdr		*shdr;
432 	Elf_Data	*data;
433 	Is_desc		*isec;
434 	size_t		size;
435 
436 	/*
437 	 * For each type of section, we have a distinct set of
438 	 * SEC_INFO_T values. This macro defines a static structure
439 	 * containing those values and generates code to set the sec_info
440 	 * pointer to refer to it. The pointer in sec_info remains valid
441 	 * outside of the declaration scope because the info_s struct is static.
442 	 *
443 	 * We can't determine the value of M_WORD_ALIGN at compile time, so
444 	 * a different variant is used for those cases.
445 	 */
446 #define	SET_SEC_INFO(d_type, d_align, sh_flags, sh_entsize) \
447 	{ \
448 		static const SEC_INFO_T info_s = { d_type, d_align, sh_flags, \
449 		    sh_entsize}; \
450 		sec_info = &info_s; \
451 	}
452 #define	SET_SEC_INFO_WORD_ALIGN(d_type, sh_flags, sh_entsize) \
453 	{ \
454 		static SEC_INFO_T info_s = { d_type, 0, sh_flags, \
455 		    sh_entsize}; \
456 		info_s.align = ld_targ.t_m.m_word_align; \
457 		sec_info = &info_s; \
458 	}
459 
460 	switch (shtype) {
461 	case SHT_PROGBITS:
462 		/*
463 		 * SHT_PROGBITS sections contain are used for many
464 		 * different sections. Alignments and flags differ.
465 		 * Some have a standard entsize, and others don't.
466 		 * We set some defaults here, but there is no expectation
467 		 * that they are correct or complete for any specific
468 		 * purpose. The caller must provide the correct values.
469 		 */
470 		SET_SEC_INFO_WORD_ALIGN(ELF_T_BYTE, SHF_ALLOC, 0)
471 		break;
472 
473 	case SHT_SYMTAB:
474 		SET_SEC_INFO_WORD_ALIGN(ELF_T_SYM, 0, sizeof (Sym))
475 		break;
476 
477 	case SHT_DYNSYM:
478 		SET_SEC_INFO_WORD_ALIGN(ELF_T_SYM, SHF_ALLOC, sizeof (Sym))
479 		break;
480 
481 	case SHT_SUNW_LDYNSYM:
482 		ofl->ofl_flags |= FLG_OF_OSABI;
483 		SET_SEC_INFO_WORD_ALIGN(ELF_T_SYM, SHF_ALLOC, sizeof (Sym))
484 		break;
485 
486 	case SHT_STRTAB:
487 		/*
488 		 * A string table may or may not be allocable, depending
489 		 * on context, so we leave that flag unset and leave it to
490 		 * the caller to add it if necessary.
491 		 *
492 		 * String tables do not have a standard entsize, so
493 		 * we set it to 0.
494 		 */
495 		SET_SEC_INFO(ELF_T_BYTE, 1, SHF_STRINGS, 0)
496 		break;
497 
498 	case SHT_RELA:
499 		/*
500 		 * Relocations with an addend (Everything except 32-bit X86).
501 		 * The caller is expected to set all section header flags.
502 		 */
503 		SET_SEC_INFO_WORD_ALIGN(ELF_T_RELA, 0, sizeof (Rela))
504 		break;
505 
506 	case SHT_REL:
507 		/*
508 		 * Relocations without an addend (32-bit X86 only).
509 		 * The caller is expected to set all section header flags.
510 		 */
511 		SET_SEC_INFO_WORD_ALIGN(ELF_T_REL, 0, sizeof (Rel))
512 		break;
513 
514 	case SHT_HASH:
515 		SET_SEC_INFO_WORD_ALIGN(ELF_T_WORD, SHF_ALLOC, sizeof (Word))
516 		break;
517 
518 	case SHT_SUNW_symsort:
519 	case SHT_SUNW_tlssort:
520 		ofl->ofl_flags |= FLG_OF_OSABI;
521 		SET_SEC_INFO_WORD_ALIGN(ELF_T_WORD, SHF_ALLOC, sizeof (Word))
522 		break;
523 
524 	case SHT_DYNAMIC:
525 		/*
526 		 * A dynamic section may or may not be allocable, and may or
527 		 * may not be writable, depending on context, so we leave the
528 		 * flags unset and leave it to the caller to add them if
529 		 * necessary.
530 		 */
531 		SET_SEC_INFO_WORD_ALIGN(ELF_T_DYN, 0, sizeof (Dyn))
532 		break;
533 
534 	case SHT_NOBITS:
535 		/*
536 		 * SHT_NOBITS is used for BSS-type sections. The size and
537 		 * alignment depend on the specific use and must be adjusted
538 		 * by the caller.
539 		 */
540 		SET_SEC_INFO(ELF_T_BYTE, 0, SHF_ALLOC | SHF_WRITE, 0)
541 		break;
542 
543 	case SHT_INIT_ARRAY:
544 	case SHT_FINI_ARRAY:
545 	case SHT_PREINIT_ARRAY:
546 		SET_SEC_INFO(ELF_T_ADDR, sizeof (Addr), SHF_ALLOC | SHF_WRITE,
547 		    sizeof (Addr))
548 		break;
549 
550 	case SHT_SYMTAB_SHNDX:
551 		/*
552 		 * Note that these sections are created to be associated
553 		 * with both symtab and dynsym symbol tables. However, they
554 		 * are non-allocable in all cases, because the runtime
555 		 * linker has no need for this information. It is purely
556 		 * informational, used by elfdump(1), debuggers, etc.
557 		 */
558 		SET_SEC_INFO_WORD_ALIGN(ELF_T_WORD, 0, sizeof (Word));
559 		break;
560 
561 	case SHT_SUNW_cap:
562 		ofl->ofl_flags |= FLG_OF_OSABI;
563 		SET_SEC_INFO_WORD_ALIGN(ELF_T_CAP, SHF_ALLOC, sizeof (Cap));
564 		break;
565 
566 	case SHT_SUNW_capchain:
567 		ofl->ofl_flags |= FLG_OF_OSABI;
568 		SET_SEC_INFO_WORD_ALIGN(ELF_T_WORD, SHF_ALLOC,
569 		    sizeof (Capchain));
570 		break;
571 
572 	case SHT_SUNW_capinfo:
573 		ofl->ofl_flags |= FLG_OF_OSABI;
574 #if	_ELF64
575 		SET_SEC_INFO(ELF_T_XWORD, sizeof (Xword), SHF_ALLOC,
576 		    sizeof (Capinfo));
577 #else
578 		SET_SEC_INFO(ELF_T_WORD, sizeof (Word), SHF_ALLOC,
579 		    sizeof (Capinfo));
580 #endif
581 		break;
582 
583 	case SHT_SUNW_move:
584 		ofl->ofl_flags |= FLG_OF_OSABI;
585 		SET_SEC_INFO(ELF_T_BYTE, sizeof (Lword),
586 		    SHF_ALLOC | SHF_WRITE, sizeof (Move));
587 		break;
588 
589 	case SHT_SUNW_syminfo:
590 		ofl->ofl_flags |= FLG_OF_OSABI;
591 		/*
592 		 * The sh_info field of the SHT_*_syminfo section points
593 		 * to the header index of the associated .dynamic section,
594 		 * so we also set SHF_INFO_LINK.
595 		 */
596 		SET_SEC_INFO_WORD_ALIGN(ELF_T_BYTE,
597 		    SHF_ALLOC | SHF_INFO_LINK, sizeof (Syminfo));
598 		break;
599 
600 	case SHT_SUNW_verneed:
601 	case SHT_SUNW_verdef:
602 		ofl->ofl_flags |= FLG_OF_OSABI;
603 		/*
604 		 * The info for verneed and versym happen to be the same.
605 		 * The entries in these sections are not of uniform size,
606 		 * so we set the entsize to 0.
607 		 */
608 		SET_SEC_INFO_WORD_ALIGN(ELF_T_BYTE, SHF_ALLOC, 0);
609 		break;
610 
611 	case SHT_SUNW_versym:
612 		ofl->ofl_flags |= FLG_OF_OSABI;
613 		SET_SEC_INFO_WORD_ALIGN(ELF_T_BYTE, SHF_ALLOC,
614 		    sizeof (Versym));
615 		break;
616 
617 	default:
618 		/* Should not happen: fcn called with unknown section type */
619 		assert(0);
620 		return (S_ERROR);
621 	}
622 #undef	SET_SEC_INFO
623 #undef	SET_SEC_INFO_WORD_ALIGN
624 
625 	size = entcnt * sec_info->sh_entsize;
626 
627 	/*
628 	 * Allocate and initialize the Elf_Data structure.
629 	 */
630 	if ((data = libld_calloc(sizeof (Elf_Data), 1)) == NULL)
631 		return (S_ERROR);
632 	data->d_type = sec_info->d_type;
633 	data->d_size = size;
634 	data->d_align = sec_info->align;
635 	data->d_version = ofl->ofl_dehdr->e_version;
636 
637 	/*
638 	 * Allocate and initialize the Shdr structure.
639 	 */
640 	if ((shdr = libld_calloc(sizeof (Shdr), 1)) == NULL)
641 		return (S_ERROR);
642 	shdr->sh_type = shtype;
643 	shdr->sh_size = size;
644 	shdr->sh_flags = sec_info->sh_flags;
645 	shdr->sh_addralign = sec_info->align;
646 	shdr->sh_entsize = sec_info->sh_entsize;
647 
648 	/*
649 	 * Allocate and initialize the Is_desc structure.
650 	 */
651 	if ((isec = libld_calloc(1, sizeof (Is_desc))) == NULL)
652 		return (S_ERROR);
653 	isec->is_name = shname;
654 	isec->is_shdr = shdr;
655 	isec->is_indata = data;
656 
657 
658 	*ret_isec = isec;
659 	*ret_shdr = shdr;
660 	*ret_data = data;
661 	return (1);
662 }
663 
664 /*
665  * Use an existing input section as a template to create a new
666  * input section with the same values as the original, other than
667  * the size of the data area which is supplied by the caller.
668  *
669  * entry:
670  *	ofl - Output file descriptor
671  *	ifl - Input file section to use as a template
672  *	size - Size of data area for new section
673  *	ret_isec, ret_shdr, ret_data - Address of pointers to
674  *		receive address of newly allocated structs.
675  *
676  * exit:
677  *	On error, returns S_ERROR. On success, returns (1), and the
678  *	ret_ pointers have been updated to point at the new structures,
679  *	which have been filled in. To finish the task, the caller must
680  *	update any fields within the supplied descriptors that differ
681  *	from its needs, and then call ld_place_section().
682  */
683 static uintptr_t
684 new_section_from_template(Ofl_desc *ofl, Is_desc *tmpl_isp, size_t size,
685 	Is_desc **ret_isec, Shdr **ret_shdr, Elf_Data **ret_data)
686 {
687 	Shdr		*shdr;
688 	Elf_Data	*data;
689 	Is_desc		*isec;
690 
691 	/*
692 	 * Allocate and initialize the Elf_Data structure.
693 	 */
694 	if ((data = libld_calloc(sizeof (Elf_Data), 1)) == NULL)
695 		return (S_ERROR);
696 	data->d_type = tmpl_isp->is_indata->d_type;
697 	data->d_size = size;
698 	data->d_align = tmpl_isp->is_shdr->sh_addralign;
699 	data->d_version = ofl->ofl_dehdr->e_version;
700 
701 	/*
702 	 * Allocate and initialize the Shdr structure.
703 	 */
704 	if ((shdr = libld_malloc(sizeof (Shdr))) == NULL)
705 		return (S_ERROR);
706 	*shdr = *tmpl_isp->is_shdr;
707 	shdr->sh_addr = 0;
708 	shdr->sh_offset = 0;
709 	shdr->sh_size = size;
710 
711 	/*
712 	 * Allocate and initialize the Is_desc structure.
713 	 */
714 	if ((isec = libld_calloc(1, sizeof (Is_desc))) == NULL)
715 		return (S_ERROR);
716 	isec->is_name = tmpl_isp->is_name;
717 	isec->is_shdr = shdr;
718 	isec->is_indata = data;
719 
720 
721 	*ret_isec = isec;
722 	*ret_shdr = shdr;
723 	*ret_data = data;
724 	return (1);
725 }
726 
727 /*
728  * Build a .bss section for allocation of tentative definitions.  Any `static'
729  * .bss definitions would have been associated to their own .bss sections and
730  * thus collected from the input files.  `global' .bss definitions are tagged
731  * as COMMON and do not cause any associated .bss section elements to be
732  * generated.  Here we add up all these COMMON symbols and generate the .bss
733  * section required to represent them.
734  */
735 uintptr_t
736 ld_make_bss(Ofl_desc *ofl, Xword size, Xword align, uint_t ident)
737 {
738 	Shdr		*shdr;
739 	Elf_Data	*data;
740 	Is_desc		*isec;
741 	Os_desc		*osp;
742 	Xword		rsize = (Xword)ofl->ofl_relocbsssz;
743 
744 	/*
745 	 * Allocate header structs. We will set the name ourselves below,
746 	 * and there is no entcnt for a BSS. So, the shname and entcnt
747 	 * arguments are 0.
748 	 */
749 	if (new_section(ofl, SHT_NOBITS, NULL, 0,
750 	    &isec, &shdr, &data) == S_ERROR)
751 		return (S_ERROR);
752 
753 	data->d_size = (size_t)size;
754 	data->d_align = (size_t)align;
755 
756 	shdr->sh_size = size;
757 	shdr->sh_addralign = align;
758 
759 	if (ident == ld_targ.t_id.id_tlsbss) {
760 		isec->is_name = MSG_ORIG(MSG_SCN_TBSS);
761 		ofl->ofl_istlsbss = isec;
762 		shdr->sh_flags |= SHF_TLS;
763 
764 	} else if (ident == ld_targ.t_id.id_bss) {
765 		isec->is_name = MSG_ORIG(MSG_SCN_BSS);
766 		ofl->ofl_isbss = isec;
767 
768 #if	defined(_ELF64)
769 	} else if ((ld_targ.t_m.m_mach == EM_AMD64) &&
770 	    (ident == ld_targ.t_id.id_lbss)) {
771 		isec->is_name = MSG_ORIG(MSG_SCN_LBSS);
772 		ofl->ofl_islbss = isec;
773 		shdr->sh_flags |= SHF_AMD64_LARGE;
774 #endif
775 	}
776 
777 	/*
778 	 * Retain this .*bss input section as this will be where global symbol
779 	 * references are added.
780 	 */
781 	if ((osp = ld_place_section(ofl, isec, NULL, ident, NULL)) ==
782 	    (Os_desc *)S_ERROR)
783 		return (S_ERROR);
784 
785 	/*
786 	 * If relocations exist against a .*bss section, a section symbol must
787 	 * be created for the section in the .dynsym symbol table.
788 	 */
789 	if (!(osp->os_flags & FLG_OS_OUTREL)) {
790 		ofl_flag_t	flagtotest;
791 
792 		if (ident == ld_targ.t_id.id_tlsbss)
793 			flagtotest = FLG_OF1_TLSOREL;
794 		else
795 			flagtotest = FLG_OF1_BSSOREL;
796 
797 		if (ofl->ofl_flags1 & flagtotest) {
798 			ofl->ofl_dynshdrcnt++;
799 			osp->os_flags |= FLG_OS_OUTREL;
800 		}
801 	}
802 
803 	osp->os_szoutrels = rsize;
804 	return (1);
805 }
806 
807 /*
808  * Build a SHT_{INIT|FINI|PREINIT}ARRAY section (specified via
809  * ld -z *array=name).
810  */
811 static uintptr_t
812 make_array(Ofl_desc *ofl, Word shtype, const char *sectname, APlist *alp)
813 {
814 	uint_t		entcount;
815 	Aliste		idx;
816 	Elf_Data	*data;
817 	Is_desc		*isec;
818 	Shdr		*shdr;
819 	Sym_desc	*sdp;
820 	Rel_desc	reld;
821 	Rela		reloc;
822 	Os_desc		*osp;
823 	uintptr_t	ret = 1;
824 
825 	if (alp == NULL)
826 		return (1);
827 
828 	entcount = 0;
829 	for (APLIST_TRAVERSE(alp, idx, sdp))
830 		entcount++;
831 
832 	if (new_section(ofl, shtype, sectname, entcount, &isec, &shdr, &data) ==
833 	    S_ERROR)
834 		return (S_ERROR);
835 
836 	if ((data->d_buf = libld_calloc(sizeof (Addr), entcount)) == NULL)
837 		return (S_ERROR);
838 
839 	if (ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_array, NULL) ==
840 	    (Os_desc *)S_ERROR)
841 		return (S_ERROR);
842 
843 	osp = isec->is_osdesc;
844 
845 	if ((ofl->ofl_osinitarray == NULL) && (shtype == SHT_INIT_ARRAY))
846 		ofl->ofl_osinitarray = osp;
847 	if ((ofl->ofl_ospreinitarray == NULL) && (shtype == SHT_PREINIT_ARRAY))
848 		ofl->ofl_ospreinitarray = osp;
849 	else if ((ofl->ofl_osfiniarray == NULL) && (shtype == SHT_FINI_ARRAY))
850 		ofl->ofl_osfiniarray = osp;
851 
852 	/*
853 	 * Create relocations against this section to initialize it to the
854 	 * function addresses.
855 	 */
856 	reld.rel_isdesc = isec;
857 	reld.rel_aux = NULL;
858 	reld.rel_flags = FLG_REL_LOAD;
859 
860 	/*
861 	 * Fabricate the relocation information (as if a relocation record had
862 	 * been input - see init_rel()).
863 	 */
864 	reld.rel_rtype = ld_targ.t_m.m_r_arrayaddr;
865 	reld.rel_roffset = 0;
866 	reld.rel_raddend = 0;
867 
868 	/*
869 	 * Create a minimal relocation record to satisfy process_sym_reloc()
870 	 * debugging requirements.
871 	 */
872 	reloc.r_offset = 0;
873 	reloc.r_info = ELF_R_INFO(0, ld_targ.t_m.m_r_arrayaddr);
874 	reloc.r_addend = 0;
875 
876 	DBG_CALL(Dbg_reloc_generate(ofl->ofl_lml, osp,
877 	    ld_targ.t_m.m_rel_sht_type));
878 	for (APLIST_TRAVERSE(alp, idx, sdp)) {
879 		reld.rel_sym = sdp;
880 
881 		if (ld_process_sym_reloc(ofl, &reld, (Rel *)&reloc, isec,
882 		    MSG_INTL(MSG_STR_COMMAND), 0) == S_ERROR) {
883 			ret = S_ERROR;
884 			continue;
885 		}
886 
887 		reld.rel_roffset += (Xword)sizeof (Addr);
888 		reloc.r_offset = reld.rel_roffset;
889 	}
890 
891 	return (ret);
892 }
893 
894 /*
895  * Build a comment section (-Qy option).
896  */
897 static uintptr_t
898 make_comment(Ofl_desc *ofl)
899 {
900 	Shdr		*shdr;
901 	Elf_Data	*data;
902 	Is_desc		*isec;
903 
904 	if (new_section(ofl, SHT_PROGBITS, MSG_ORIG(MSG_SCN_COMMENT), 0,
905 	    &isec, &shdr, &data) == S_ERROR)
906 		return (S_ERROR);
907 
908 	data->d_buf = (void *)ofl->ofl_sgsid;
909 	data->d_size = strlen(ofl->ofl_sgsid) + 1;
910 	data->d_align = 1;
911 
912 	shdr->sh_size = (Xword)data->d_size;
913 	shdr->sh_flags = 0;
914 	shdr->sh_addralign = 1;
915 
916 	return ((uintptr_t)ld_place_section(ofl, isec, NULL,
917 	    ld_targ.t_id.id_note, NULL));
918 }
919 
920 /*
921  * Make the dynamic section.  Calculate the size of any strings referenced
922  * within this structure, they will be added to the global string table
923  * (.dynstr).  This routine should be called before make_dynstr().
924  *
925  * This routine must be maintained in parallel with update_odynamic()
926  * in update.c
927  */
928 static uintptr_t
929 make_dynamic(Ofl_desc *ofl)
930 {
931 	Shdr		*shdr;
932 	Os_desc		*osp;
933 	Elf_Data	*data;
934 	Is_desc		*isec;
935 	size_t		cnt = 0;
936 	Aliste		idx;
937 	Ifl_desc	*ifl;
938 	Sym_desc	*sdp;
939 	size_t		size;
940 	Str_tbl		*strtbl;
941 	ofl_flag_t	flags = ofl->ofl_flags;
942 	int		not_relobj = !(flags & FLG_OF_RELOBJ);
943 	int		unused = 0;
944 
945 	/*
946 	 * Select the required string table.
947 	 */
948 	if (OFL_IS_STATIC_OBJ(ofl))
949 		strtbl = ofl->ofl_strtab;
950 	else
951 		strtbl = ofl->ofl_dynstrtab;
952 
953 	/*
954 	 * Only a limited subset of DT_ entries apply to relocatable
955 	 * objects. See the comment at the head of update_odynamic() in
956 	 * update.c for details.
957 	 */
958 	if (new_section(ofl, SHT_DYNAMIC, MSG_ORIG(MSG_SCN_DYNAMIC), 0,
959 	    &isec, &shdr, &data) == S_ERROR)
960 		return (S_ERROR);
961 
962 	/*
963 	 * new_section() does not set SHF_ALLOC.  If we're building anything
964 	 * besides a relocatable object, then the .dynamic section should
965 	 * reside in allocatable memory.
966 	 */
967 	if (not_relobj)
968 		shdr->sh_flags |= SHF_ALLOC;
969 
970 	/*
971 	 * new_section() does not set SHF_WRITE.  If we're building an object
972 	 * that specifies an interpretor, then a DT_DEBUG entry is created,
973 	 * which is initialized to the applications link-map list at runtime.
974 	 */
975 	if (ofl->ofl_osinterp)
976 		shdr->sh_flags |= SHF_WRITE;
977 
978 	osp = ofl->ofl_osdynamic =
979 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_dynamic, NULL);
980 
981 	/*
982 	 * Reserve entries for any needed dependencies.
983 	 */
984 	for (APLIST_TRAVERSE(ofl->ofl_sos, idx, ifl)) {
985 		if (!(ifl->ifl_flags & (FLG_IF_NEEDED | FLG_IF_NEEDSTR)))
986 			continue;
987 
988 		/*
989 		 * If this dependency didn't satisfy any symbol references,
990 		 * generate a debugging diagnostic (ld(1) -Dunused can be used
991 		 * to display these).  If this is a standard needed dependency,
992 		 * and -z ignore is in effect, drop the dependency.  Explicitly
993 		 * defined dependencies (i.e., -N dep) don't get dropped, and
994 		 * are flagged as being required to simplify update_odynamic()
995 		 * processing.
996 		 */
997 		if ((ifl->ifl_flags & FLG_IF_NEEDSTR) ||
998 		    ((ifl->ifl_flags & FLG_IF_DEPREQD) == 0)) {
999 			if (unused++ == 0)
1000 				DBG_CALL(Dbg_util_nl(ofl->ofl_lml, DBG_NL_STD));
1001 			DBG_CALL(Dbg_unused_file(ofl->ofl_lml, ifl->ifl_soname,
1002 			    (ifl->ifl_flags & FLG_IF_NEEDSTR), 0));
1003 
1004 			if (ifl->ifl_flags & FLG_IF_NEEDSTR)
1005 				ifl->ifl_flags |= FLG_IF_DEPREQD;
1006 			else if (ifl->ifl_flags & FLG_IF_IGNORE)
1007 				continue;
1008 		}
1009 
1010 		/*
1011 		 * If this object requires a DT_POSFLAG_1 entry, reserve it.
1012 		 */
1013 		if ((ifl->ifl_flags & MSK_IF_POSFLAG1) && not_relobj)
1014 			cnt++;
1015 
1016 		if (st_insert(strtbl, ifl->ifl_soname) == -1)
1017 			return (S_ERROR);
1018 		cnt++;
1019 
1020 		/*
1021 		 * If the needed entry contains the $ORIGIN token make sure
1022 		 * the associated DT_1_FLAGS entry is created.
1023 		 */
1024 		if (strstr(ifl->ifl_soname, MSG_ORIG(MSG_STR_ORIGIN))) {
1025 			ofl->ofl_dtflags_1 |= DF_1_ORIGIN;
1026 			ofl->ofl_dtflags |= DF_ORIGIN;
1027 		}
1028 	}
1029 
1030 	if (unused)
1031 		DBG_CALL(Dbg_util_nl(ofl->ofl_lml, DBG_NL_STD));
1032 
1033 	if (not_relobj) {
1034 		/*
1035 		 * Reserve entries for any per-symbol auxiliary/filter strings.
1036 		 */
1037 		cnt += alist_nitems(ofl->ofl_dtsfltrs);
1038 
1039 		/*
1040 		 * Reserve entries for _init() and _fini() section addresses.
1041 		 */
1042 		if (((sdp = ld_sym_find(MSG_ORIG(MSG_SYM_INIT_U),
1043 		    SYM_NOHASH, NULL, ofl)) != NULL) &&
1044 		    (sdp->sd_ref == REF_REL_NEED) &&
1045 		    (sdp->sd_sym->st_shndx != SHN_UNDEF)) {
1046 			sdp->sd_flags |= FLG_SY_UPREQD;
1047 			cnt++;
1048 		}
1049 		if (((sdp = ld_sym_find(MSG_ORIG(MSG_SYM_FINI_U),
1050 		    SYM_NOHASH, NULL, ofl)) != NULL) &&
1051 		    (sdp->sd_ref == REF_REL_NEED) &&
1052 		    (sdp->sd_sym->st_shndx != SHN_UNDEF)) {
1053 			sdp->sd_flags |= FLG_SY_UPREQD;
1054 			cnt++;
1055 		}
1056 
1057 		/*
1058 		 * Reserve entries for any soname, filter name (shared libs
1059 		 * only), run-path pointers, cache names and audit requirements.
1060 		 */
1061 		if (ofl->ofl_soname) {
1062 			cnt++;
1063 			if (st_insert(strtbl, ofl->ofl_soname) == -1)
1064 				return (S_ERROR);
1065 		}
1066 		if (ofl->ofl_filtees) {
1067 			cnt++;
1068 			if (st_insert(strtbl, ofl->ofl_filtees) == -1)
1069 				return (S_ERROR);
1070 
1071 			/*
1072 			 * If the filtees entry contains the $ORIGIN token
1073 			 * make sure the associated DT_1_FLAGS entry is created.
1074 			 */
1075 			if (strstr(ofl->ofl_filtees,
1076 			    MSG_ORIG(MSG_STR_ORIGIN))) {
1077 				ofl->ofl_dtflags_1 |= DF_1_ORIGIN;
1078 				ofl->ofl_dtflags |= DF_ORIGIN;
1079 			}
1080 		}
1081 	}
1082 
1083 	if (ofl->ofl_rpath) {
1084 		cnt += 2;	/* DT_RPATH & DT_RUNPATH */
1085 		if (st_insert(strtbl, ofl->ofl_rpath) == -1)
1086 			return (S_ERROR);
1087 
1088 		/*
1089 		 * If the rpath entry contains the $ORIGIN token make sure
1090 		 * the associated DT_1_FLAGS entry is created.
1091 		 */
1092 		if (strstr(ofl->ofl_rpath, MSG_ORIG(MSG_STR_ORIGIN))) {
1093 			ofl->ofl_dtflags_1 |= DF_1_ORIGIN;
1094 			ofl->ofl_dtflags |= DF_ORIGIN;
1095 		}
1096 	}
1097 
1098 	if (not_relobj) {
1099 		Aliste	idx;
1100 		Sg_desc	*sgp;
1101 
1102 		if (ofl->ofl_config) {
1103 			cnt++;
1104 			if (st_insert(strtbl, ofl->ofl_config) == -1)
1105 				return (S_ERROR);
1106 
1107 			/*
1108 			 * If the config entry contains the $ORIGIN token
1109 			 * make sure the associated DT_1_FLAGS entry is created.
1110 			 */
1111 			if (strstr(ofl->ofl_config, MSG_ORIG(MSG_STR_ORIGIN))) {
1112 				ofl->ofl_dtflags_1 |= DF_1_ORIGIN;
1113 				ofl->ofl_dtflags |= DF_ORIGIN;
1114 			}
1115 		}
1116 		if (ofl->ofl_depaudit) {
1117 			cnt++;
1118 			if (st_insert(strtbl, ofl->ofl_depaudit) == -1)
1119 				return (S_ERROR);
1120 		}
1121 		if (ofl->ofl_audit) {
1122 			cnt++;
1123 			if (st_insert(strtbl, ofl->ofl_audit) == -1)
1124 				return (S_ERROR);
1125 		}
1126 
1127 		/*
1128 		 * Reserve entries for the DT_HASH, DT_STRTAB, DT_STRSZ,
1129 		 * DT_SYMTAB, DT_SYMENT, and DT_CHECKSUM.
1130 		 */
1131 		cnt += 6;
1132 
1133 		/*
1134 		 * If we are including local functions at the head of
1135 		 * the dynsym, then also reserve entries for DT_SUNW_SYMTAB
1136 		 * and DT_SUNW_SYMSZ.
1137 		 */
1138 		if (OFL_ALLOW_LDYNSYM(ofl))
1139 			cnt += 2;
1140 
1141 		if ((ofl->ofl_dynsymsortcnt > 0) ||
1142 		    (ofl->ofl_dyntlssortcnt > 0))
1143 			cnt++;		/* DT_SUNW_SORTENT */
1144 
1145 		if (ofl->ofl_dynsymsortcnt > 0)
1146 			cnt += 2;	/* DT_SUNW_[SYMSORT|SYMSORTSZ] */
1147 
1148 		if (ofl->ofl_dyntlssortcnt > 0)
1149 			cnt += 2;	/* DT_SUNW_[TLSSORT|TLSSORTSZ] */
1150 
1151 		if ((flags & (FLG_OF_VERDEF | FLG_OF_NOVERSEC)) ==
1152 		    FLG_OF_VERDEF)
1153 			cnt += 2;		/* DT_VERDEF & DT_VERDEFNUM */
1154 
1155 		if ((flags & (FLG_OF_VERNEED | FLG_OF_NOVERSEC)) ==
1156 		    FLG_OF_VERNEED)
1157 			cnt += 2;		/* DT_VERNEED & DT_VERNEEDNUM */
1158 
1159 		if ((flags & FLG_OF_COMREL) && ofl->ofl_relocrelcnt)
1160 			cnt++;			/* DT_RELACOUNT */
1161 
1162 		if (flags & FLG_OF_TEXTREL)	/* DT_TEXTREL */
1163 			cnt++;
1164 
1165 		if (ofl->ofl_osfiniarray)	/* DT_FINI_ARRAY */
1166 			cnt += 2;		/*    DT_FINI_ARRAYSZ */
1167 
1168 		if (ofl->ofl_osinitarray)	/* DT_INIT_ARRAY */
1169 			cnt += 2;		/*    DT_INIT_ARRAYSZ */
1170 
1171 		if (ofl->ofl_ospreinitarray)	/* DT_PREINIT_ARRAY & */
1172 			cnt += 2;		/*    DT_PREINIT_ARRAYSZ */
1173 
1174 		/*
1175 		 * If we have plt's reserve a DT_PLTRELSZ, DT_PLTREL and
1176 		 * DT_JMPREL.
1177 		 */
1178 		if (ofl->ofl_pltcnt)
1179 			cnt += 3;
1180 
1181 		/*
1182 		 * If plt padding is needed (Sparcv9).
1183 		 */
1184 		if (ofl->ofl_pltpad)
1185 			cnt += 2;		/* DT_PLTPAD & DT_PLTPADSZ */
1186 
1187 		/*
1188 		 * If we have any relocations reserve a DT_REL, DT_RELSZ and
1189 		 * DT_RELENT entry.
1190 		 */
1191 		if (ofl->ofl_relocsz)
1192 			cnt += 3;
1193 
1194 		/*
1195 		 * If a syminfo section is required create DT_SYMINFO,
1196 		 * DT_SYMINSZ, and DT_SYMINENT entries.
1197 		 */
1198 		if (flags & FLG_OF_SYMINFO)
1199 			cnt += 3;
1200 
1201 		/*
1202 		 * If there are any partially initialized sections allocate
1203 		 * DT_MOVETAB, DT_MOVESZ and DT_MOVEENT.
1204 		 */
1205 		if (ofl->ofl_osmove)
1206 			cnt += 3;
1207 
1208 		/*
1209 		 * Allocate one DT_REGISTER entry for every register symbol.
1210 		 */
1211 		cnt += ofl->ofl_regsymcnt;
1212 
1213 		/*
1214 		 * Reserve a entry for each '-zrtldinfo=...' specified
1215 		 * on the command line.
1216 		 */
1217 		for (APLIST_TRAVERSE(ofl->ofl_rtldinfo, idx, sdp))
1218 			cnt++;
1219 
1220 		/*
1221 		 * The following entry should only be placed in a segment that
1222 		 * is writable.
1223 		 */
1224 		if (((sgp = osp->os_sgdesc) != NULL) &&
1225 		    (sgp->sg_phdr.p_flags & PF_W) && ofl->ofl_osinterp)
1226 			cnt++;		/* DT_DEBUG */
1227 
1228 		/*
1229 		 * Capabilities require a .dynamic entry for the .SUNW_cap
1230 		 * section.
1231 		 */
1232 		if (ofl->ofl_oscap)
1233 			cnt++;			/* DT_SUNW_CAP */
1234 
1235 		/*
1236 		 * Symbol capabilities require a .dynamic entry for the
1237 		 * .SUNW_capinfo section.
1238 		 */
1239 		if (ofl->ofl_oscapinfo)
1240 			cnt++;			/* DT_SUNW_CAPINFO */
1241 
1242 		/*
1243 		 * Capabilities chain information requires a .SUNW_capchain
1244 		 * entry (DT_SUNW_CAPCHAIN), entry size (DT_SUNW_CAPCHAINENT),
1245 		 * and total size (DT_SUNW_CAPCHAINSZ).
1246 		 */
1247 		if (ofl->ofl_oscapchain)
1248 			cnt += 3;
1249 
1250 		if (flags & FLG_OF_SYMBOLIC)
1251 			cnt++;			/* DT_SYMBOLIC */
1252 	}
1253 
1254 	/*
1255 	 * Account for Architecture dependent .dynamic entries, and defaults.
1256 	 */
1257 	(*ld_targ.t_mr.mr_mach_make_dynamic)(ofl, &cnt);
1258 
1259 	/*
1260 	 * DT_FLAGS, DT_FLAGS_1, DT_SUNW_STRPAD, and DT_NULL. Also,
1261 	 * allow room for the unused extra DT_NULLs. These are included
1262 	 * to allow an ELF editor room to add items later.
1263 	 */
1264 	cnt += 4 + DYNAMIC_EXTRA_ELTS;
1265 
1266 	/*
1267 	 * DT_SUNW_LDMACH. Used to hold the ELF machine code of the
1268 	 * linker that produced the output object. This information
1269 	 * allows us to determine whether a given object was linked
1270 	 * natively, or by a linker running on a different type of
1271 	 * system. This information can be valuable if one suspects
1272 	 * that a problem might be due to alignment or byte order issues.
1273 	 */
1274 	cnt++;
1275 
1276 	/*
1277 	 * Determine the size of the section from the number of entries.
1278 	 */
1279 	size = cnt * (size_t)shdr->sh_entsize;
1280 
1281 	shdr->sh_size = (Xword)size;
1282 	data->d_size = size;
1283 
1284 	/*
1285 	 * There are several tags that are specific to the Solaris osabi
1286 	 * range which we unconditionally put into any dynamic section
1287 	 * we create (e.g. DT_SUNW_STRPAD or DT_SUNW_LDMACH). As such,
1288 	 * any Solaris object with a dynamic section should be tagged as
1289 	 * ELFOSABI_SOLARIS.
1290 	 */
1291 	ofl->ofl_flags |= FLG_OF_OSABI;
1292 
1293 	return ((uintptr_t)ofl->ofl_osdynamic);
1294 }
1295 
1296 /*
1297  * Build the GOT section and its associated relocation entries.
1298  */
1299 uintptr_t
1300 ld_make_got(Ofl_desc *ofl)
1301 {
1302 	Elf_Data	*data;
1303 	Shdr	*shdr;
1304 	Is_desc	*isec;
1305 	size_t	size = (size_t)ofl->ofl_gotcnt * ld_targ.t_m.m_got_entsize;
1306 	size_t	rsize = (size_t)ofl->ofl_relocgotsz;
1307 
1308 	if (new_section(ofl, SHT_PROGBITS, MSG_ORIG(MSG_SCN_GOT), 0,
1309 	    &isec, &shdr, &data) == S_ERROR)
1310 		return (S_ERROR);
1311 
1312 	data->d_size = size;
1313 
1314 	shdr->sh_flags |= SHF_WRITE;
1315 	shdr->sh_size = (Xword)size;
1316 	shdr->sh_entsize = ld_targ.t_m.m_got_entsize;
1317 
1318 	ofl->ofl_osgot = ld_place_section(ofl, isec, NULL,
1319 	    ld_targ.t_id.id_got, NULL);
1320 	if (ofl->ofl_osgot == (Os_desc *)S_ERROR)
1321 		return (S_ERROR);
1322 
1323 	ofl->ofl_osgot->os_szoutrels = (Xword)rsize;
1324 
1325 	return (1);
1326 }
1327 
1328 /*
1329  * Build an interpreter section.
1330  */
1331 static uintptr_t
1332 make_interp(Ofl_desc *ofl)
1333 {
1334 	Shdr		*shdr;
1335 	Elf_Data	*data;
1336 	Is_desc		*isec;
1337 	const char	*iname = ofl->ofl_interp;
1338 	size_t		size;
1339 
1340 	/*
1341 	 * If -z nointerp is in effect, don't create an interpreter section.
1342 	 */
1343 	if (ofl->ofl_flags1 & FLG_OF1_NOINTRP)
1344 		return (1);
1345 
1346 	/*
1347 	 * An .interp section is always created for a dynamic executable.
1348 	 * A user can define the interpreter to use.  This definition overrides
1349 	 * the default that would be recorded in an executable, and triggers
1350 	 * the creation of an .interp section in any other object.  Presumably
1351 	 * the user knows what they are doing.  Refer to the generic ELF ABI
1352 	 * section 5-4, and the ld(1) -I option.
1353 	 */
1354 	if (((ofl->ofl_flags & (FLG_OF_DYNAMIC | FLG_OF_EXEC |
1355 	    FLG_OF_RELOBJ)) != (FLG_OF_DYNAMIC | FLG_OF_EXEC)) && !iname)
1356 		return (1);
1357 
1358 	/*
1359 	 * In the case of a dynamic executable, supply a default interpreter
1360 	 * if the user has not specified their own.
1361 	 */
1362 	if (iname == NULL)
1363 		iname = ofl->ofl_interp = ld_targ.t_m.m_def_interp;
1364 
1365 	size = strlen(iname) + 1;
1366 
1367 	if (new_section(ofl, SHT_PROGBITS, MSG_ORIG(MSG_SCN_INTERP), 0,
1368 	    &isec, &shdr, &data) == S_ERROR)
1369 		return (S_ERROR);
1370 
1371 	data->d_size = size;
1372 	shdr->sh_size = (Xword)size;
1373 	data->d_align = shdr->sh_addralign = 1;
1374 
1375 	ofl->ofl_osinterp =
1376 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_interp, NULL);
1377 	return ((uintptr_t)ofl->ofl_osinterp);
1378 }
1379 
1380 /*
1381  * Common function used to build the SHT_SUNW_versym section, SHT_SUNW_syminfo
1382  * section, and SHT_SUNW_capinfo section.  Each of these sections provide
1383  * additional symbol information, and their size parallels the associated
1384  * symbol table.
1385  */
1386 static Os_desc *
1387 make_sym_sec(Ofl_desc *ofl, const char *sectname, Word stype, int ident)
1388 {
1389 	Shdr		*shdr;
1390 	Elf_Data	*data;
1391 	Is_desc		*isec;
1392 
1393 	/*
1394 	 * We don't know the size of this section yet, so set it to 0.  The
1395 	 * size gets filled in after the associated symbol table is sized.
1396 	 */
1397 	if (new_section(ofl, stype, sectname, 0, &isec, &shdr, &data) ==
1398 	    S_ERROR)
1399 		return ((Os_desc *)S_ERROR);
1400 
1401 	return (ld_place_section(ofl, isec, NULL, ident, NULL));
1402 }
1403 
1404 /*
1405  * Determine whether a symbol capability is redundant because the object
1406  * capabilities are more restrictive.
1407  */
1408 inline static int
1409 is_cap_redundant(Objcapset *ocapset, Objcapset *scapset)
1410 {
1411 	Alist		*oalp, *salp;
1412 	elfcap_mask_t	omsk, smsk;
1413 
1414 	/*
1415 	 * Inspect any platform capabilities.  If the object defines platform
1416 	 * capabilities, then the object will only be loaded for those
1417 	 * platforms.  A symbol capability set that doesn't define the same
1418 	 * platforms is redundant, and a symbol capability that does not provide
1419 	 * at least one platform name that matches a platform name in the object
1420 	 * capabilities will never execute (as the object wouldn't have been
1421 	 * loaded).
1422 	 */
1423 	oalp = ocapset->oc_plat.cl_val;
1424 	salp = scapset->oc_plat.cl_val;
1425 	if (oalp && ((salp == NULL) || cap_names_match(oalp, salp)))
1426 		return (1);
1427 
1428 	/*
1429 	 * If the symbol capability set defines platforms, and the object
1430 	 * doesn't, then the symbol set is more restrictive.
1431 	 */
1432 	if (salp && (oalp == NULL))
1433 		return (0);
1434 
1435 	/*
1436 	 * Next, inspect any machine name capabilities.  If the object defines
1437 	 * machine name capabilities, then the object will only be loaded for
1438 	 * those machines.  A symbol capability set that doesn't define the same
1439 	 * machine names is redundant, and a symbol capability that does not
1440 	 * provide at least one machine name that matches a machine name in the
1441 	 * object capabilities will never execute (as the object wouldn't have
1442 	 * been loaded).
1443 	 */
1444 	oalp = ocapset->oc_plat.cl_val;
1445 	salp = scapset->oc_plat.cl_val;
1446 	if (oalp && ((salp == NULL) || cap_names_match(oalp, salp)))
1447 		return (1);
1448 
1449 	/*
1450 	 * If the symbol capability set defines machine names, and the object
1451 	 * doesn't, then the symbol set is more restrictive.
1452 	 */
1453 	if (salp && (oalp == NULL))
1454 		return (0);
1455 
1456 	/*
1457 	 * Next, inspect any hardware capabilities.  If the objects hardware
1458 	 * capabilities are greater than or equal to that of the symbols
1459 	 * capabilities, then the symbol capability set is redundant.  If the
1460 	 * symbols hardware capabilities are greater that the objects, then the
1461 	 * symbol set is more restrictive.
1462 	 *
1463 	 * Note that this is a somewhat arbitrary definition, as each capability
1464 	 * bit is independent of the others, and some of the higher order bits
1465 	 * could be considered to be less important than lower ones.  However,
1466 	 * this is the only reasonable non-subjective definition.
1467 	 */
1468 	omsk = ocapset->oc_hw_2.cm_val;
1469 	smsk = scapset->oc_hw_2.cm_val;
1470 	if ((omsk > smsk) || (omsk && (omsk == smsk)))
1471 		return (1);
1472 	if (omsk < smsk)
1473 		return (0);
1474 
1475 	/*
1476 	 * Finally, inspect the remaining hardware capabilities.
1477 	 */
1478 	omsk = ocapset->oc_hw_1.cm_val;
1479 	smsk = scapset->oc_hw_1.cm_val;
1480 	if ((omsk > smsk) || (omsk && (omsk == smsk)))
1481 		return (1);
1482 
1483 	return (0);
1484 }
1485 
1486 /*
1487  * Capabilities values might have been assigned excluded values.  These
1488  * excluded values should be removed before calculating any capabilities
1489  * sections size.
1490  */
1491 static void
1492 capmask_value(Lm_list *lml, Word type, Capmask *capmask, int *title)
1493 {
1494 	/*
1495 	 * First determine whether any bits should be excluded.
1496 	 */
1497 	if ((capmask->cm_val & capmask->cm_exc) == 0)
1498 		return;
1499 
1500 	DBG_CALL(Dbg_cap_post_title(lml, title));
1501 
1502 	DBG_CALL(Dbg_cap_val_entry(lml, DBG_STATE_CURRENT, type,
1503 	    capmask->cm_val, ld_targ.t_m.m_mach));
1504 	DBG_CALL(Dbg_cap_val_entry(lml, DBG_STATE_EXCLUDE, type,
1505 	    capmask->cm_exc, ld_targ.t_m.m_mach));
1506 
1507 	capmask->cm_val &= ~capmask->cm_exc;
1508 
1509 	DBG_CALL(Dbg_cap_val_entry(lml, DBG_STATE_RESOLVED, type,
1510 	    capmask->cm_val, ld_targ.t_m.m_mach));
1511 }
1512 
1513 static void
1514 capstr_value(Lm_list *lml, Word type, Caplist *caplist, int *title)
1515 {
1516 	Aliste	idx1, idx2;
1517 	char	*estr;
1518 	Capstr	*capstr;
1519 	Boolean	found = FALSE;
1520 
1521 	/*
1522 	 * First determine whether any strings should be excluded.
1523 	 */
1524 	for (APLIST_TRAVERSE(caplist->cl_exc, idx1, estr)) {
1525 		for (ALIST_TRAVERSE(caplist->cl_val, idx2, capstr)) {
1526 			if (strcmp(estr, capstr->cs_str) == 0) {
1527 				found = TRUE;
1528 				break;
1529 			}
1530 		}
1531 	}
1532 
1533 	if (found == FALSE)
1534 		return;
1535 
1536 	/*
1537 	 * Traverse the current strings, then delete the excluded strings,
1538 	 * and finally display the resolved strings.
1539 	 */
1540 	if (DBG_ENABLED) {
1541 		Dbg_cap_post_title(lml, title);
1542 		for (ALIST_TRAVERSE(caplist->cl_val, idx2, capstr)) {
1543 			Dbg_cap_ptr_entry(lml, DBG_STATE_CURRENT, type,
1544 			    capstr->cs_str);
1545 		}
1546 	}
1547 	for (APLIST_TRAVERSE(caplist->cl_exc, idx1, estr)) {
1548 		for (ALIST_TRAVERSE(caplist->cl_val, idx2, capstr)) {
1549 			if (strcmp(estr, capstr->cs_str) == 0) {
1550 				DBG_CALL(Dbg_cap_ptr_entry(lml,
1551 				    DBG_STATE_EXCLUDE, type, capstr->cs_str));
1552 				alist_delete(caplist->cl_val, &idx2);
1553 				break;
1554 			}
1555 		}
1556 	}
1557 	if (DBG_ENABLED) {
1558 		for (ALIST_TRAVERSE(caplist->cl_val, idx2, capstr)) {
1559 			Dbg_cap_ptr_entry(lml, DBG_STATE_RESOLVED, type,
1560 			    capstr->cs_str);
1561 		}
1562 	}
1563 }
1564 
1565 /*
1566  * Build a capabilities section.
1567  */
1568 #define	CAP_UPDATE(cap, capndx, tag, val)	\
1569 	cap->c_tag = tag; \
1570 	cap->c_un.c_val = val; \
1571 	cap++, capndx++;
1572 
1573 static uintptr_t
1574 make_cap(Ofl_desc *ofl, Word shtype, const char *shname, int ident)
1575 {
1576 	Shdr		*shdr;
1577 	Elf_Data	*data;
1578 	Is_desc		*isec;
1579 	Cap		*cap;
1580 	size_t		size = 0;
1581 	Word		capndx = 0;
1582 	Str_tbl		*strtbl;
1583 	Objcapset	*ocapset = &ofl->ofl_ocapset;
1584 	Aliste		idx1;
1585 	Capstr		*capstr;
1586 	int		title = 0;
1587 
1588 	/*
1589 	 * Determine which string table to use for any CA_SUNW_MACH,
1590 	 * CA_SUNW_PLAT, or CA_SUNW_ID strings.
1591 	 */
1592 	if (OFL_IS_STATIC_OBJ(ofl))
1593 		strtbl = ofl->ofl_strtab;
1594 	else
1595 		strtbl = ofl->ofl_dynstrtab;
1596 
1597 	/*
1598 	 * If symbol capabilities have been requested, but none have been
1599 	 * created, warn the user.  This scenario can occur if none of the
1600 	 * input relocatable objects defined any object capabilities.
1601 	 */
1602 	if ((ofl->ofl_flags & FLG_OF_OTOSCAP) && (ofl->ofl_capsymcnt == 0)) {
1603 		eprintf(ofl->ofl_lml, ERR_WARNING,
1604 		    MSG_INTL(MSG_CAP_NOSYMSFOUND));
1605 	}
1606 
1607 	/*
1608 	 * If symbol capabilities have been collected, but no symbols are left
1609 	 * referencing these capabilities, promote the capability groups back
1610 	 * to an object capability definition.
1611 	 */
1612 	if ((ofl->ofl_flags & FLG_OF_OTOSCAP) && ofl->ofl_capsymcnt &&
1613 	    (ofl->ofl_capfamilies == NULL)) {
1614 		eprintf(ofl->ofl_lml, ERR_WARNING,
1615 		    MSG_INTL(MSG_CAP_NOSYMSFOUND));
1616 		ld_cap_move_symtoobj(ofl);
1617 		ofl->ofl_capsymcnt = 0;
1618 		ofl->ofl_capgroups = NULL;
1619 		ofl->ofl_flags &= ~FLG_OF_OTOSCAP;
1620 	}
1621 
1622 	/*
1623 	 * Remove any excluded capabilities.
1624 	 */
1625 	capstr_value(ofl->ofl_lml, CA_SUNW_PLAT, &ocapset->oc_plat, &title);
1626 	capstr_value(ofl->ofl_lml, CA_SUNW_MACH, &ocapset->oc_mach, &title);
1627 	capmask_value(ofl->ofl_lml, CA_SUNW_HW_2, &ocapset->oc_hw_2, &title);
1628 	capmask_value(ofl->ofl_lml, CA_SUNW_HW_1, &ocapset->oc_hw_1, &title);
1629 	capmask_value(ofl->ofl_lml, CA_SUNW_SF_1, &ocapset->oc_sf_1, &title);
1630 
1631 	/*
1632 	 * Determine how many entries are required for any object capabilities.
1633 	 */
1634 	size += alist_nitems(ocapset->oc_plat.cl_val);
1635 	size += alist_nitems(ocapset->oc_mach.cl_val);
1636 	if (ocapset->oc_hw_2.cm_val)
1637 		size++;
1638 	if (ocapset->oc_hw_1.cm_val)
1639 		size++;
1640 	if (ocapset->oc_sf_1.cm_val)
1641 		size++;
1642 
1643 	/*
1644 	 * Only identify a capabilities group if the group has content.  If a
1645 	 * capabilities identifier exists, and no other capabilities have been
1646 	 * supplied, remove the identifier.  This scenario could exist if a
1647 	 * user mistakenly defined a lone identifier, or if an identified group
1648 	 * was overridden so as to clear the existing capabilities and the
1649 	 * identifier was not also cleared.
1650 	 */
1651 	if (ocapset->oc_id.cs_str) {
1652 		if (size)
1653 			size++;
1654 		else
1655 			ocapset->oc_id.cs_str = NULL;
1656 	}
1657 	if (size)
1658 		size++;			/* Add CA_SUNW_NULL */
1659 
1660 	/*
1661 	 * Determine how many entries are required for any symbol capabilities.
1662 	 */
1663 	if (ofl->ofl_capsymcnt) {
1664 		/*
1665 		 * If there are no object capabilities, a CA_SUNW_NULL entry
1666 		 * is required before any symbol capabilities.
1667 		 */
1668 		if (size == 0)
1669 			size++;
1670 		size += ofl->ofl_capsymcnt;
1671 	}
1672 
1673 	if (size == 0)
1674 		return (NULL);
1675 
1676 	if (new_section(ofl, shtype, shname, size, &isec,
1677 	    &shdr, &data) == S_ERROR)
1678 		return (S_ERROR);
1679 
1680 	if ((data->d_buf = libld_malloc(shdr->sh_size)) == NULL)
1681 		return (S_ERROR);
1682 
1683 	cap = (Cap *)data->d_buf;
1684 
1685 	/*
1686 	 * Fill in any object capabilities.  If there is an identifier, then the
1687 	 * identifier comes first.  The remaining items follow in precedence
1688 	 * order, although the order isn't important for runtime verification.
1689 	 */
1690 	if (ocapset->oc_id.cs_str) {
1691 		ofl->ofl_flags |= FLG_OF_CAPSTRS;
1692 		if (st_insert(strtbl, ocapset->oc_id.cs_str) == -1)
1693 			return (S_ERROR);
1694 		ocapset->oc_id.cs_ndx = capndx;
1695 		CAP_UPDATE(cap, capndx, CA_SUNW_ID, 0);
1696 	}
1697 	if (ocapset->oc_plat.cl_val) {
1698 		ofl->ofl_flags |= (FLG_OF_PTCAP | FLG_OF_CAPSTRS);
1699 
1700 		/*
1701 		 * Insert any platform name strings in the appropriate string
1702 		 * table.  The capability value can't be filled in yet, as the
1703 		 * final offset of the strings isn't known until later.
1704 		 */
1705 		for (ALIST_TRAVERSE(ocapset->oc_plat.cl_val, idx1, capstr)) {
1706 			if (st_insert(strtbl, capstr->cs_str) == -1)
1707 				return (S_ERROR);
1708 			capstr->cs_ndx = capndx;
1709 			CAP_UPDATE(cap, capndx, CA_SUNW_PLAT, 0);
1710 		}
1711 	}
1712 	if (ocapset->oc_mach.cl_val) {
1713 		ofl->ofl_flags |= (FLG_OF_PTCAP | FLG_OF_CAPSTRS);
1714 
1715 		/*
1716 		 * Insert the machine name strings in the appropriate string
1717 		 * table.  The capability value can't be filled in yet, as the
1718 		 * final offset of the strings isn't known until later.
1719 		 */
1720 		for (ALIST_TRAVERSE(ocapset->oc_mach.cl_val, idx1, capstr)) {
1721 			if (st_insert(strtbl, capstr->cs_str) == -1)
1722 				return (S_ERROR);
1723 			capstr->cs_ndx = capndx;
1724 			CAP_UPDATE(cap, capndx, CA_SUNW_MACH, 0);
1725 		}
1726 	}
1727 	if (ocapset->oc_hw_2.cm_val) {
1728 		ofl->ofl_flags |= FLG_OF_PTCAP;
1729 		CAP_UPDATE(cap, capndx, CA_SUNW_HW_2, ocapset->oc_hw_2.cm_val);
1730 	}
1731 	if (ocapset->oc_hw_1.cm_val) {
1732 		ofl->ofl_flags |= FLG_OF_PTCAP;
1733 		CAP_UPDATE(cap, capndx, CA_SUNW_HW_1, ocapset->oc_hw_1.cm_val);
1734 	}
1735 	if (ocapset->oc_sf_1.cm_val) {
1736 		ofl->ofl_flags |= FLG_OF_PTCAP;
1737 		CAP_UPDATE(cap, capndx, CA_SUNW_SF_1, ocapset->oc_sf_1.cm_val);
1738 	}
1739 	CAP_UPDATE(cap, capndx, CA_SUNW_NULL, 0);
1740 
1741 	/*
1742 	 * Fill in any symbol capabilities.
1743 	 */
1744 	if (ofl->ofl_capgroups) {
1745 		Cap_group	*cgp;
1746 
1747 		for (APLIST_TRAVERSE(ofl->ofl_capgroups, idx1, cgp)) {
1748 			Objcapset	*scapset = &cgp->cg_set;
1749 			Aliste		idx2;
1750 			Is_desc		*isp;
1751 
1752 			cgp->cg_ndx = capndx;
1753 
1754 			if (scapset->oc_id.cs_str) {
1755 				ofl->ofl_flags |= FLG_OF_CAPSTRS;
1756 				/*
1757 				 * Insert the identifier string in the
1758 				 * appropriate string table.  The capability
1759 				 * value can't be filled in yet, as the final
1760 				 * offset of the string isn't known until later.
1761 				 */
1762 				if (st_insert(strtbl,
1763 				    scapset->oc_id.cs_str) == -1)
1764 					return (S_ERROR);
1765 				scapset->oc_id.cs_ndx = capndx;
1766 				CAP_UPDATE(cap, capndx, CA_SUNW_ID, 0);
1767 			}
1768 
1769 			if (scapset->oc_plat.cl_val) {
1770 				ofl->ofl_flags |= FLG_OF_CAPSTRS;
1771 
1772 				/*
1773 				 * Insert the platform name string in the
1774 				 * appropriate string table.  The capability
1775 				 * value can't be filled in yet, as the final
1776 				 * offset of the string isn't known until later.
1777 				 */
1778 				for (ALIST_TRAVERSE(scapset->oc_plat.cl_val,
1779 				    idx2, capstr)) {
1780 					if (st_insert(strtbl,
1781 					    capstr->cs_str) == -1)
1782 						return (S_ERROR);
1783 					capstr->cs_ndx = capndx;
1784 					CAP_UPDATE(cap, capndx,
1785 					    CA_SUNW_PLAT, 0);
1786 				}
1787 			}
1788 			if (scapset->oc_mach.cl_val) {
1789 				ofl->ofl_flags |= FLG_OF_CAPSTRS;
1790 
1791 				/*
1792 				 * Insert the machine name string in the
1793 				 * appropriate string table.  The capability
1794 				 * value can't be filled in yet, as the final
1795 				 * offset of the string isn't known until later.
1796 				 */
1797 				for (ALIST_TRAVERSE(scapset->oc_mach.cl_val,
1798 				    idx2, capstr)) {
1799 					if (st_insert(strtbl,
1800 					    capstr->cs_str) == -1)
1801 						return (S_ERROR);
1802 					capstr->cs_ndx = capndx;
1803 					CAP_UPDATE(cap, capndx,
1804 					    CA_SUNW_MACH, 0);
1805 				}
1806 			}
1807 			if (scapset->oc_hw_2.cm_val) {
1808 				CAP_UPDATE(cap, capndx, CA_SUNW_HW_2,
1809 				    scapset->oc_hw_2.cm_val);
1810 			}
1811 			if (scapset->oc_hw_1.cm_val) {
1812 				CAP_UPDATE(cap, capndx, CA_SUNW_HW_1,
1813 				    scapset->oc_hw_1.cm_val);
1814 			}
1815 			if (scapset->oc_sf_1.cm_val) {
1816 				CAP_UPDATE(cap, capndx, CA_SUNW_SF_1,
1817 				    scapset->oc_sf_1.cm_val);
1818 			}
1819 			CAP_UPDATE(cap, capndx, CA_SUNW_NULL, 0);
1820 
1821 			/*
1822 			 * If any object capabilities are available, determine
1823 			 * whether these symbol capabilities are less
1824 			 * restrictive, and hence redundant.
1825 			 */
1826 			if (((ofl->ofl_flags & FLG_OF_PTCAP) == 0) ||
1827 			    (is_cap_redundant(ocapset, scapset) == 0))
1828 				continue;
1829 
1830 			/*
1831 			 * Indicate any files that provide redundant symbol
1832 			 * capabilities.
1833 			 */
1834 			for (APLIST_TRAVERSE(cgp->cg_secs, idx2, isp)) {
1835 				eprintf(ofl->ofl_lml, ERR_WARNING,
1836 				    MSG_INTL(MSG_CAP_REDUNDANT),
1837 				    isp->is_file->ifl_name,
1838 				    EC_WORD(isp->is_scnndx), isp->is_name);
1839 			}
1840 		}
1841 	}
1842 
1843 	/*
1844 	 * If capabilities strings are required, the sh_info field of the
1845 	 * section header will be set to the associated string table.
1846 	 */
1847 	if (ofl->ofl_flags & FLG_OF_CAPSTRS)
1848 		shdr->sh_flags |= SHF_INFO_LINK;
1849 
1850 	/*
1851 	 * Place these capabilities in the output file.
1852 	 */
1853 	if ((ofl->ofl_oscap = ld_place_section(ofl, isec,
1854 	    NULL, ident, NULL)) == (Os_desc *)S_ERROR)
1855 		return (S_ERROR);
1856 
1857 	/*
1858 	 * If symbol capabilities are required, then a .SUNW_capinfo section is
1859 	 * also created.  This table will eventually be sized to match the
1860 	 * associated symbol table.
1861 	 */
1862 	if (ofl->ofl_capfamilies) {
1863 		if ((ofl->ofl_oscapinfo = make_sym_sec(ofl,
1864 		    MSG_ORIG(MSG_SCN_SUNWCAPINFO), SHT_SUNW_capinfo,
1865 		    ld_targ.t_id.id_capinfo)) == (Os_desc *)S_ERROR)
1866 			return (S_ERROR);
1867 
1868 		/*
1869 		 * If we're generating a dynamic object, capabilities family
1870 		 * members are maintained in a .SUNW_capchain section.
1871 		 */
1872 		if (ofl->ofl_capchaincnt &&
1873 		    ((ofl->ofl_flags & FLG_OF_RELOBJ) == 0)) {
1874 			if (new_section(ofl, SHT_SUNW_capchain,
1875 			    MSG_ORIG(MSG_SCN_SUNWCAPCHAIN),
1876 			    ofl->ofl_capchaincnt, &isec, &shdr,
1877 			    &data) == S_ERROR)
1878 				return (S_ERROR);
1879 
1880 			ofl->ofl_oscapchain = ld_place_section(ofl, isec,
1881 			    NULL, ld_targ.t_id.id_capchain, NULL);
1882 			if (ofl->ofl_oscapchain == (Os_desc *)S_ERROR)
1883 				return (S_ERROR);
1884 
1885 		}
1886 	}
1887 	return (1);
1888 }
1889 #undef	CAP_UPDATE
1890 
1891 /*
1892  * Build the PLT section and its associated relocation entries.
1893  */
1894 static uintptr_t
1895 make_plt(Ofl_desc *ofl)
1896 {
1897 	Shdr		*shdr;
1898 	Elf_Data	*data;
1899 	Is_desc		*isec;
1900 	size_t		size = ld_targ.t_m.m_plt_reservsz +
1901 	    (((size_t)ofl->ofl_pltcnt + (size_t)ofl->ofl_pltpad) *
1902 	    ld_targ.t_m.m_plt_entsize);
1903 	size_t		rsize = (size_t)ofl->ofl_relocpltsz;
1904 
1905 	/*
1906 	 * On sparc, account for the NOP at the end of the plt.
1907 	 */
1908 	if (ld_targ.t_m.m_mach == LD_TARG_BYCLASS(EM_SPARC, EM_SPARCV9))
1909 		size += sizeof (Word);
1910 
1911 	if (new_section(ofl, SHT_PROGBITS, MSG_ORIG(MSG_SCN_PLT), 0,
1912 	    &isec, &shdr, &data) == S_ERROR)
1913 		return (S_ERROR);
1914 
1915 	data->d_size = size;
1916 	data->d_align = ld_targ.t_m.m_plt_align;
1917 
1918 	shdr->sh_flags = ld_targ.t_m.m_plt_shf_flags;
1919 	shdr->sh_size = (Xword)size;
1920 	shdr->sh_addralign = ld_targ.t_m.m_plt_align;
1921 	shdr->sh_entsize = ld_targ.t_m.m_plt_entsize;
1922 
1923 	ofl->ofl_osplt = ld_place_section(ofl, isec, NULL,
1924 	    ld_targ.t_id.id_plt, NULL);
1925 	if (ofl->ofl_osplt == (Os_desc *)S_ERROR)
1926 		return (S_ERROR);
1927 
1928 	ofl->ofl_osplt->os_szoutrels = (Xword)rsize;
1929 
1930 	return (1);
1931 }
1932 
1933 /*
1934  * Make the hash table.  Only built for dynamic executables and shared
1935  * libraries, and provides hashed lookup into the global symbol table
1936  * (.dynsym) for the run-time linker to resolve symbol lookups.
1937  */
1938 static uintptr_t
1939 make_hash(Ofl_desc *ofl)
1940 {
1941 	Shdr		*shdr;
1942 	Elf_Data	*data;
1943 	Is_desc		*isec;
1944 	size_t		size;
1945 	Word		nsyms = ofl->ofl_globcnt;
1946 	size_t		cnt;
1947 
1948 	/*
1949 	 * Allocate section header structures. We set entcnt to 0
1950 	 * because it's going to change after we place this section.
1951 	 */
1952 	if (new_section(ofl, SHT_HASH, MSG_ORIG(MSG_SCN_HASH), 0,
1953 	    &isec, &shdr, &data) == S_ERROR)
1954 		return (S_ERROR);
1955 
1956 	/*
1957 	 * Place the section first since it will affect the local symbol
1958 	 * count.
1959 	 */
1960 	ofl->ofl_oshash =
1961 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_hash, NULL);
1962 	if (ofl->ofl_oshash == (Os_desc *)S_ERROR)
1963 		return (S_ERROR);
1964 
1965 	/*
1966 	 * Calculate the number of output hash buckets.
1967 	 */
1968 	ofl->ofl_hashbkts = findprime(nsyms);
1969 
1970 	/*
1971 	 * The size of the hash table is determined by
1972 	 *
1973 	 *	i.	the initial nbucket and nchain entries (2)
1974 	 *	ii.	the number of buckets (calculated above)
1975 	 *	iii.	the number of chains (this is based on the number of
1976 	 *		symbols in the .dynsym array).
1977 	 */
1978 	cnt = 2 + ofl->ofl_hashbkts + DYNSYM_ALL_CNT(ofl);
1979 	size = cnt * shdr->sh_entsize;
1980 
1981 	/*
1982 	 * Finalize the section header and data buffer initialization.
1983 	 */
1984 	if ((data->d_buf = libld_calloc(size, 1)) == NULL)
1985 		return (S_ERROR);
1986 	data->d_size = size;
1987 	shdr->sh_size = (Xword)size;
1988 
1989 	return (1);
1990 }
1991 
1992 /*
1993  * Generate the standard symbol table.  Contains all locals and globals,
1994  * and resides in a non-allocatable section (ie. it can be stripped).
1995  */
1996 static uintptr_t
1997 make_symtab(Ofl_desc *ofl)
1998 {
1999 	Shdr		*shdr;
2000 	Elf_Data	*data;
2001 	Is_desc		*isec;
2002 	Is_desc		*xisec = 0;
2003 	size_t		size;
2004 	Word		symcnt;
2005 
2006 	/*
2007 	 * Create the section headers. Note that we supply an ent_cnt
2008 	 * of 0. We won't know the count until the section has been placed.
2009 	 */
2010 	if (new_section(ofl, SHT_SYMTAB, MSG_ORIG(MSG_SCN_SYMTAB), 0,
2011 	    &isec, &shdr, &data) == S_ERROR)
2012 		return (S_ERROR);
2013 
2014 	/*
2015 	 * Place the section first since it will affect the local symbol
2016 	 * count.
2017 	 */
2018 	if ((ofl->ofl_ossymtab = ld_place_section(ofl, isec, NULL,
2019 	    ld_targ.t_id.id_symtab, NULL)) == (Os_desc *)S_ERROR)
2020 		return (S_ERROR);
2021 
2022 	/*
2023 	 * At this point we've created all but the 'shstrtab' section.
2024 	 * Determine if we have to use 'Extended Sections'.  If so - then
2025 	 * also create a SHT_SYMTAB_SHNDX section.
2026 	 */
2027 	if ((ofl->ofl_shdrcnt + 1) >= SHN_LORESERVE) {
2028 		Shdr		*xshdr;
2029 		Elf_Data	*xdata;
2030 
2031 		if (new_section(ofl, SHT_SYMTAB_SHNDX,
2032 		    MSG_ORIG(MSG_SCN_SYMTAB_SHNDX), 0, &xisec,
2033 		    &xshdr, &xdata) == S_ERROR)
2034 			return (S_ERROR);
2035 
2036 		if ((ofl->ofl_ossymshndx = ld_place_section(ofl, xisec, NULL,
2037 		    ld_targ.t_id.id_symtab_ndx, NULL)) == (Os_desc *)S_ERROR)
2038 			return (S_ERROR);
2039 	}
2040 
2041 	/*
2042 	 * Calculated number of symbols, which need to be augmented by
2043 	 * the (yet to be created) .shstrtab entry.
2044 	 */
2045 	symcnt = (size_t)(1 + SYMTAB_ALL_CNT(ofl));
2046 	size = symcnt * shdr->sh_entsize;
2047 
2048 	/*
2049 	 * Finalize the section header and data buffer initialization.
2050 	 */
2051 	data->d_size = size;
2052 	shdr->sh_size = (Xword)size;
2053 
2054 	/*
2055 	 * If we created a SHT_SYMTAB_SHNDX - then set it's sizes too.
2056 	 */
2057 	if (xisec) {
2058 		size_t	xsize = symcnt * sizeof (Word);
2059 
2060 		xisec->is_indata->d_size = xsize;
2061 		xisec->is_shdr->sh_size = (Xword)xsize;
2062 	}
2063 
2064 	return (1);
2065 }
2066 
2067 /*
2068  * Build a dynamic symbol table. These tables reside in the text
2069  * segment of a dynamic executable or shared library.
2070  *
2071  *	.SUNW_ldynsym contains local function symbols
2072  *	.dynsym contains only globals symbols
2073  *
2074  * The two tables are created adjacent to each other, with .SUNW_ldynsym
2075  * coming first.
2076  */
2077 static uintptr_t
2078 make_dynsym(Ofl_desc *ofl)
2079 {
2080 	Shdr		*shdr, *lshdr;
2081 	Elf_Data	*data, *ldata;
2082 	Is_desc		*isec, *lisec;
2083 	size_t		size;
2084 	Xword		cnt;
2085 	int		allow_ldynsym;
2086 
2087 	/*
2088 	 * Unless explicitly disabled, always produce a .SUNW_ldynsym section
2089 	 * when it is allowed by the file type, even if the resulting
2090 	 * table only ends up with a single STT_FILE in it. There are
2091 	 * two reasons: (1) It causes the generation of the DT_SUNW_SYMTAB
2092 	 * entry in the .dynamic section, which is something we would
2093 	 * like to encourage, and (2) Without it, we cannot generate
2094 	 * the associated .SUNW_dyn[sym|tls]sort sections, which are of
2095 	 * value to DTrace.
2096 	 *
2097 	 * In practice, it is extremely rare for an object not to have
2098 	 * local symbols for .SUNW_ldynsym, so 99% of the time, we'd be
2099 	 * doing it anyway.
2100 	 */
2101 	allow_ldynsym = OFL_ALLOW_LDYNSYM(ofl);
2102 
2103 	/*
2104 	 * Create the section headers. Note that we supply an ent_cnt
2105 	 * of 0. We won't know the count until the section has been placed.
2106 	 */
2107 	if (allow_ldynsym && new_section(ofl, SHT_SUNW_LDYNSYM,
2108 	    MSG_ORIG(MSG_SCN_LDYNSYM), 0, &lisec, &lshdr, &ldata) == S_ERROR)
2109 		return (S_ERROR);
2110 
2111 	if (new_section(ofl, SHT_DYNSYM, MSG_ORIG(MSG_SCN_DYNSYM), 0,
2112 	    &isec, &shdr, &data) == S_ERROR)
2113 		return (S_ERROR);
2114 
2115 	/*
2116 	 * Place the section(s) first since it will affect the local symbol
2117 	 * count.
2118 	 */
2119 	if (allow_ldynsym &&
2120 	    ((ofl->ofl_osldynsym = ld_place_section(ofl, lisec, NULL,
2121 	    ld_targ.t_id.id_ldynsym, NULL)) == (Os_desc *)S_ERROR))
2122 		return (S_ERROR);
2123 	ofl->ofl_osdynsym =
2124 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_dynsym, NULL);
2125 	if (ofl->ofl_osdynsym == (Os_desc *)S_ERROR)
2126 		return (S_ERROR);
2127 
2128 	cnt = DYNSYM_ALL_CNT(ofl);
2129 	size = (size_t)cnt * shdr->sh_entsize;
2130 
2131 	/*
2132 	 * Finalize the section header and data buffer initialization.
2133 	 */
2134 	data->d_size = size;
2135 	shdr->sh_size = (Xword)size;
2136 
2137 	/*
2138 	 * An ldynsym contains local function symbols. It is not
2139 	 * used for linking, but if present, serves to allow better
2140 	 * stack traces to be generated in contexts where the symtab
2141 	 * is not available. (dladdr(), or stripped executable/library files).
2142 	 */
2143 	if (allow_ldynsym) {
2144 		cnt = 1 + ofl->ofl_dynlocscnt + ofl->ofl_dynscopecnt;
2145 		size = (size_t)cnt * shdr->sh_entsize;
2146 
2147 		ldata->d_size = size;
2148 		lshdr->sh_size = (Xword)size;
2149 	}
2150 
2151 	return (1);
2152 }
2153 
2154 /*
2155  * Build .SUNW_dynsymsort and/or .SUNW_dyntlssort sections. These are
2156  * index sections for the .SUNW_ldynsym/.dynsym pair that present data
2157  * and function symbols sorted by address.
2158  */
2159 static uintptr_t
2160 make_dynsort(Ofl_desc *ofl)
2161 {
2162 	Shdr		*shdr;
2163 	Elf_Data	*data;
2164 	Is_desc		*isec;
2165 
2166 	/* Only do it if the .SUNW_ldynsym section is present */
2167 	if (!OFL_ALLOW_LDYNSYM(ofl))
2168 		return (1);
2169 
2170 	/* .SUNW_dynsymsort */
2171 	if (ofl->ofl_dynsymsortcnt > 0) {
2172 		if (new_section(ofl, SHT_SUNW_symsort,
2173 		    MSG_ORIG(MSG_SCN_DYNSYMSORT), ofl->ofl_dynsymsortcnt,
2174 		    &isec, &shdr, &data) == S_ERROR)
2175 		return (S_ERROR);
2176 
2177 		if ((ofl->ofl_osdynsymsort = ld_place_section(ofl, isec, NULL,
2178 		    ld_targ.t_id.id_dynsort, NULL)) == (Os_desc *)S_ERROR)
2179 			return (S_ERROR);
2180 	}
2181 
2182 	/* .SUNW_dyntlssort */
2183 	if (ofl->ofl_dyntlssortcnt > 0) {
2184 		if (new_section(ofl, SHT_SUNW_tlssort,
2185 		    MSG_ORIG(MSG_SCN_DYNTLSSORT),
2186 		    ofl->ofl_dyntlssortcnt, &isec, &shdr, &data) == S_ERROR)
2187 		return (S_ERROR);
2188 
2189 		if ((ofl->ofl_osdyntlssort = ld_place_section(ofl, isec, NULL,
2190 		    ld_targ.t_id.id_dynsort, NULL)) == (Os_desc *)S_ERROR)
2191 			return (S_ERROR);
2192 	}
2193 
2194 	return (1);
2195 }
2196 
2197 /*
2198  * Helper routine for make_dynsym_shndx. Builds a
2199  * a SHT_SYMTAB_SHNDX for .dynsym or .SUNW_ldynsym, without knowing
2200  * which one it is.
2201  */
2202 static uintptr_t
2203 make_dyn_shndx(Ofl_desc *ofl, const char *shname, Os_desc *symtab,
2204     Os_desc **ret_os)
2205 {
2206 	Is_desc		*isec;
2207 	Is_desc		*dynsymisp;
2208 	Shdr		*shdr, *dynshdr;
2209 	Elf_Data	*data;
2210 
2211 	dynsymisp = ld_os_first_isdesc(symtab);
2212 	dynshdr = dynsymisp->is_shdr;
2213 
2214 	if (new_section(ofl, SHT_SYMTAB_SHNDX, shname,
2215 	    (dynshdr->sh_size / dynshdr->sh_entsize),
2216 	    &isec, &shdr, &data) == S_ERROR)
2217 		return (S_ERROR);
2218 
2219 	if ((*ret_os = ld_place_section(ofl, isec, NULL,
2220 	    ld_targ.t_id.id_dynsym_ndx, NULL)) == (Os_desc *)S_ERROR)
2221 		return (S_ERROR);
2222 
2223 	assert(*ret_os);
2224 
2225 	return (1);
2226 }
2227 
2228 /*
2229  * Build a SHT_SYMTAB_SHNDX for the .dynsym, and .SUNW_ldynsym
2230  */
2231 static uintptr_t
2232 make_dynsym_shndx(Ofl_desc *ofl)
2233 {
2234 	/*
2235 	 * If there is a .SUNW_ldynsym, generate a section for its extended
2236 	 * index section as well.
2237 	 */
2238 	if (OFL_ALLOW_LDYNSYM(ofl)) {
2239 		if (make_dyn_shndx(ofl, MSG_ORIG(MSG_SCN_LDYNSYM_SHNDX),
2240 		    ofl->ofl_osldynsym, &ofl->ofl_osldynshndx) == S_ERROR)
2241 			return (S_ERROR);
2242 	}
2243 
2244 	/* The Generate a section for the dynsym */
2245 	if (make_dyn_shndx(ofl, MSG_ORIG(MSG_SCN_DYNSYM_SHNDX),
2246 	    ofl->ofl_osdynsym, &ofl->ofl_osdynshndx) == S_ERROR)
2247 		return (S_ERROR);
2248 
2249 	return (1);
2250 }
2251 
2252 
2253 /*
2254  * Build a string table for the section headers.
2255  */
2256 static uintptr_t
2257 make_shstrtab(Ofl_desc *ofl)
2258 {
2259 	Shdr		*shdr;
2260 	Elf_Data	*data;
2261 	Is_desc		*isec;
2262 	size_t		size;
2263 
2264 	if (new_section(ofl, SHT_STRTAB, MSG_ORIG(MSG_SCN_SHSTRTAB),
2265 	    0, &isec, &shdr, &data) == S_ERROR)
2266 		return (S_ERROR);
2267 
2268 	/*
2269 	 * Place the section first, as it may effect the number of section
2270 	 * headers to account for.
2271 	 */
2272 	ofl->ofl_osshstrtab =
2273 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_note, NULL);
2274 	if (ofl->ofl_osshstrtab == (Os_desc *)S_ERROR)
2275 		return (S_ERROR);
2276 
2277 	size = st_getstrtab_sz(ofl->ofl_shdrsttab);
2278 	assert(size > 0);
2279 
2280 	data->d_size = size;
2281 	shdr->sh_size = (Xword)size;
2282 
2283 	return (1);
2284 }
2285 
2286 /*
2287  * Build a string section for the standard symbol table.
2288  */
2289 static uintptr_t
2290 make_strtab(Ofl_desc *ofl)
2291 {
2292 	Shdr		*shdr;
2293 	Elf_Data	*data;
2294 	Is_desc		*isec;
2295 	size_t		size;
2296 
2297 	/*
2298 	 * This string table consists of all the global and local symbols.
2299 	 * Account for null bytes at end of the file name and the beginning
2300 	 * of section.
2301 	 */
2302 	if (st_insert(ofl->ofl_strtab, ofl->ofl_name) == -1)
2303 		return (S_ERROR);
2304 
2305 	size = st_getstrtab_sz(ofl->ofl_strtab);
2306 	assert(size > 0);
2307 
2308 	if (new_section(ofl, SHT_STRTAB, MSG_ORIG(MSG_SCN_STRTAB),
2309 	    0, &isec, &shdr, &data) == S_ERROR)
2310 		return (S_ERROR);
2311 
2312 	/* Set the size of the data area */
2313 	data->d_size = size;
2314 	shdr->sh_size = (Xword)size;
2315 
2316 	ofl->ofl_osstrtab =
2317 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_strtab, NULL);
2318 	return ((uintptr_t)ofl->ofl_osstrtab);
2319 }
2320 
2321 /*
2322  * Build a string table for the dynamic symbol table.
2323  */
2324 static uintptr_t
2325 make_dynstr(Ofl_desc *ofl)
2326 {
2327 	Shdr		*shdr;
2328 	Elf_Data	*data;
2329 	Is_desc		*isec;
2330 	size_t		size;
2331 
2332 	/*
2333 	 * If producing a .SUNW_ldynsym, account for the initial STT_FILE
2334 	 * symbol that precedes the scope reduced global symbols.
2335 	 */
2336 	if (OFL_ALLOW_LDYNSYM(ofl)) {
2337 		if (st_insert(ofl->ofl_dynstrtab, ofl->ofl_name) == -1)
2338 			return (S_ERROR);
2339 		ofl->ofl_dynscopecnt++;
2340 	}
2341 
2342 	/*
2343 	 * Account for any local, named register symbols.  These locals are
2344 	 * required for reference from DT_REGISTER .dynamic entries.
2345 	 */
2346 	if (ofl->ofl_regsyms) {
2347 		int	ndx;
2348 
2349 		for (ndx = 0; ndx < ofl->ofl_regsymsno; ndx++) {
2350 			Sym_desc	*sdp;
2351 
2352 			if ((sdp = ofl->ofl_regsyms[ndx]) == NULL)
2353 				continue;
2354 
2355 			if (!SYM_IS_HIDDEN(sdp) &&
2356 			    (ELF_ST_BIND(sdp->sd_sym->st_info) != STB_LOCAL))
2357 				continue;
2358 
2359 			if (sdp->sd_sym->st_name == NULL)
2360 				continue;
2361 
2362 			if (st_insert(ofl->ofl_dynstrtab, sdp->sd_name) == -1)
2363 				return (S_ERROR);
2364 		}
2365 	}
2366 
2367 	/*
2368 	 * Reserve entries for any per-symbol auxiliary/filter strings.
2369 	 */
2370 	if (ofl->ofl_dtsfltrs != NULL) {
2371 		Dfltr_desc	*dftp;
2372 		Aliste		idx;
2373 
2374 		for (ALIST_TRAVERSE(ofl->ofl_dtsfltrs, idx, dftp))
2375 			if (st_insert(ofl->ofl_dynstrtab, dftp->dft_str) == -1)
2376 				return (S_ERROR);
2377 	}
2378 
2379 	size = st_getstrtab_sz(ofl->ofl_dynstrtab);
2380 	assert(size > 0);
2381 
2382 	if (new_section(ofl, SHT_STRTAB, MSG_ORIG(MSG_SCN_DYNSTR),
2383 	    0, &isec, &shdr, &data) == S_ERROR)
2384 		return (S_ERROR);
2385 
2386 	/* Make it allocable if necessary */
2387 	if (!(ofl->ofl_flags & FLG_OF_RELOBJ))
2388 		shdr->sh_flags |= SHF_ALLOC;
2389 
2390 	/* Set the size of the data area */
2391 	data->d_size = size + DYNSTR_EXTRA_PAD;
2392 
2393 	shdr->sh_size = (Xword)size;
2394 
2395 	ofl->ofl_osdynstr =
2396 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_dynstr, NULL);
2397 	return ((uintptr_t)ofl->ofl_osdynstr);
2398 }
2399 
2400 /*
2401  * Generate an output relocation section which will contain the relocation
2402  * information to be applied to the `osp' section.
2403  *
2404  * If (osp == NULL) then we are creating the coalesced relocation section
2405  * for an executable and/or a shared object.
2406  */
2407 static uintptr_t
2408 make_reloc(Ofl_desc *ofl, Os_desc *osp)
2409 {
2410 	Shdr		*shdr;
2411 	Elf_Data	*data;
2412 	Is_desc		*isec;
2413 	size_t		size;
2414 	Xword		sh_flags;
2415 	char 		*sectname;
2416 	Os_desc		*rosp;
2417 	Word		relsize;
2418 	const char	*rel_prefix;
2419 
2420 	/* LINTED */
2421 	if (ld_targ.t_m.m_rel_sht_type == SHT_REL) {
2422 		/* REL */
2423 		relsize = sizeof (Rel);
2424 		rel_prefix = MSG_ORIG(MSG_SCN_REL);
2425 	} else {
2426 		/* RELA */
2427 		relsize = sizeof (Rela);
2428 		rel_prefix = MSG_ORIG(MSG_SCN_RELA);
2429 	}
2430 
2431 	if (osp) {
2432 		size = osp->os_szoutrels;
2433 		sh_flags = osp->os_shdr->sh_flags;
2434 		if ((sectname = libld_malloc(strlen(rel_prefix) +
2435 		    strlen(osp->os_name) + 1)) == 0)
2436 			return (S_ERROR);
2437 		(void) strcpy(sectname, rel_prefix);
2438 		(void) strcat(sectname, osp->os_name);
2439 	} else if (ofl->ofl_flags & FLG_OF_COMREL) {
2440 		size = (ofl->ofl_reloccnt - ofl->ofl_reloccntsub) * relsize;
2441 		sh_flags = SHF_ALLOC;
2442 		sectname = (char *)MSG_ORIG(MSG_SCN_SUNWRELOC);
2443 	} else {
2444 		size = ofl->ofl_relocrelsz;
2445 		sh_flags = SHF_ALLOC;
2446 		sectname = (char *)rel_prefix;
2447 	}
2448 
2449 	/*
2450 	 * Keep track of total size of 'output relocations' (to be stored
2451 	 * in .dynamic)
2452 	 */
2453 	/* LINTED */
2454 	ofl->ofl_relocsz += (Xword)size;
2455 
2456 	if (new_section(ofl, ld_targ.t_m.m_rel_sht_type, sectname, 0, &isec,
2457 	    &shdr, &data) == S_ERROR)
2458 		return (S_ERROR);
2459 
2460 	data->d_size = size;
2461 
2462 	shdr->sh_size = (Xword)size;
2463 	if (OFL_ALLOW_DYNSYM(ofl) && (sh_flags & SHF_ALLOC))
2464 		shdr->sh_flags = SHF_ALLOC;
2465 
2466 	if (osp) {
2467 		/*
2468 		 * The sh_info field of the SHT_REL* sections points to the
2469 		 * section the relocations are to be applied to.
2470 		 */
2471 		shdr->sh_flags |= SHF_INFO_LINK;
2472 	}
2473 
2474 	rosp = ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_rel, NULL);
2475 	if (rosp == (Os_desc *)S_ERROR)
2476 		return (S_ERROR);
2477 
2478 	/*
2479 	 * Associate this relocation section to the section its going to
2480 	 * relocate.
2481 	 */
2482 	if (osp) {
2483 		Aliste	idx;
2484 		Is_desc	*risp;
2485 
2486 		/*
2487 		 * This is used primarily so that we can update
2488 		 * SHT_GROUP[sect_no] entries to point to the
2489 		 * created output relocation sections.
2490 		 */
2491 		for (APLIST_TRAVERSE(osp->os_relisdescs, idx, risp)) {
2492 			risp->is_osdesc = rosp;
2493 
2494 			/*
2495 			 * If the input relocation section had the SHF_GROUP
2496 			 * flag set - propagate it to the output relocation
2497 			 * section.
2498 			 */
2499 			if (risp->is_shdr->sh_flags & SHF_GROUP) {
2500 				rosp->os_shdr->sh_flags |= SHF_GROUP;
2501 				break;
2502 			}
2503 		}
2504 		osp->os_relosdesc = rosp;
2505 	} else
2506 		ofl->ofl_osrel = rosp;
2507 
2508 	/*
2509 	 * If this is the first relocation section we've encountered save it
2510 	 * so that the .dynamic entry can be initialized accordingly.
2511 	 */
2512 	if (ofl->ofl_osrelhead == (Os_desc *)0)
2513 		ofl->ofl_osrelhead = rosp;
2514 
2515 	return (1);
2516 }
2517 
2518 /*
2519  * Generate version needed section.
2520  */
2521 static uintptr_t
2522 make_verneed(Ofl_desc *ofl)
2523 {
2524 	Shdr		*shdr;
2525 	Elf_Data	*data;
2526 	Is_desc		*isec;
2527 
2528 	/*
2529 	 * verneed sections do not have a constant element size, so the
2530 	 * value of ent_cnt specified here (0) is meaningless.
2531 	 */
2532 	if (new_section(ofl, SHT_SUNW_verneed, MSG_ORIG(MSG_SCN_SUNWVERSION),
2533 	    0, &isec, &shdr, &data) == S_ERROR)
2534 		return (S_ERROR);
2535 
2536 	/* During version processing we calculated the total size. */
2537 	data->d_size = ofl->ofl_verneedsz;
2538 	shdr->sh_size = (Xword)ofl->ofl_verneedsz;
2539 
2540 	ofl->ofl_osverneed =
2541 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_version, NULL);
2542 	return ((uintptr_t)ofl->ofl_osverneed);
2543 }
2544 
2545 /*
2546  * Generate a version definition section.
2547  *
2548  *  o	the SHT_SUNW_verdef section defines the versions that exist within this
2549  *	image.
2550  */
2551 static uintptr_t
2552 make_verdef(Ofl_desc *ofl)
2553 {
2554 	Shdr		*shdr;
2555 	Elf_Data	*data;
2556 	Is_desc		*isec;
2557 	Ver_desc	*vdp;
2558 	Str_tbl		*strtab;
2559 
2560 	/*
2561 	 * Reserve a string table entry for the base version dependency (other
2562 	 * dependencies have symbol representations, which will already be
2563 	 * accounted for during symbol processing).
2564 	 */
2565 	vdp = (Ver_desc *)ofl->ofl_verdesc->apl_data[0];
2566 
2567 	if (OFL_IS_STATIC_OBJ(ofl))
2568 		strtab = ofl->ofl_strtab;
2569 	else
2570 		strtab = ofl->ofl_dynstrtab;
2571 
2572 	if (st_insert(strtab, vdp->vd_name) == -1)
2573 		return (S_ERROR);
2574 
2575 	/*
2576 	 * verdef sections do not have a constant element size, so the
2577 	 * value of ent_cnt specified here (0) is meaningless.
2578 	 */
2579 	if (new_section(ofl, SHT_SUNW_verdef, MSG_ORIG(MSG_SCN_SUNWVERSION),
2580 	    0, &isec, &shdr, &data) == S_ERROR)
2581 		return (S_ERROR);
2582 
2583 	/* During version processing we calculated the total size. */
2584 	data->d_size = ofl->ofl_verdefsz;
2585 	shdr->sh_size = (Xword)ofl->ofl_verdefsz;
2586 
2587 	ofl->ofl_osverdef =
2588 	    ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_version, NULL);
2589 	return ((uintptr_t)ofl->ofl_osverdef);
2590 }
2591 
2592 /*
2593  * This routine is called when -z nopartial is in effect.
2594  */
2595 uintptr_t
2596 ld_make_parexpn_data(Ofl_desc *ofl, size_t size, Xword align)
2597 {
2598 	Shdr		*shdr;
2599 	Elf_Data	*data;
2600 	Is_desc		*isec;
2601 	Os_desc		*osp;
2602 
2603 	if (new_section(ofl, SHT_PROGBITS, MSG_ORIG(MSG_SCN_DATA), 0,
2604 	    &isec, &shdr, &data) == S_ERROR)
2605 		return (S_ERROR);
2606 
2607 	shdr->sh_flags |= SHF_WRITE;
2608 	data->d_size = size;
2609 	shdr->sh_size = (Xword)size;
2610 	if (align != 0) {
2611 		data->d_align = align;
2612 		shdr->sh_addralign = align;
2613 	}
2614 
2615 	if ((data->d_buf = libld_calloc(size, 1)) == NULL)
2616 		return (S_ERROR);
2617 
2618 	/*
2619 	 * Retain handle to this .data input section. Variables using move
2620 	 * sections (partial initialization) will be redirected here when
2621 	 * such global references are added and '-z nopartial' is in effect.
2622 	 */
2623 	ofl->ofl_isparexpn = isec;
2624 	osp = ld_place_section(ofl, isec, NULL, ld_targ.t_id.id_data, NULL);
2625 	if (osp == (Os_desc *)S_ERROR)
2626 		return (S_ERROR);
2627 
2628 	if (!(osp->os_flags & FLG_OS_OUTREL)) {
2629 		ofl->ofl_dynshdrcnt++;
2630 		osp->os_flags |= FLG_OS_OUTREL;
2631 	}
2632 	return (1);
2633 }
2634 
2635 /*
2636  * Make .sunwmove section
2637  */
2638 uintptr_t
2639 ld_make_sunwmove(Ofl_desc *ofl, int mv_nums)
2640 {
2641 	Shdr		*shdr;
2642 	Elf_Data	*data;
2643 	Is_desc		*isec;
2644 	Aliste		idx;
2645 	Sym_desc	*sdp;
2646 	int 		cnt = 1;
2647 
2648 
2649 	if (new_section(ofl, SHT_SUNW_move, MSG_ORIG(MSG_SCN_SUNWMOVE),
2650 	    mv_nums, &isec, &shdr, &data) == S_ERROR)
2651 		return (S_ERROR);
2652 
2653 	if ((data->d_buf = libld_calloc(data->d_size, 1)) == NULL)
2654 		return (S_ERROR);
2655 
2656 	/*
2657 	 * Copy move entries
2658 	 */
2659 	for (APLIST_TRAVERSE(ofl->ofl_parsyms, idx, sdp)) {
2660 		Aliste		idx2;
2661 		Mv_desc		*mdp;
2662 
2663 		if (sdp->sd_flags & FLG_SY_PAREXPN)
2664 			continue;
2665 
2666 		for (ALIST_TRAVERSE(sdp->sd_move, idx2, mdp))
2667 			mdp->md_oidx = cnt++;
2668 	}
2669 
2670 	if ((ofl->ofl_osmove = ld_place_section(ofl, isec, NULL, 0, NULL)) ==
2671 	    (Os_desc *)S_ERROR)
2672 		return (S_ERROR);
2673 
2674 	return (1);
2675 }
2676 
2677 /*
2678  * Given a relocation descriptor that references a string table
2679  * input section, locate the string referenced and return a pointer
2680  * to it.
2681  */
2682 static const char *
2683 strmerge_get_reloc_str(Ofl_desc *ofl, Rel_desc *rsp)
2684 {
2685 	Sym_desc *sdp = rsp->rel_sym;
2686 	Xword	 str_off;
2687 
2688 	/*
2689 	 * In the case of an STT_SECTION symbol, the addend of the
2690 	 * relocation gives the offset into the string section. For
2691 	 * other symbol types, the symbol value is the offset.
2692 	 */
2693 
2694 	if (ELF_ST_TYPE(sdp->sd_sym->st_info) != STT_SECTION) {
2695 		str_off = sdp->sd_sym->st_value;
2696 	} else if ((rsp->rel_flags & FLG_REL_RELA) == FLG_REL_RELA) {
2697 		/*
2698 		 * For SHT_RELA, the addend value is found in the
2699 		 * rel_raddend field of the relocation.
2700 		 */
2701 		str_off = rsp->rel_raddend;
2702 	} else {	/* REL and STT_SECTION */
2703 		/*
2704 		 * For SHT_REL, the "addend" is not part of the relocation
2705 		 * record. Instead, it is found at the relocation target
2706 		 * address.
2707 		 */
2708 		uchar_t *addr = (uchar_t *)((uintptr_t)rsp->rel_roffset +
2709 		    (uintptr_t)rsp->rel_isdesc->is_indata->d_buf);
2710 
2711 		if (ld_reloc_targval_get(ofl, rsp, addr, &str_off) == 0)
2712 			return (0);
2713 	}
2714 
2715 	return (str_off + (char *)sdp->sd_isc->is_indata->d_buf);
2716 }
2717 
2718 /*
2719  * First pass over the relocation records for string table merging.
2720  * Build lists of relocations and symbols that will need modification,
2721  * and insert the strings they reference into the mstrtab string table.
2722  *
2723  * entry:
2724  *	ofl, osp - As passed to ld_make_strmerge().
2725  *	mstrtab - String table to receive input strings. This table
2726  *		must be in its first (initialization) pass and not
2727  *		yet cooked (st_getstrtab_sz() not yet called).
2728  *	rel_alpp - APlist to receive pointer to any relocation
2729  *		descriptors with STT_SECTION symbols that reference
2730  *		one of the input sections being merged.
2731  *	sym_alpp - APlist to receive pointer to any symbols that reference
2732  *		one of the input sections being merged.
2733  *	rcp - Pointer to cache of relocation descriptors to examine.
2734  *		Either &ofl->ofl_actrels (active relocations)
2735  *		or &ofl->ofl_outrels (output relocations).
2736  *
2737  * exit:
2738  *	On success, rel_alpp and sym_alpp are updated, and
2739  *	any strings in the mergeable input sections referenced by
2740  *	a relocation has been entered into mstrtab. True (1) is returned.
2741  *
2742  *	On failure, False (0) is returned.
2743  */
2744 static int
2745 strmerge_pass1(Ofl_desc *ofl, Os_desc *osp, Str_tbl *mstrtab,
2746     APlist **rel_alpp, APlist **sym_alpp, Rel_cache *rcp)
2747 {
2748 	Aliste		idx;
2749 	Rel_cachebuf	*rcbp;
2750 	Sym_desc	*sdp;
2751 	Sym_desc	*last_sdp = NULL;
2752 	Rel_desc	*rsp;
2753 	const char	*name;
2754 
2755 	REL_CACHE_TRAVERSE(rcp, idx, rcbp, rsp) {
2756 		sdp = rsp->rel_sym;
2757 		if ((sdp->sd_isc == NULL) || ((sdp->sd_isc->is_flags &
2758 		    (FLG_IS_DISCARD | FLG_IS_INSTRMRG)) != FLG_IS_INSTRMRG) ||
2759 		    (sdp->sd_isc->is_osdesc != osp))
2760 			continue;
2761 
2762 		/*
2763 		 * Remember symbol for use in the third pass. There is no
2764 		 * reason to save a given symbol more than once, so we take
2765 		 * advantage of the fact that relocations to a given symbol
2766 		 * tend to cluster in the list. If this is the same symbol
2767 		 * we saved last time, don't bother.
2768 		 */
2769 		if (last_sdp != sdp) {
2770 			if (aplist_append(sym_alpp, sdp, AL_CNT_STRMRGSYM) ==
2771 			    NULL)
2772 				return (0);
2773 			last_sdp = sdp;
2774 		}
2775 
2776 		/* Enter the string into our new string table */
2777 		name = strmerge_get_reloc_str(ofl, rsp);
2778 		if (st_insert(mstrtab, name) == -1)
2779 			return (0);
2780 
2781 		/*
2782 		 * If this is an STT_SECTION symbol, then the second pass
2783 		 * will need to modify this relocation, so hang on to it.
2784 		 */
2785 		if ((ELF_ST_TYPE(sdp->sd_sym->st_info) == STT_SECTION) &&
2786 		    (aplist_append(rel_alpp, rsp, AL_CNT_STRMRGREL) == NULL))
2787 			return (0);
2788 	}
2789 
2790 	return (1);
2791 }
2792 
2793 /*
2794  * If the output section has any SHF_MERGE|SHF_STRINGS input sections,
2795  * replace them with a single merged/compressed input section.
2796  *
2797  * entry:
2798  *	ofl - Output file descriptor
2799  *	osp - Output section descriptor
2800  *	rel_alpp, sym_alpp, - Address of 2 APlists, to be used
2801  *		for internal processing. On the initial call to
2802  *		ld_make_strmerge, these list pointers must be NULL.
2803  *		The caller is encouraged to pass the same lists back for
2804  *		successive calls to this function without freeing
2805  *		them in between calls. This causes a single pair of
2806  *		memory allocations to be reused multiple times.
2807  *
2808  * exit:
2809  *	If section merging is possible, it is done. If no errors are
2810  *	encountered, True (1) is returned. On error, S_ERROR.
2811  *
2812  *	The contents of rel_alpp and sym_alpp on exit are
2813  *	undefined. The caller can free them, or pass them back to a subsequent
2814  *	call to this routine, but should not examine their contents.
2815  */
2816 static uintptr_t
2817 ld_make_strmerge(Ofl_desc *ofl, Os_desc *osp, APlist **rel_alpp,
2818     APlist **sym_alpp)
2819 {
2820 	Str_tbl		*mstrtab;	/* string table for string merge secs */
2821 	Is_desc		*mstrsec;	/* Generated string merge section */
2822 	Is_desc		*isp;
2823 	Shdr		*mstr_shdr;
2824 	Elf_Data	*mstr_data;
2825 	Sym_desc	*sdp;
2826 	Rel_desc	*rsp;
2827 	Aliste		idx;
2828 	size_t		data_size;
2829 	int		st_setstring_status;
2830 	size_t		stoff;
2831 
2832 	/* If string table compression is disabled, there's nothing to do */
2833 	if ((ofl->ofl_flags1 & FLG_OF1_NCSTTAB) != 0)
2834 		return (1);
2835 
2836 	/*
2837 	 * Pass over the mergeable input sections, and if they haven't
2838 	 * all been discarded, create a string table.
2839 	 */
2840 	mstrtab = NULL;
2841 	for (APLIST_TRAVERSE(osp->os_mstrisdescs, idx, isp)) {
2842 		if (isp->is_flags & FLG_IS_DISCARD)
2843 			continue;
2844 
2845 		/*
2846 		 * We have at least one non-discarded section.
2847 		 * Create a string table descriptor.
2848 		 */
2849 		if ((mstrtab = st_new(FLG_STNEW_COMPRESS)) == NULL)
2850 			return (S_ERROR);
2851 		break;
2852 	}
2853 
2854 	/* If no string table was created, we have no mergeable sections */
2855 	if (mstrtab == NULL)
2856 		return (1);
2857 
2858 	/*
2859 	 * This routine has to make 3 passes:
2860 	 *
2861 	 *	1) Examine all relocations, insert strings from relocations
2862 	 *		to the mergeable input sections into the string table.
2863 	 *	2) Modify the relocation values to be correct for the
2864 	 *		new merged section.
2865 	 *	3) Modify the symbols used by the relocations to reference
2866 	 *		the new section.
2867 	 *
2868 	 * These passes cannot be combined:
2869 	 *	- The string table code works in two passes, and all
2870 	 *		strings have to be loaded in pass one before the
2871 	 *		offset of any strings can be determined.
2872 	 *	- Multiple relocations reference a single symbol, so the
2873 	 *		symbol cannot be modified until all relocations are
2874 	 *		fixed.
2875 	 *
2876 	 * The number of relocations related to section merging is usually
2877 	 * a mere fraction of the overall active and output relocation lists,
2878 	 * and the number of symbols is usually a fraction of the number
2879 	 * of related relocations. We therefore build APlists for the
2880 	 * relocations and symbols in the first pass, and then use those
2881 	 * lists to accelerate the operation of pass 2 and 3.
2882 	 *
2883 	 * Reinitialize the lists to a completely empty state.
2884 	 */
2885 	aplist_reset(*rel_alpp);
2886 	aplist_reset(*sym_alpp);
2887 
2888 	/*
2889 	 * Pass 1:
2890 	 *
2891 	 * Every relocation related to this output section (and the input
2892 	 * sections that make it up) is found in either the active, or the
2893 	 * output relocation list, depending on whether the relocation is to
2894 	 * be processed by this invocation of the linker, or inserted into the
2895 	 * output object.
2896 	 *
2897 	 * Build lists of relocations and symbols that will need modification,
2898 	 * and insert the strings they reference into the mstrtab string table.
2899 	 */
2900 	if (strmerge_pass1(ofl, osp, mstrtab, rel_alpp, sym_alpp,
2901 	    &ofl->ofl_actrels) == 0)
2902 		goto return_s_error;
2903 	if (strmerge_pass1(ofl, osp, mstrtab, rel_alpp, sym_alpp,
2904 	    &ofl->ofl_outrels) == 0)
2905 		goto return_s_error;
2906 
2907 	/*
2908 	 * Get the size of the new input section. Requesting the
2909 	 * string table size "cooks" the table, and finalizes its contents.
2910 	 */
2911 	data_size = st_getstrtab_sz(mstrtab);
2912 
2913 	/* Create a new input section to hold the merged strings */
2914 	if (new_section_from_template(ofl, isp, data_size,
2915 	    &mstrsec, &mstr_shdr, &mstr_data) == S_ERROR)
2916 		goto return_s_error;
2917 	mstrsec->is_flags |= FLG_IS_GNSTRMRG;
2918 
2919 	/*
2920 	 * Allocate a data buffer for the new input section.
2921 	 * Then, associate the buffer with the string table descriptor.
2922 	 */
2923 	if ((mstr_data->d_buf = libld_malloc(data_size)) == NULL)
2924 		goto return_s_error;
2925 	if (st_setstrbuf(mstrtab, mstr_data->d_buf, data_size) == -1)
2926 		goto return_s_error;
2927 
2928 	/* Add the new section to the output image */
2929 	if (ld_place_section(ofl, mstrsec, NULL, osp->os_identndx, NULL) ==
2930 	    (Os_desc *)S_ERROR)
2931 		goto return_s_error;
2932 
2933 	/*
2934 	 * Pass 2:
2935 	 *
2936 	 * Revisit the relocation descriptors with STT_SECTION symbols
2937 	 * that were saved by the first pass. Update each relocation
2938 	 * record so that the offset it contains is for the new section
2939 	 * instead of the original.
2940 	 */
2941 	for (APLIST_TRAVERSE(*rel_alpp, idx, rsp)) {
2942 		const char	*name;
2943 
2944 		/* Put the string into the merged string table */
2945 		name = strmerge_get_reloc_str(ofl, rsp);
2946 		st_setstring_status = st_setstring(mstrtab, name, &stoff);
2947 		if (st_setstring_status == -1) {
2948 			/*
2949 			 * A failure to insert at this point means that
2950 			 * something is corrupt. This isn't a resource issue.
2951 			 */
2952 			assert(st_setstring_status != -1);
2953 			goto return_s_error;
2954 		}
2955 
2956 		/*
2957 		 * Alter the relocation to access the string at the
2958 		 * new offset in our new string table.
2959 		 *
2960 		 * For SHT_RELA platforms, it suffices to simply
2961 		 * update the rel_raddend field of the relocation.
2962 		 *
2963 		 * For SHT_REL platforms, the new "addend" value
2964 		 * needs to be written at the address being relocated.
2965 		 * However, we can't alter the input sections which
2966 		 * are mapped readonly, and the output image has not
2967 		 * been created yet. So, we defer this operation,
2968 		 * using the rel_raddend field of the relocation
2969 		 * which is normally 0 on a REL platform, to pass the
2970 		 * new "addend" value to ld_perform_outreloc() or
2971 		 * ld_do_activerelocs(). The FLG_REL_NADDEND flag
2972 		 * tells them that this is the case.
2973 		 */
2974 		if ((rsp->rel_flags & FLG_REL_RELA) == 0)   /* REL */
2975 			rsp->rel_flags |= FLG_REL_NADDEND;
2976 		rsp->rel_raddend = (Sxword)stoff;
2977 
2978 		/*
2979 		 * Generate a symbol name string for STT_SECTION symbols
2980 		 * that might reference our merged section. This shows up
2981 		 * in debug output and helps show how the relocation has
2982 		 * changed from its original input section to our merged one.
2983 		 */
2984 		if (ld_stt_section_sym_name(mstrsec) == NULL)
2985 			goto return_s_error;
2986 	}
2987 
2988 	/*
2989 	 * Pass 3:
2990 	 *
2991 	 * Modify the symbols referenced by the relocation descriptors
2992 	 * so that they reference the new input section containing the
2993 	 * merged strings instead of the original input sections.
2994 	 */
2995 	for (APLIST_TRAVERSE(*sym_alpp, idx, sdp)) {
2996 		/*
2997 		 * If we've already processed this symbol, don't do it
2998 		 * twice. strmerge_pass1() uses a heuristic (relocations to
2999 		 * the same symbol clump together) to avoid inserting a
3000 		 * given symbol more than once, but repeat symbols in
3001 		 * the list can occur.
3002 		 */
3003 		if ((sdp->sd_isc->is_flags & FLG_IS_INSTRMRG) == 0)
3004 			continue;
3005 
3006 		if (ELF_ST_TYPE(sdp->sd_sym->st_info) != STT_SECTION) {
3007 			/*
3008 			 * This is not an STT_SECTION symbol, so its
3009 			 * value is the offset of the string within the
3010 			 * input section. Update the address to reflect
3011 			 * the address in our new merged section.
3012 			 */
3013 			const char *name = sdp->sd_sym->st_value +
3014 			    (char *)sdp->sd_isc->is_indata->d_buf;
3015 
3016 			st_setstring_status =
3017 			    st_setstring(mstrtab, name, &stoff);
3018 			if (st_setstring_status == -1) {
3019 				/*
3020 				 * A failure to insert at this point means
3021 				 * something is corrupt. This isn't a
3022 				 * resource issue.
3023 				 */
3024 				assert(st_setstring_status != -1);
3025 				goto return_s_error;
3026 			}
3027 
3028 			if (ld_sym_copy(sdp) == S_ERROR)
3029 				goto return_s_error;
3030 			sdp->sd_sym->st_value = (Word)stoff;
3031 		}
3032 
3033 		/* Redirect the symbol to our new merged section */
3034 		sdp->sd_isc = mstrsec;
3035 	}
3036 
3037 	/*
3038 	 * There are no references left to the original input string sections.
3039 	 * Mark them as discarded so they don't go into the output image.
3040 	 * At the same time, add up the sizes of the replaced sections.
3041 	 */
3042 	data_size = 0;
3043 	for (APLIST_TRAVERSE(osp->os_mstrisdescs, idx, isp)) {
3044 		if (isp->is_flags & (FLG_IS_DISCARD | FLG_IS_GNSTRMRG))
3045 			continue;
3046 
3047 		data_size += isp->is_indata->d_size;
3048 
3049 		isp->is_flags |= FLG_IS_DISCARD;
3050 		DBG_CALL(Dbg_sec_discarded(ofl->ofl_lml, isp, mstrsec));
3051 	}
3052 
3053 	/* Report how much space we saved in the output section */
3054 	DBG_CALL(Dbg_sec_genstr_compress(ofl->ofl_lml, osp->os_name, data_size,
3055 	    mstr_data->d_size));
3056 
3057 	st_destroy(mstrtab);
3058 	return (1);
3059 
3060 return_s_error:
3061 	st_destroy(mstrtab);
3062 	return (S_ERROR);
3063 }
3064 
3065 /*
3066  * Update a data buffers size.  A number of sections have to be created, and
3067  * the sections header contributes to the size of the eventual section.  Thus,
3068  * a section may be created, and once all associated sections have been created,
3069  * we return to establish the required section size.
3070  */
3071 inline static void
3072 update_data_size(Os_desc *osp, ulong_t cnt)
3073 {
3074 	Is_desc		*isec = ld_os_first_isdesc(osp);
3075 	Elf_Data	*data = isec->is_indata;
3076 	Shdr		*shdr = osp->os_shdr;
3077 	size_t		size = cnt * shdr->sh_entsize;
3078 
3079 	shdr->sh_size = (Xword)size;
3080 	data->d_size = size;
3081 }
3082 
3083 /*
3084  * The following sections are built after all input file processing and symbol
3085  * validation has been carried out.  The order is important (because the
3086  * addition of a section adds a new symbol there is a chicken and egg problem
3087  * of maintaining the appropriate counts).  By maintaining a known order the
3088  * individual routines can compensate for later, known, additions.
3089  */
3090 uintptr_t
3091 ld_make_sections(Ofl_desc *ofl)
3092 {
3093 	ofl_flag_t	flags = ofl->ofl_flags;
3094 	Sg_desc		*sgp;
3095 
3096 	/*
3097 	 * Generate any special sections.
3098 	 */
3099 	if (flags & FLG_OF_ADDVERS)
3100 		if (make_comment(ofl) == S_ERROR)
3101 			return (S_ERROR);
3102 
3103 	if (make_interp(ofl) == S_ERROR)
3104 		return (S_ERROR);
3105 
3106 	/*
3107 	 * Create a capabilities section if required.
3108 	 */
3109 	if (make_cap(ofl, SHT_SUNW_cap, MSG_ORIG(MSG_SCN_SUNWCAP),
3110 	    ld_targ.t_id.id_cap) == S_ERROR)
3111 		return (S_ERROR);
3112 
3113 	/*
3114 	 * Create any init/fini array sections.
3115 	 */
3116 	if (make_array(ofl, SHT_INIT_ARRAY, MSG_ORIG(MSG_SCN_INITARRAY),
3117 	    ofl->ofl_initarray) == S_ERROR)
3118 		return (S_ERROR);
3119 
3120 	if (make_array(ofl, SHT_FINI_ARRAY, MSG_ORIG(MSG_SCN_FINIARRAY),
3121 	    ofl->ofl_finiarray) == S_ERROR)
3122 		return (S_ERROR);
3123 
3124 	if (make_array(ofl, SHT_PREINIT_ARRAY, MSG_ORIG(MSG_SCN_PREINITARRAY),
3125 	    ofl->ofl_preiarray) == S_ERROR)
3126 		return (S_ERROR);
3127 
3128 	/*
3129 	 * Make the .plt section.  This occurs after any other relocation
3130 	 * sections are generated (see reloc_init()) to ensure that the
3131 	 * associated relocation section is after all the other relocation
3132 	 * sections.
3133 	 */
3134 	if ((ofl->ofl_pltcnt) || (ofl->ofl_pltpad))
3135 		if (make_plt(ofl) == S_ERROR)
3136 			return (S_ERROR);
3137 
3138 	/*
3139 	 * Determine whether any sections or files are not referenced.  Under
3140 	 * -Dunused a diagnostic for any unused components is generated, under
3141 	 * -zignore the component is removed from the final output.
3142 	 */
3143 	if (DBG_ENABLED || (ofl->ofl_flags1 & FLG_OF1_IGNPRC)) {
3144 		if (ignore_section_processing(ofl) == S_ERROR)
3145 			return (S_ERROR);
3146 	}
3147 
3148 	/*
3149 	 * If we have detected a situation in which previously placed
3150 	 * output sections may have been discarded, perform the necessary
3151 	 * readjustment.
3152 	 */
3153 	if (ofl->ofl_flags & FLG_OF_ADJOSCNT)
3154 		adjust_os_count(ofl);
3155 
3156 	/*
3157 	 * Do any of the output sections contain input sections that
3158 	 * are candidates for string table merging? For each such case,
3159 	 * we create a replacement section, insert it, and discard the
3160 	 * originals.
3161 	 *
3162 	 * rel_alpp and sym_alpp are used by ld_make_strmerge()
3163 	 * for its internal processing. We are responsible for the
3164 	 * initialization and cleanup, and ld_make_strmerge() handles the rest.
3165 	 * This allows us to reuse a single pair of memory buffers, allocated
3166 	 * for this processing, for all the output sections.
3167 	 */
3168 	if ((ofl->ofl_flags1 & FLG_OF1_NCSTTAB) == 0) {
3169 		int	error_seen = 0;
3170 		APlist	*rel_alpp = NULL;
3171 		APlist	*sym_alpp = NULL;
3172 		Aliste	idx1;
3173 
3174 		for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp)) {
3175 			Os_desc	*osp;
3176 			Aliste	idx2;
3177 
3178 			for (APLIST_TRAVERSE(sgp->sg_osdescs, idx2, osp))
3179 				if ((osp->os_mstrisdescs != NULL) &&
3180 				    (ld_make_strmerge(ofl, osp,
3181 				    &rel_alpp, &sym_alpp) ==
3182 				    S_ERROR)) {
3183 					error_seen = 1;
3184 					break;
3185 				}
3186 		}
3187 		if (rel_alpp != NULL)
3188 			libld_free(rel_alpp);
3189 		if (sym_alpp != NULL)
3190 			libld_free(sym_alpp);
3191 		if (error_seen != 0)
3192 			return (S_ERROR);
3193 	}
3194 
3195 	/*
3196 	 * Add any necessary versioning information.
3197 	 */
3198 	if (!(flags & FLG_OF_NOVERSEC)) {
3199 		if ((flags & FLG_OF_VERNEED) &&
3200 		    (make_verneed(ofl) == S_ERROR))
3201 			return (S_ERROR);
3202 		if ((flags & FLG_OF_VERDEF) &&
3203 		    (make_verdef(ofl) == S_ERROR))
3204 			return (S_ERROR);
3205 		if ((flags & (FLG_OF_VERNEED | FLG_OF_VERDEF)) &&
3206 		    ((ofl->ofl_osversym = make_sym_sec(ofl,
3207 		    MSG_ORIG(MSG_SCN_SUNWVERSYM), SHT_SUNW_versym,
3208 		    ld_targ.t_id.id_version)) == (Os_desc*)S_ERROR))
3209 			return (S_ERROR);
3210 	}
3211 
3212 	/*
3213 	 * Create a syminfo section if necessary.
3214 	 */
3215 	if (flags & FLG_OF_SYMINFO) {
3216 		if ((ofl->ofl_ossyminfo = make_sym_sec(ofl,
3217 		    MSG_ORIG(MSG_SCN_SUNWSYMINFO), SHT_SUNW_syminfo,
3218 		    ld_targ.t_id.id_syminfo)) == (Os_desc *)S_ERROR)
3219 			return (S_ERROR);
3220 	}
3221 
3222 	if (flags & FLG_OF_COMREL) {
3223 		/*
3224 		 * If -zcombreloc is enabled then all relocations (except for
3225 		 * the PLT's) are coalesced into a single relocation section.
3226 		 */
3227 		if (ofl->ofl_reloccnt) {
3228 			if (make_reloc(ofl, NULL) == S_ERROR)
3229 				return (S_ERROR);
3230 		}
3231 	} else {
3232 		Aliste	idx1;
3233 
3234 		/*
3235 		 * Create the required output relocation sections.  Note, new
3236 		 * sections may be added to the section list that is being
3237 		 * traversed.  These insertions can move the elements of the
3238 		 * Alist such that a section descriptor is re-read.  Recursion
3239 		 * is prevented by maintaining a previous section pointer and
3240 		 * insuring that this pointer isn't re-examined.
3241 		 */
3242 		for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp)) {
3243 			Os_desc	*osp, *posp = 0;
3244 			Aliste	idx2;
3245 
3246 			for (APLIST_TRAVERSE(sgp->sg_osdescs, idx2, osp)) {
3247 				if ((osp != posp) && osp->os_szoutrels &&
3248 				    (osp != ofl->ofl_osplt)) {
3249 					if (make_reloc(ofl, osp) == S_ERROR)
3250 						return (S_ERROR);
3251 				}
3252 				posp = osp;
3253 			}
3254 		}
3255 
3256 		/*
3257 		 * If we're not building a combined relocation section, then
3258 		 * build a .rel[a] section as required.
3259 		 */
3260 		if (ofl->ofl_relocrelsz) {
3261 			if (make_reloc(ofl, NULL) == S_ERROR)
3262 				return (S_ERROR);
3263 		}
3264 	}
3265 
3266 	/*
3267 	 * The PLT relocations are always in their own section, and we try to
3268 	 * keep them at the end of the PLT table.  We do this to keep the hot
3269 	 * "data" PLT's at the head of the table nearer the .dynsym & .hash.
3270 	 */
3271 	if (ofl->ofl_osplt && ofl->ofl_relocpltsz) {
3272 		if (make_reloc(ofl, ofl->ofl_osplt) == S_ERROR)
3273 			return (S_ERROR);
3274 	}
3275 
3276 	/*
3277 	 * Finally build the symbol and section header sections.
3278 	 */
3279 	if (flags & FLG_OF_DYNAMIC) {
3280 		if (make_dynamic(ofl) == S_ERROR)
3281 			return (S_ERROR);
3282 
3283 		/*
3284 		 * A number of sections aren't necessary within a relocatable
3285 		 * object, even if -dy has been used.
3286 		 */
3287 		if (!(flags & FLG_OF_RELOBJ)) {
3288 			if (make_hash(ofl) == S_ERROR)
3289 				return (S_ERROR);
3290 			if (make_dynstr(ofl) == S_ERROR)
3291 				return (S_ERROR);
3292 			if (make_dynsym(ofl) == S_ERROR)
3293 				return (S_ERROR);
3294 			if (ld_unwind_make_hdr(ofl) == S_ERROR)
3295 				return (S_ERROR);
3296 			if (make_dynsort(ofl) == S_ERROR)
3297 				return (S_ERROR);
3298 		}
3299 	}
3300 
3301 	if (!(flags & FLG_OF_STRIP) || (flags & FLG_OF_RELOBJ) ||
3302 	    ((flags & FLG_OF_STATIC) && ofl->ofl_osversym)) {
3303 		/*
3304 		 * Do we need to make a SHT_SYMTAB_SHNDX section
3305 		 * for the dynsym.  If so - do it now.
3306 		 */
3307 		if (ofl->ofl_osdynsym &&
3308 		    ((ofl->ofl_shdrcnt + 3) >= SHN_LORESERVE)) {
3309 			if (make_dynsym_shndx(ofl) == S_ERROR)
3310 				return (S_ERROR);
3311 		}
3312 
3313 		if (make_strtab(ofl) == S_ERROR)
3314 			return (S_ERROR);
3315 		if (make_symtab(ofl) == S_ERROR)
3316 			return (S_ERROR);
3317 	} else {
3318 		/*
3319 		 * Do we need to make a SHT_SYMTAB_SHNDX section
3320 		 * for the dynsym.  If so - do it now.
3321 		 */
3322 		if (ofl->ofl_osdynsym &&
3323 		    ((ofl->ofl_shdrcnt + 1) >= SHN_LORESERVE)) {
3324 			if (make_dynsym_shndx(ofl) == S_ERROR)
3325 				return (S_ERROR);
3326 		}
3327 	}
3328 
3329 	if (make_shstrtab(ofl) == S_ERROR)
3330 		return (S_ERROR);
3331 
3332 	/*
3333 	 * Now that we've created all output sections, adjust the size of the
3334 	 * SHT_SUNW_versym and SHT_SUNW_syminfo section, which are dependent on
3335 	 * the associated symbol table sizes.
3336 	 */
3337 	if (ofl->ofl_osversym || ofl->ofl_ossyminfo) {
3338 		ulong_t		cnt;
3339 		Is_desc		*isp;
3340 		Os_desc		*osp;
3341 
3342 		if (OFL_IS_STATIC_OBJ(ofl))
3343 			osp = ofl->ofl_ossymtab;
3344 		else
3345 			osp = ofl->ofl_osdynsym;
3346 
3347 		isp = ld_os_first_isdesc(osp);
3348 		cnt = (isp->is_shdr->sh_size / isp->is_shdr->sh_entsize);
3349 
3350 		if (ofl->ofl_osversym)
3351 			update_data_size(ofl->ofl_osversym, cnt);
3352 
3353 		if (ofl->ofl_ossyminfo)
3354 			update_data_size(ofl->ofl_ossyminfo, cnt);
3355 	}
3356 
3357 	/*
3358 	 * Now that we've created all output sections, adjust the size of the
3359 	 * SHT_SUNW_capinfo, which is dependent on the associated symbol table
3360 	 * size.
3361 	 */
3362 	if (ofl->ofl_oscapinfo) {
3363 		ulong_t	cnt;
3364 
3365 		/*
3366 		 * Symbol capabilities symbols are placed directly after the
3367 		 * STT_FILE symbol, section symbols, and any register symbols.
3368 		 * Effectively these are the first of any series of demoted
3369 		 * (scoped) symbols.
3370 		 */
3371 		if (OFL_IS_STATIC_OBJ(ofl))
3372 			cnt = SYMTAB_ALL_CNT(ofl);
3373 		else
3374 			cnt = DYNSYM_ALL_CNT(ofl);
3375 
3376 		update_data_size(ofl->ofl_oscapinfo, cnt);
3377 	}
3378 	return (1);
3379 }
3380 
3381 /*
3382  * Build an additional data section - used to back OBJT symbol definitions
3383  * added with a mapfile.
3384  */
3385 Is_desc *
3386 ld_make_data(Ofl_desc *ofl, size_t size)
3387 {
3388 	Shdr		*shdr;
3389 	Elf_Data	*data;
3390 	Is_desc		*isec;
3391 
3392 	if (new_section(ofl, SHT_PROGBITS, MSG_ORIG(MSG_SCN_DATA), 0,
3393 	    &isec, &shdr, &data) == S_ERROR)
3394 		return ((Is_desc *)S_ERROR);
3395 
3396 	data->d_size = size;
3397 	shdr->sh_size = (Xword)size;
3398 	shdr->sh_flags |= SHF_WRITE;
3399 
3400 	if (aplist_append(&ofl->ofl_mapdata, isec, AL_CNT_OFL_MAPSECS) == NULL)
3401 		return ((Is_desc *)S_ERROR);
3402 
3403 	return (isec);
3404 }
3405 
3406 /*
3407  * Build an additional text section - used to back FUNC symbol definitions
3408  * added with a mapfile.
3409  */
3410 Is_desc *
3411 ld_make_text(Ofl_desc *ofl, size_t size)
3412 {
3413 	Shdr		*shdr;
3414 	Elf_Data	*data;
3415 	Is_desc		*isec;
3416 
3417 	/*
3418 	 * Insure the size is sufficient to contain the minimum return
3419 	 * instruction.
3420 	 */
3421 	if (size < ld_targ.t_nf.nf_size)
3422 		size = ld_targ.t_nf.nf_size;
3423 
3424 	if (new_section(ofl, SHT_PROGBITS, MSG_ORIG(MSG_SCN_TEXT), 0,
3425 	    &isec, &shdr, &data) == S_ERROR)
3426 		return ((Is_desc *)S_ERROR);
3427 
3428 	data->d_size = size;
3429 	shdr->sh_size = (Xword)size;
3430 	shdr->sh_flags |= SHF_EXECINSTR;
3431 
3432 	/*
3433 	 * Fill the buffer with the appropriate return instruction.
3434 	 * Note that there is no need to swap bytes on a non-native,
3435 	 * link, as the data being copied is given in bytes.
3436 	 */
3437 	if ((data->d_buf = libld_calloc(size, 1)) == NULL)
3438 		return ((Is_desc *)S_ERROR);
3439 	(void) memcpy(data->d_buf, ld_targ.t_nf.nf_template,
3440 	    ld_targ.t_nf.nf_size);
3441 
3442 	/*
3443 	 * If size was larger than required, and the target supplies
3444 	 * a fill function, use it to fill the balance. If there is no
3445 	 * fill function, we accept the 0-fill supplied by libld_calloc().
3446 	 */
3447 	if ((ld_targ.t_ff.ff_execfill != NULL) && (size > ld_targ.t_nf.nf_size))
3448 		ld_targ.t_ff.ff_execfill(data->d_buf, ld_targ.t_nf.nf_size,
3449 		    size - ld_targ.t_nf.nf_size);
3450 
3451 	if (aplist_append(&ofl->ofl_maptext, isec, AL_CNT_OFL_MAPSECS) == NULL)
3452 		return ((Is_desc *)S_ERROR);
3453 
3454 	return (isec);
3455 }
3456