xref: /illumos-gate/usr/src/cmd/sgs/libld/common/place.c (revision e8d3efa1c56e5f2b5368600a2baeb7b1d54a07f8)
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) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
27  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
28  * Copyright 2026 Oxide Computer Company
29  */
30 
31 /*
32  * Map file parsing and input section to output segment mapping.
33  */
34 #include	<stdio.h>
35 #include	<string.h>
36 #include	<debug.h>
37 #include	"msg.h"
38 #include	"_libld.h"
39 
40 /*
41  * Each time a section is placed, the function set_addralign()
42  * is called.  This function performs:
43  *
44  * -	if the section is from an external file, check if this is empty or not.
45  *	If not, we know the segment this section will belong needs a program
46  *	header. (Of course, the program is needed only if this section falls
47  *	into a loadable segment.)
48  * -	compute the Least Common Multiplier for setting the segment alignment.
49  */
50 static void
51 set_addralign(Ofl_desc *ofl, Os_desc *osp, Is_desc *isp)
52 {
53 	Shdr	*shdr = isp->is_shdr;
54 
55 	/* A discarded section has no influence on the output */
56 	if (isp->is_flags & FLG_IS_DISCARD)
57 		return;
58 
59 	/*
60 	 * If this section has data or will be assigned data
61 	 * later, mark this segment not-empty.
62 	 */
63 	if ((shdr->sh_size != 0) ||
64 	    ((isp->is_flags & FLG_IS_EXTERNAL) == 0))
65 		osp->os_sgdesc->sg_flags |= FLG_SG_PHREQ;
66 
67 	if ((ofl->ofl_dtflags_1 & DF_1_NOHDR) &&
68 	    (osp->os_sgdesc->sg_phdr).p_type != PT_LOAD)
69 		return;
70 
71 	osp->os_sgdesc->sg_align =
72 	    ld_lcm(osp->os_sgdesc->sg_align, shdr->sh_addralign);
73 }
74 
75 /*
76  * Return the first input descriptor for a given output descriptor,
77  * or NULL if there are none.
78  */
79 
80 Is_desc *
81 ld_os_first_isdesc(Os_desc *osp)
82 {
83 	int i;
84 
85 	for (i = 0; i < OS_ISD_NUM; i++) {
86 		APlist *ap_isdesc = osp->os_isdescs[i];
87 
88 		if (aplist_nitems(ap_isdesc) > 0)
89 			return ((Is_desc *)ap_isdesc->apl_data[0]);
90 	}
91 
92 	return (NULL);
93 }
94 
95 /*
96  * Attach an input section to an output section
97  *
98  * entry:
99  *	ofl - File descriptor
100  *	osp - Output section descriptor
101  *	isp - Input section descriptor
102  *	mapfile_sort - True (1) if segment supports mapfile specified ordering
103  *		of otherwise unordered input sections, and False (0) otherwise.
104  *
105  * exit:
106  *	- The input section has been attached to the output section
107  *	- If the input section is a candidate for string table merging,
108  *		then it is appended to the output section's list of merge
109  *		candidates (os_mstridescs).
110  *
111  *	On success, returns True (1). On failure, False (0).
112  */
113 static int
114 os_attach_isp(Ofl_desc *ofl, Os_desc *osp, Is_desc *isp, int mapfile_sort)
115 {
116 	Aliste	init_arritems;
117 	int	os_isdescs_idx, do_append = 1;
118 
119 	if ((isp->is_flags & FLG_IS_ORDERED) == 0) {
120 		init_arritems = AL_CNT_OS_ISDESCS;
121 		os_isdescs_idx = OS_ISD_DEFAULT;
122 
123 		/*
124 		 * If section ordering was specified for an unordered section
125 		 * via the mapfile, then search in the OS_ISD_DEFAULT list
126 		 * and insert it in the specified position. Ordered sections
127 		 * are placed in ascending order before unordered sections
128 		 * (sections with an is_ordndx value of zero).
129 		 *
130 		 * If no mapfile ordering was specified, we append it in
131 		 * the usual way below.
132 		 */
133 		if (mapfile_sort && (isp->is_ordndx > 0)) {
134 			APlist *ap_isdesc = osp->os_isdescs[OS_ISD_DEFAULT];
135 			Aliste	idx2;
136 			Is_desc	*isp2;
137 
138 			for (APLIST_TRAVERSE(ap_isdesc, idx2, isp2)) {
139 				if (isp2->is_ordndx &&
140 				    (isp2->is_ordndx <= isp->is_ordndx))
141 						continue;
142 
143 				if (aplist_insert(
144 				    &osp->os_isdescs[OS_ISD_DEFAULT],
145 				    isp, init_arritems, idx2) == NULL)
146 					return (0);
147 				do_append = 0;
148 				break;
149 			}
150 		}
151 	} else {		/* Ordered section (via shdr flags) */
152 		Word shndx;
153 
154 		/* SHF_ORDERED uses sh_info, SHF_LINK_ORDERED uses sh_link */
155 		shndx = (isp->is_shdr->sh_flags & SHF_ORDERED) ?
156 		    isp->is_shdr->sh_info : isp->is_shdr->sh_link;
157 
158 		if (shndx == SHN_BEFORE) {
159 			init_arritems = AL_CNT_OS_ISDESCS_BA;
160 			os_isdescs_idx = OS_ISD_BEFORE;
161 		} else if (shndx == SHN_AFTER) {
162 			init_arritems = AL_CNT_OS_ISDESCS_BA;
163 			os_isdescs_idx = OS_ISD_AFTER;
164 		} else {
165 			init_arritems = AL_CNT_OS_ISDESCS;
166 			os_isdescs_idx = OS_ISD_ORDERED;
167 		}
168 	}
169 
170 	/*
171 	 * If we didn't insert a section into the default list using
172 	 * mapfile specified ordering above, then append the input
173 	 * section to the appropriate list.
174 	 */
175 	if (do_append && aplist_append(&(osp->os_isdescs[os_isdescs_idx]),
176 	    isp, init_arritems) == NULL)
177 		return (0);
178 	isp->is_osdesc = osp;
179 
180 	/*
181 	 * A section can be merged if the following are true:
182 	 * -	The SHF_MERGE|SHF_STRINGS flags must be set
183 	 * -	String table compression must not be disabled (-znocompstrtab)
184 	 * -	Mapfile ordering must not have been used.
185 	 * -	The section must not be ordered via section header flags.
186 	 * -	It must not be the generated section being built to
187 	 *	replace the sections on this list.
188 	 */
189 	if (((isp->is_shdr->sh_flags & (SHF_MERGE | SHF_STRINGS)) !=
190 	    (SHF_MERGE | SHF_STRINGS)) ||
191 	    ((ofl->ofl_flags1 & FLG_OF1_NCSTTAB) != 0) ||
192 	    !do_append ||
193 	    ((isp->is_flags & (FLG_IS_ORDERED | FLG_IS_GNSTRMRG)) != 0))
194 		return (1);
195 
196 	/*
197 	 * Skip sections with (sh_entsize > 1) or (sh_addralign > 1).
198 	 *
199 	 * sh_entsize:
200 	 *	We are currently only able to merge string tables containing
201 	 *	strings with 1-byte (char) characters. Support for wide
202 	 *	characters will require our string table compression code
203 	 *	to be extended to handle larger character sizes.
204 	 *
205 	 * sh_addralign:
206 	 *	Alignments greater than 1 would require our string table
207 	 *	compression code to insert null bytes to move each
208 	 *	string to the required alignment.
209 	 */
210 	if ((isp->is_shdr->sh_entsize > 1) ||
211 	    (isp->is_shdr->sh_addralign > 1)) {
212 		DBG_CALL(Dbg_sec_unsup_strmerge(ofl->ofl_lml, isp));
213 		return (1);
214 	}
215 
216 	if (aplist_append(&osp->os_mstrisdescs, isp,
217 	    AL_CNT_OS_MSTRISDESCS) == NULL)
218 		return (0);
219 
220 	/*
221 	 * The SHF_MERGE|SHF_STRINGS flags tell us that the program that
222 	 * created the section intended it to be mergeable. The
223 	 * FLG_IS_INSTRMRG flag says that we have done validity testing
224 	 * and decided that it is safe to act on that hint.
225 	 */
226 	isp->is_flags |= FLG_IS_INSTRMRG;
227 
228 	return (1);
229 }
230 
231 /*
232  * Determine whether this input COMDAT section already exists for the associated
233  * output section.  If so, then discard this input section.  Otherwise, this
234  * must be the first COMDAT section, thus it is kept for future comparisons.
235  */
236 static uintptr_t
237 add_comdat(Ofl_desc *ofl, Os_desc *osp, Is_desc *isp)
238 {
239 	Isd_node	isd, *isdp;
240 	avl_tree_t	*avlt;
241 	avl_index_t	where;
242 	Group_desc	*gr;
243 
244 	/*
245 	 * Sections to which COMDAT groups apply are FLG_IS_COMDAT but are
246 	 * discarded separately by the group logic so should never be
247 	 * discarded here.
248 	 */
249 	if ((isp->is_shdr->sh_flags & SHF_GROUP) &&
250 	    ((gr = ld_get_group(ofl, isp)) != NULL) &&
251 	    (gr->gd_data[0] & GRP_COMDAT))
252 		return (1);
253 
254 	/*
255 	 * Create a COMDAT avl tree for this output section if required.
256 	 */
257 	if ((avlt = osp->os_comdats) == NULL) {
258 		if ((avlt = libld_calloc(1, sizeof (avl_tree_t))) == NULL)
259 			return (S_ERROR);
260 		avl_create(avlt, isdavl_compare, sizeof (Isd_node),
261 		    SGSOFFSETOF(Isd_node, isd_avl));
262 		osp->os_comdats = avlt;
263 	}
264 
265 	/*
266 	 * A standard COMDAT section uses the section name as search key.
267 	 */
268 	isd.isd_name = isp->is_name;
269 	isd.isd_hash = sgs_str_hash(isd.isd_name);
270 
271 	if ((isdp = avl_find(avlt, &isd, &where)) != NULL) {
272 		isp->is_osdesc = osp;
273 
274 		/*
275 		 * If this section hasn't already been identified as discarded,
276 		 * generate a suitable diagnostic.
277 		 */
278 		if ((isp->is_flags & FLG_IS_DISCARD) == 0) {
279 			isp->is_flags |= FLG_IS_DISCARD;
280 			isp->is_comdatkeep = isdp->isd_isp;
281 			DBG_CALL(Dbg_sec_discarded(ofl->ofl_lml, isp,
282 			    isdp->isd_isp));
283 		}
284 
285 		/*
286 		 * A discarded section does not require assignment to an output
287 		 * section.  However, if relaxed relocations have been enabled
288 		 * (either from -z relaxreloc, or asserted with .gnu.linkonce
289 		 * processing), then this section must still be assigned to an
290 		 * output section so that the sloppy relocation logic will have
291 		 * the information necessary to do its work.
292 		 */
293 		return (0);
294 	}
295 
296 	/*
297 	 * This is a new COMDAT section - so keep it.
298 	 */
299 	if ((isdp = libld_calloc(1, sizeof (Isd_node))) == NULL)
300 		return (S_ERROR);
301 
302 	isdp->isd_name = isd.isd_name;
303 	isdp->isd_hash = isd.isd_hash;
304 	isdp->isd_isp = isp;
305 
306 	avl_insert(avlt, isdp, where);
307 	return (1);
308 }
309 
310 /*
311  * Determine whether a GNU group COMDAT section name follows the convention
312  *
313  *	section-name.symbol-name
314  *
315  * Each section within the input file is compared to see if the full section
316  * name matches the beginning of the COMDAT section, with a following '.'.
317  * A pointer to the symbol name, starting with the '.' is returned so that the
318  * caller can strip off the required section name.
319  */
320 static char *
321 gnu_comdat_sym(Ifl_desc *ifl, Is_desc *gisp)
322 {
323 	size_t	ndx;
324 
325 	for (ndx = 1; ndx < ifl->ifl_shnum; ndx++) {
326 		Is_desc	*isp;
327 		size_t	ssize;
328 
329 		if (((isp = ifl->ifl_isdesc[ndx]) == NULL) ||
330 		    (isp == gisp) || (isp->is_name == NULL))
331 			continue;
332 
333 		/*
334 		 * It's questionable whether this size should be cached in the
335 		 * Is_desc.  However, this seems an infrequent operation and
336 		 * adding Is_desc members can escalate memory usage for large
337 		 * link-edits.  For now, size the section name dynamically.
338 		 */
339 		ssize = strlen(isp->is_name);
340 		if ((strncmp(isp->is_name, gisp->is_name, ssize) == 0) &&
341 		    (gisp->is_name[ssize] == '.'))
342 			return ((char *)&gisp->is_name[ssize]);
343 	}
344 	return (NULL);
345 }
346 
347 /*
348  * GNU .gnu.linkonce sections follow a naming convention that indicates the
349  * required association with an output section.  Determine whether this input
350  * section follows the convention, and if so return the appropriate output
351  * section name.
352  *
353  *	.gnu.linkonce.b.*    ->	.bss
354  *	.gnu.linkonce.d.*    ->	.data
355  *	.gnu.linkonce.l.*    ->	.ldata
356  *	.gnu.linkonce.lb.*   ->	.lbss
357  *	.gnu.linkonce.lr.*   ->	.lrodata
358  *	.gnu.linkonce.r.*    ->	.rodata
359  *	.gnu.linkonce.s.*    ->	.sdata
360  *	.gnu.linkonce.s2.*   ->	.sdata2
361  *	.gnu.linkonce.sb.*   ->	.sbss
362  *	.gnu.linkonce.sb2.*  ->	.sbss2
363  *	.gnu.linkonce.t.*    ->	.text
364  *	.gnu.linkonce.tb.*   ->	.tbss
365  *	.gnu.linkonce.td.*   ->	.tdata
366  *	.gnu.linkonce.wi.*   ->	.debug_info
367  */
368 #define	NSTR_CH1(ch) (*(nstr + 1) == (ch))
369 #define	NSTR_CH2(ch) (*(nstr + 2) == (ch))
370 #define	NSTR_CH3(ch) (*(nstr + 3) == (ch))
371 
372 static const char *
373 gnu_linkonce_sec(const char *ostr)
374 {
375 	const char	*nstr = &ostr[MSG_SCN_GNU_LINKONCE_SIZE];
376 
377 	switch (*nstr) {
378 	case 'b':
379 		if (NSTR_CH1('.'))
380 			return (MSG_ORIG(MSG_SCN_BSS));
381 		break;
382 	case 'd':
383 		if (NSTR_CH1('.'))
384 			return (MSG_ORIG(MSG_SCN_DATA));
385 		break;
386 	case 'l':
387 		if (NSTR_CH1('.'))
388 			return (MSG_ORIG(MSG_SCN_LDATA));
389 		else if (NSTR_CH1('b') && NSTR_CH2('.'))
390 			return (MSG_ORIG(MSG_SCN_LBSS));
391 		else if (NSTR_CH1('r') && NSTR_CH2('.'))
392 			return (MSG_ORIG(MSG_SCN_LRODATA));
393 		break;
394 	case 'r':
395 		if (NSTR_CH1('.'))
396 			return (MSG_ORIG(MSG_SCN_RODATA));
397 		break;
398 	case 's':
399 		if (NSTR_CH1('.'))
400 			return (MSG_ORIG(MSG_SCN_SDATA));
401 		else if (NSTR_CH1('2') && NSTR_CH2('.'))
402 			return (MSG_ORIG(MSG_SCN_SDATA2));
403 		else if (NSTR_CH1('b') && NSTR_CH2('.'))
404 			return (MSG_ORIG(MSG_SCN_SBSS));
405 		else if (NSTR_CH1('b') && NSTR_CH2('2') && NSTR_CH3('.'))
406 			return (MSG_ORIG(MSG_SCN_SBSS2));
407 		break;
408 	case 't':
409 		if (NSTR_CH1('.'))
410 			return (MSG_ORIG(MSG_SCN_TEXT));
411 		else if (NSTR_CH1('b') && NSTR_CH2('.'))
412 			return (MSG_ORIG(MSG_SCN_TBSS));
413 		else if (NSTR_CH1('d') && NSTR_CH2('.'))
414 			return (MSG_ORIG(MSG_SCN_TDATA));
415 		break;
416 	case 'w':
417 		if (NSTR_CH1('i') && NSTR_CH2('.'))
418 			return (MSG_ORIG(MSG_SCN_DEBUG_INFO));
419 		break;
420 	default:
421 		break;
422 	}
423 
424 	/*
425 	 * No special name match found.
426 	 */
427 	return (ostr);
428 }
429 #undef	NSTR_CH1
430 #undef	NSTR_CH2
431 #undef	NSTR_CH3
432 
433 /*
434  * The GNU link-editor maps sections generated by the GNU compiler separately
435  * due to -ffunction-sections, -fdata-sections or for other reasons into the
436  * "normal" section represented.
437  *
438  * Sections are named .<main>.<symbol> where <main> is the usual section to
439  * which it should be mapped, and <symbol> is providing the unique name for
440  * the original section.  Both parts of the name may contain periods, in cases
441  * where the unique part of the name contains a '.' and/or the section it
442  * contributes to does (such as .data.rel.ro)
443  *
444  * .rodata.str* and .rodata.cst* are mapped to .rodata.
445  *
446  * As a further complication, the GNU link-editor may or may not merge
447  * .ctors.* and .dtors.* into init_array and fini_array, rather than ctors and
448  * dtors.  We do not implement this at this time.
449  *
450  * The GNU link editor may also arrange for sections with .local in their name
451  * to be mapped as above, but grouped together.  We do not implement this (and
452  * do not merge them at all, to make this clear)
453  *
454  * This table is processed in order.  Longer mappings must come first.
455  */
456 static struct split_sec_mapping {
457 	char *leader;
458 	char *section;
459 	boolean_t precise;
460 } split_sec_mapping[] = {
461 	{ ".bss.",			".bss",			B_FALSE },
462 	{ ".ctors.",			".ctors",		B_FALSE },
463 	{ ".data.rel.local.",		".data.rel.local",	B_FALSE },
464 	{ ".data.rel.local",		".data.rel.local",	B_TRUE },
465 	{ ".data.rel.ro.local.",	".data.rel.ro",		B_FALSE },
466 	{ ".data.rel.ro.",		".data.rel.ro",		B_FALSE },
467 	{ ".data.rel.ro",		".data.rel.ro",		B_TRUE },
468 	{ ".data.rel.",			".data.rel",		B_FALSE },
469 	{ ".data.rel",			".data.rel",		B_TRUE },
470 	{ ".data.",			".data",		B_FALSE },
471 	{ ".dtors.",			".dtors",		B_FALSE },
472 	{ ".fini_array.",		".fini_array",		B_FALSE },
473 	{ ".gcc_except_table.",		".gcc_except_table",	B_FALSE },
474 	{ ".init_array.",		".init_array",		B_FALSE },
475 	{ ".lbss.",			".lbss",		B_FALSE },
476 	{ ".ldata.",			".ldata",		B_FALSE },
477 	{ ".lrodata.",			".lrodata",		B_FALSE },
478 	/* This intentionally applies to .rodata.cstN and .rodata.strN, too */
479 	{ ".rodata.",			".rodata",		B_FALSE },
480 	{ ".sbss2.",			".sbss2",		B_FALSE },
481 	{ ".sbss.",			".sbss",		B_FALSE },
482 	{ ".sdata2.",			".sdata2",		B_FALSE },
483 	{ ".sdata.",			".sdata",		B_FALSE },
484 	{ ".tbss.",			".tbss",		B_FALSE },
485 	{ ".tdata.",			".tdata",		B_FALSE },
486 	{ ".text.",			".text",		B_FALSE },
487 	{ NULL,				NULL,			B_FALSE }
488 };
489 
490 static const char *
491 gnu_split_sec(const char *ostr)
492 {
493 	struct split_sec_mapping *mp;
494 
495 	for (mp = split_sec_mapping; mp->leader != NULL; mp++) {
496 		if (mp->precise) {
497 			if (strcmp(ostr, mp->leader) == 0)
498 				return (mp->section);
499 		} else if (strncmp(ostr, mp->leader, strlen(mp->leader)) == 0) {
500 			return (mp->section);
501 		}
502 	}
503 
504 	return (ostr);
505 }
506 
507 /*
508  * Initialize a path info buffer for use with ld_place_section().
509  *
510  * entry:
511  *	ofl - Output descriptor
512  *	ifl - Descriptor for input file, or NULL if there is none.
513  *	info - Address of buffer to be initialized.
514  *
515  * exit:
516  *	If this is an input file, and if the entrance criteria list
517  *	contains at least one criteria that has a non-empty file string
518  *	match list (ec_files), then the block pointed at by info is
519  *	initialized, and info is returned.
520  *
521  *	If there is no input file, and/or no entrance criteria containing
522  *	a non-empty ec_files list, then NULL is returned. This is not
523  *	an error --- the NULL is simply an optimization, understood by
524  *	ld_place_path(), that allows it to skip unnecessary work.
525  */
526 Place_path_info *
527 ld_place_path_info_init(Ofl_desc *ofl, Ifl_desc *ifl, Place_path_info *info)
528 {
529 	/*
530 	 * Return NULL if there is no input file (internally generated section)
531 	 * or if the entrance criteria list does not contain any items that will
532 	 * need to be compared to the path (all the ec_files lists are empty).
533 	 */
534 	if ((ifl == NULL) || !(ofl->ofl_flags & FLG_OF_EC_FILES))
535 		return (NULL);
536 
537 	info->ppi_path = ifl->ifl_name;
538 	info->ppi_path_len = strlen(info->ppi_path);
539 	info->ppi_isar = (ifl->ifl_flags & FLG_IF_EXTRACT) != 0;
540 
541 	/*
542 	 * The basename is the final segment of the path, equivalent to
543 	 * the path itself if there are no '/' delimiters.
544 	 */
545 	info->ppi_bname = strrchr(info->ppi_path, '/');
546 	if (info->ppi_bname == NULL)
547 		info->ppi_bname = info->ppi_path;
548 	else
549 		info->ppi_bname++;	/* Skip leading '/' */
550 	info->ppi_bname_len =
551 	    info->ppi_path_len - (info->ppi_bname - info->ppi_path);
552 
553 	/*
554 	 * For an archive, the object name is the member name, which is
555 	 * enclosed in () at the end of the name string. Otherwise, it is
556 	 * the same as the basename.
557 	 */
558 	if (info->ppi_isar) {
559 		info->ppi_oname = strrchr(info->ppi_bname, '(');
560 		/* There must be an archive member suffix delimited by parens */
561 		assert((info->ppi_bname[info->ppi_bname_len - 1] == ')') &&
562 		    (info->ppi_oname != NULL));
563 		info->ppi_oname++;	/* skip leading '(' */
564 		info->ppi_oname_len = info->ppi_bname_len -
565 		    (info->ppi_oname - info->ppi_bname + 1);
566 	} else {
567 		info->ppi_oname = info->ppi_bname;
568 		info->ppi_oname_len = info->ppi_bname_len;
569 	}
570 
571 	return (info);
572 }
573 
574 /*
575  * Compare an input section path to the file comparison list the given
576  * entrance criteria.
577  *
578  * entry:
579  *	path_info - A non-NULL Place_path_info block for the file
580  *		containing the input section, initialized by
581  *		ld_place_path_info_init()
582  *	enp - Entrance criteria with a non-empty ec_files list of file
583  *		comparisons to be carried out.
584  *
585  * exit:
586  *	Return TRUE if a match is seen, and FALSE otherwise.
587  */
588 static Boolean
589 eval_ec_files(Place_path_info *path_info, Ent_desc *enp)
590 {
591 	Aliste		idx;
592 	Ent_desc_file	*edfp;
593 	size_t		cmp_len;
594 	const char	*cmp_str;
595 
596 	for (ALIST_TRAVERSE(enp->ec_files, idx, edfp)) {
597 		Word	type = edfp->edf_flags & TYP_ECF_MASK;
598 
599 		/*
600 		 * Determine the starting character, and # of characters,
601 		 * from the file path to compare against this entrance criteria
602 		 * file string.
603 		 */
604 		if (type == TYP_ECF_OBJNAME) {
605 			cmp_str = path_info->ppi_oname;
606 			cmp_len = path_info->ppi_oname_len;
607 		} else {
608 			int ar_stat_diff = path_info->ppi_isar !=
609 			    ((edfp->edf_flags & FLG_ECF_ARMEMBER) != 0);
610 
611 			/*
612 			 * If the entrance criteria specifies an archive member
613 			 * and the file does not, then there can be no match.
614 			 */
615 
616 			if (ar_stat_diff && !path_info->ppi_isar)
617 				continue;
618 
619 			if (type == TYP_ECF_PATH) {
620 				cmp_str = path_info->ppi_path;
621 				cmp_len = path_info->ppi_path_len;
622 			} else {	/* TYP_ECF_BASENAME */
623 				cmp_str = path_info->ppi_bname;
624 				cmp_len = path_info->ppi_bname_len;
625 			}
626 
627 			/*
628 			 * If the entrance criteria does not specify an archive
629 			 * member and the file does, then a match just requires
630 			 * the paths (without the archive member) to match.
631 			 * Reduce the length to not include the ar member or
632 			 * the '(' that precedes it.
633 			 */
634 			if (ar_stat_diff && path_info->ppi_isar)
635 				cmp_len = path_info->ppi_oname - cmp_str - 1;
636 		}
637 
638 		/*
639 		 * Compare the resulting string to the one from the
640 		 * entrance criteria.
641 		 */
642 		if ((cmp_len == edfp->edf_name_len) &&
643 		    (strncmp(edfp->edf_name, cmp_str, cmp_len) == 0))
644 			return (TRUE);
645 	}
646 
647 	return (FALSE);
648 }
649 
650 /*
651  * Replace the section header for the given input section with a new section
652  * header of the specified type. All values in the replacement header other
653  * than the type retain their previous values.
654  *
655  * entry:
656  *	isp - Input section to replace
657  *	sh_type - New section type to apply
658  *
659  * exit:
660  *	Returns the pointer to the new section header on success, and
661  *	NULL for failure.
662  */
663 static Shdr *
664 isp_convert_type(Is_desc *isp, Word sh_type)
665 {
666 	Shdr	*shdr;
667 
668 	if ((shdr = libld_malloc(sizeof (Shdr))) == NULL)
669 		return (NULL);
670 	*shdr = *isp->is_shdr;
671 	isp->is_shdr = shdr;
672 	shdr->sh_type = sh_type;
673 	return (shdr);
674 }
675 
676 /*
677  * Issue a fatal warning for the given .eh_frame section, which
678  * cannot be merged with the existing .eh_frame output section.
679  */
680 static void
681 eh_frame_muldef(Ofl_desc *ofl, Is_desc *isp)
682 {
683 	Sg_desc	*sgp;
684 	Is_desc *isp1;
685 	Os_desc	*osp;
686 	Aliste	idx1, idx2, idx3;
687 
688 	/*
689 	 * Locate the .eh_frame output section, and use the first section
690 	 * assigned to it in the error message. The user can then compare
691 	 * the two sections to determine what attribute prevented the merge.
692 	 */
693 	for (APLIST_TRAVERSE(ofl->ofl_segs, idx1, sgp)) {
694 		for (APLIST_TRAVERSE(sgp->sg_osdescs, idx2, osp)) {
695 			if ((osp->os_flags & FLG_OS_EHFRAME) == 0)
696 				continue;
697 
698 			for (idx3 = 0; idx3 < OS_ISD_NUM; idx3++) {
699 				APlist *lst = osp->os_isdescs[idx3];
700 
701 				if (aplist_nitems(lst) == 0)
702 					continue;
703 
704 				isp1 = lst->apl_data[0];
705 				ld_eprintf(ofl, ERR_FATAL,
706 				    MSG_INTL(MSG_UPD_MULEHFRAME),
707 				    isp1->is_file->ifl_name,
708 				    EC_WORD(isp1->is_scnndx), isp1->is_name,
709 				    isp->is_file->ifl_name,
710 				    EC_WORD(isp->is_scnndx), isp->is_name);
711 				return;
712 			}
713 		}
714 	}
715 }
716 
717 /*
718  * Hash the specified Os_desc on the specified segment descriptor, allocating
719  * and resizing the hash table as necessary.  (We only hash when the number of
720  * output secctions exceeds a minimum, below which we deem it not worth it to
721  * have the auxiliary structure.)
722  */
723 static void
724 os_desc_hash(Sg_desc *sgp, Os_desc *osp)
725 {
726 	const size_t min_size = 31;
727 	Aliste nitems, idx, idx1;
728 	os_desc_hash_t *hash;
729 	size_t new_size;
730 
731 	if ((nitems = aplist_nitems(sgp->sg_osdescs)) < min_size) {
732 		return;
733 	}
734 
735 	if ((hash = sgp->sg_hashtab) != NULL && hash->osh_hashtab != NULL) {
736 		if (nitems < hash->osh_size) {
737 			/*
738 			 * We have a hash table, and it's not undersized -- just
739 			 * add our newest element.
740 			 */
741 			idx = osp->os_namehash % hash->osh_size;
742 			osp->os_hashnext = hash->osh_hashtab[idx];
743 			hash->osh_hashtab[idx] = osp;
744 			return;
745 		}
746 
747 		/*
748 		 * We have a hash table, but it's full:  we are going to want
749 		 * to double our size and rehash all of the output section
750 		 * descriptions.  First, free our old hash table...
751 		 */
752 		libld_free(hash->osh_hashtab);
753 		new_size = (hash->osh_size << 1) - 1;
754 	} else {
755 		/*
756 		 * We either don't have a hash structure or we don't have a
757 		 * hash table (the partial construction of which may be due to
758 		 * a previous allocation failure).  Determine what we want
759 		 * our new size to be, and allocate our hash structure as
760 		 * needed.
761 		 */
762 		new_size = min_size;
763 
764 		while (new_size <= nitems)
765 			new_size = (new_size << 1) - 1;
766 
767 		if (hash == NULL) {
768 			hash = libld_calloc(1, sizeof (os_desc_hash_t));
769 
770 			if ((sgp->sg_hashtab = hash) == NULL)
771 				return;
772 		}
773 	}
774 
775 	if ((hash->osh_hashtab =
776 	    libld_calloc(new_size, sizeof (void *))) == NULL) {
777 		return;
778 	}
779 
780 	/*
781 	 * Set our new size, and scan everything and hash it in.
782 	 */
783 	hash->osh_size = new_size;
784 
785 	for (APLIST_TRAVERSE(sgp->sg_osdescs, idx1, osp)) {
786 		idx = osp->os_namehash % hash->osh_size;
787 		osp->os_hashnext = hash->osh_hashtab[idx];
788 		hash->osh_hashtab[idx] = osp;
789 	}
790 }
791 
792 /*
793  * Place a section into the appropriate segment and output section.
794  *
795  * entry:
796  *	ofl - File descriptor
797  *	isp - Input section descriptor of section to be placed.
798  *	path_info - NULL, or pointer to Place_path_info buffer initialized
799  *		by ld_place_path_info_init() for the file associated to isp,
800  *		for use in processing entrance criteria with non-empty
801  *		file matching string list (ec_files)
802  *	ident - Section identifier, used to order sections relative to
803  *		others within the output segment.
804  *	alt_os_name - If non-NULL, the name of the output section to place
805  *		isp into. If NULL, input sections go to an output section
806  *		with the same name as the input section.
807  */
808 Os_desc *
809 ld_place_section(Ofl_desc *ofl, Is_desc *isp, Place_path_info *path_info,
810     int ident, const char *alt_os_name)
811 {
812 	Ent_desc	*enp;
813 	Sg_desc		*sgp;
814 	Os_desc		*osp;
815 	Aliste		idx1, iidx;
816 	int		os_ndx;
817 	Shdr		*shdr = isp->is_shdr;
818 	Xword		shflagmask, shflags = shdr->sh_flags;
819 	Ifl_desc	*ifl = isp->is_file;
820 	char		*oname, *sname;
821 	uint_t		onamehash;
822 	Boolean		is_ehframe = (isp->is_flags & FLG_IS_EHFRAME) != 0;
823 	Boolean		linear_scan = TRUE;
824 	os_desc_hash_t	*hash;
825 
826 	/*
827 	 * Define any sections that must be thought of as referenced.  These
828 	 * sections may not be referenced externally in a manner ld(1) can
829 	 * discover, but they must be retained (ie. not removed by -zignore).
830 	 */
831 	static const Msg RefSecs[] = {
832 		MSG_SCN_INIT,		/* MSG_ORIG(MSG_SCN_INIT) */
833 		MSG_SCN_FINI,		/* MSG_ORIG(MSG_SCN_FINI) */
834 		MSG_SCN_EX_RANGES,	/* MSG_ORIG(MSG_SCN_EX_RANGES) */
835 		MSG_SCN_EX_SHARED,	/* MSG_ORIG(MSG_SCN_EX_SHARED) */
836 		MSG_SCN_CTORS,		/* MSG_ORIG(MSG_SCN_CTORS) */
837 		MSG_SCN_DTORS,		/* MSG_ORIG(MSG_SCN_DTORS) */
838 		MSG_SCN_EHFRAME,	/* MSG_ORIG(MSG_SCN_EHFRAME) */
839 		MSG_SCN_EHFRAME_HDR,	/* MSG_ORIG(MSG_SCN_EHFRAME_HDR) */
840 		MSG_SCN_JCR,		/* MSG_ORIG(MSG_SCN_JCR) */
841 		MSG_SCN_INITARRAY,	/* MSG_ORIG(MSG_SCN_INITARRAY) */
842 		MSG_SCN_FINIARRAY,	/* MSG_ORIG(MSG_SCN_FINIARRAY) */
843 		MSG_SCN_PREINITARRAY,	/* MSG_ORIG(MSG_SCN_PREINITARRAY) */
844 		0
845 	};
846 
847 	DBG_CALL(Dbg_sec_in(ofl->ofl_lml, isp));
848 
849 	/*
850 	 * If this section identifies group members, or this section indicates
851 	 * that it is a member of a group, determine whether the section is
852 	 * still required.
853 	 */
854 	if ((shflags & SHF_GROUP) || (shdr->sh_type == SHT_GROUP)) {
855 		Group_desc	*gdesc;
856 
857 		if ((gdesc = ld_get_group(ofl, isp)) != NULL) {
858 			DBG_CALL(Dbg_sec_group(ofl->ofl_lml, isp, gdesc));
859 
860 			/*
861 			 * If this group has been replaced by another group,
862 			 * then this section needs to be discarded.
863 			 */
864 			if (gdesc->gd_oisc) {
865 				isp->is_flags |= FLG_IS_DISCARD;
866 
867 				/*
868 				 * Since we're discarding the section, we
869 				 * can skip assigning it to an output section.
870 				 * The exception is that if the user
871 				 * specifies -z relaxreloc, then
872 				 * we need to assign the output section so
873 				 * that the sloppy relocation logic will have
874 				 * the information necessary to do its work.
875 				 */
876 				if (!(ofl->ofl_flags1 & FLG_OF1_RLXREL))
877 					return (NULL);
878 			}
879 		}
880 
881 		/*
882 		 * SHT_GROUP sections can only be included into relocatable
883 		 * objects.
884 		 */
885 		if (shdr->sh_type == SHT_GROUP) {
886 			if ((ofl->ofl_flags & FLG_OF_RELOBJ) == 0) {
887 				isp->is_flags |= FLG_IS_DISCARD;
888 				return (NULL);
889 			}
890 		}
891 	}
892 
893 	/*
894 	 * Always assign SHF_TLS sections to the DATA segment (and then the
895 	 * PT_TLS embedded inside of there).
896 	 */
897 	if (shflags & SHF_TLS)
898 		shflags |= SHF_WRITE;
899 
900 	/*
901 	 * Traverse the entrance criteria list searching for a segment that
902 	 * matches the input section we have.  If an entrance criterion is set
903 	 * then there must be an exact match.  If we complete the loop without
904 	 * finding a segment, then sgp will be NULL.
905 	 */
906 	sgp = NULL;
907 	for (APLIST_TRAVERSE(ofl->ofl_ents, idx1, enp)) {
908 
909 		/* Disabled segments are not available for assignment */
910 		if (enp->ec_segment->sg_flags & FLG_SG_DISABLED)
911 			continue;
912 
913 		/*
914 		 * If an entrance criteria doesn't have any of its fields
915 		 * set, it will match any section it is tested against.
916 		 * We set the FLG_EC_CATCHALL flag on these, primarily because
917 		 * it helps readers of our debug output to understand what
918 		 * the criteria means --- otherwise the user would just see
919 		 * that every field is 0, but might not understand the
920 		 * significance of that.
921 		 *
922 		 * Given that we set this flag, we can use it here as an
923 		 * optimization to short circuit all of the tests in this
924 		 * loop. Note however, that if we did not do this, the end
925 		 * result would be the same --- the empty criteria will sail
926 		 * past the following tests and reach the end of the loop.
927 		 */
928 		if (enp->ec_flags & FLG_EC_CATCHALL) {
929 			sgp = enp->ec_segment;
930 			break;
931 		}
932 
933 		if (enp->ec_type && (enp->ec_type != shdr->sh_type))
934 			continue;
935 		if (enp->ec_attrmask &&
936 		    /* LINTED */
937 		    (enp->ec_attrmask & enp->ec_attrbits) !=
938 		    (enp->ec_attrmask & shflags))
939 			continue;
940 		if (enp->ec_is_name &&
941 		    (strcmp(enp->ec_is_name, isp->is_name) != 0))
942 			continue;
943 
944 		if ((alist_nitems(enp->ec_files) > 0) &&
945 		    ((path_info == NULL) || !eval_ec_files(path_info, enp)))
946 			continue;
947 
948 		/* All entrance criteria tests passed */
949 		sgp = enp->ec_segment;
950 		break;
951 	}
952 
953 	/*
954 	 * The final entrance criteria record is a FLG_EC_CATCHALL that points
955 	 * at the final predefined segment "extra", and this final segment is
956 	 * tagged FLG_SG_NODISABLE. Therefore, the above loop must always find
957 	 * a segment.
958 	 */
959 	assert(sgp != NULL);
960 
961 	/*
962 	 * Transfer the input section sorting key from the entrance criteria
963 	 * to the input section. A non-zero value means that the section
964 	 * will be sorted on this key amoung the other sections that have a
965 	 * non-zero key. These sorted sections are collectively placed at the
966 	 * head of the output section.
967 	 *
968 	 * If the sort key is 0, the section is placed after the sorted
969 	 * sections in the order they are encountered.
970 	 */
971 	isp->is_ordndx = enp->ec_ordndx;
972 
973 	/* Remember that this entrance criteria has placed a section */
974 	enp->ec_flags |= FLG_EC_USED;
975 
976 	/*
977 	 * If our caller has supplied an alternative name for the output
978 	 * section, then we defer to their request. Otherwise, the default
979 	 * is to use the same name as that of the input section being placed.
980 	 *
981 	 * The COMDAT, SHT_GROUP and GNU name translations that follow have
982 	 * the potential to alter this initial name.
983 	 */
984 	oname = (char *)((alt_os_name == NULL) ? isp->is_name : alt_os_name);
985 
986 	/*
987 	 * Solaris section names may follow the convention:
988 	 *
989 	 *	section-name%symbol-name
990 	 *
991 	 * This convention has been used to order the layout of sections within
992 	 * segments for objects built with the compilers -xF option.  However,
993 	 * the final object should not contain individual section headers for
994 	 * all such input sections, instead the symbol name is stripped from the
995 	 * name to establish the final output section name.
996 	 *
997 	 * This convention has also been followed for COMDAT and sections
998 	 * identified though SHT_GROUP data.
999 	 *
1000 	 * Strip out the % from the section name for:
1001 	 *	- Non-relocatable objects
1002 	 *	- Relocatable objects if input section sorting is
1003 	 *	  in force for the segment in question.
1004 	 */
1005 	if (((ofl->ofl_flags & FLG_OF_RELOBJ) == 0) ||
1006 	    (sgp->sg_flags & FLG_SG_IS_ORDER)) {
1007 		if ((sname = strchr(isp->is_name, '%')) != NULL) {
1008 			size_t	size = sname - isp->is_name;
1009 
1010 			if ((oname = libld_malloc(size + 1)) == NULL)
1011 				return ((Os_desc *)S_ERROR);
1012 			(void) strncpy(oname, isp->is_name, size);
1013 			oname[size] = '\0';
1014 			DBG_CALL(Dbg_sec_redirected(ofl->ofl_lml, isp, oname));
1015 		}
1016 	}
1017 
1018 	/*
1019 	 * When building relocatable objects, we must not redirect COMDAT
1020 	 * section names into their outputs, such that our output object may
1021 	 * be successfully used as an input object also requiring COMDAT
1022 	 * processing
1023 	 */
1024 
1025 	/*
1026 	 * GNU section names may follow the convention:
1027 	 *
1028 	 *	.gnu.linkonce.*
1029 	 *
1030 	 * The .gnu.linkonce is a section naming convention that indicates a
1031 	 * COMDAT requirement.  Determine whether this section follows the GNU
1032 	 * pattern, and if so, determine whether this section should be
1033 	 * discarded or retained.  The comparison of is_name[1] with 'g'
1034 	 * is an optimization to skip using strncmp() too much. This is safe,
1035 	 * because we know the name is not NULL, and therefore must have
1036 	 * at least one character plus a NULL termination.
1037 	 */
1038 	if ((isp->is_name == oname) && (isp->is_name[1] == 'g') &&
1039 	    (strncmp(MSG_ORIG(MSG_SCN_GNU_LINKONCE), isp->is_name,
1040 	    MSG_SCN_GNU_LINKONCE_SIZE) == 0)) {
1041 		if ((ofl->ofl_flags & FLG_OF_RELOBJ) == 0) {
1042 			if ((oname = (char *)gnu_linkonce_sec(isp->is_name)) !=
1043 			    isp->is_name) {
1044 				DBG_CALL(Dbg_sec_redirected(ofl->ofl_lml, isp,
1045 				    oname));
1046 			}
1047 		}
1048 
1049 		/*
1050 		 * Explicitly identify this section type as COMDAT.  Also,
1051 		 * enable relaxed relocation processing, as this is typically
1052 		 * a requirement with .gnu.linkonce sections.
1053 		 */
1054 		isp->is_flags |= FLG_IS_COMDAT;
1055 		if ((ofl->ofl_flags1 & FLG_OF1_NRLXREL) == 0)
1056 			ofl->ofl_flags1 |= FLG_OF1_RLXREL;
1057 		DBG_CALL(Dbg_sec_gnu_comdat(ofl->ofl_lml, isp, TRUE,
1058 		    (ofl->ofl_flags1 & FLG_OF1_RLXREL) != 0));
1059 	}
1060 
1061 	/*
1062 	 * GNU section names may also follow the convention:
1063 	 *
1064 	 *	section-name.symbol-name
1065 	 *
1066 	 * This convention is used when defining SHT_GROUP sections of type
1067 	 * COMDAT.  Thus, any group processing will have discovered any group
1068 	 * sections, and this identification can be triggered by a pattern
1069 	 * match section names.
1070 	 */
1071 	if ((isp->is_name == oname) && (isp->is_flags & FLG_IS_COMDAT) &&
1072 	    ((sname = gnu_comdat_sym(ifl, isp)) != NULL)) {
1073 		size_t	size = sname - isp->is_name;
1074 
1075 		if ((ofl->ofl_flags & FLG_OF_RELOBJ) == 0) {
1076 			if ((oname = libld_malloc(size + 1)) == NULL)
1077 				return ((Os_desc *)S_ERROR);
1078 			(void) strncpy(oname, isp->is_name, size);
1079 			oname[size] = '\0';
1080 			DBG_CALL(Dbg_sec_redirected(ofl->ofl_lml, isp, oname));
1081 		}
1082 
1083 		/*
1084 		 * Enable relaxed relocation processing, as this is
1085 		 * typically a requirement with GNU COMDAT sections.
1086 		 */
1087 		if ((ofl->ofl_flags1 & FLG_OF1_NRLXREL) == 0) {
1088 			ofl->ofl_flags1 |= FLG_OF1_RLXREL;
1089 			DBG_CALL(Dbg_sec_gnu_comdat(ofl->ofl_lml, isp,
1090 			    FALSE, TRUE));
1091 		}
1092 	}
1093 
1094 	/*
1095 	 * GNU section names named section-name.symbol-name which are not
1096 	 * members of COMDAT groups are merged according to the behaviour of
1097 	 * the GNU link-editor.
1098 	 *
1099 	 * See the description of gnu_split_sec().
1100 	 */
1101 	if (((ofl->ofl_flags & FLG_OF_RELOBJ) == 0) &&
1102 	    (isp->is_name == oname) &&
1103 	    ((oname = (char *)gnu_split_sec(oname)) != isp->is_name)) {
1104 		DBG_CALL(Dbg_sec_redirected(ofl->ofl_lml, isp, oname));
1105 	}
1106 
1107 	/*
1108 	 * Assign a hash value now that the output section name has been
1109 	 * finalized.
1110 	 */
1111 	onamehash = sgs_str_hash(oname);
1112 
1113 	/*
1114 	 * Determine if output section ordering is turned on. If so, return
1115 	 * the appropriate ordering index for the section. This information
1116 	 * is derived from the Sg_desc->sg_os_order list that was built
1117 	 * up from the Mapfile.
1118 	 *
1119 	 * A value of 0 for os_ndx means that the section is not sorted
1120 	 * (i.e. is not found in the sg_os_order). The items in sg_os_order
1121 	 * are in the desired sort order, so adding 1 to their alist index
1122 	 * gives a suitable index for sorting.
1123 	 */
1124 	os_ndx = 0;
1125 	if (alist_nitems(sgp->sg_os_order) > 0) {
1126 		Sec_order	*scop;
1127 
1128 		for (ALIST_TRAVERSE(sgp->sg_os_order, idx1, scop)) {
1129 			if (strcmp(scop->sco_secname, oname) == 0) {
1130 				scop->sco_flags |= FLG_SGO_USED;
1131 				os_ndx = idx1 + 1;
1132 				break;
1133 			}
1134 		}
1135 	}
1136 
1137 	/*
1138 	 * Mask of section header flags to ignore when matching sections. We
1139 	 * are more strict with relocatable objects, ignoring only the order
1140 	 * flags, and keeping sections apart if they differ otherwise. This
1141 	 * follows the policy that sections in a relative object should only
1142 	 * be merged if their flags are the same, and avoids destroying
1143 	 * information prematurely. For final products however, we ignore all
1144 	 * flags that do not prevent a merge.
1145 	 */
1146 	shflagmask =
1147 	    (ofl->ofl_flags & FLG_OF_RELOBJ) ? ALL_SHF_ORDER : ALL_SHF_IGNORE;
1148 
1149 	/*
1150 	 * Traverse the input section list for the output section we have been
1151 	 * assigned. If we find a matching section simply add this new section.
1152 	 */
1153 	iidx = 0;
1154 
1155 	/*
1156 	 * To not become quadratic with respect to the number of output
1157 	 * sections, we want to avoid a scan of the existing output sections
1158 	 * on every section placement.  To effect this, we use a hash table
1159 	 * for sections when the number of sections gets sufficiently large;
1160 	 * if this hash table is present, we check the absence of the other
1161 	 * (uncommon) conditions that necessitate a linear scan, using the
1162 	 * hash chain if we can.
1163 	 */
1164 	if (os_ndx == 0 && (hash = sgp->sg_hashtab) != NULL) {
1165 		APlist *list = sgp->sg_osdescs;
1166 
1167 		osp = list->apl_data[list->apl_nitems - 1];
1168 
1169 		if (ident >= osp->os_identndx) {
1170 			linear_scan = FALSE;
1171 			osp = hash->osh_hashtab[onamehash % hash->osh_size];
1172 		}
1173 	}
1174 
1175 	/*
1176 	 * We now want to iterate over output sections, looking for a match
1177 	 * or an insertion point.  Note that this loop condition is a bit
1178 	 * convoluted because it's encoding two different ways of iterating
1179 	 * over output section descriptors:  if it's a linear scan, we will
1180 	 * iterate over the list elements, and if it's not a linear scan we
1181 	 * will iterate over the hash chain that we discovered above.  (The
1182 	 * only condition that will actually change over the loop is osp; the
1183 	 * mechanics of iterating to the next section depend on linear_scan
1184 	 * and are contained in the body of the loop.)
1185 	 */
1186 	while ((linear_scan && sgp->sg_osdescs != NULL) ||
1187 	    (!linear_scan && osp != NULL)) {
1188 		if (linear_scan) {
1189 			if ((idx1 = iidx) >= sgp->sg_osdescs->apl_nitems)
1190 				break;
1191 
1192 			osp = sgp->sg_osdescs->apl_data[idx1];
1193 		}
1194 
1195 		Shdr	*os_shdr = osp->os_shdr;
1196 
1197 		/*
1198 		 * An input section matches an output section if:
1199 		 * -	The ident values match
1200 		 * -	The names match
1201 		 * -	Not a GROUP section
1202 		 * -	Not a GROUP member, if producing a relocatable object
1203 		 * -	Not a DTrace dof section
1204 		 * -	Section types match
1205 		 * -	Matching section flags, after screening out the
1206 		 *	shflagmask flags.
1207 		 *
1208 		 * Section types are considered to match if any one of
1209 		 * the following are true:
1210 		 * -	The type codes are the same
1211 		 * -	Both are .eh_frame sections (regardless of type code)
1212 		 * -	The input section is COMDAT, and the output section
1213 		 *	is SHT_PROGBITS.
1214 		 */
1215 		if ((ident == osp->os_identndx) &&
1216 		    (ident != ld_targ.t_id.id_rel) &&
1217 		    (onamehash == osp->os_namehash) &&
1218 		    (shdr->sh_type != SHT_GROUP) &&
1219 		    (((shdr->sh_flags & SHF_GROUP) == 0) ||
1220 		    ((ofl->ofl_flags & FLG_OF_RELOBJ) == 0)) &&
1221 		    (shdr->sh_type != SHT_SUNW_dof) &&
1222 		    ((shdr->sh_type == os_shdr->sh_type) ||
1223 		    (is_ehframe && (osp->os_flags & FLG_OS_EHFRAME)) ||
1224 		    ((shdr->sh_type == SHT_SUNW_COMDAT) &&
1225 		    (os_shdr->sh_type == SHT_PROGBITS))) &&
1226 		    ((shflags & ~shflagmask) ==
1227 		    (os_shdr->sh_flags & ~shflagmask)) &&
1228 		    (strcmp(oname, osp->os_name) == 0)) {
1229 			uintptr_t	err;
1230 
1231 			/*
1232 			 * Process any COMDAT section, keeping the first and
1233 			 * discarding all others.
1234 			 */
1235 			if ((isp->is_flags & FLG_IS_COMDAT) &&
1236 			    ((err = add_comdat(ofl, osp, isp)) != 1))
1237 				return ((Os_desc *)err);
1238 
1239 			/*
1240 			 * Set alignment
1241 			 */
1242 			set_addralign(ofl, osp, isp);
1243 
1244 			/*
1245 			 * If this section is a non-empty TLS section indicate
1246 			 * that a PT_TLS program header is required.
1247 			 */
1248 			if ((shflags & SHF_TLS) && shdr->sh_size &&
1249 			    ((ofl->ofl_flags & FLG_OF_RELOBJ) == 0))
1250 				ofl->ofl_flags |= FLG_OF_TLSPHDR;
1251 
1252 			/*
1253 			 * Insert the input section descriptor on the proper
1254 			 * output section descriptor list.
1255 			 *
1256 			 * If this segment requires input section ordering,
1257 			 * honor any mapfile specified ordering for otherwise
1258 			 * unordered sections by setting the mapfile_sort
1259 			 * argument of os_attach_isp() to True.
1260 			 */
1261 
1262 			if (os_attach_isp(ofl, osp, isp,
1263 			    (sgp->sg_flags & FLG_SG_IS_ORDER) != 0) == 0)
1264 				return ((Os_desc *)S_ERROR);
1265 
1266 			/*
1267 			 * If this input section and file is associated to an
1268 			 * artificially referenced output section, make sure
1269 			 * they are marked as referenced also. This ensures
1270 			 * that this input section and file isn't eliminated
1271 			 * when -zignore is in effect.
1272 			 *
1273 			 * See -zignore comments when creating a new output
1274 			 * section below.
1275 			 */
1276 			if (((ifl &&
1277 			    (ifl->ifl_flags & FLG_IF_IGNORE)) || DBG_ENABLED) &&
1278 			    (osp->os_flags & FLG_OS_SECTREF)) {
1279 				isp->is_flags |= FLG_IS_SECTREF;
1280 				if (ifl)
1281 					ifl->ifl_flags |= FLG_IF_FILEREF;
1282 			}
1283 
1284 			DBG_CALL(Dbg_sec_added(ofl->ofl_lml, osp, sgp));
1285 			return (osp);
1286 		}
1287 
1288 		if (!linear_scan) {
1289 			osp = osp->os_hashnext;
1290 			continue;
1291 		}
1292 
1293 		/*
1294 		 * Do we need to worry about section ordering?
1295 		 */
1296 		if (os_ndx) {
1297 			if (osp->os_ordndx) {
1298 				if (os_ndx < osp->os_ordndx)
1299 					/* insert section here. */
1300 					break;
1301 				else {
1302 					iidx = idx1 + 1;
1303 					continue;
1304 				}
1305 			} else {
1306 				/* insert section here. */
1307 				break;
1308 			}
1309 		} else if (osp->os_ordndx) {
1310 			iidx = idx1 + 1;
1311 			continue;
1312 		}
1313 
1314 		/*
1315 		 * If the new sections identifier is less than that of the
1316 		 * present input section we need to insert the new section
1317 		 * at this point.
1318 		 */
1319 		if (ident < osp->os_identndx)
1320 			break;
1321 
1322 		iidx = idx1 + 1;
1323 	}
1324 
1325 	if (!linear_scan) {
1326 		iidx = sgp->sg_osdescs->apl_nitems;
1327 	}
1328 
1329 	/*
1330 	 * We are adding a new output section.  Update the section header
1331 	 * count and associated string size.
1332 	 *
1333 	 * If the input section triggering this output section has been marked
1334 	 * for discard, and if no other non-discarded input section comes along
1335 	 * to join it, then we will over count. We cannot know if this will
1336 	 * happen or not until all input is seen. Set FLG_OF_AJDOSCNT to
1337 	 * trigger a final count readjustment.
1338 	 */
1339 	if (isp->is_flags & FLG_IS_DISCARD)
1340 		ofl->ofl_flags |= FLG_OF_ADJOSCNT;
1341 	ofl->ofl_shdrcnt++;
1342 	if (st_insert(ofl->ofl_shdrsttab, oname) == -1)
1343 		return ((Os_desc *)S_ERROR);
1344 
1345 	/*
1346 	 * Create a new output section descriptor.
1347 	 */
1348 	if ((osp = libld_calloc(1, sizeof (Os_desc))) == NULL)
1349 		return ((Os_desc *)S_ERROR);
1350 	if ((osp->os_shdr = libld_calloc(1, sizeof (Shdr))) == NULL)
1351 		return ((Os_desc *)S_ERROR);
1352 
1353 	/*
1354 	 * Convert COMDAT section to PROGBITS as this the first section of the
1355 	 * output section.  Save any COMDAT section for later processing, as
1356 	 * additional COMDAT sections that match this section need discarding.
1357 	 */
1358 	if ((shdr->sh_type == SHT_SUNW_COMDAT) &&
1359 	    ((shdr = isp_convert_type(isp, SHT_PROGBITS)) == NULL))
1360 		return ((Os_desc *)S_ERROR);
1361 	if ((isp->is_flags & FLG_IS_COMDAT) &&
1362 	    (add_comdat(ofl, osp, isp) == S_ERROR))
1363 		return ((Os_desc *)S_ERROR);
1364 
1365 	if (is_ehframe) {
1366 		/*
1367 		 * Executable or sharable objects can have at most a single
1368 		 * .eh_frame section. Detect attempts to create more than
1369 		 * one. This occurs if the input sections have incompatible
1370 		 * attributes.
1371 		 */
1372 		if ((ofl->ofl_flags & FLG_OF_EHFRAME) &&
1373 		    !(ofl->ofl_flags & FLG_OF_RELOBJ)) {
1374 			eh_frame_muldef(ofl, isp);
1375 			return ((Os_desc *)S_ERROR);
1376 		}
1377 		ofl->ofl_flags |= FLG_OF_EHFRAME;
1378 
1379 		/*
1380 		 * For .eh_frame sections, we always set the type to be the
1381 		 * type specified by the ABI.  This allows .eh_frame sections
1382 		 * of type SHT_PROGBITS to be correctly merged with .eh_frame
1383 		 * sections of the ABI-defined type (e.g. SHT_AMD64_UNWIND),
1384 		 * with the output being of the ABI-defined type.
1385 		 */
1386 		osp->os_shdr->sh_type = ld_targ.t_m.m_sht_unwind;
1387 	} else {
1388 		osp->os_shdr->sh_type = shdr->sh_type;
1389 	}
1390 
1391 	osp->os_shdr->sh_flags = shdr->sh_flags;
1392 	osp->os_shdr->sh_entsize = shdr->sh_entsize;
1393 	osp->os_name = oname;
1394 	osp->os_namehash = onamehash;
1395 	osp->os_ordndx = os_ndx;
1396 	osp->os_sgdesc = sgp;
1397 	if (is_ehframe)
1398 		osp->os_flags |= FLG_OS_EHFRAME;
1399 
1400 	if (ifl && (shdr->sh_type == SHT_PROGBITS)) {
1401 		/*
1402 		 * Try to preserve the intended meaning of sh_link/sh_info.
1403 		 * See the translate_link() in update.c.
1404 		 */
1405 		osp->os_shdr->sh_link = shdr->sh_link;
1406 		if (shdr->sh_flags & SHF_INFO_LINK)
1407 			osp->os_shdr->sh_info = shdr->sh_info;
1408 	}
1409 
1410 	/*
1411 	 * When -zignore is in effect, user supplied sections and files that are
1412 	 * not referenced from other sections, are eliminated from the object
1413 	 * being produced.  Some sections, although unreferenced, are special,
1414 	 * and must not be eliminated.  Determine if this new output section is
1415 	 * one of those special sections, and if so mark it artificially as
1416 	 * referenced.  Any input section and file associated to this output
1417 	 * section is also be marked as referenced, and thus won't be eliminated
1418 	 * from the final output.
1419 	 */
1420 	if (ifl && ((ofl->ofl_flags1 & FLG_OF1_IGNPRC) || DBG_ENABLED)) {
1421 		const Msg	*refsec;
1422 
1423 		for (refsec = RefSecs; *refsec; refsec++) {
1424 			if (strcmp(osp->os_name, MSG_ORIG(*refsec)) == 0) {
1425 				osp->os_flags |= FLG_OS_SECTREF;
1426 
1427 				if ((ifl->ifl_flags & FLG_IF_IGNORE) ||
1428 				    DBG_ENABLED) {
1429 					isp->is_flags |= FLG_IS_SECTREF;
1430 					ifl->ifl_flags |= FLG_IF_FILEREF;
1431 				}
1432 				break;
1433 			}
1434 		}
1435 	}
1436 
1437 	/*
1438 	 * Sections of type SHT_GROUP are added to the ofl->ofl_osgroups list,
1439 	 * so that they can be updated as a group later.
1440 	 */
1441 	if ((shdr->sh_type == SHT_GROUP) &&
1442 	    ((isp->is_flags & FLG_IS_DISCARD) == 0) &&
1443 	    (aplist_append(&ofl->ofl_osgroups, osp,
1444 	    AL_CNT_OFL_OSGROUPS) == NULL))
1445 		return ((Os_desc *)S_ERROR);
1446 
1447 	/*
1448 	 * If this section is a non-empty TLS section indicate that a PT_TLS
1449 	 * program header is required.
1450 	 */
1451 	if ((shflags & SHF_TLS) && shdr->sh_size &&
1452 	    ((ofl->ofl_flags & FLG_OF_RELOBJ) == 0))
1453 		ofl->ofl_flags |= FLG_OF_TLSPHDR;
1454 
1455 	/*
1456 	 * If a non-allocatable section is going to be put into a loadable
1457 	 * segment then turn on the allocate bit for this section and warn the
1458 	 * user that we have done so.  This could only happen through the use
1459 	 * of a mapfile.
1460 	 */
1461 	if ((sgp->sg_phdr.p_type == PT_LOAD) &&
1462 	    ((osp->os_shdr->sh_flags & SHF_ALLOC) == 0)) {
1463 		ld_eprintf(ofl, ERR_WARNING, MSG_INTL(MSG_SCN_NONALLOC),
1464 		    ofl->ofl_name, osp->os_name, sgp->sg_name);
1465 		osp->os_shdr->sh_flags |= SHF_ALLOC;
1466 	}
1467 
1468 	/*
1469 	 * Retain this sections identifier for future comparisons when placing
1470 	 * a section (after all sections have been processed this variable will
1471 	 * be used to hold the sections symbol index as we don't need to retain
1472 	 * the identifier any more).
1473 	 */
1474 	osp->os_identndx = ident;
1475 
1476 	/*
1477 	 * Set alignment.
1478 	 */
1479 	set_addralign(ofl, osp, isp);
1480 
1481 	if (os_attach_isp(ofl, osp, isp, 0) == 0)
1482 		return ((Os_desc *)S_ERROR);
1483 
1484 	DBG_CALL(Dbg_sec_created(ofl->ofl_lml, osp, sgp));
1485 
1486 	/*
1487 	 * Insert the new section at the offset given by iidx.  If no position
1488 	 * for it was identified above, this will be index 0, causing the new
1489 	 * section to be prepended to the beginning of the section list.
1490 	 * Otherwise, it is the index following the section that was identified.
1491 	 */
1492 	if (aplist_insert(&sgp->sg_osdescs, osp, AL_CNT_SG_OSDESC,
1493 	    iidx) == NULL)
1494 		return ((Os_desc *)S_ERROR);
1495 
1496 	os_desc_hash(sgp, osp);
1497 
1498 	return (osp);
1499 }
1500