xref: /dragonfly/contrib/binutils-2.27/bfd/elf.c (revision a3127495)
1 /* ELF executable support for BFD.
2 
3    Copyright (C) 1993-2016 Free Software Foundation, Inc.
4 
5    This file is part of BFD, the Binary File Descriptor library.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20    MA 02110-1301, USA.  */
21 
22 
23 /*
24 SECTION
25 	ELF backends
26 
27 	BFD support for ELF formats is being worked on.
28 	Currently, the best supported back ends are for sparc and i386
29 	(running svr4 or Solaris 2).
30 
31 	Documentation of the internals of the support code still needs
32 	to be written.  The code is changing quickly enough that we
33 	haven't bothered yet.  */
34 
35 /* For sparc64-cross-sparc32.  */
36 #define _SYSCALL32
37 #include "sysdep.h"
38 #include "bfd.h"
39 #include "bfdlink.h"
40 #include "libbfd.h"
41 #define ARCH_SIZE 0
42 #include "elf-bfd.h"
43 #include "libiberty.h"
44 #include "safe-ctype.h"
45 #include "elf-linux-core.h"
46 
47 #ifdef CORE_HEADER
48 #include CORE_HEADER
49 #endif
50 
51 static int elf_sort_sections (const void *, const void *);
52 static bfd_boolean assign_file_positions_except_relocs (bfd *, struct bfd_link_info *);
53 static bfd_boolean prep_headers (bfd *);
54 static bfd_boolean swap_out_syms (bfd *, struct elf_strtab_hash **, int) ;
55 static bfd_boolean elf_read_notes (bfd *, file_ptr, bfd_size_type) ;
56 static bfd_boolean elf_parse_notes (bfd *abfd, char *buf, size_t size,
57 				    file_ptr offset);
58 
59 /* Swap version information in and out.  The version information is
60    currently size independent.  If that ever changes, this code will
61    need to move into elfcode.h.  */
62 
63 /* Swap in a Verdef structure.  */
64 
65 void
66 _bfd_elf_swap_verdef_in (bfd *abfd,
67 			 const Elf_External_Verdef *src,
68 			 Elf_Internal_Verdef *dst)
69 {
70   dst->vd_version = H_GET_16 (abfd, src->vd_version);
71   dst->vd_flags   = H_GET_16 (abfd, src->vd_flags);
72   dst->vd_ndx     = H_GET_16 (abfd, src->vd_ndx);
73   dst->vd_cnt     = H_GET_16 (abfd, src->vd_cnt);
74   dst->vd_hash    = H_GET_32 (abfd, src->vd_hash);
75   dst->vd_aux     = H_GET_32 (abfd, src->vd_aux);
76   dst->vd_next    = H_GET_32 (abfd, src->vd_next);
77 }
78 
79 /* Swap out a Verdef structure.  */
80 
81 void
82 _bfd_elf_swap_verdef_out (bfd *abfd,
83 			  const Elf_Internal_Verdef *src,
84 			  Elf_External_Verdef *dst)
85 {
86   H_PUT_16 (abfd, src->vd_version, dst->vd_version);
87   H_PUT_16 (abfd, src->vd_flags, dst->vd_flags);
88   H_PUT_16 (abfd, src->vd_ndx, dst->vd_ndx);
89   H_PUT_16 (abfd, src->vd_cnt, dst->vd_cnt);
90   H_PUT_32 (abfd, src->vd_hash, dst->vd_hash);
91   H_PUT_32 (abfd, src->vd_aux, dst->vd_aux);
92   H_PUT_32 (abfd, src->vd_next, dst->vd_next);
93 }
94 
95 /* Swap in a Verdaux structure.  */
96 
97 void
98 _bfd_elf_swap_verdaux_in (bfd *abfd,
99 			  const Elf_External_Verdaux *src,
100 			  Elf_Internal_Verdaux *dst)
101 {
102   dst->vda_name = H_GET_32 (abfd, src->vda_name);
103   dst->vda_next = H_GET_32 (abfd, src->vda_next);
104 }
105 
106 /* Swap out a Verdaux structure.  */
107 
108 void
109 _bfd_elf_swap_verdaux_out (bfd *abfd,
110 			   const Elf_Internal_Verdaux *src,
111 			   Elf_External_Verdaux *dst)
112 {
113   H_PUT_32 (abfd, src->vda_name, dst->vda_name);
114   H_PUT_32 (abfd, src->vda_next, dst->vda_next);
115 }
116 
117 /* Swap in a Verneed structure.  */
118 
119 void
120 _bfd_elf_swap_verneed_in (bfd *abfd,
121 			  const Elf_External_Verneed *src,
122 			  Elf_Internal_Verneed *dst)
123 {
124   dst->vn_version = H_GET_16 (abfd, src->vn_version);
125   dst->vn_cnt     = H_GET_16 (abfd, src->vn_cnt);
126   dst->vn_file    = H_GET_32 (abfd, src->vn_file);
127   dst->vn_aux     = H_GET_32 (abfd, src->vn_aux);
128   dst->vn_next    = H_GET_32 (abfd, src->vn_next);
129 }
130 
131 /* Swap out a Verneed structure.  */
132 
133 void
134 _bfd_elf_swap_verneed_out (bfd *abfd,
135 			   const Elf_Internal_Verneed *src,
136 			   Elf_External_Verneed *dst)
137 {
138   H_PUT_16 (abfd, src->vn_version, dst->vn_version);
139   H_PUT_16 (abfd, src->vn_cnt, dst->vn_cnt);
140   H_PUT_32 (abfd, src->vn_file, dst->vn_file);
141   H_PUT_32 (abfd, src->vn_aux, dst->vn_aux);
142   H_PUT_32 (abfd, src->vn_next, dst->vn_next);
143 }
144 
145 /* Swap in a Vernaux structure.  */
146 
147 void
148 _bfd_elf_swap_vernaux_in (bfd *abfd,
149 			  const Elf_External_Vernaux *src,
150 			  Elf_Internal_Vernaux *dst)
151 {
152   dst->vna_hash  = H_GET_32 (abfd, src->vna_hash);
153   dst->vna_flags = H_GET_16 (abfd, src->vna_flags);
154   dst->vna_other = H_GET_16 (abfd, src->vna_other);
155   dst->vna_name  = H_GET_32 (abfd, src->vna_name);
156   dst->vna_next  = H_GET_32 (abfd, src->vna_next);
157 }
158 
159 /* Swap out a Vernaux structure.  */
160 
161 void
162 _bfd_elf_swap_vernaux_out (bfd *abfd,
163 			   const Elf_Internal_Vernaux *src,
164 			   Elf_External_Vernaux *dst)
165 {
166   H_PUT_32 (abfd, src->vna_hash, dst->vna_hash);
167   H_PUT_16 (abfd, src->vna_flags, dst->vna_flags);
168   H_PUT_16 (abfd, src->vna_other, dst->vna_other);
169   H_PUT_32 (abfd, src->vna_name, dst->vna_name);
170   H_PUT_32 (abfd, src->vna_next, dst->vna_next);
171 }
172 
173 /* Swap in a Versym structure.  */
174 
175 void
176 _bfd_elf_swap_versym_in (bfd *abfd,
177 			 const Elf_External_Versym *src,
178 			 Elf_Internal_Versym *dst)
179 {
180   dst->vs_vers = H_GET_16 (abfd, src->vs_vers);
181 }
182 
183 /* Swap out a Versym structure.  */
184 
185 void
186 _bfd_elf_swap_versym_out (bfd *abfd,
187 			  const Elf_Internal_Versym *src,
188 			  Elf_External_Versym *dst)
189 {
190   H_PUT_16 (abfd, src->vs_vers, dst->vs_vers);
191 }
192 
193 /* Standard ELF hash function.  Do not change this function; you will
194    cause invalid hash tables to be generated.  */
195 
196 unsigned long
197 bfd_elf_hash (const char *namearg)
198 {
199   const unsigned char *name = (const unsigned char *) namearg;
200   unsigned long h = 0;
201   unsigned long g;
202   int ch;
203 
204   while ((ch = *name++) != '\0')
205     {
206       h = (h << 4) + ch;
207       if ((g = (h & 0xf0000000)) != 0)
208 	{
209 	  h ^= g >> 24;
210 	  /* The ELF ABI says `h &= ~g', but this is equivalent in
211 	     this case and on some machines one insn instead of two.  */
212 	  h ^= g;
213 	}
214     }
215   return h & 0xffffffff;
216 }
217 
218 /* DT_GNU_HASH hash function.  Do not change this function; you will
219    cause invalid hash tables to be generated.  */
220 
221 unsigned long
222 bfd_elf_gnu_hash (const char *namearg)
223 {
224   const unsigned char *name = (const unsigned char *) namearg;
225   unsigned long h = 5381;
226   unsigned char ch;
227 
228   while ((ch = *name++) != '\0')
229     h = (h << 5) + h + ch;
230   return h & 0xffffffff;
231 }
232 
233 /* Create a tdata field OBJECT_SIZE bytes in length, zeroed out and with
234    the object_id field of an elf_obj_tdata field set to OBJECT_ID.  */
235 bfd_boolean
236 bfd_elf_allocate_object (bfd *abfd,
237 			 size_t object_size,
238 			 enum elf_target_id object_id)
239 {
240   BFD_ASSERT (object_size >= sizeof (struct elf_obj_tdata));
241   abfd->tdata.any = bfd_zalloc (abfd, object_size);
242   if (abfd->tdata.any == NULL)
243     return FALSE;
244 
245   elf_object_id (abfd) = object_id;
246   if (abfd->direction != read_direction)
247     {
248       struct output_elf_obj_tdata *o = bfd_zalloc (abfd, sizeof *o);
249       if (o == NULL)
250 	return FALSE;
251       elf_tdata (abfd)->o = o;
252       elf_program_header_size (abfd) = (bfd_size_type) -1;
253     }
254   return TRUE;
255 }
256 
257 
258 bfd_boolean
259 bfd_elf_make_object (bfd *abfd)
260 {
261   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
262   return bfd_elf_allocate_object (abfd, sizeof (struct elf_obj_tdata),
263 				  bed->target_id);
264 }
265 
266 bfd_boolean
267 bfd_elf_mkcorefile (bfd *abfd)
268 {
269   /* I think this can be done just like an object file.  */
270   if (!abfd->xvec->_bfd_set_format[(int) bfd_object] (abfd))
271     return FALSE;
272   elf_tdata (abfd)->core = bfd_zalloc (abfd, sizeof (*elf_tdata (abfd)->core));
273   return elf_tdata (abfd)->core != NULL;
274 }
275 
276 static char *
277 bfd_elf_get_str_section (bfd *abfd, unsigned int shindex)
278 {
279   Elf_Internal_Shdr **i_shdrp;
280   bfd_byte *shstrtab = NULL;
281   file_ptr offset;
282   bfd_size_type shstrtabsize;
283 
284   i_shdrp = elf_elfsections (abfd);
285   if (i_shdrp == 0
286       || shindex >= elf_numsections (abfd)
287       || i_shdrp[shindex] == 0)
288     return NULL;
289 
290   shstrtab = i_shdrp[shindex]->contents;
291   if (shstrtab == NULL)
292     {
293       /* No cached one, attempt to read, and cache what we read.  */
294       offset = i_shdrp[shindex]->sh_offset;
295       shstrtabsize = i_shdrp[shindex]->sh_size;
296 
297       /* Allocate and clear an extra byte at the end, to prevent crashes
298 	 in case the string table is not terminated.  */
299       if (shstrtabsize + 1 <= 1
300 	  || bfd_seek (abfd, offset, SEEK_SET) != 0
301 	  || (shstrtab = (bfd_byte *) bfd_alloc (abfd, shstrtabsize + 1)) == NULL)
302 	shstrtab = NULL;
303       else if (bfd_bread (shstrtab, shstrtabsize, abfd) != shstrtabsize)
304 	{
305 	  if (bfd_get_error () != bfd_error_system_call)
306 	    bfd_set_error (bfd_error_file_truncated);
307 	  bfd_release (abfd, shstrtab);
308 	  shstrtab = NULL;
309 	  /* Once we've failed to read it, make sure we don't keep
310 	     trying.  Otherwise, we'll keep allocating space for
311 	     the string table over and over.  */
312 	  i_shdrp[shindex]->sh_size = 0;
313 	}
314       else
315 	shstrtab[shstrtabsize] = '\0';
316       i_shdrp[shindex]->contents = shstrtab;
317     }
318   return (char *) shstrtab;
319 }
320 
321 char *
322 bfd_elf_string_from_elf_section (bfd *abfd,
323 				 unsigned int shindex,
324 				 unsigned int strindex)
325 {
326   Elf_Internal_Shdr *hdr;
327 
328   if (strindex == 0)
329     return "";
330 
331   if (elf_elfsections (abfd) == NULL || shindex >= elf_numsections (abfd))
332     return NULL;
333 
334   hdr = elf_elfsections (abfd)[shindex];
335 
336   if (hdr->contents == NULL)
337     {
338       if (hdr->sh_type != SHT_STRTAB && hdr->sh_type < SHT_LOOS)
339 	{
340 	  /* PR 17512: file: f057ec89.  */
341 	  _bfd_error_handler (_("%B: attempt to load strings from a non-string section (number %d)"),
342 			      abfd, shindex);
343 	  return NULL;
344 	}
345 
346       if (bfd_elf_get_str_section (abfd, shindex) == NULL)
347 	return NULL;
348     }
349 
350   if (strindex >= hdr->sh_size)
351     {
352       unsigned int shstrndx = elf_elfheader(abfd)->e_shstrndx;
353       (*_bfd_error_handler)
354 	(_("%B: invalid string offset %u >= %lu for section `%s'"),
355 	 abfd, strindex, (unsigned long) hdr->sh_size,
356 	 (shindex == shstrndx && strindex == hdr->sh_name
357 	  ? ".shstrtab"
358 	  : bfd_elf_string_from_elf_section (abfd, shstrndx, hdr->sh_name)));
359       return NULL;
360     }
361 
362   return ((char *) hdr->contents) + strindex;
363 }
364 
365 /* Read and convert symbols to internal format.
366    SYMCOUNT specifies the number of symbols to read, starting from
367    symbol SYMOFFSET.  If any of INTSYM_BUF, EXTSYM_BUF or EXTSHNDX_BUF
368    are non-NULL, they are used to store the internal symbols, external
369    symbols, and symbol section index extensions, respectively.
370    Returns a pointer to the internal symbol buffer (malloced if necessary)
371    or NULL if there were no symbols or some kind of problem.  */
372 
373 Elf_Internal_Sym *
374 bfd_elf_get_elf_syms (bfd *ibfd,
375 		      Elf_Internal_Shdr *symtab_hdr,
376 		      size_t symcount,
377 		      size_t symoffset,
378 		      Elf_Internal_Sym *intsym_buf,
379 		      void *extsym_buf,
380 		      Elf_External_Sym_Shndx *extshndx_buf)
381 {
382   Elf_Internal_Shdr *shndx_hdr;
383   void *alloc_ext;
384   const bfd_byte *esym;
385   Elf_External_Sym_Shndx *alloc_extshndx;
386   Elf_External_Sym_Shndx *shndx;
387   Elf_Internal_Sym *alloc_intsym;
388   Elf_Internal_Sym *isym;
389   Elf_Internal_Sym *isymend;
390   const struct elf_backend_data *bed;
391   size_t extsym_size;
392   bfd_size_type amt;
393   file_ptr pos;
394 
395   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
396     abort ();
397 
398   if (symcount == 0)
399     return intsym_buf;
400 
401   /* Normal syms might have section extension entries.  */
402   shndx_hdr = NULL;
403   if (elf_symtab_shndx_list (ibfd) != NULL)
404     {
405       elf_section_list * entry;
406       Elf_Internal_Shdr **sections = elf_elfsections (ibfd);
407 
408       /* Find an index section that is linked to this symtab section.  */
409       for (entry = elf_symtab_shndx_list (ibfd); entry != NULL; entry = entry->next)
410 	{
411 	  /* PR 20063.  */
412 	  if (entry->hdr.sh_link >= elf_numsections (ibfd))
413 	    continue;
414 
415 	  if (sections[entry->hdr.sh_link] == symtab_hdr)
416 	    {
417 	      shndx_hdr = & entry->hdr;
418 	      break;
419 	    };
420 	}
421 
422       if (shndx_hdr == NULL)
423 	{
424 	  if (symtab_hdr == & elf_symtab_hdr (ibfd))
425 	    /* Not really accurate, but this was how the old code used to work.  */
426 	    shndx_hdr = & elf_symtab_shndx_list (ibfd)->hdr;
427 	  /* Otherwise we do nothing.  The assumption is that
428 	     the index table will not be needed.  */
429 	}
430     }
431 
432   /* Read the symbols.  */
433   alloc_ext = NULL;
434   alloc_extshndx = NULL;
435   alloc_intsym = NULL;
436   bed = get_elf_backend_data (ibfd);
437   extsym_size = bed->s->sizeof_sym;
438   amt = (bfd_size_type) symcount * extsym_size;
439   pos = symtab_hdr->sh_offset + symoffset * extsym_size;
440   if (extsym_buf == NULL)
441     {
442       alloc_ext = bfd_malloc2 (symcount, extsym_size);
443       extsym_buf = alloc_ext;
444     }
445   if (extsym_buf == NULL
446       || bfd_seek (ibfd, pos, SEEK_SET) != 0
447       || bfd_bread (extsym_buf, amt, ibfd) != amt)
448     {
449       intsym_buf = NULL;
450       goto out;
451     }
452 
453   if (shndx_hdr == NULL || shndx_hdr->sh_size == 0)
454     extshndx_buf = NULL;
455   else
456     {
457       amt = (bfd_size_type) symcount * sizeof (Elf_External_Sym_Shndx);
458       pos = shndx_hdr->sh_offset + symoffset * sizeof (Elf_External_Sym_Shndx);
459       if (extshndx_buf == NULL)
460 	{
461 	  alloc_extshndx = (Elf_External_Sym_Shndx *)
462               bfd_malloc2 (symcount, sizeof (Elf_External_Sym_Shndx));
463 	  extshndx_buf = alloc_extshndx;
464 	}
465       if (extshndx_buf == NULL
466 	  || bfd_seek (ibfd, pos, SEEK_SET) != 0
467 	  || bfd_bread (extshndx_buf, amt, ibfd) != amt)
468 	{
469 	  intsym_buf = NULL;
470 	  goto out;
471 	}
472     }
473 
474   if (intsym_buf == NULL)
475     {
476       alloc_intsym = (Elf_Internal_Sym *)
477           bfd_malloc2 (symcount, sizeof (Elf_Internal_Sym));
478       intsym_buf = alloc_intsym;
479       if (intsym_buf == NULL)
480 	goto out;
481     }
482 
483   /* Convert the symbols to internal form.  */
484   isymend = intsym_buf + symcount;
485   for (esym = (const bfd_byte *) extsym_buf, isym = intsym_buf,
486            shndx = extshndx_buf;
487        isym < isymend;
488        esym += extsym_size, isym++, shndx = shndx != NULL ? shndx + 1 : NULL)
489     if (!(*bed->s->swap_symbol_in) (ibfd, esym, shndx, isym))
490       {
491 	symoffset += (esym - (bfd_byte *) extsym_buf) / extsym_size;
492 	(*_bfd_error_handler) (_("%B symbol number %lu references "
493 				 "nonexistent SHT_SYMTAB_SHNDX section"),
494 			       ibfd, (unsigned long) symoffset);
495 	if (alloc_intsym != NULL)
496 	  free (alloc_intsym);
497 	intsym_buf = NULL;
498 	goto out;
499       }
500 
501  out:
502   if (alloc_ext != NULL)
503     free (alloc_ext);
504   if (alloc_extshndx != NULL)
505     free (alloc_extshndx);
506 
507   return intsym_buf;
508 }
509 
510 /* Look up a symbol name.  */
511 const char *
512 bfd_elf_sym_name (bfd *abfd,
513 		  Elf_Internal_Shdr *symtab_hdr,
514 		  Elf_Internal_Sym *isym,
515 		  asection *sym_sec)
516 {
517   const char *name;
518   unsigned int iname = isym->st_name;
519   unsigned int shindex = symtab_hdr->sh_link;
520 
521   if (iname == 0 && ELF_ST_TYPE (isym->st_info) == STT_SECTION
522       /* Check for a bogus st_shndx to avoid crashing.  */
523       && isym->st_shndx < elf_numsections (abfd))
524     {
525       iname = elf_elfsections (abfd)[isym->st_shndx]->sh_name;
526       shindex = elf_elfheader (abfd)->e_shstrndx;
527     }
528 
529   name = bfd_elf_string_from_elf_section (abfd, shindex, iname);
530   if (name == NULL)
531     name = "(null)";
532   else if (sym_sec && *name == '\0')
533     name = bfd_section_name (abfd, sym_sec);
534 
535   return name;
536 }
537 
538 /* Elf_Internal_Shdr->contents is an array of these for SHT_GROUP
539    sections.  The first element is the flags, the rest are section
540    pointers.  */
541 
542 typedef union elf_internal_group {
543   Elf_Internal_Shdr *shdr;
544   unsigned int flags;
545 } Elf_Internal_Group;
546 
547 /* Return the name of the group signature symbol.  Why isn't the
548    signature just a string?  */
549 
550 static const char *
551 group_signature (bfd *abfd, Elf_Internal_Shdr *ghdr)
552 {
553   Elf_Internal_Shdr *hdr;
554   unsigned char esym[sizeof (Elf64_External_Sym)];
555   Elf_External_Sym_Shndx eshndx;
556   Elf_Internal_Sym isym;
557 
558   /* First we need to ensure the symbol table is available.  Make sure
559      that it is a symbol table section.  */
560   if (ghdr->sh_link >= elf_numsections (abfd))
561     return NULL;
562   hdr = elf_elfsections (abfd) [ghdr->sh_link];
563   if (hdr->sh_type != SHT_SYMTAB
564       || ! bfd_section_from_shdr (abfd, ghdr->sh_link))
565     return NULL;
566 
567   /* Go read the symbol.  */
568   hdr = &elf_tdata (abfd)->symtab_hdr;
569   if (bfd_elf_get_elf_syms (abfd, hdr, 1, ghdr->sh_info,
570 			    &isym, esym, &eshndx) == NULL)
571     return NULL;
572 
573   return bfd_elf_sym_name (abfd, hdr, &isym, NULL);
574 }
575 
576 /* Set next_in_group list pointer, and group name for NEWSECT.  */
577 
578 static bfd_boolean
579 setup_group (bfd *abfd, Elf_Internal_Shdr *hdr, asection *newsect)
580 {
581   unsigned int num_group = elf_tdata (abfd)->num_group;
582 
583   /* If num_group is zero, read in all SHT_GROUP sections.  The count
584      is set to -1 if there are no SHT_GROUP sections.  */
585   if (num_group == 0)
586     {
587       unsigned int i, shnum;
588 
589       /* First count the number of groups.  If we have a SHT_GROUP
590 	 section with just a flag word (ie. sh_size is 4), ignore it.  */
591       shnum = elf_numsections (abfd);
592       num_group = 0;
593 
594 #define IS_VALID_GROUP_SECTION_HEADER(shdr, minsize)	\
595 	(   (shdr)->sh_type == SHT_GROUP		\
596 	 && (shdr)->sh_size >= minsize			\
597 	 && (shdr)->sh_entsize == GRP_ENTRY_SIZE	\
598 	 && ((shdr)->sh_size % GRP_ENTRY_SIZE) == 0)
599 
600       for (i = 0; i < shnum; i++)
601 	{
602 	  Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
603 
604 	  if (IS_VALID_GROUP_SECTION_HEADER (shdr, 2 * GRP_ENTRY_SIZE))
605 	    num_group += 1;
606 	}
607 
608       if (num_group == 0)
609 	{
610 	  num_group = (unsigned) -1;
611 	  elf_tdata (abfd)->num_group = num_group;
612 	}
613       else
614 	{
615 	  /* We keep a list of elf section headers for group sections,
616 	     so we can find them quickly.  */
617 	  bfd_size_type amt;
618 
619 	  elf_tdata (abfd)->num_group = num_group;
620 	  elf_tdata (abfd)->group_sect_ptr = (Elf_Internal_Shdr **)
621               bfd_alloc2 (abfd, num_group, sizeof (Elf_Internal_Shdr *));
622 	  if (elf_tdata (abfd)->group_sect_ptr == NULL)
623 	    return FALSE;
624 
625 	  num_group = 0;
626 	  for (i = 0; i < shnum; i++)
627 	    {
628 	      Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
629 
630 	      if (IS_VALID_GROUP_SECTION_HEADER (shdr, 2 * GRP_ENTRY_SIZE))
631 		{
632 		  unsigned char *src;
633 		  Elf_Internal_Group *dest;
634 
635 		  /* Add to list of sections.  */
636 		  elf_tdata (abfd)->group_sect_ptr[num_group] = shdr;
637 		  num_group += 1;
638 
639 		  /* Read the raw contents.  */
640 		  BFD_ASSERT (sizeof (*dest) >= 4);
641 		  amt = shdr->sh_size * sizeof (*dest) / 4;
642 		  shdr->contents = (unsigned char *)
643                       bfd_alloc2 (abfd, shdr->sh_size, sizeof (*dest) / 4);
644 		  /* PR binutils/4110: Handle corrupt group headers.  */
645 		  if (shdr->contents == NULL)
646 		    {
647 		      _bfd_error_handler
648 			(_("%B: corrupt size field in group section header: 0x%lx"), abfd, shdr->sh_size);
649 		      bfd_set_error (bfd_error_bad_value);
650 		      -- num_group;
651 		      continue;
652 		    }
653 
654 		  memset (shdr->contents, 0, amt);
655 
656 		  if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0
657 		      || (bfd_bread (shdr->contents, shdr->sh_size, abfd)
658 			  != shdr->sh_size))
659 		    {
660 		      _bfd_error_handler
661 			(_("%B: invalid size field in group section header: 0x%lx"), abfd, shdr->sh_size);
662 		      bfd_set_error (bfd_error_bad_value);
663 		      -- num_group;
664 		      /* PR 17510: If the group contents are even partially
665 			 corrupt, do not allow any of the contents to be used.  */
666 		      memset (shdr->contents, 0, amt);
667 		      continue;
668 		    }
669 
670 		  /* Translate raw contents, a flag word followed by an
671 		     array of elf section indices all in target byte order,
672 		     to the flag word followed by an array of elf section
673 		     pointers.  */
674 		  src = shdr->contents + shdr->sh_size;
675 		  dest = (Elf_Internal_Group *) (shdr->contents + amt);
676 
677 		  while (1)
678 		    {
679 		      unsigned int idx;
680 
681 		      src -= 4;
682 		      --dest;
683 		      idx = H_GET_32 (abfd, src);
684 		      if (src == shdr->contents)
685 			{
686 			  dest->flags = idx;
687 			  if (shdr->bfd_section != NULL && (idx & GRP_COMDAT))
688 			    shdr->bfd_section->flags
689 			      |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
690 			  break;
691 			}
692 		      if (idx >= shnum)
693 			{
694 			  ((*_bfd_error_handler)
695 			   (_("%B: invalid SHT_GROUP entry"), abfd));
696 			  idx = 0;
697 			}
698 		      dest->shdr = elf_elfsections (abfd)[idx];
699 		    }
700 		}
701 	    }
702 
703 	  /* PR 17510: Corrupt binaries might contain invalid groups.  */
704 	  if (num_group != (unsigned) elf_tdata (abfd)->num_group)
705 	    {
706 	      elf_tdata (abfd)->num_group = num_group;
707 
708 	      /* If all groups are invalid then fail.  */
709 	      if (num_group == 0)
710 		{
711 		  elf_tdata (abfd)->group_sect_ptr = NULL;
712 		  elf_tdata (abfd)->num_group = num_group = -1;
713 		  (*_bfd_error_handler) (_("%B: no valid group sections found"), abfd);
714 		  bfd_set_error (bfd_error_bad_value);
715 		}
716 	    }
717 	}
718     }
719 
720   if (num_group != (unsigned) -1)
721     {
722       unsigned int i;
723 
724       for (i = 0; i < num_group; i++)
725 	{
726 	  Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
727 	  Elf_Internal_Group *idx = (Elf_Internal_Group *) shdr->contents;
728 	  unsigned int n_elt = shdr->sh_size / 4;
729 
730 	  /* Look through this group's sections to see if current
731 	     section is a member.  */
732 	  while (--n_elt != 0)
733 	    if ((++idx)->shdr == hdr)
734 	      {
735 		asection *s = NULL;
736 
737 		/* We are a member of this group.  Go looking through
738 		   other members to see if any others are linked via
739 		   next_in_group.  */
740 		idx = (Elf_Internal_Group *) shdr->contents;
741 		n_elt = shdr->sh_size / 4;
742 		while (--n_elt != 0)
743 		  if ((s = (++idx)->shdr->bfd_section) != NULL
744 		      && elf_next_in_group (s) != NULL)
745 		    break;
746 		if (n_elt != 0)
747 		  {
748 		    /* Snarf the group name from other member, and
749 		       insert current section in circular list.  */
750 		    elf_group_name (newsect) = elf_group_name (s);
751 		    elf_next_in_group (newsect) = elf_next_in_group (s);
752 		    elf_next_in_group (s) = newsect;
753 		  }
754 		else
755 		  {
756 		    const char *gname;
757 
758 		    gname = group_signature (abfd, shdr);
759 		    if (gname == NULL)
760 		      return FALSE;
761 		    elf_group_name (newsect) = gname;
762 
763 		    /* Start a circular list with one element.  */
764 		    elf_next_in_group (newsect) = newsect;
765 		  }
766 
767 		/* If the group section has been created, point to the
768 		   new member.  */
769 		if (shdr->bfd_section != NULL)
770 		  elf_next_in_group (shdr->bfd_section) = newsect;
771 
772 		i = num_group - 1;
773 		break;
774 	      }
775 	}
776     }
777 
778   if (elf_group_name (newsect) == NULL)
779     {
780       (*_bfd_error_handler) (_("%B: no group info for section %A"),
781 			     abfd, newsect);
782       return FALSE;
783     }
784   return TRUE;
785 }
786 
787 bfd_boolean
788 _bfd_elf_setup_sections (bfd *abfd)
789 {
790   unsigned int i;
791   unsigned int num_group = elf_tdata (abfd)->num_group;
792   bfd_boolean result = TRUE;
793   asection *s;
794 
795   /* Process SHF_LINK_ORDER.  */
796   for (s = abfd->sections; s != NULL; s = s->next)
797     {
798       Elf_Internal_Shdr *this_hdr = &elf_section_data (s)->this_hdr;
799       if ((this_hdr->sh_flags & SHF_LINK_ORDER) != 0)
800 	{
801 	  unsigned int elfsec = this_hdr->sh_link;
802 	  /* FIXME: The old Intel compiler and old strip/objcopy may
803 	     not set the sh_link or sh_info fields.  Hence we could
804 	     get the situation where elfsec is 0.  */
805 	  if (elfsec == 0)
806 	    {
807 	      const struct elf_backend_data *bed = get_elf_backend_data (abfd);
808 	      if (bed->link_order_error_handler)
809 		bed->link_order_error_handler
810 		  (_("%B: warning: sh_link not set for section `%A'"),
811 		   abfd, s);
812 	    }
813 	  else
814 	    {
815 	      asection *linksec = NULL;
816 
817 	      if (elfsec < elf_numsections (abfd))
818 		{
819 		  this_hdr = elf_elfsections (abfd)[elfsec];
820 		  linksec = this_hdr->bfd_section;
821 		}
822 
823 	      /* PR 1991, 2008:
824 		 Some strip/objcopy may leave an incorrect value in
825 		 sh_link.  We don't want to proceed.  */
826 	      if (linksec == NULL)
827 		{
828 		  (*_bfd_error_handler)
829 		    (_("%B: sh_link [%d] in section `%A' is incorrect"),
830 		     s->owner, s, elfsec);
831 		  result = FALSE;
832 		}
833 
834 	      elf_linked_to_section (s) = linksec;
835 	    }
836 	}
837     }
838 
839   /* Process section groups.  */
840   if (num_group == (unsigned) -1)
841     return result;
842 
843   for (i = 0; i < num_group; i++)
844     {
845       Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
846       Elf_Internal_Group *idx;
847       unsigned int n_elt;
848 
849       /* PR binutils/18758: Beware of corrupt binaries with invalid group data.  */
850       if (shdr == NULL || shdr->bfd_section == NULL || shdr->contents == NULL)
851 	{
852 	  (*_bfd_error_handler)
853 	    (_("%B: section group entry number %u is corrupt"),
854 	     abfd, i);
855 	  result = FALSE;
856 	  continue;
857 	}
858 
859       idx = (Elf_Internal_Group *) shdr->contents;
860       n_elt = shdr->sh_size / 4;
861 
862       while (--n_elt != 0)
863 	if ((++idx)->shdr->bfd_section)
864 	  elf_sec_group (idx->shdr->bfd_section) = shdr->bfd_section;
865 	else if (idx->shdr->sh_type == SHT_RELA
866 		 || idx->shdr->sh_type == SHT_REL)
867 	  /* We won't include relocation sections in section groups in
868 	     output object files. We adjust the group section size here
869 	     so that relocatable link will work correctly when
870 	     relocation sections are in section group in input object
871 	     files.  */
872 	  shdr->bfd_section->size -= 4;
873 	else
874 	  {
875 	    /* There are some unknown sections in the group.  */
876 	    (*_bfd_error_handler)
877 	      (_("%B: unknown [%d] section `%s' in group [%s]"),
878 	       abfd,
879 	       (unsigned int) idx->shdr->sh_type,
880 	       bfd_elf_string_from_elf_section (abfd,
881 						(elf_elfheader (abfd)
882 						 ->e_shstrndx),
883 						idx->shdr->sh_name),
884 	       shdr->bfd_section->name);
885 	    result = FALSE;
886 	  }
887     }
888   return result;
889 }
890 
891 bfd_boolean
892 bfd_elf_is_group_section (bfd *abfd ATTRIBUTE_UNUSED, const asection *sec)
893 {
894   return elf_next_in_group (sec) != NULL;
895 }
896 
897 static char *
898 convert_debug_to_zdebug (bfd *abfd, const char *name)
899 {
900   unsigned int len = strlen (name);
901   char *new_name = bfd_alloc (abfd, len + 2);
902   if (new_name == NULL)
903     return NULL;
904   new_name[0] = '.';
905   new_name[1] = 'z';
906   memcpy (new_name + 2, name + 1, len);
907   return new_name;
908 }
909 
910 static char *
911 convert_zdebug_to_debug (bfd *abfd, const char *name)
912 {
913   unsigned int len = strlen (name);
914   char *new_name = bfd_alloc (abfd, len);
915   if (new_name == NULL)
916     return NULL;
917   new_name[0] = '.';
918   memcpy (new_name + 1, name + 2, len - 1);
919   return new_name;
920 }
921 
922 /* Make a BFD section from an ELF section.  We store a pointer to the
923    BFD section in the bfd_section field of the header.  */
924 
925 bfd_boolean
926 _bfd_elf_make_section_from_shdr (bfd *abfd,
927 				 Elf_Internal_Shdr *hdr,
928 				 const char *name,
929 				 int shindex)
930 {
931   asection *newsect;
932   flagword flags;
933   const struct elf_backend_data *bed;
934 
935   if (hdr->bfd_section != NULL)
936     return TRUE;
937 
938   newsect = bfd_make_section_anyway (abfd, name);
939   if (newsect == NULL)
940     return FALSE;
941 
942   hdr->bfd_section = newsect;
943   elf_section_data (newsect)->this_hdr = *hdr;
944   elf_section_data (newsect)->this_idx = shindex;
945 
946   /* Always use the real type/flags.  */
947   elf_section_type (newsect) = hdr->sh_type;
948   elf_section_flags (newsect) = hdr->sh_flags;
949 
950   newsect->filepos = hdr->sh_offset;
951 
952   if (! bfd_set_section_vma (abfd, newsect, hdr->sh_addr)
953       || ! bfd_set_section_size (abfd, newsect, hdr->sh_size)
954       || ! bfd_set_section_alignment (abfd, newsect,
955 				      bfd_log2 (hdr->sh_addralign)))
956     return FALSE;
957 
958   flags = SEC_NO_FLAGS;
959   if (hdr->sh_type != SHT_NOBITS)
960     flags |= SEC_HAS_CONTENTS;
961   if (hdr->sh_type == SHT_GROUP)
962     flags |= SEC_GROUP | SEC_EXCLUDE;
963   if ((hdr->sh_flags & SHF_ALLOC) != 0)
964     {
965       flags |= SEC_ALLOC;
966       if (hdr->sh_type != SHT_NOBITS)
967 	flags |= SEC_LOAD;
968     }
969   if ((hdr->sh_flags & SHF_WRITE) == 0)
970     flags |= SEC_READONLY;
971   if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
972     flags |= SEC_CODE;
973   else if ((flags & SEC_LOAD) != 0)
974     flags |= SEC_DATA;
975   if ((hdr->sh_flags & SHF_MERGE) != 0)
976     {
977       flags |= SEC_MERGE;
978       newsect->entsize = hdr->sh_entsize;
979     }
980   if ((hdr->sh_flags & SHF_STRINGS) != 0)
981     flags |= SEC_STRINGS;
982   if (hdr->sh_flags & SHF_GROUP)
983     if (!setup_group (abfd, hdr, newsect))
984       return FALSE;
985   if ((hdr->sh_flags & SHF_TLS) != 0)
986     flags |= SEC_THREAD_LOCAL;
987   if ((hdr->sh_flags & SHF_EXCLUDE) != 0)
988     flags |= SEC_EXCLUDE;
989 
990   if ((flags & SEC_ALLOC) == 0)
991     {
992       /* The debugging sections appear to be recognized only by name,
993 	 not any sort of flag.  Their SEC_ALLOC bits are cleared.  */
994       if (name [0] == '.')
995 	{
996 	  const char *p;
997 	  int n;
998 	  if (name[1] == 'd')
999 	    p = ".debug", n = 6;
1000 	  else if (name[1] == 'g' && name[2] == 'n')
1001 	    p = ".gnu.linkonce.wi.", n = 17;
1002 	  else if (name[1] == 'g' && name[2] == 'd')
1003 	    p = ".gdb_index", n = 11; /* yes we really do mean 11.  */
1004 	  else if (name[1] == 'l')
1005 	    p = ".line", n = 5;
1006 	  else if (name[1] == 's')
1007 	    p = ".stab", n = 5;
1008 	  else if (name[1] == 'z')
1009 	    p = ".zdebug", n = 7;
1010 	  else
1011 	    p = NULL, n = 0;
1012 	  if (p != NULL && strncmp (name, p, n) == 0)
1013 	    flags |= SEC_DEBUGGING;
1014 	}
1015     }
1016 
1017   /* As a GNU extension, if the name begins with .gnu.linkonce, we
1018      only link a single copy of the section.  This is used to support
1019      g++.  g++ will emit each template expansion in its own section.
1020      The symbols will be defined as weak, so that multiple definitions
1021      are permitted.  The GNU linker extension is to actually discard
1022      all but one of the sections.  */
1023   if (CONST_STRNEQ (name, ".gnu.linkonce")
1024       && elf_next_in_group (newsect) == NULL)
1025     flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
1026 
1027   bed = get_elf_backend_data (abfd);
1028   if (bed->elf_backend_section_flags)
1029     if (! bed->elf_backend_section_flags (&flags, hdr))
1030       return FALSE;
1031 
1032   if (! bfd_set_section_flags (abfd, newsect, flags))
1033     return FALSE;
1034 
1035   /* We do not parse the PT_NOTE segments as we are interested even in the
1036      separate debug info files which may have the segments offsets corrupted.
1037      PT_NOTEs from the core files are currently not parsed using BFD.  */
1038   if (hdr->sh_type == SHT_NOTE)
1039     {
1040       bfd_byte *contents;
1041 
1042       if (!bfd_malloc_and_get_section (abfd, newsect, &contents))
1043 	return FALSE;
1044 
1045       elf_parse_notes (abfd, (char *) contents, hdr->sh_size, -1);
1046       free (contents);
1047     }
1048 
1049   if ((flags & SEC_ALLOC) != 0)
1050     {
1051       Elf_Internal_Phdr *phdr;
1052       unsigned int i, nload;
1053 
1054       /* Some ELF linkers produce binaries with all the program header
1055 	 p_paddr fields zero.  If we have such a binary with more than
1056 	 one PT_LOAD header, then leave the section lma equal to vma
1057 	 so that we don't create sections with overlapping lma.  */
1058       phdr = elf_tdata (abfd)->phdr;
1059       for (nload = 0, i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
1060 	if (phdr->p_paddr != 0)
1061 	  break;
1062 	else if (phdr->p_type == PT_LOAD && phdr->p_memsz != 0)
1063 	  ++nload;
1064       if (i >= elf_elfheader (abfd)->e_phnum && nload > 1)
1065 	return TRUE;
1066 
1067       phdr = elf_tdata (abfd)->phdr;
1068       for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
1069 	{
1070 	  if (((phdr->p_type == PT_LOAD
1071 		&& (hdr->sh_flags & SHF_TLS) == 0)
1072 	       || phdr->p_type == PT_TLS)
1073 	      && ELF_SECTION_IN_SEGMENT (hdr, phdr))
1074 	    {
1075 	      if ((flags & SEC_LOAD) == 0)
1076 		newsect->lma = (phdr->p_paddr
1077 				+ hdr->sh_addr - phdr->p_vaddr);
1078 	      else
1079 		/* We used to use the same adjustment for SEC_LOAD
1080 		   sections, but that doesn't work if the segment
1081 		   is packed with code from multiple VMAs.
1082 		   Instead we calculate the section LMA based on
1083 		   the segment LMA.  It is assumed that the
1084 		   segment will contain sections with contiguous
1085 		   LMAs, even if the VMAs are not.  */
1086 		newsect->lma = (phdr->p_paddr
1087 				+ hdr->sh_offset - phdr->p_offset);
1088 
1089 	      /* With contiguous segments, we can't tell from file
1090 		 offsets whether a section with zero size should
1091 		 be placed at the end of one segment or the
1092 		 beginning of the next.  Decide based on vaddr.  */
1093 	      if (hdr->sh_addr >= phdr->p_vaddr
1094 		  && (hdr->sh_addr + hdr->sh_size
1095 		      <= phdr->p_vaddr + phdr->p_memsz))
1096 		break;
1097 	    }
1098 	}
1099     }
1100 
1101   /* Compress/decompress DWARF debug sections with names: .debug_* and
1102      .zdebug_*, after the section flags is set.  */
1103   if ((flags & SEC_DEBUGGING)
1104       && ((name[1] == 'd' && name[6] == '_')
1105 	  || (name[1] == 'z' && name[7] == '_')))
1106     {
1107       enum { nothing, compress, decompress } action = nothing;
1108       int compression_header_size;
1109       bfd_size_type uncompressed_size;
1110       bfd_boolean compressed
1111 	= bfd_is_section_compressed_with_header (abfd, newsect,
1112 						 &compression_header_size,
1113 						 &uncompressed_size);
1114 
1115       if (compressed)
1116 	{
1117 	  /* Compressed section.  Check if we should decompress.  */
1118 	  if ((abfd->flags & BFD_DECOMPRESS))
1119 	    action = decompress;
1120 	}
1121 
1122       /* Compress the uncompressed section or convert from/to .zdebug*
1123 	 section.  Check if we should compress.  */
1124       if (action == nothing)
1125 	{
1126 	  if (newsect->size != 0
1127 	      && (abfd->flags & BFD_COMPRESS)
1128 	      && compression_header_size >= 0
1129 	      && uncompressed_size > 0
1130 	      && (!compressed
1131 		  || ((compression_header_size > 0)
1132 		      != ((abfd->flags & BFD_COMPRESS_GABI) != 0))))
1133 	    action = compress;
1134 	  else
1135 	    return TRUE;
1136 	}
1137 
1138       if (action == compress)
1139 	{
1140 	  if (!bfd_init_section_compress_status (abfd, newsect))
1141 	    {
1142 	      (*_bfd_error_handler)
1143 		(_("%B: unable to initialize compress status for section %s"),
1144 		 abfd, name);
1145 	      return FALSE;
1146 	    }
1147 	}
1148       else
1149 	{
1150 	  if (!bfd_init_section_decompress_status (abfd, newsect))
1151 	    {
1152 	      (*_bfd_error_handler)
1153 		(_("%B: unable to initialize decompress status for section %s"),
1154 		 abfd, name);
1155 	      return FALSE;
1156 	    }
1157 	}
1158 
1159       if (abfd->is_linker_input)
1160 	{
1161 	  if (name[1] == 'z'
1162 	      && (action == decompress
1163 		  || (action == compress
1164 		      && (abfd->flags & BFD_COMPRESS_GABI) != 0)))
1165 	    {
1166 	      /* Convert section name from .zdebug_* to .debug_* so
1167 		 that linker will consider this section as a debug
1168 		 section.  */
1169 	      char *new_name = convert_zdebug_to_debug (abfd, name);
1170 	      if (new_name == NULL)
1171 		return FALSE;
1172 	      bfd_rename_section (abfd, newsect, new_name);
1173 	    }
1174 	}
1175       else
1176 	/* For objdump, don't rename the section.  For objcopy, delay
1177 	   section rename to elf_fake_sections.  */
1178 	newsect->flags |= SEC_ELF_RENAME;
1179     }
1180 
1181   return TRUE;
1182 }
1183 
1184 const char *const bfd_elf_section_type_names[] =
1185 {
1186   "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB",
1187   "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE",
1188   "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM",
1189 };
1190 
1191 /* ELF relocs are against symbols.  If we are producing relocatable
1192    output, and the reloc is against an external symbol, and nothing
1193    has given us any additional addend, the resulting reloc will also
1194    be against the same symbol.  In such a case, we don't want to
1195    change anything about the way the reloc is handled, since it will
1196    all be done at final link time.  Rather than put special case code
1197    into bfd_perform_relocation, all the reloc types use this howto
1198    function.  It just short circuits the reloc if producing
1199    relocatable output against an external symbol.  */
1200 
1201 bfd_reloc_status_type
1202 bfd_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED,
1203 		       arelent *reloc_entry,
1204 		       asymbol *symbol,
1205 		       void *data ATTRIBUTE_UNUSED,
1206 		       asection *input_section,
1207 		       bfd *output_bfd,
1208 		       char **error_message ATTRIBUTE_UNUSED)
1209 {
1210   if (output_bfd != NULL
1211       && (symbol->flags & BSF_SECTION_SYM) == 0
1212       && (! reloc_entry->howto->partial_inplace
1213 	  || reloc_entry->addend == 0))
1214     {
1215       reloc_entry->address += input_section->output_offset;
1216       return bfd_reloc_ok;
1217     }
1218 
1219   return bfd_reloc_continue;
1220 }
1221 
1222 /* Returns TRUE if section A matches section B.
1223    Names, addresses and links may be different, but everything else
1224    should be the same.  */
1225 
1226 static bfd_boolean
1227 section_match (const Elf_Internal_Shdr * a,
1228 	       const Elf_Internal_Shdr * b)
1229 {
1230   return
1231     a->sh_type         == b->sh_type
1232     && (a->sh_flags & ~ SHF_INFO_LINK)
1233     == (b->sh_flags & ~ SHF_INFO_LINK)
1234     && a->sh_addralign == b->sh_addralign
1235     && a->sh_size      == b->sh_size
1236     && a->sh_entsize   == b->sh_entsize
1237     /* FIXME: Check sh_addr ?  */
1238     ;
1239 }
1240 
1241 /* Find a section in OBFD that has the same characteristics
1242    as IHEADER.  Return the index of this section or SHN_UNDEF if
1243    none can be found.  Check's section HINT first, as this is likely
1244    to be the correct section.  */
1245 
1246 static unsigned int
1247 find_link (const bfd * obfd, const Elf_Internal_Shdr * iheader, const unsigned int hint)
1248 {
1249   Elf_Internal_Shdr ** oheaders = elf_elfsections (obfd);
1250   unsigned int i;
1251 
1252   if (section_match (oheaders[hint], iheader))
1253     return hint;
1254 
1255   for (i = 1; i < elf_numsections (obfd); i++)
1256     {
1257       Elf_Internal_Shdr * oheader = oheaders[i];
1258 
1259       if (section_match (oheader, iheader))
1260 	/* FIXME: Do we care if there is a potential for
1261 	   multiple matches ?  */
1262 	return i;
1263     }
1264 
1265   return SHN_UNDEF;
1266 }
1267 
1268 /* PR 19938: Attempt to set the ELF section header fields of an OS or
1269    Processor specific section, based upon a matching input section.
1270    Returns TRUE upon success, FALSE otherwise.  */
1271 
1272 static bfd_boolean
1273 copy_special_section_fields (const bfd *ibfd,
1274 			     bfd *obfd,
1275 			     const Elf_Internal_Shdr *iheader,
1276 			     Elf_Internal_Shdr *oheader,
1277 			     const unsigned int secnum)
1278 {
1279   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
1280   const Elf_Internal_Shdr **iheaders = (const Elf_Internal_Shdr **) elf_elfsections (ibfd);
1281   bfd_boolean changed = FALSE;
1282   unsigned int sh_link;
1283 
1284   if (oheader->sh_type == SHT_NOBITS)
1285     {
1286       /* This is a feature for objcopy --only-keep-debug:
1287 	 When a section's type is changed to NOBITS, we preserve
1288 	 the sh_link and sh_info fields so that they can be
1289 	 matched up with the original.
1290 
1291 	 Note: Strictly speaking these assignments are wrong.
1292 	 The sh_link and sh_info fields should point to the
1293 	 relevent sections in the output BFD, which may not be in
1294 	 the same location as they were in the input BFD.  But
1295 	 the whole point of this action is to preserve the
1296 	 original values of the sh_link and sh_info fields, so
1297 	 that they can be matched up with the section headers in
1298 	 the original file.  So strictly speaking we may be
1299 	 creating an invalid ELF file, but it is only for a file
1300 	 that just contains debug info and only for sections
1301 	 without any contents.  */
1302       if (oheader->sh_link == 0)
1303 	oheader->sh_link = iheader->sh_link;
1304       if (oheader->sh_info == 0)
1305 	oheader->sh_info = iheader->sh_info;
1306       return TRUE;
1307     }
1308 
1309   /* Allow the target a chance to decide how these fields should be set.  */
1310   if (bed->elf_backend_copy_special_section_fields != NULL
1311       && bed->elf_backend_copy_special_section_fields
1312       (ibfd, obfd, iheader, oheader))
1313     return TRUE;
1314 
1315   /* We have an iheader which might match oheader, and which has non-zero
1316      sh_info and/or sh_link fields.  Attempt to follow those links and find
1317      the section in the output bfd which corresponds to the linked section
1318      in the input bfd.  */
1319   if (iheader->sh_link != SHN_UNDEF)
1320     {
1321       sh_link = find_link (obfd, iheaders[iheader->sh_link], iheader->sh_link);
1322       if (sh_link != SHN_UNDEF)
1323 	{
1324 	  oheader->sh_link = sh_link;
1325 	  changed = TRUE;
1326 	}
1327       else
1328 	/* FIXME: Should we install iheader->sh_link
1329 	   if we could not find a match ?  */
1330 	(* _bfd_error_handler)
1331 	  (_("%B: Failed to find link section for section %d"), obfd, secnum);
1332     }
1333 
1334   if (iheader->sh_info)
1335     {
1336       /* The sh_info field can hold arbitrary information, but if the
1337 	 SHF_LINK_INFO flag is set then it should be interpreted as a
1338 	 section index.  */
1339       if (iheader->sh_flags & SHF_INFO_LINK)
1340 	{
1341 	  sh_link = find_link (obfd, iheaders[iheader->sh_info],
1342 			       iheader->sh_info);
1343 	  if (sh_link != SHN_UNDEF)
1344 	    oheader->sh_flags |= SHF_INFO_LINK;
1345 	}
1346       else
1347 	/* No idea what it means - just copy it.  */
1348 	sh_link = iheader->sh_info;
1349 
1350       if (sh_link != SHN_UNDEF)
1351 	{
1352 	  oheader->sh_info = sh_link;
1353 	  changed = TRUE;
1354 	}
1355       else
1356 	(* _bfd_error_handler)
1357 	  (_("%B: Failed to find info section for section %d"), obfd, secnum);
1358     }
1359 
1360   return changed;
1361 }
1362 
1363 /* Copy the program header and other data from one object module to
1364    another.  */
1365 
1366 bfd_boolean
1367 _bfd_elf_copy_private_bfd_data (bfd *ibfd, bfd *obfd)
1368 {
1369   const Elf_Internal_Shdr **iheaders = (const Elf_Internal_Shdr **) elf_elfsections (ibfd);
1370   Elf_Internal_Shdr **oheaders = elf_elfsections (obfd);
1371   const struct elf_backend_data *bed;
1372   unsigned int i;
1373 
1374   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
1375     || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
1376     return TRUE;
1377 
1378   if (!elf_flags_init (obfd))
1379     {
1380       elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags;
1381       elf_flags_init (obfd) = TRUE;
1382     }
1383 
1384   elf_gp (obfd) = elf_gp (ibfd);
1385 
1386   /* Also copy the EI_OSABI field.  */
1387   elf_elfheader (obfd)->e_ident[EI_OSABI] =
1388     elf_elfheader (ibfd)->e_ident[EI_OSABI];
1389 
1390   /* If set, copy the EI_ABIVERSION field.  */
1391   if (elf_elfheader (ibfd)->e_ident[EI_ABIVERSION])
1392     elf_elfheader (obfd)->e_ident[EI_ABIVERSION]
1393       = elf_elfheader (ibfd)->e_ident[EI_ABIVERSION];
1394 
1395   /* Copy object attributes.  */
1396   _bfd_elf_copy_obj_attributes (ibfd, obfd);
1397 
1398   if (iheaders == NULL || oheaders == NULL)
1399     return TRUE;
1400 
1401   bed = get_elf_backend_data (obfd);
1402 
1403   /* Possibly copy other fields in the section header.  */
1404   for (i = 1; i < elf_numsections (obfd); i++)
1405     {
1406       unsigned int j;
1407       Elf_Internal_Shdr * oheader = oheaders[i];
1408 
1409       /* Ignore ordinary sections.  SHT_NOBITS sections are considered however
1410 	 because of a special case need for generating separate debug info
1411 	 files.  See below for more details.  */
1412       if (oheader == NULL
1413 	  || (oheader->sh_type != SHT_NOBITS
1414 	      && oheader->sh_type < SHT_LOOS))
1415 	continue;
1416 
1417       /* Ignore empty sections, and sections whose
1418 	 fields have already been initialised.  */
1419       if (oheader->sh_size == 0
1420 	  || (oheader->sh_info != 0 && oheader->sh_link != 0))
1421 	continue;
1422 
1423       /* Scan for the matching section in the input bfd.
1424 	 First we try for a direct mapping between the input and output sections.  */
1425       for (j = 1; j < elf_numsections (ibfd); j++)
1426 	{
1427 	  const Elf_Internal_Shdr * iheader = iheaders[j];
1428 
1429 	  if (iheader == NULL)
1430 	    continue;
1431 
1432 	  if (oheader->bfd_section != NULL
1433 	      && iheader->bfd_section != NULL
1434 	      && iheader->bfd_section->output_section != NULL
1435 	      && iheader->bfd_section->output_section == oheader->bfd_section)
1436 	    {
1437 	      /* We have found a connection from the input section to the
1438 		 output section.  Attempt to copy the header fields.  If
1439 		 this fails then do not try any further sections - there
1440 		 should only be a one-to-one mapping between input and output. */
1441 	      if (! copy_special_section_fields (ibfd, obfd, iheader, oheader, i))
1442 		j = elf_numsections (ibfd);
1443 	      break;
1444 	    }
1445 	}
1446 
1447       if (j < elf_numsections (ibfd))
1448 	continue;
1449 
1450       /* That failed.  So try to deduce the corresponding input section.
1451 	 Unfortunately we cannot compare names as the output string table
1452 	 is empty, so instead we check size, address and type.  */
1453       for (j = 1; j < elf_numsections (ibfd); j++)
1454 	{
1455 	  const Elf_Internal_Shdr * iheader = iheaders[j];
1456 
1457 	  if (iheader == NULL)
1458 	    continue;
1459 
1460 	  /* Try matching fields in the input section's header.
1461 	     Since --only-keep-debug turns all non-debug sections into
1462 	     SHT_NOBITS sections, the output SHT_NOBITS type matches any
1463 	     input type.  */
1464 	  if ((oheader->sh_type == SHT_NOBITS
1465 	       || iheader->sh_type == oheader->sh_type)
1466 	      && (iheader->sh_flags & ~ SHF_INFO_LINK)
1467 	      == (oheader->sh_flags & ~ SHF_INFO_LINK)
1468 	      && iheader->sh_addralign == oheader->sh_addralign
1469 	      && iheader->sh_entsize == oheader->sh_entsize
1470 	      && iheader->sh_size == oheader->sh_size
1471 	      && iheader->sh_addr == oheader->sh_addr
1472 	      && (iheader->sh_info != oheader->sh_info
1473 		  || iheader->sh_link != oheader->sh_link))
1474 	    {
1475 	      if (copy_special_section_fields (ibfd, obfd, iheader, oheader, i))
1476 		break;
1477 	    }
1478 	}
1479 
1480       if (j == elf_numsections (ibfd) && oheader->sh_type >= SHT_LOOS)
1481 	{
1482 	  /* Final attempt.  Call the backend copy function
1483 	     with a NULL input section.  */
1484 	  if (bed->elf_backend_copy_special_section_fields != NULL)
1485 	    bed->elf_backend_copy_special_section_fields (ibfd, obfd, NULL, oheader);
1486 	}
1487     }
1488 
1489   return TRUE;
1490 }
1491 
1492 static const char *
1493 get_segment_type (unsigned int p_type)
1494 {
1495   const char *pt;
1496   switch (p_type)
1497     {
1498     case PT_NULL: pt = "NULL"; break;
1499     case PT_LOAD: pt = "LOAD"; break;
1500     case PT_DYNAMIC: pt = "DYNAMIC"; break;
1501     case PT_INTERP: pt = "INTERP"; break;
1502     case PT_NOTE: pt = "NOTE"; break;
1503     case PT_SHLIB: pt = "SHLIB"; break;
1504     case PT_PHDR: pt = "PHDR"; break;
1505     case PT_TLS: pt = "TLS"; break;
1506     case PT_GNU_EH_FRAME: pt = "EH_FRAME"; break;
1507     case PT_GNU_STACK: pt = "STACK"; break;
1508     case PT_GNU_RELRO: pt = "RELRO"; break;
1509     default: pt = NULL; break;
1510     }
1511   return pt;
1512 }
1513 
1514 /* Print out the program headers.  */
1515 
1516 bfd_boolean
1517 _bfd_elf_print_private_bfd_data (bfd *abfd, void *farg)
1518 {
1519   FILE *f = (FILE *) farg;
1520   Elf_Internal_Phdr *p;
1521   asection *s;
1522   bfd_byte *dynbuf = NULL;
1523 
1524   p = elf_tdata (abfd)->phdr;
1525   if (p != NULL)
1526     {
1527       unsigned int i, c;
1528 
1529       fprintf (f, _("\nProgram Header:\n"));
1530       c = elf_elfheader (abfd)->e_phnum;
1531       for (i = 0; i < c; i++, p++)
1532 	{
1533 	  const char *pt = get_segment_type (p->p_type);
1534 	  char buf[20];
1535 
1536 	  if (pt == NULL)
1537 	    {
1538 	      sprintf (buf, "0x%lx", p->p_type);
1539 	      pt = buf;
1540 	    }
1541 	  fprintf (f, "%8s off    0x", pt);
1542 	  bfd_fprintf_vma (abfd, f, p->p_offset);
1543 	  fprintf (f, " vaddr 0x");
1544 	  bfd_fprintf_vma (abfd, f, p->p_vaddr);
1545 	  fprintf (f, " paddr 0x");
1546 	  bfd_fprintf_vma (abfd, f, p->p_paddr);
1547 	  fprintf (f, " align 2**%u\n", bfd_log2 (p->p_align));
1548 	  fprintf (f, "         filesz 0x");
1549 	  bfd_fprintf_vma (abfd, f, p->p_filesz);
1550 	  fprintf (f, " memsz 0x");
1551 	  bfd_fprintf_vma (abfd, f, p->p_memsz);
1552 	  fprintf (f, " flags %c%c%c",
1553 		   (p->p_flags & PF_R) != 0 ? 'r' : '-',
1554 		   (p->p_flags & PF_W) != 0 ? 'w' : '-',
1555 		   (p->p_flags & PF_X) != 0 ? 'x' : '-');
1556 	  if ((p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X)) != 0)
1557 	    fprintf (f, " %lx", p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X));
1558 	  fprintf (f, "\n");
1559 	}
1560     }
1561 
1562   s = bfd_get_section_by_name (abfd, ".dynamic");
1563   if (s != NULL)
1564     {
1565       unsigned int elfsec;
1566       unsigned long shlink;
1567       bfd_byte *extdyn, *extdynend;
1568       size_t extdynsize;
1569       void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
1570 
1571       fprintf (f, _("\nDynamic Section:\n"));
1572 
1573       if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
1574 	goto error_return;
1575 
1576       elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
1577       if (elfsec == SHN_BAD)
1578 	goto error_return;
1579       shlink = elf_elfsections (abfd)[elfsec]->sh_link;
1580 
1581       extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
1582       swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
1583 
1584       extdyn = dynbuf;
1585       /* PR 17512: file: 6f427532.  */
1586       if (s->size < extdynsize)
1587 	goto error_return;
1588       extdynend = extdyn + s->size;
1589       /* PR 17512: file: id:000006,sig:06,src:000000,op:flip4,pos:5664.
1590          Fix range check.  */
1591       for (; extdyn <= (extdynend - extdynsize); extdyn += extdynsize)
1592 	{
1593 	  Elf_Internal_Dyn dyn;
1594 	  const char *name = "";
1595 	  char ab[20];
1596 	  bfd_boolean stringp;
1597 	  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1598 
1599 	  (*swap_dyn_in) (abfd, extdyn, &dyn);
1600 
1601 	  if (dyn.d_tag == DT_NULL)
1602 	    break;
1603 
1604 	  stringp = FALSE;
1605 	  switch (dyn.d_tag)
1606 	    {
1607 	    default:
1608 	      if (bed->elf_backend_get_target_dtag)
1609 		name = (*bed->elf_backend_get_target_dtag) (dyn.d_tag);
1610 
1611 	      if (!strcmp (name, ""))
1612 		{
1613 		  sprintf (ab, "0x%lx", (unsigned long) dyn.d_tag);
1614 		  name = ab;
1615 		}
1616 	      break;
1617 
1618 	    case DT_NEEDED: name = "NEEDED"; stringp = TRUE; break;
1619 	    case DT_PLTRELSZ: name = "PLTRELSZ"; break;
1620 	    case DT_PLTGOT: name = "PLTGOT"; break;
1621 	    case DT_HASH: name = "HASH"; break;
1622 	    case DT_STRTAB: name = "STRTAB"; break;
1623 	    case DT_SYMTAB: name = "SYMTAB"; break;
1624 	    case DT_RELA: name = "RELA"; break;
1625 	    case DT_RELASZ: name = "RELASZ"; break;
1626 	    case DT_RELAENT: name = "RELAENT"; break;
1627 	    case DT_STRSZ: name = "STRSZ"; break;
1628 	    case DT_SYMENT: name = "SYMENT"; break;
1629 	    case DT_INIT: name = "INIT"; break;
1630 	    case DT_FINI: name = "FINI"; break;
1631 	    case DT_SONAME: name = "SONAME"; stringp = TRUE; break;
1632 	    case DT_RPATH: name = "RPATH"; stringp = TRUE; break;
1633 	    case DT_SYMBOLIC: name = "SYMBOLIC"; break;
1634 	    case DT_REL: name = "REL"; break;
1635 	    case DT_RELSZ: name = "RELSZ"; break;
1636 	    case DT_RELENT: name = "RELENT"; break;
1637 	    case DT_PLTREL: name = "PLTREL"; break;
1638 	    case DT_DEBUG: name = "DEBUG"; break;
1639 	    case DT_TEXTREL: name = "TEXTREL"; break;
1640 	    case DT_JMPREL: name = "JMPREL"; break;
1641 	    case DT_BIND_NOW: name = "BIND_NOW"; break;
1642 	    case DT_INIT_ARRAY: name = "INIT_ARRAY"; break;
1643 	    case DT_FINI_ARRAY: name = "FINI_ARRAY"; break;
1644 	    case DT_INIT_ARRAYSZ: name = "INIT_ARRAYSZ"; break;
1645 	    case DT_FINI_ARRAYSZ: name = "FINI_ARRAYSZ"; break;
1646 	    case DT_RUNPATH: name = "RUNPATH"; stringp = TRUE; break;
1647 	    case DT_FLAGS: name = "FLAGS"; break;
1648 	    case DT_PREINIT_ARRAY: name = "PREINIT_ARRAY"; break;
1649 	    case DT_PREINIT_ARRAYSZ: name = "PREINIT_ARRAYSZ"; break;
1650 	    case DT_CHECKSUM: name = "CHECKSUM"; break;
1651 	    case DT_PLTPADSZ: name = "PLTPADSZ"; break;
1652 	    case DT_MOVEENT: name = "MOVEENT"; break;
1653 	    case DT_MOVESZ: name = "MOVESZ"; break;
1654 	    case DT_FEATURE: name = "FEATURE"; break;
1655 	    case DT_POSFLAG_1: name = "POSFLAG_1"; break;
1656 	    case DT_SYMINSZ: name = "SYMINSZ"; break;
1657 	    case DT_SYMINENT: name = "SYMINENT"; break;
1658 	    case DT_CONFIG: name = "CONFIG"; stringp = TRUE; break;
1659 	    case DT_DEPAUDIT: name = "DEPAUDIT"; stringp = TRUE; break;
1660 	    case DT_AUDIT: name = "AUDIT"; stringp = TRUE; break;
1661 	    case DT_PLTPAD: name = "PLTPAD"; break;
1662 	    case DT_MOVETAB: name = "MOVETAB"; break;
1663 	    case DT_SYMINFO: name = "SYMINFO"; break;
1664 	    case DT_RELACOUNT: name = "RELACOUNT"; break;
1665 	    case DT_RELCOUNT: name = "RELCOUNT"; break;
1666 	    case DT_FLAGS_1: name = "FLAGS_1"; break;
1667 	    case DT_VERSYM: name = "VERSYM"; break;
1668 	    case DT_VERDEF: name = "VERDEF"; break;
1669 	    case DT_VERDEFNUM: name = "VERDEFNUM"; break;
1670 	    case DT_VERNEED: name = "VERNEED"; break;
1671 	    case DT_VERNEEDNUM: name = "VERNEEDNUM"; break;
1672 	    case DT_AUXILIARY: name = "AUXILIARY"; stringp = TRUE; break;
1673 	    case DT_USED: name = "USED"; break;
1674 	    case DT_FILTER: name = "FILTER"; stringp = TRUE; break;
1675 	    case DT_GNU_HASH: name = "GNU_HASH"; break;
1676 	    }
1677 
1678 	  fprintf (f, "  %-20s ", name);
1679 	  if (! stringp)
1680 	    {
1681 	      fprintf (f, "0x");
1682 	      bfd_fprintf_vma (abfd, f, dyn.d_un.d_val);
1683 	    }
1684 	  else
1685 	    {
1686 	      const char *string;
1687 	      unsigned int tagv = dyn.d_un.d_val;
1688 
1689 	      string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
1690 	      if (string == NULL)
1691 		goto error_return;
1692 	      fprintf (f, "%s", string);
1693 	    }
1694 	  fprintf (f, "\n");
1695 	}
1696 
1697       free (dynbuf);
1698       dynbuf = NULL;
1699     }
1700 
1701   if ((elf_dynverdef (abfd) != 0 && elf_tdata (abfd)->verdef == NULL)
1702       || (elf_dynverref (abfd) != 0 && elf_tdata (abfd)->verref == NULL))
1703     {
1704       if (! _bfd_elf_slurp_version_tables (abfd, FALSE))
1705 	return FALSE;
1706     }
1707 
1708   if (elf_dynverdef (abfd) != 0)
1709     {
1710       Elf_Internal_Verdef *t;
1711 
1712       fprintf (f, _("\nVersion definitions:\n"));
1713       for (t = elf_tdata (abfd)->verdef; t != NULL; t = t->vd_nextdef)
1714 	{
1715 	  fprintf (f, "%d 0x%2.2x 0x%8.8lx %s\n", t->vd_ndx,
1716 		   t->vd_flags, t->vd_hash,
1717 		   t->vd_nodename ? t->vd_nodename : "<corrupt>");
1718 	  if (t->vd_auxptr != NULL && t->vd_auxptr->vda_nextptr != NULL)
1719 	    {
1720 	      Elf_Internal_Verdaux *a;
1721 
1722 	      fprintf (f, "\t");
1723 	      for (a = t->vd_auxptr->vda_nextptr;
1724 		   a != NULL;
1725 		   a = a->vda_nextptr)
1726 		fprintf (f, "%s ",
1727 			 a->vda_nodename ? a->vda_nodename : "<corrupt>");
1728 	      fprintf (f, "\n");
1729 	    }
1730 	}
1731     }
1732 
1733   if (elf_dynverref (abfd) != 0)
1734     {
1735       Elf_Internal_Verneed *t;
1736 
1737       fprintf (f, _("\nVersion References:\n"));
1738       for (t = elf_tdata (abfd)->verref; t != NULL; t = t->vn_nextref)
1739 	{
1740 	  Elf_Internal_Vernaux *a;
1741 
1742 	  fprintf (f, _("  required from %s:\n"),
1743 		   t->vn_filename ? t->vn_filename : "<corrupt>");
1744 	  for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1745 	    fprintf (f, "    0x%8.8lx 0x%2.2x %2.2d %s\n", a->vna_hash,
1746 		     a->vna_flags, a->vna_other,
1747 		     a->vna_nodename ? a->vna_nodename : "<corrupt>");
1748 	}
1749     }
1750 
1751   return TRUE;
1752 
1753  error_return:
1754   if (dynbuf != NULL)
1755     free (dynbuf);
1756   return FALSE;
1757 }
1758 
1759 /* Get version string.  */
1760 
1761 const char *
1762 _bfd_elf_get_symbol_version_string (bfd *abfd, asymbol *symbol,
1763 				    bfd_boolean *hidden)
1764 {
1765   const char *version_string = NULL;
1766   if (elf_dynversym (abfd) != 0
1767       && (elf_dynverdef (abfd) != 0 || elf_dynverref (abfd) != 0))
1768     {
1769       unsigned int vernum = ((elf_symbol_type *) symbol)->version;
1770 
1771       *hidden = (vernum & VERSYM_HIDDEN) != 0;
1772       vernum &= VERSYM_VERSION;
1773 
1774       if (vernum == 0)
1775 	version_string = "";
1776       else if (vernum == 1)
1777 	version_string = "Base";
1778       else if (vernum <= elf_tdata (abfd)->cverdefs)
1779 	version_string =
1780 	  elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
1781       else
1782 	{
1783 	  Elf_Internal_Verneed *t;
1784 
1785 	  version_string = "";
1786 	  for (t = elf_tdata (abfd)->verref;
1787 	       t != NULL;
1788 	       t = t->vn_nextref)
1789 	    {
1790 	      Elf_Internal_Vernaux *a;
1791 
1792 	      for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1793 		{
1794 		  if (a->vna_other == vernum)
1795 		    {
1796 		      version_string = a->vna_nodename;
1797 		      break;
1798 		    }
1799 		}
1800 	    }
1801 	}
1802     }
1803   return version_string;
1804 }
1805 
1806 /* Display ELF-specific fields of a symbol.  */
1807 
1808 void
1809 bfd_elf_print_symbol (bfd *abfd,
1810 		      void *filep,
1811 		      asymbol *symbol,
1812 		      bfd_print_symbol_type how)
1813 {
1814   FILE *file = (FILE *) filep;
1815   switch (how)
1816     {
1817     case bfd_print_symbol_name:
1818       fprintf (file, "%s", symbol->name);
1819       break;
1820     case bfd_print_symbol_more:
1821       fprintf (file, "elf ");
1822       bfd_fprintf_vma (abfd, file, symbol->value);
1823       fprintf (file, " %lx", (unsigned long) symbol->flags);
1824       break;
1825     case bfd_print_symbol_all:
1826       {
1827 	const char *section_name;
1828 	const char *name = NULL;
1829 	const struct elf_backend_data *bed;
1830 	unsigned char st_other;
1831 	bfd_vma val;
1832 	const char *version_string;
1833 	bfd_boolean hidden;
1834 
1835 	section_name = symbol->section ? symbol->section->name : "(*none*)";
1836 
1837 	bed = get_elf_backend_data (abfd);
1838 	if (bed->elf_backend_print_symbol_all)
1839 	  name = (*bed->elf_backend_print_symbol_all) (abfd, filep, symbol);
1840 
1841 	if (name == NULL)
1842 	  {
1843 	    name = symbol->name;
1844 	    bfd_print_symbol_vandf (abfd, file, symbol);
1845 	  }
1846 
1847 	fprintf (file, " %s\t", section_name);
1848 	/* Print the "other" value for a symbol.  For common symbols,
1849 	   we've already printed the size; now print the alignment.
1850 	   For other symbols, we have no specified alignment, and
1851 	   we've printed the address; now print the size.  */
1852 	if (symbol->section && bfd_is_com_section (symbol->section))
1853 	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_value;
1854 	else
1855 	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_size;
1856 	bfd_fprintf_vma (abfd, file, val);
1857 
1858 	/* If we have version information, print it.  */
1859 	version_string = _bfd_elf_get_symbol_version_string (abfd,
1860 							     symbol,
1861 							     &hidden);
1862 	if (version_string)
1863 	  {
1864 	    if (!hidden)
1865 	      fprintf (file, "  %-11s", version_string);
1866 	    else
1867 	      {
1868 		int i;
1869 
1870 		fprintf (file, " (%s)", version_string);
1871 		for (i = 10 - strlen (version_string); i > 0; --i)
1872 		  putc (' ', file);
1873 	      }
1874 	  }
1875 
1876 	/* If the st_other field is not zero, print it.  */
1877 	st_other = ((elf_symbol_type *) symbol)->internal_elf_sym.st_other;
1878 
1879 	switch (st_other)
1880 	  {
1881 	  case 0: break;
1882 	  case STV_INTERNAL:  fprintf (file, " .internal");  break;
1883 	  case STV_HIDDEN:    fprintf (file, " .hidden");    break;
1884 	  case STV_PROTECTED: fprintf (file, " .protected"); break;
1885 	  default:
1886 	    /* Some other non-defined flags are also present, so print
1887 	       everything hex.  */
1888 	    fprintf (file, " 0x%02x", (unsigned int) st_other);
1889 	  }
1890 
1891 	fprintf (file, " %s", name);
1892       }
1893       break;
1894     }
1895 }
1896 
1897 /* ELF .o/exec file reading */
1898 
1899 /* Create a new bfd section from an ELF section header.  */
1900 
1901 bfd_boolean
1902 bfd_section_from_shdr (bfd *abfd, unsigned int shindex)
1903 {
1904   Elf_Internal_Shdr *hdr;
1905   Elf_Internal_Ehdr *ehdr;
1906   const struct elf_backend_data *bed;
1907   const char *name;
1908   bfd_boolean ret = TRUE;
1909   static bfd_boolean * sections_being_created = NULL;
1910   static bfd * sections_being_created_abfd = NULL;
1911   static unsigned int nesting = 0;
1912 
1913   if (shindex >= elf_numsections (abfd))
1914     return FALSE;
1915 
1916   if (++ nesting > 3)
1917     {
1918       /* PR17512: A corrupt ELF binary might contain a recursive group of
1919 	 sections, with each the string indicies pointing to the next in the
1920 	 loop.  Detect this here, by refusing to load a section that we are
1921 	 already in the process of loading.  We only trigger this test if
1922 	 we have nested at least three sections deep as normal ELF binaries
1923 	 can expect to recurse at least once.
1924 
1925 	 FIXME: It would be better if this array was attached to the bfd,
1926 	 rather than being held in a static pointer.  */
1927 
1928       if (sections_being_created_abfd != abfd)
1929 	sections_being_created = NULL;
1930       if (sections_being_created == NULL)
1931 	{
1932 	  /* FIXME: It would be more efficient to attach this array to the bfd somehow.  */
1933 	  sections_being_created = (bfd_boolean *)
1934 	    bfd_zalloc (abfd, elf_numsections (abfd) * sizeof (bfd_boolean));
1935 	  sections_being_created_abfd = abfd;
1936 	}
1937       if (sections_being_created [shindex])
1938 	{
1939 	  (*_bfd_error_handler)
1940 	    (_("%B: warning: loop in section dependencies detected"), abfd);
1941 	  return FALSE;
1942 	}
1943       sections_being_created [shindex] = TRUE;
1944     }
1945 
1946   hdr = elf_elfsections (abfd)[shindex];
1947   ehdr = elf_elfheader (abfd);
1948   name = bfd_elf_string_from_elf_section (abfd, ehdr->e_shstrndx,
1949 					  hdr->sh_name);
1950   if (name == NULL)
1951     goto fail;
1952 
1953   bed = get_elf_backend_data (abfd);
1954   switch (hdr->sh_type)
1955     {
1956     case SHT_NULL:
1957       /* Inactive section. Throw it away.  */
1958       goto success;
1959 
1960     case SHT_PROGBITS:		/* Normal section with contents.  */
1961     case SHT_NOBITS:		/* .bss section.  */
1962     case SHT_HASH:		/* .hash section.  */
1963     case SHT_NOTE:		/* .note section.  */
1964     case SHT_INIT_ARRAY:	/* .init_array section.  */
1965     case SHT_FINI_ARRAY:	/* .fini_array section.  */
1966     case SHT_PREINIT_ARRAY:	/* .preinit_array section.  */
1967     case SHT_GNU_LIBLIST:	/* .gnu.liblist section.  */
1968     case SHT_GNU_HASH:		/* .gnu.hash section.  */
1969       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
1970       goto success;
1971 
1972     case SHT_DYNAMIC:	/* Dynamic linking information.  */
1973       if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
1974 	goto fail;
1975 
1976       if (hdr->sh_link > elf_numsections (abfd))
1977 	{
1978 	  /* PR 10478: Accept Solaris binaries with a sh_link
1979 	     field set to SHN_BEFORE or SHN_AFTER.  */
1980 	  switch (bfd_get_arch (abfd))
1981 	    {
1982 	    case bfd_arch_i386:
1983 	    case bfd_arch_sparc:
1984 	      if (hdr->sh_link == (SHN_LORESERVE & 0xffff) /* SHN_BEFORE */
1985 		  || hdr->sh_link == ((SHN_LORESERVE + 1) & 0xffff) /* SHN_AFTER */)
1986 		break;
1987 	      /* Otherwise fall through.  */
1988 	    default:
1989 	      goto fail;
1990 	    }
1991 	}
1992       else if (elf_elfsections (abfd)[hdr->sh_link] == NULL)
1993 	goto fail;
1994       else if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_STRTAB)
1995 	{
1996 	  Elf_Internal_Shdr *dynsymhdr;
1997 
1998 	  /* The shared libraries distributed with hpux11 have a bogus
1999 	     sh_link field for the ".dynamic" section.  Find the
2000 	     string table for the ".dynsym" section instead.  */
2001 	  if (elf_dynsymtab (abfd) != 0)
2002 	    {
2003 	      dynsymhdr = elf_elfsections (abfd)[elf_dynsymtab (abfd)];
2004 	      hdr->sh_link = dynsymhdr->sh_link;
2005 	    }
2006 	  else
2007 	    {
2008 	      unsigned int i, num_sec;
2009 
2010 	      num_sec = elf_numsections (abfd);
2011 	      for (i = 1; i < num_sec; i++)
2012 		{
2013 		  dynsymhdr = elf_elfsections (abfd)[i];
2014 		  if (dynsymhdr->sh_type == SHT_DYNSYM)
2015 		    {
2016 		      hdr->sh_link = dynsymhdr->sh_link;
2017 		      break;
2018 		    }
2019 		}
2020 	    }
2021 	}
2022       goto success;
2023 
2024     case SHT_SYMTAB:		/* A symbol table.  */
2025       if (elf_onesymtab (abfd) == shindex)
2026 	goto success;
2027 
2028       if (hdr->sh_entsize != bed->s->sizeof_sym)
2029 	goto fail;
2030 
2031       if (hdr->sh_info * hdr->sh_entsize > hdr->sh_size)
2032 	{
2033 	  if (hdr->sh_size != 0)
2034 	    goto fail;
2035 	  /* Some assemblers erroneously set sh_info to one with a
2036 	     zero sh_size.  ld sees this as a global symbol count
2037 	     of (unsigned) -1.  Fix it here.  */
2038 	  hdr->sh_info = 0;
2039 	  goto success;
2040 	}
2041 
2042       /* PR 18854: A binary might contain more than one symbol table.
2043 	 Unusual, but possible.  Warn, but continue.  */
2044       if (elf_onesymtab (abfd) != 0)
2045 	{
2046 	  (*_bfd_error_handler)
2047 	    (_("%B: warning: multiple symbol tables detected - ignoring the table in section %u"),
2048 	     abfd, shindex);
2049 	  goto success;
2050 	}
2051       elf_onesymtab (abfd) = shindex;
2052       elf_symtab_hdr (abfd) = *hdr;
2053       elf_elfsections (abfd)[shindex] = hdr = & elf_symtab_hdr (abfd);
2054       abfd->flags |= HAS_SYMS;
2055 
2056       /* Sometimes a shared object will map in the symbol table.  If
2057 	 SHF_ALLOC is set, and this is a shared object, then we also
2058 	 treat this section as a BFD section.  We can not base the
2059 	 decision purely on SHF_ALLOC, because that flag is sometimes
2060 	 set in a relocatable object file, which would confuse the
2061 	 linker.  */
2062       if ((hdr->sh_flags & SHF_ALLOC) != 0
2063 	  && (abfd->flags & DYNAMIC) != 0
2064 	  && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name,
2065 						shindex))
2066 	goto fail;
2067 
2068       /* Go looking for SHT_SYMTAB_SHNDX too, since if there is one we
2069 	 can't read symbols without that section loaded as well.  It
2070 	 is most likely specified by the next section header.  */
2071       {
2072 	elf_section_list * entry;
2073 	unsigned int i, num_sec;
2074 
2075 	for (entry = elf_symtab_shndx_list (abfd); entry != NULL; entry = entry->next)
2076 	  if (entry->hdr.sh_link == shindex)
2077 	    goto success;
2078 
2079 	num_sec = elf_numsections (abfd);
2080 	for (i = shindex + 1; i < num_sec; i++)
2081 	  {
2082 	    Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
2083 
2084 	    if (hdr2->sh_type == SHT_SYMTAB_SHNDX
2085 		&& hdr2->sh_link == shindex)
2086 	      break;
2087 	  }
2088 
2089 	if (i == num_sec)
2090 	  for (i = 1; i < shindex; i++)
2091 	    {
2092 	      Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
2093 
2094 	      if (hdr2->sh_type == SHT_SYMTAB_SHNDX
2095 		  && hdr2->sh_link == shindex)
2096 		break;
2097 	    }
2098 
2099 	if (i != shindex)
2100 	  ret = bfd_section_from_shdr (abfd, i);
2101 	/* else FIXME: we have failed to find the symbol table - should we issue an error ? */
2102 	goto success;
2103       }
2104 
2105     case SHT_DYNSYM:		/* A dynamic symbol table.  */
2106       if (elf_dynsymtab (abfd) == shindex)
2107 	goto success;
2108 
2109       if (hdr->sh_entsize != bed->s->sizeof_sym)
2110 	goto fail;
2111 
2112       if (hdr->sh_info * hdr->sh_entsize > hdr->sh_size)
2113 	{
2114 	  if (hdr->sh_size != 0)
2115 	    goto fail;
2116 
2117 	  /* Some linkers erroneously set sh_info to one with a
2118 	     zero sh_size.  ld sees this as a global symbol count
2119 	     of (unsigned) -1.  Fix it here.  */
2120 	  hdr->sh_info = 0;
2121 	  goto success;
2122 	}
2123 
2124       /* PR 18854: A binary might contain more than one dynamic symbol table.
2125 	 Unusual, but possible.  Warn, but continue.  */
2126       if (elf_dynsymtab (abfd) != 0)
2127 	{
2128 	  (*_bfd_error_handler)
2129 	    (_("%B: warning: multiple dynamic symbol tables detected - ignoring the table in section %u"),
2130 	     abfd, shindex);
2131 	  goto success;
2132 	}
2133       elf_dynsymtab (abfd) = shindex;
2134       elf_tdata (abfd)->dynsymtab_hdr = *hdr;
2135       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2136       abfd->flags |= HAS_SYMS;
2137 
2138       /* Besides being a symbol table, we also treat this as a regular
2139 	 section, so that objcopy can handle it.  */
2140       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2141       goto success;
2142 
2143     case SHT_SYMTAB_SHNDX:	/* Symbol section indices when >64k sections.  */
2144       {
2145 	elf_section_list * entry;
2146 
2147 	for (entry = elf_symtab_shndx_list (abfd); entry != NULL; entry = entry->next)
2148 	  if (entry->ndx == shindex)
2149 	    goto success;
2150 
2151 	entry = bfd_alloc (abfd, sizeof * entry);
2152 	if (entry == NULL)
2153 	  goto fail;
2154 	entry->ndx = shindex;
2155 	entry->hdr = * hdr;
2156 	entry->next = elf_symtab_shndx_list (abfd);
2157 	elf_symtab_shndx_list (abfd) = entry;
2158 	elf_elfsections (abfd)[shindex] = & entry->hdr;
2159 	goto success;
2160       }
2161 
2162     case SHT_STRTAB:		/* A string table.  */
2163       if (hdr->bfd_section != NULL)
2164 	goto success;
2165 
2166       if (ehdr->e_shstrndx == shindex)
2167 	{
2168 	  elf_tdata (abfd)->shstrtab_hdr = *hdr;
2169 	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
2170 	  goto success;
2171 	}
2172 
2173       if (elf_elfsections (abfd)[elf_onesymtab (abfd)]->sh_link == shindex)
2174 	{
2175 	symtab_strtab:
2176 	  elf_tdata (abfd)->strtab_hdr = *hdr;
2177 	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->strtab_hdr;
2178 	  goto success;
2179 	}
2180 
2181       if (elf_elfsections (abfd)[elf_dynsymtab (abfd)]->sh_link == shindex)
2182 	{
2183 	dynsymtab_strtab:
2184 	  elf_tdata (abfd)->dynstrtab_hdr = *hdr;
2185 	  hdr = &elf_tdata (abfd)->dynstrtab_hdr;
2186 	  elf_elfsections (abfd)[shindex] = hdr;
2187 	  /* We also treat this as a regular section, so that objcopy
2188 	     can handle it.  */
2189 	  ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
2190 						 shindex);
2191 	  goto success;
2192 	}
2193 
2194       /* If the string table isn't one of the above, then treat it as a
2195 	 regular section.  We need to scan all the headers to be sure,
2196 	 just in case this strtab section appeared before the above.  */
2197       if (elf_onesymtab (abfd) == 0 || elf_dynsymtab (abfd) == 0)
2198 	{
2199 	  unsigned int i, num_sec;
2200 
2201 	  num_sec = elf_numsections (abfd);
2202 	  for (i = 1; i < num_sec; i++)
2203 	    {
2204 	      Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
2205 	      if (hdr2->sh_link == shindex)
2206 		{
2207 		  /* Prevent endless recursion on broken objects.  */
2208 		  if (i == shindex)
2209 		    goto fail;
2210 		  if (! bfd_section_from_shdr (abfd, i))
2211 		    goto fail;
2212 		  if (elf_onesymtab (abfd) == i)
2213 		    goto symtab_strtab;
2214 		  if (elf_dynsymtab (abfd) == i)
2215 		    goto dynsymtab_strtab;
2216 		}
2217 	    }
2218 	}
2219       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2220       goto success;
2221 
2222     case SHT_REL:
2223     case SHT_RELA:
2224       /* *These* do a lot of work -- but build no sections!  */
2225       {
2226 	asection *target_sect;
2227 	Elf_Internal_Shdr *hdr2, **p_hdr;
2228 	unsigned int num_sec = elf_numsections (abfd);
2229 	struct bfd_elf_section_data *esdt;
2230 
2231 	if (hdr->sh_entsize
2232 	    != (bfd_size_type) (hdr->sh_type == SHT_REL
2233 				? bed->s->sizeof_rel : bed->s->sizeof_rela))
2234 	  goto fail;
2235 
2236 	/* Check for a bogus link to avoid crashing.  */
2237 	if (hdr->sh_link >= num_sec)
2238 	  {
2239 	    ((*_bfd_error_handler)
2240 	     (_("%B: invalid link %lu for reloc section %s (index %u)"),
2241 	      abfd, hdr->sh_link, name, shindex));
2242 	    ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
2243 						   shindex);
2244 	    goto success;
2245 	  }
2246 
2247 	/* For some incomprehensible reason Oracle distributes
2248 	   libraries for Solaris in which some of the objects have
2249 	   bogus sh_link fields.  It would be nice if we could just
2250 	   reject them, but, unfortunately, some people need to use
2251 	   them.  We scan through the section headers; if we find only
2252 	   one suitable symbol table, we clobber the sh_link to point
2253 	   to it.  I hope this doesn't break anything.
2254 
2255 	   Don't do it on executable nor shared library.  */
2256 	if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0
2257 	    && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_SYMTAB
2258 	    && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_DYNSYM)
2259 	  {
2260 	    unsigned int scan;
2261 	    int found;
2262 
2263 	    found = 0;
2264 	    for (scan = 1; scan < num_sec; scan++)
2265 	      {
2266 		if (elf_elfsections (abfd)[scan]->sh_type == SHT_SYMTAB
2267 		    || elf_elfsections (abfd)[scan]->sh_type == SHT_DYNSYM)
2268 		  {
2269 		    if (found != 0)
2270 		      {
2271 			found = 0;
2272 			break;
2273 		      }
2274 		    found = scan;
2275 		  }
2276 	      }
2277 	    if (found != 0)
2278 	      hdr->sh_link = found;
2279 	  }
2280 
2281 	/* Get the symbol table.  */
2282 	if ((elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_SYMTAB
2283 	     || elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_DYNSYM)
2284 	    && ! bfd_section_from_shdr (abfd, hdr->sh_link))
2285 	  goto fail;
2286 
2287 	/* If this reloc section does not use the main symbol table we
2288 	   don't treat it as a reloc section.  BFD can't adequately
2289 	   represent such a section, so at least for now, we don't
2290 	   try.  We just present it as a normal section.  We also
2291 	   can't use it as a reloc section if it points to the null
2292 	   section, an invalid section, another reloc section, or its
2293 	   sh_link points to the null section.  */
2294 	if (hdr->sh_link != elf_onesymtab (abfd)
2295 	    || hdr->sh_link == SHN_UNDEF
2296 	    || hdr->sh_info == SHN_UNDEF
2297 	    || hdr->sh_info >= num_sec
2298 	    || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_REL
2299 	    || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_RELA)
2300 	  {
2301 	    ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
2302 						   shindex);
2303 	    goto success;
2304 	  }
2305 
2306 	if (! bfd_section_from_shdr (abfd, hdr->sh_info))
2307 	  goto fail;
2308 
2309 	target_sect = bfd_section_from_elf_index (abfd, hdr->sh_info);
2310 	if (target_sect == NULL)
2311 	  goto fail;
2312 
2313 	esdt = elf_section_data (target_sect);
2314 	if (hdr->sh_type == SHT_RELA)
2315 	  p_hdr = &esdt->rela.hdr;
2316 	else
2317 	  p_hdr = &esdt->rel.hdr;
2318 
2319 	/* PR 17512: file: 0b4f81b7.  */
2320 	if (*p_hdr != NULL)
2321 	  goto fail;
2322 	hdr2 = (Elf_Internal_Shdr *) bfd_alloc (abfd, sizeof (*hdr2));
2323 	if (hdr2 == NULL)
2324 	  goto fail;
2325 	*hdr2 = *hdr;
2326 	*p_hdr = hdr2;
2327 	elf_elfsections (abfd)[shindex] = hdr2;
2328 	target_sect->reloc_count += NUM_SHDR_ENTRIES (hdr);
2329 	target_sect->flags |= SEC_RELOC;
2330 	target_sect->relocation = NULL;
2331 	target_sect->rel_filepos = hdr->sh_offset;
2332 	/* In the section to which the relocations apply, mark whether
2333 	   its relocations are of the REL or RELA variety.  */
2334 	if (hdr->sh_size != 0)
2335 	  {
2336 	    if (hdr->sh_type == SHT_RELA)
2337 	      target_sect->use_rela_p = 1;
2338 	  }
2339 	abfd->flags |= HAS_RELOC;
2340 	goto success;
2341       }
2342 
2343     case SHT_GNU_verdef:
2344       elf_dynverdef (abfd) = shindex;
2345       elf_tdata (abfd)->dynverdef_hdr = *hdr;
2346       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2347       goto success;
2348 
2349     case SHT_GNU_versym:
2350       if (hdr->sh_entsize != sizeof (Elf_External_Versym))
2351 	goto fail;
2352 
2353       elf_dynversym (abfd) = shindex;
2354       elf_tdata (abfd)->dynversym_hdr = *hdr;
2355       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2356       goto success;
2357 
2358     case SHT_GNU_verneed:
2359       elf_dynverref (abfd) = shindex;
2360       elf_tdata (abfd)->dynverref_hdr = *hdr;
2361       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2362       goto success;
2363 
2364     case SHT_SHLIB:
2365       goto success;
2366 
2367     case SHT_GROUP:
2368       if (! IS_VALID_GROUP_SECTION_HEADER (hdr, GRP_ENTRY_SIZE))
2369 	goto fail;
2370 
2371       if (!_bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
2372 	goto fail;
2373 
2374       if (hdr->contents != NULL)
2375 	{
2376 	  Elf_Internal_Group *idx = (Elf_Internal_Group *) hdr->contents;
2377 	  unsigned int n_elt = hdr->sh_size / sizeof (* idx);
2378 	  asection *s;
2379 
2380 	  if (n_elt == 0)
2381 	    goto fail;
2382 	  if (idx->flags & GRP_COMDAT)
2383 	    hdr->bfd_section->flags
2384 	      |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
2385 
2386 	  /* We try to keep the same section order as it comes in.  */
2387 	  idx += n_elt;
2388 
2389 	  while (--n_elt != 0)
2390 	    {
2391 	      --idx;
2392 
2393 	      if (idx->shdr != NULL
2394 		  && (s = idx->shdr->bfd_section) != NULL
2395 		  && elf_next_in_group (s) != NULL)
2396 		{
2397 		  elf_next_in_group (hdr->bfd_section) = s;
2398 		  break;
2399 		}
2400 	    }
2401 	}
2402       goto success;
2403 
2404     default:
2405       /* Possibly an attributes section.  */
2406       if (hdr->sh_type == SHT_GNU_ATTRIBUTES
2407 	  || hdr->sh_type == bed->obj_attrs_section_type)
2408 	{
2409 	  if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
2410 	    goto fail;
2411 	  _bfd_elf_parse_attributes (abfd, hdr);
2412 	  goto success;
2413 	}
2414 
2415       /* Check for any processor-specific section types.  */
2416       if (bed->elf_backend_section_from_shdr (abfd, hdr, name, shindex))
2417 	goto success;
2418 
2419       if (hdr->sh_type >= SHT_LOUSER && hdr->sh_type <= SHT_HIUSER)
2420 	{
2421 	  if ((hdr->sh_flags & SHF_ALLOC) != 0)
2422 	    /* FIXME: How to properly handle allocated section reserved
2423 	       for applications?  */
2424 	    (*_bfd_error_handler)
2425 	      (_("%B: don't know how to handle allocated, application "
2426 		 "specific section `%s' [0x%8x]"),
2427 	       abfd, name, hdr->sh_type);
2428 	  else
2429 	    {
2430 	      /* Allow sections reserved for applications.  */
2431 	      ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
2432 						     shindex);
2433 	      goto success;
2434 	    }
2435 	}
2436       else if (hdr->sh_type >= SHT_LOPROC
2437 	       && hdr->sh_type <= SHT_HIPROC)
2438 	/* FIXME: We should handle this section.  */
2439 	(*_bfd_error_handler)
2440 	  (_("%B: don't know how to handle processor specific section "
2441 	     "`%s' [0x%8x]"),
2442 	   abfd, name, hdr->sh_type);
2443       else if (hdr->sh_type >= SHT_LOOS && hdr->sh_type <= SHT_HIOS)
2444 	{
2445 	  /* Unrecognised OS-specific sections.  */
2446 	  if ((hdr->sh_flags & SHF_OS_NONCONFORMING) != 0)
2447 	    /* SHF_OS_NONCONFORMING indicates that special knowledge is
2448 	       required to correctly process the section and the file should
2449 	       be rejected with an error message.  */
2450 	    (*_bfd_error_handler)
2451 	      (_("%B: don't know how to handle OS specific section "
2452 		 "`%s' [0x%8x]"),
2453 	       abfd, name, hdr->sh_type);
2454 	  else
2455 	    {
2456 	      /* Otherwise it should be processed.  */
2457 	      ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
2458 	      goto success;
2459 	    }
2460 	}
2461       else
2462 	/* FIXME: We should handle this section.  */
2463 	(*_bfd_error_handler)
2464 	  (_("%B: don't know how to handle section `%s' [0x%8x]"),
2465 	   abfd, name, hdr->sh_type);
2466 
2467       goto fail;
2468     }
2469 
2470  fail:
2471   ret = FALSE;
2472  success:
2473   if (sections_being_created && sections_being_created_abfd == abfd)
2474     sections_being_created [shindex] = FALSE;
2475   if (-- nesting == 0)
2476     {
2477       sections_being_created = NULL;
2478       sections_being_created_abfd = abfd;
2479     }
2480   return ret;
2481 }
2482 
2483 /* Return the local symbol specified by ABFD, R_SYMNDX.  */
2484 
2485 Elf_Internal_Sym *
2486 bfd_sym_from_r_symndx (struct sym_cache *cache,
2487 		       bfd *abfd,
2488 		       unsigned long r_symndx)
2489 {
2490   unsigned int ent = r_symndx % LOCAL_SYM_CACHE_SIZE;
2491 
2492   if (cache->abfd != abfd || cache->indx[ent] != r_symndx)
2493     {
2494       Elf_Internal_Shdr *symtab_hdr;
2495       unsigned char esym[sizeof (Elf64_External_Sym)];
2496       Elf_External_Sym_Shndx eshndx;
2497 
2498       symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2499       if (bfd_elf_get_elf_syms (abfd, symtab_hdr, 1, r_symndx,
2500 				&cache->sym[ent], esym, &eshndx) == NULL)
2501 	return NULL;
2502 
2503       if (cache->abfd != abfd)
2504 	{
2505 	  memset (cache->indx, -1, sizeof (cache->indx));
2506 	  cache->abfd = abfd;
2507 	}
2508       cache->indx[ent] = r_symndx;
2509     }
2510 
2511   return &cache->sym[ent];
2512 }
2513 
2514 /* Given an ELF section number, retrieve the corresponding BFD
2515    section.  */
2516 
2517 asection *
2518 bfd_section_from_elf_index (bfd *abfd, unsigned int sec_index)
2519 {
2520   if (sec_index >= elf_numsections (abfd))
2521     return NULL;
2522   return elf_elfsections (abfd)[sec_index]->bfd_section;
2523 }
2524 
2525 static const struct bfd_elf_special_section special_sections_b[] =
2526 {
2527   { STRING_COMMA_LEN (".bss"), -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE },
2528   { NULL,                   0,  0, 0,            0 }
2529 };
2530 
2531 static const struct bfd_elf_special_section special_sections_c[] =
2532 {
2533   { STRING_COMMA_LEN (".comment"), 0, SHT_PROGBITS, 0 },
2534   { NULL,                       0, 0, 0,            0 }
2535 };
2536 
2537 static const struct bfd_elf_special_section special_sections_d[] =
2538 {
2539   { STRING_COMMA_LEN (".data"),         -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
2540   { STRING_COMMA_LEN (".data1"),         0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
2541   /* There are more DWARF sections than these, but they needn't be added here
2542      unless you have to cope with broken compilers that don't emit section
2543      attributes or you want to help the user writing assembler.  */
2544   { STRING_COMMA_LEN (".debug"),         0, SHT_PROGBITS, 0 },
2545   { STRING_COMMA_LEN (".debug_line"),    0, SHT_PROGBITS, 0 },
2546   { STRING_COMMA_LEN (".debug_info"),    0, SHT_PROGBITS, 0 },
2547   { STRING_COMMA_LEN (".debug_abbrev"),  0, SHT_PROGBITS, 0 },
2548   { STRING_COMMA_LEN (".debug_aranges"), 0, SHT_PROGBITS, 0 },
2549   { STRING_COMMA_LEN (".dynamic"),       0, SHT_DYNAMIC,  SHF_ALLOC },
2550   { STRING_COMMA_LEN (".dynstr"),        0, SHT_STRTAB,   SHF_ALLOC },
2551   { STRING_COMMA_LEN (".dynsym"),        0, SHT_DYNSYM,   SHF_ALLOC },
2552   { NULL,                      0,        0, 0,            0 }
2553 };
2554 
2555 static const struct bfd_elf_special_section special_sections_f[] =
2556 {
2557   { STRING_COMMA_LEN (".fini"),       0, SHT_PROGBITS,   SHF_ALLOC + SHF_EXECINSTR },
2558   { STRING_COMMA_LEN (".fini_array"), 0, SHT_FINI_ARRAY, SHF_ALLOC + SHF_WRITE },
2559   { NULL,                          0, 0, 0,              0 }
2560 };
2561 
2562 static const struct bfd_elf_special_section special_sections_g[] =
2563 {
2564   { STRING_COMMA_LEN (".gnu.linkonce.b"), -2, SHT_NOBITS,      SHF_ALLOC + SHF_WRITE },
2565   { STRING_COMMA_LEN (".gnu.lto_"),       -1, SHT_PROGBITS,    SHF_EXCLUDE },
2566   { STRING_COMMA_LEN (".got"),             0, SHT_PROGBITS,    SHF_ALLOC + SHF_WRITE },
2567   { STRING_COMMA_LEN (".gnu.version"),     0, SHT_GNU_versym,  0 },
2568   { STRING_COMMA_LEN (".gnu.version_d"),   0, SHT_GNU_verdef,  0 },
2569   { STRING_COMMA_LEN (".gnu.version_r"),   0, SHT_GNU_verneed, 0 },
2570   { STRING_COMMA_LEN (".gnu.liblist"),     0, SHT_GNU_LIBLIST, SHF_ALLOC },
2571   { STRING_COMMA_LEN (".gnu.conflict"),    0, SHT_RELA,        SHF_ALLOC },
2572   { STRING_COMMA_LEN (".gnu.hash"),        0, SHT_GNU_HASH,    SHF_ALLOC },
2573   { NULL,                        0,        0, 0,               0 }
2574 };
2575 
2576 static const struct bfd_elf_special_section special_sections_h[] =
2577 {
2578   { STRING_COMMA_LEN (".hash"), 0, SHT_HASH,     SHF_ALLOC },
2579   { NULL,                    0, 0, 0,            0 }
2580 };
2581 
2582 static const struct bfd_elf_special_section special_sections_i[] =
2583 {
2584   { STRING_COMMA_LEN (".init"),       0, SHT_PROGBITS,   SHF_ALLOC + SHF_EXECINSTR },
2585   { STRING_COMMA_LEN (".init_array"), 0, SHT_INIT_ARRAY, SHF_ALLOC + SHF_WRITE },
2586   { STRING_COMMA_LEN (".interp"),     0, SHT_PROGBITS,   0 },
2587   { NULL,                      0,     0, 0,              0 }
2588 };
2589 
2590 static const struct bfd_elf_special_section special_sections_l[] =
2591 {
2592   { STRING_COMMA_LEN (".line"), 0, SHT_PROGBITS, 0 },
2593   { NULL,                    0, 0, 0,            0 }
2594 };
2595 
2596 static const struct bfd_elf_special_section special_sections_n[] =
2597 {
2598   { STRING_COMMA_LEN (".note.GNU-stack"), 0, SHT_PROGBITS, 0 },
2599   { STRING_COMMA_LEN (".note"),          -1, SHT_NOTE,     0 },
2600   { NULL,                    0,           0, 0,            0 }
2601 };
2602 
2603 static const struct bfd_elf_special_section special_sections_p[] =
2604 {
2605   { STRING_COMMA_LEN (".preinit_array"), 0, SHT_PREINIT_ARRAY, SHF_ALLOC + SHF_WRITE },
2606   { STRING_COMMA_LEN (".plt"),           0, SHT_PROGBITS,      SHF_ALLOC + SHF_EXECINSTR },
2607   { NULL,                   0,           0, 0,                 0 }
2608 };
2609 
2610 static const struct bfd_elf_special_section special_sections_r[] =
2611 {
2612   { STRING_COMMA_LEN (".rodata"), -2, SHT_PROGBITS, SHF_ALLOC },
2613   { STRING_COMMA_LEN (".rodata1"), 0, SHT_PROGBITS, SHF_ALLOC },
2614   { STRING_COMMA_LEN (".rela"),   -1, SHT_RELA,     0 },
2615   { STRING_COMMA_LEN (".rel"),    -1, SHT_REL,      0 },
2616   { NULL,                   0,     0, 0,            0 }
2617 };
2618 
2619 static const struct bfd_elf_special_section special_sections_s[] =
2620 {
2621   { STRING_COMMA_LEN (".shstrtab"), 0, SHT_STRTAB, 0 },
2622   { STRING_COMMA_LEN (".strtab"),   0, SHT_STRTAB, 0 },
2623   { STRING_COMMA_LEN (".symtab"),   0, SHT_SYMTAB, 0 },
2624   /* See struct bfd_elf_special_section declaration for the semantics of
2625      this special case where .prefix_length != strlen (.prefix).  */
2626   { ".stabstr",			5,  3, SHT_STRTAB, 0 },
2627   { NULL,                       0,  0, 0,          0 }
2628 };
2629 
2630 static const struct bfd_elf_special_section special_sections_t[] =
2631 {
2632   { STRING_COMMA_LEN (".text"),  -2, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
2633   { STRING_COMMA_LEN (".tbss"),  -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE + SHF_TLS },
2634   { STRING_COMMA_LEN (".tdata"), -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_TLS },
2635   { NULL,                     0,  0, 0,            0 }
2636 };
2637 
2638 static const struct bfd_elf_special_section special_sections_z[] =
2639 {
2640   { STRING_COMMA_LEN (".zdebug_line"),    0, SHT_PROGBITS, 0 },
2641   { STRING_COMMA_LEN (".zdebug_info"),    0, SHT_PROGBITS, 0 },
2642   { STRING_COMMA_LEN (".zdebug_abbrev"),  0, SHT_PROGBITS, 0 },
2643   { STRING_COMMA_LEN (".zdebug_aranges"), 0, SHT_PROGBITS, 0 },
2644   { NULL,                     0,  0, 0,            0 }
2645 };
2646 
2647 static const struct bfd_elf_special_section * const special_sections[] =
2648 {
2649   special_sections_b,		/* 'b' */
2650   special_sections_c,		/* 'c' */
2651   special_sections_d,		/* 'd' */
2652   NULL,				/* 'e' */
2653   special_sections_f,		/* 'f' */
2654   special_sections_g,		/* 'g' */
2655   special_sections_h,		/* 'h' */
2656   special_sections_i,		/* 'i' */
2657   NULL,				/* 'j' */
2658   NULL,				/* 'k' */
2659   special_sections_l,		/* 'l' */
2660   NULL,				/* 'm' */
2661   special_sections_n,		/* 'n' */
2662   NULL,				/* 'o' */
2663   special_sections_p,		/* 'p' */
2664   NULL,				/* 'q' */
2665   special_sections_r,		/* 'r' */
2666   special_sections_s,		/* 's' */
2667   special_sections_t,		/* 't' */
2668   NULL,				/* 'u' */
2669   NULL,				/* 'v' */
2670   NULL,				/* 'w' */
2671   NULL,				/* 'x' */
2672   NULL,				/* 'y' */
2673   special_sections_z		/* 'z' */
2674 };
2675 
2676 const struct bfd_elf_special_section *
2677 _bfd_elf_get_special_section (const char *name,
2678 			      const struct bfd_elf_special_section *spec,
2679 			      unsigned int rela)
2680 {
2681   int i;
2682   int len;
2683 
2684   len = strlen (name);
2685 
2686   for (i = 0; spec[i].prefix != NULL; i++)
2687     {
2688       int suffix_len;
2689       int prefix_len = spec[i].prefix_length;
2690 
2691       if (len < prefix_len)
2692 	continue;
2693       if (memcmp (name, spec[i].prefix, prefix_len) != 0)
2694 	continue;
2695 
2696       suffix_len = spec[i].suffix_length;
2697       if (suffix_len <= 0)
2698 	{
2699 	  if (name[prefix_len] != 0)
2700 	    {
2701 	      if (suffix_len == 0)
2702 		continue;
2703 	      if (name[prefix_len] != '.'
2704 		  && (suffix_len == -2
2705 		      || (rela && spec[i].type == SHT_REL)))
2706 		continue;
2707 	    }
2708 	}
2709       else
2710 	{
2711 	  if (len < prefix_len + suffix_len)
2712 	    continue;
2713 	  if (memcmp (name + len - suffix_len,
2714 		      spec[i].prefix + prefix_len,
2715 		      suffix_len) != 0)
2716 	    continue;
2717 	}
2718       return &spec[i];
2719     }
2720 
2721   return NULL;
2722 }
2723 
2724 const struct bfd_elf_special_section *
2725 _bfd_elf_get_sec_type_attr (bfd *abfd, asection *sec)
2726 {
2727   int i;
2728   const struct bfd_elf_special_section *spec;
2729   const struct elf_backend_data *bed;
2730 
2731   /* See if this is one of the special sections.  */
2732   if (sec->name == NULL)
2733     return NULL;
2734 
2735   bed = get_elf_backend_data (abfd);
2736   spec = bed->special_sections;
2737   if (spec)
2738     {
2739       spec = _bfd_elf_get_special_section (sec->name,
2740 					   bed->special_sections,
2741 					   sec->use_rela_p);
2742       if (spec != NULL)
2743 	return spec;
2744     }
2745 
2746   if (sec->name[0] != '.')
2747     return NULL;
2748 
2749   i = sec->name[1] - 'b';
2750   if (i < 0 || i > 'z' - 'b')
2751     return NULL;
2752 
2753   spec = special_sections[i];
2754 
2755   if (spec == NULL)
2756     return NULL;
2757 
2758   return _bfd_elf_get_special_section (sec->name, spec, sec->use_rela_p);
2759 }
2760 
2761 bfd_boolean
2762 _bfd_elf_new_section_hook (bfd *abfd, asection *sec)
2763 {
2764   struct bfd_elf_section_data *sdata;
2765   const struct elf_backend_data *bed;
2766   const struct bfd_elf_special_section *ssect;
2767 
2768   sdata = (struct bfd_elf_section_data *) sec->used_by_bfd;
2769   if (sdata == NULL)
2770     {
2771       sdata = (struct bfd_elf_section_data *) bfd_zalloc (abfd,
2772                                                           sizeof (*sdata));
2773       if (sdata == NULL)
2774 	return FALSE;
2775       sec->used_by_bfd = sdata;
2776     }
2777 
2778   /* Indicate whether or not this section should use RELA relocations.  */
2779   bed = get_elf_backend_data (abfd);
2780   sec->use_rela_p = bed->default_use_rela_p;
2781 
2782   /* When we read a file, we don't need to set ELF section type and
2783      flags.  They will be overridden in _bfd_elf_make_section_from_shdr
2784      anyway.  We will set ELF section type and flags for all linker
2785      created sections.  If user specifies BFD section flags, we will
2786      set ELF section type and flags based on BFD section flags in
2787      elf_fake_sections.  Special handling for .init_array/.fini_array
2788      output sections since they may contain .ctors/.dtors input
2789      sections.  We don't want _bfd_elf_init_private_section_data to
2790      copy ELF section type from .ctors/.dtors input sections.  */
2791   if (abfd->direction != read_direction
2792       || (sec->flags & SEC_LINKER_CREATED) != 0)
2793     {
2794       ssect = (*bed->get_sec_type_attr) (abfd, sec);
2795       if (ssect != NULL
2796 	  && (!sec->flags
2797 	      || (sec->flags & SEC_LINKER_CREATED) != 0
2798 	      || ssect->type == SHT_INIT_ARRAY
2799 	      || ssect->type == SHT_FINI_ARRAY))
2800 	{
2801 	  elf_section_type (sec) = ssect->type;
2802 	  elf_section_flags (sec) = ssect->attr;
2803 	}
2804     }
2805 
2806   return _bfd_generic_new_section_hook (abfd, sec);
2807 }
2808 
2809 /* Create a new bfd section from an ELF program header.
2810 
2811    Since program segments have no names, we generate a synthetic name
2812    of the form segment<NUM>, where NUM is generally the index in the
2813    program header table.  For segments that are split (see below) we
2814    generate the names segment<NUM>a and segment<NUM>b.
2815 
2816    Note that some program segments may have a file size that is different than
2817    (less than) the memory size.  All this means is that at execution the
2818    system must allocate the amount of memory specified by the memory size,
2819    but only initialize it with the first "file size" bytes read from the
2820    file.  This would occur for example, with program segments consisting
2821    of combined data+bss.
2822 
2823    To handle the above situation, this routine generates TWO bfd sections
2824    for the single program segment.  The first has the length specified by
2825    the file size of the segment, and the second has the length specified
2826    by the difference between the two sizes.  In effect, the segment is split
2827    into its initialized and uninitialized parts.
2828 
2829  */
2830 
2831 bfd_boolean
2832 _bfd_elf_make_section_from_phdr (bfd *abfd,
2833 				 Elf_Internal_Phdr *hdr,
2834 				 int hdr_index,
2835 				 const char *type_name)
2836 {
2837   asection *newsect;
2838   char *name;
2839   char namebuf[64];
2840   size_t len;
2841   int split;
2842 
2843   split = ((hdr->p_memsz > 0)
2844 	    && (hdr->p_filesz > 0)
2845 	    && (hdr->p_memsz > hdr->p_filesz));
2846 
2847   if (hdr->p_filesz > 0)
2848     {
2849       sprintf (namebuf, "%s%d%s", type_name, hdr_index, split ? "a" : "");
2850       len = strlen (namebuf) + 1;
2851       name = (char *) bfd_alloc (abfd, len);
2852       if (!name)
2853 	return FALSE;
2854       memcpy (name, namebuf, len);
2855       newsect = bfd_make_section (abfd, name);
2856       if (newsect == NULL)
2857 	return FALSE;
2858       newsect->vma = hdr->p_vaddr;
2859       newsect->lma = hdr->p_paddr;
2860       newsect->size = hdr->p_filesz;
2861       newsect->filepos = hdr->p_offset;
2862       newsect->flags |= SEC_HAS_CONTENTS;
2863       newsect->alignment_power = bfd_log2 (hdr->p_align);
2864       if (hdr->p_type == PT_LOAD)
2865 	{
2866 	  newsect->flags |= SEC_ALLOC;
2867 	  newsect->flags |= SEC_LOAD;
2868 	  if (hdr->p_flags & PF_X)
2869 	    {
2870 	      /* FIXME: all we known is that it has execute PERMISSION,
2871 		 may be data.  */
2872 	      newsect->flags |= SEC_CODE;
2873 	    }
2874 	}
2875       if (!(hdr->p_flags & PF_W))
2876 	{
2877 	  newsect->flags |= SEC_READONLY;
2878 	}
2879     }
2880 
2881   if (hdr->p_memsz > hdr->p_filesz)
2882     {
2883       bfd_vma align;
2884 
2885       sprintf (namebuf, "%s%d%s", type_name, hdr_index, split ? "b" : "");
2886       len = strlen (namebuf) + 1;
2887       name = (char *) bfd_alloc (abfd, len);
2888       if (!name)
2889 	return FALSE;
2890       memcpy (name, namebuf, len);
2891       newsect = bfd_make_section (abfd, name);
2892       if (newsect == NULL)
2893 	return FALSE;
2894       newsect->vma = hdr->p_vaddr + hdr->p_filesz;
2895       newsect->lma = hdr->p_paddr + hdr->p_filesz;
2896       newsect->size = hdr->p_memsz - hdr->p_filesz;
2897       newsect->filepos = hdr->p_offset + hdr->p_filesz;
2898       align = newsect->vma & -newsect->vma;
2899       if (align == 0 || align > hdr->p_align)
2900 	align = hdr->p_align;
2901       newsect->alignment_power = bfd_log2 (align);
2902       if (hdr->p_type == PT_LOAD)
2903 	{
2904 	  /* Hack for gdb.  Segments that have not been modified do
2905 	     not have their contents written to a core file, on the
2906 	     assumption that a debugger can find the contents in the
2907 	     executable.  We flag this case by setting the fake
2908 	     section size to zero.  Note that "real" bss sections will
2909 	     always have their contents dumped to the core file.  */
2910 	  if (bfd_get_format (abfd) == bfd_core)
2911 	    newsect->size = 0;
2912 	  newsect->flags |= SEC_ALLOC;
2913 	  if (hdr->p_flags & PF_X)
2914 	    newsect->flags |= SEC_CODE;
2915 	}
2916       if (!(hdr->p_flags & PF_W))
2917 	newsect->flags |= SEC_READONLY;
2918     }
2919 
2920   return TRUE;
2921 }
2922 
2923 bfd_boolean
2924 bfd_section_from_phdr (bfd *abfd, Elf_Internal_Phdr *hdr, int hdr_index)
2925 {
2926   const struct elf_backend_data *bed;
2927 
2928   switch (hdr->p_type)
2929     {
2930     case PT_NULL:
2931       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "null");
2932 
2933     case PT_LOAD:
2934       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "load");
2935 
2936     case PT_DYNAMIC:
2937       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "dynamic");
2938 
2939     case PT_INTERP:
2940       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "interp");
2941 
2942     case PT_NOTE:
2943       if (! _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "note"))
2944 	return FALSE;
2945       if (! elf_read_notes (abfd, hdr->p_offset, hdr->p_filesz))
2946 	return FALSE;
2947       return TRUE;
2948 
2949     case PT_SHLIB:
2950       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "shlib");
2951 
2952     case PT_PHDR:
2953       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "phdr");
2954 
2955     case PT_GNU_EH_FRAME:
2956       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index,
2957 					      "eh_frame_hdr");
2958 
2959     case PT_GNU_STACK:
2960       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "stack");
2961 
2962     case PT_GNU_RELRO:
2963       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "relro");
2964 
2965     default:
2966       /* Check for any processor-specific program segment types.  */
2967       bed = get_elf_backend_data (abfd);
2968       return bed->elf_backend_section_from_phdr (abfd, hdr, hdr_index, "proc");
2969     }
2970 }
2971 
2972 /* Return the REL_HDR for SEC, assuming there is only a single one, either
2973    REL or RELA.  */
2974 
2975 Elf_Internal_Shdr *
2976 _bfd_elf_single_rel_hdr (asection *sec)
2977 {
2978   if (elf_section_data (sec)->rel.hdr)
2979     {
2980       BFD_ASSERT (elf_section_data (sec)->rela.hdr == NULL);
2981       return elf_section_data (sec)->rel.hdr;
2982     }
2983   else
2984     return elf_section_data (sec)->rela.hdr;
2985 }
2986 
2987 static bfd_boolean
2988 _bfd_elf_set_reloc_sh_name (bfd *abfd,
2989 			    Elf_Internal_Shdr *rel_hdr,
2990 			    const char *sec_name,
2991 			    bfd_boolean use_rela_p)
2992 {
2993   char *name = (char *) bfd_alloc (abfd,
2994 				   sizeof ".rela" + strlen (sec_name));
2995   if (name == NULL)
2996     return FALSE;
2997 
2998   sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", sec_name);
2999   rel_hdr->sh_name =
3000     (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd), name,
3001 					FALSE);
3002   if (rel_hdr->sh_name == (unsigned int) -1)
3003     return FALSE;
3004 
3005   return TRUE;
3006 }
3007 
3008 /* Allocate and initialize a section-header for a new reloc section,
3009    containing relocations against ASECT.  It is stored in RELDATA.  If
3010    USE_RELA_P is TRUE, we use RELA relocations; otherwise, we use REL
3011    relocations.  */
3012 
3013 static bfd_boolean
3014 _bfd_elf_init_reloc_shdr (bfd *abfd,
3015 			  struct bfd_elf_section_reloc_data *reldata,
3016 			  const char *sec_name,
3017 			  bfd_boolean use_rela_p,
3018 			  bfd_boolean delay_st_name_p)
3019 {
3020   Elf_Internal_Shdr *rel_hdr;
3021   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3022 
3023   BFD_ASSERT (reldata->hdr == NULL);
3024   rel_hdr = bfd_zalloc (abfd, sizeof (*rel_hdr));
3025   reldata->hdr = rel_hdr;
3026 
3027   if (delay_st_name_p)
3028     rel_hdr->sh_name = (unsigned int) -1;
3029   else if (!_bfd_elf_set_reloc_sh_name (abfd, rel_hdr, sec_name,
3030 					use_rela_p))
3031     return FALSE;
3032   rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
3033   rel_hdr->sh_entsize = (use_rela_p
3034 			 ? bed->s->sizeof_rela
3035 			 : bed->s->sizeof_rel);
3036   rel_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
3037   rel_hdr->sh_flags = 0;
3038   rel_hdr->sh_addr = 0;
3039   rel_hdr->sh_size = 0;
3040   rel_hdr->sh_offset = 0;
3041 
3042   return TRUE;
3043 }
3044 
3045 /* Return the default section type based on the passed in section flags.  */
3046 
3047 int
3048 bfd_elf_get_default_section_type (flagword flags)
3049 {
3050   if ((flags & SEC_ALLOC) != 0
3051       && (flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
3052     return SHT_NOBITS;
3053   return SHT_PROGBITS;
3054 }
3055 
3056 struct fake_section_arg
3057 {
3058   struct bfd_link_info *link_info;
3059   bfd_boolean failed;
3060 };
3061 
3062 /* Set up an ELF internal section header for a section.  */
3063 
3064 static void
3065 elf_fake_sections (bfd *abfd, asection *asect, void *fsarg)
3066 {
3067   struct fake_section_arg *arg = (struct fake_section_arg *)fsarg;
3068   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3069   struct bfd_elf_section_data *esd = elf_section_data (asect);
3070   Elf_Internal_Shdr *this_hdr;
3071   unsigned int sh_type;
3072   const char *name = asect->name;
3073   bfd_boolean delay_st_name_p = FALSE;
3074 
3075   if (arg->failed)
3076     {
3077       /* We already failed; just get out of the bfd_map_over_sections
3078 	 loop.  */
3079       return;
3080     }
3081 
3082   this_hdr = &esd->this_hdr;
3083 
3084   if (arg->link_info)
3085     {
3086       /* ld: compress DWARF debug sections with names: .debug_*.  */
3087       if ((arg->link_info->compress_debug & COMPRESS_DEBUG)
3088 	  && (asect->flags & SEC_DEBUGGING)
3089 	  && name[1] == 'd'
3090 	  && name[6] == '_')
3091 	{
3092 	  /* Set SEC_ELF_COMPRESS to indicate this section should be
3093 	     compressed.  */
3094 	  asect->flags |= SEC_ELF_COMPRESS;
3095 
3096 	  /* If this section will be compressed, delay adding setion
3097 	     name to section name section after it is compressed in
3098 	     _bfd_elf_assign_file_positions_for_non_load.  */
3099 	  delay_st_name_p = TRUE;
3100 	}
3101     }
3102   else if ((asect->flags & SEC_ELF_RENAME))
3103     {
3104       /* objcopy: rename output DWARF debug section.  */
3105       if ((abfd->flags & (BFD_DECOMPRESS | BFD_COMPRESS_GABI)))
3106 	{
3107 	  /* When we decompress or compress with SHF_COMPRESSED,
3108 	     convert section name from .zdebug_* to .debug_* if
3109 	     needed.  */
3110 	  if (name[1] == 'z')
3111 	    {
3112 	      char *new_name = convert_zdebug_to_debug (abfd, name);
3113 	      if (new_name == NULL)
3114 		{
3115 		  arg->failed = TRUE;
3116 		  return;
3117 		}
3118 	      name = new_name;
3119 	    }
3120 	}
3121       else if (asect->compress_status == COMPRESS_SECTION_DONE)
3122 	{
3123 	  /* PR binutils/18087: Compression does not always make a
3124 	     section smaller.  So only rename the section when
3125 	     compression has actually taken place.  If input section
3126 	     name is .zdebug_*, we should never compress it again.  */
3127 	  char *new_name = convert_debug_to_zdebug (abfd, name);
3128 	  if (new_name == NULL)
3129 	    {
3130 	      arg->failed = TRUE;
3131 	      return;
3132 	    }
3133 	  BFD_ASSERT (name[1] != 'z');
3134 	  name = new_name;
3135 	}
3136     }
3137 
3138   if (delay_st_name_p)
3139     this_hdr->sh_name = (unsigned int) -1;
3140   else
3141     {
3142       this_hdr->sh_name
3143 	= (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
3144 					      name, FALSE);
3145       if (this_hdr->sh_name == (unsigned int) -1)
3146 	{
3147 	  arg->failed = TRUE;
3148 	  return;
3149 	}
3150     }
3151 
3152   /* Don't clear sh_flags. Assembler may set additional bits.  */
3153 
3154   if ((asect->flags & SEC_ALLOC) != 0
3155       || asect->user_set_vma)
3156     this_hdr->sh_addr = asect->vma;
3157   else
3158     this_hdr->sh_addr = 0;
3159 
3160   this_hdr->sh_offset = 0;
3161   this_hdr->sh_size = asect->size;
3162   this_hdr->sh_link = 0;
3163   /* PR 17512: file: 0eb809fe, 8b0535ee.  */
3164   if (asect->alignment_power >= (sizeof (bfd_vma) * 8) - 1)
3165     {
3166       (*_bfd_error_handler)
3167 	(_("%B: error: Alignment power %d of section `%A' is too big"),
3168 	 abfd, asect, asect->alignment_power);
3169       arg->failed = TRUE;
3170       return;
3171     }
3172   this_hdr->sh_addralign = (bfd_vma) 1 << asect->alignment_power;
3173   /* The sh_entsize and sh_info fields may have been set already by
3174      copy_private_section_data.  */
3175 
3176   this_hdr->bfd_section = asect;
3177   this_hdr->contents = NULL;
3178 
3179   /* If the section type is unspecified, we set it based on
3180      asect->flags.  */
3181   if ((asect->flags & SEC_GROUP) != 0)
3182     sh_type = SHT_GROUP;
3183   else
3184     sh_type = bfd_elf_get_default_section_type (asect->flags);
3185 
3186   if (this_hdr->sh_type == SHT_NULL)
3187     this_hdr->sh_type = sh_type;
3188   else if (this_hdr->sh_type == SHT_NOBITS
3189 	   && sh_type == SHT_PROGBITS
3190 	   && (asect->flags & SEC_ALLOC) != 0)
3191     {
3192       /* Warn if we are changing a NOBITS section to PROGBITS, but
3193 	 allow the link to proceed.  This can happen when users link
3194 	 non-bss input sections to bss output sections, or emit data
3195 	 to a bss output section via a linker script.  */
3196       (*_bfd_error_handler)
3197 	(_("warning: section `%A' type changed to PROGBITS"), asect);
3198       this_hdr->sh_type = sh_type;
3199     }
3200 
3201   switch (this_hdr->sh_type)
3202     {
3203     default:
3204       break;
3205 
3206     case SHT_STRTAB:
3207     case SHT_NOTE:
3208     case SHT_NOBITS:
3209     case SHT_PROGBITS:
3210       break;
3211 
3212     case SHT_INIT_ARRAY:
3213     case SHT_FINI_ARRAY:
3214     case SHT_PREINIT_ARRAY:
3215       this_hdr->sh_entsize = bed->s->arch_size / 8;
3216       break;
3217 
3218     case SHT_HASH:
3219       this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
3220       break;
3221 
3222     case SHT_DYNSYM:
3223       this_hdr->sh_entsize = bed->s->sizeof_sym;
3224       break;
3225 
3226     case SHT_DYNAMIC:
3227       this_hdr->sh_entsize = bed->s->sizeof_dyn;
3228       break;
3229 
3230     case SHT_RELA:
3231       if (get_elf_backend_data (abfd)->may_use_rela_p)
3232 	this_hdr->sh_entsize = bed->s->sizeof_rela;
3233       break;
3234 
3235      case SHT_REL:
3236       if (get_elf_backend_data (abfd)->may_use_rel_p)
3237 	this_hdr->sh_entsize = bed->s->sizeof_rel;
3238       break;
3239 
3240      case SHT_GNU_versym:
3241       this_hdr->sh_entsize = sizeof (Elf_External_Versym);
3242       break;
3243 
3244      case SHT_GNU_verdef:
3245       this_hdr->sh_entsize = 0;
3246       /* objcopy or strip will copy over sh_info, but may not set
3247 	 cverdefs.  The linker will set cverdefs, but sh_info will be
3248 	 zero.  */
3249       if (this_hdr->sh_info == 0)
3250 	this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
3251       else
3252 	BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
3253 		    || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
3254       break;
3255 
3256     case SHT_GNU_verneed:
3257       this_hdr->sh_entsize = 0;
3258       /* objcopy or strip will copy over sh_info, but may not set
3259 	 cverrefs.  The linker will set cverrefs, but sh_info will be
3260 	 zero.  */
3261       if (this_hdr->sh_info == 0)
3262 	this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
3263       else
3264 	BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
3265 		    || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
3266       break;
3267 
3268     case SHT_GROUP:
3269       this_hdr->sh_entsize = GRP_ENTRY_SIZE;
3270       break;
3271 
3272     case SHT_GNU_HASH:
3273       this_hdr->sh_entsize = bed->s->arch_size == 64 ? 0 : 4;
3274       break;
3275     }
3276 
3277   if ((asect->flags & SEC_ALLOC) != 0)
3278     this_hdr->sh_flags |= SHF_ALLOC;
3279   if ((asect->flags & SEC_READONLY) == 0)
3280     this_hdr->sh_flags |= SHF_WRITE;
3281   if ((asect->flags & SEC_CODE) != 0)
3282     this_hdr->sh_flags |= SHF_EXECINSTR;
3283   if ((asect->flags & SEC_MERGE) != 0)
3284     {
3285       this_hdr->sh_flags |= SHF_MERGE;
3286       this_hdr->sh_entsize = asect->entsize;
3287     }
3288   if ((asect->flags & SEC_STRINGS) != 0)
3289     this_hdr->sh_flags |= SHF_STRINGS;
3290   if ((asect->flags & SEC_GROUP) == 0 && elf_group_name (asect) != NULL)
3291     this_hdr->sh_flags |= SHF_GROUP;
3292   if ((asect->flags & SEC_THREAD_LOCAL) != 0)
3293     {
3294       this_hdr->sh_flags |= SHF_TLS;
3295       if (asect->size == 0
3296 	  && (asect->flags & SEC_HAS_CONTENTS) == 0)
3297 	{
3298 	  struct bfd_link_order *o = asect->map_tail.link_order;
3299 
3300 	  this_hdr->sh_size = 0;
3301 	  if (o != NULL)
3302 	    {
3303 	      this_hdr->sh_size = o->offset + o->size;
3304 	      if (this_hdr->sh_size != 0)
3305 		this_hdr->sh_type = SHT_NOBITS;
3306 	    }
3307 	}
3308     }
3309   if ((asect->flags & (SEC_GROUP | SEC_EXCLUDE)) == SEC_EXCLUDE)
3310     this_hdr->sh_flags |= SHF_EXCLUDE;
3311 
3312   /* If the section has relocs, set up a section header for the
3313      SHT_REL[A] section.  If two relocation sections are required for
3314      this section, it is up to the processor-specific back-end to
3315      create the other.  */
3316   if ((asect->flags & SEC_RELOC) != 0)
3317     {
3318       /* When doing a relocatable link, create both REL and RELA sections if
3319 	 needed.  */
3320       if (arg->link_info
3321 	  /* Do the normal setup if we wouldn't create any sections here.  */
3322 	  && esd->rel.count + esd->rela.count > 0
3323 	  && (bfd_link_relocatable (arg->link_info)
3324 	      || arg->link_info->emitrelocations))
3325 	{
3326 	  if (esd->rel.count && esd->rel.hdr == NULL
3327 	      && !_bfd_elf_init_reloc_shdr (abfd, &esd->rel, name, FALSE,
3328 					    delay_st_name_p))
3329 	    {
3330 	      arg->failed = TRUE;
3331 	      return;
3332 	    }
3333 	  if (esd->rela.count && esd->rela.hdr == NULL
3334 	      && !_bfd_elf_init_reloc_shdr (abfd, &esd->rela, name, TRUE,
3335 					    delay_st_name_p))
3336 	    {
3337 	      arg->failed = TRUE;
3338 	      return;
3339 	    }
3340 	}
3341       else if (!_bfd_elf_init_reloc_shdr (abfd,
3342 					  (asect->use_rela_p
3343 					   ? &esd->rela : &esd->rel),
3344 					  name,
3345 					  asect->use_rela_p,
3346 					  delay_st_name_p))
3347 	  arg->failed = TRUE;
3348     }
3349 
3350   /* Check for processor-specific section types.  */
3351   sh_type = this_hdr->sh_type;
3352   if (bed->elf_backend_fake_sections
3353       && !(*bed->elf_backend_fake_sections) (abfd, this_hdr, asect))
3354     arg->failed = TRUE;
3355 
3356   if (sh_type == SHT_NOBITS && asect->size != 0)
3357     {
3358       /* Don't change the header type from NOBITS if we are being
3359 	 called for objcopy --only-keep-debug.  */
3360       this_hdr->sh_type = sh_type;
3361     }
3362 }
3363 
3364 /* Fill in the contents of a SHT_GROUP section.  Called from
3365    _bfd_elf_compute_section_file_positions for gas, objcopy, and
3366    when ELF targets use the generic linker, ld.  Called for ld -r
3367    from bfd_elf_final_link.  */
3368 
3369 void
3370 bfd_elf_set_group_contents (bfd *abfd, asection *sec, void *failedptrarg)
3371 {
3372   bfd_boolean *failedptr = (bfd_boolean *) failedptrarg;
3373   asection *elt, *first;
3374   unsigned char *loc;
3375   bfd_boolean gas;
3376 
3377   /* Ignore linker created group section.  See elfNN_ia64_object_p in
3378      elfxx-ia64.c.  */
3379   if (((sec->flags & (SEC_GROUP | SEC_LINKER_CREATED)) != SEC_GROUP)
3380       || *failedptr)
3381     return;
3382 
3383   if (elf_section_data (sec)->this_hdr.sh_info == 0)
3384     {
3385       unsigned long symindx = 0;
3386 
3387       /* elf_group_id will have been set up by objcopy and the
3388 	 generic linker.  */
3389       if (elf_group_id (sec) != NULL)
3390 	symindx = elf_group_id (sec)->udata.i;
3391 
3392       if (symindx == 0)
3393 	{
3394 	  /* If called from the assembler, swap_out_syms will have set up
3395 	     elf_section_syms.  */
3396 	  BFD_ASSERT (elf_section_syms (abfd) != NULL);
3397 	  symindx = elf_section_syms (abfd)[sec->index]->udata.i;
3398 	}
3399       elf_section_data (sec)->this_hdr.sh_info = symindx;
3400     }
3401   else if (elf_section_data (sec)->this_hdr.sh_info == (unsigned int) -2)
3402     {
3403       /* The ELF backend linker sets sh_info to -2 when the group
3404 	 signature symbol is global, and thus the index can't be
3405 	 set until all local symbols are output.  */
3406       asection *igroup = elf_sec_group (elf_next_in_group (sec));
3407       struct bfd_elf_section_data *sec_data = elf_section_data (igroup);
3408       unsigned long symndx = sec_data->this_hdr.sh_info;
3409       unsigned long extsymoff = 0;
3410       struct elf_link_hash_entry *h;
3411 
3412       if (!elf_bad_symtab (igroup->owner))
3413 	{
3414 	  Elf_Internal_Shdr *symtab_hdr;
3415 
3416 	  symtab_hdr = &elf_tdata (igroup->owner)->symtab_hdr;
3417 	  extsymoff = symtab_hdr->sh_info;
3418 	}
3419       h = elf_sym_hashes (igroup->owner)[symndx - extsymoff];
3420       while (h->root.type == bfd_link_hash_indirect
3421 	     || h->root.type == bfd_link_hash_warning)
3422 	h = (struct elf_link_hash_entry *) h->root.u.i.link;
3423 
3424       elf_section_data (sec)->this_hdr.sh_info = h->indx;
3425     }
3426 
3427   /* The contents won't be allocated for "ld -r" or objcopy.  */
3428   gas = TRUE;
3429   if (sec->contents == NULL)
3430     {
3431       gas = FALSE;
3432       sec->contents = (unsigned char *) bfd_alloc (abfd, sec->size);
3433 
3434       /* Arrange for the section to be written out.  */
3435       elf_section_data (sec)->this_hdr.contents = sec->contents;
3436       if (sec->contents == NULL)
3437 	{
3438 	  *failedptr = TRUE;
3439 	  return;
3440 	}
3441     }
3442 
3443   loc = sec->contents + sec->size;
3444 
3445   /* Get the pointer to the first section in the group that gas
3446      squirreled away here.  objcopy arranges for this to be set to the
3447      start of the input section group.  */
3448   first = elt = elf_next_in_group (sec);
3449 
3450   /* First element is a flag word.  Rest of section is elf section
3451      indices for all the sections of the group.  Write them backwards
3452      just to keep the group in the same order as given in .section
3453      directives, not that it matters.  */
3454   while (elt != NULL)
3455     {
3456       asection *s;
3457 
3458       s = elt;
3459       if (!gas)
3460 	s = s->output_section;
3461       if (s != NULL
3462 	  && !bfd_is_abs_section (s))
3463 	{
3464 	  unsigned int idx = elf_section_data (s)->this_idx;
3465 
3466 	  loc -= 4;
3467 	  H_PUT_32 (abfd, idx, loc);
3468 	}
3469       elt = elf_next_in_group (elt);
3470       if (elt == first)
3471 	break;
3472     }
3473 
3474   if ((loc -= 4) != sec->contents)
3475     abort ();
3476 
3477   H_PUT_32 (abfd, sec->flags & SEC_LINK_ONCE ? GRP_COMDAT : 0, loc);
3478 }
3479 
3480 /* Return the section which RELOC_SEC applies to.  */
3481 
3482 asection *
3483 _bfd_elf_get_reloc_section (asection *reloc_sec)
3484 {
3485   const char *name;
3486   unsigned int type;
3487   bfd *abfd;
3488 
3489   if (reloc_sec == NULL)
3490     return NULL;
3491 
3492   type = elf_section_data (reloc_sec)->this_hdr.sh_type;
3493   if (type != SHT_REL && type != SHT_RELA)
3494     return NULL;
3495 
3496   /* We look up the section the relocs apply to by name.  */
3497   name = reloc_sec->name;
3498   if (type == SHT_REL)
3499     name += 4;
3500   else
3501     name += 5;
3502 
3503   /* If a target needs .got.plt section, relocations in rela.plt/rel.plt
3504      section apply to .got.plt section.  */
3505   abfd = reloc_sec->owner;
3506   if (get_elf_backend_data (abfd)->want_got_plt
3507       && strcmp (name, ".plt") == 0)
3508     {
3509       /* .got.plt is a linker created input section.  It may be mapped
3510 	 to some other output section.  Try two likely sections.  */
3511       name = ".got.plt";
3512       reloc_sec = bfd_get_section_by_name (abfd, name);
3513       if (reloc_sec != NULL)
3514 	return reloc_sec;
3515       name = ".got";
3516     }
3517 
3518   reloc_sec = bfd_get_section_by_name (abfd, name);
3519   return reloc_sec;
3520 }
3521 
3522 /* Assign all ELF section numbers.  The dummy first section is handled here
3523    too.  The link/info pointers for the standard section types are filled
3524    in here too, while we're at it.  */
3525 
3526 static bfd_boolean
3527 assign_section_numbers (bfd *abfd, struct bfd_link_info *link_info)
3528 {
3529   struct elf_obj_tdata *t = elf_tdata (abfd);
3530   asection *sec;
3531   unsigned int section_number;
3532   Elf_Internal_Shdr **i_shdrp;
3533   struct bfd_elf_section_data *d;
3534   bfd_boolean need_symtab;
3535 
3536   section_number = 1;
3537 
3538   _bfd_elf_strtab_clear_all_refs (elf_shstrtab (abfd));
3539 
3540   /* SHT_GROUP sections are in relocatable files only.  */
3541   if (link_info == NULL || bfd_link_relocatable (link_info))
3542     {
3543       size_t reloc_count = 0;
3544 
3545       /* Put SHT_GROUP sections first.  */
3546       for (sec = abfd->sections; sec != NULL; sec = sec->next)
3547 	{
3548 	  d = elf_section_data (sec);
3549 
3550 	  if (d->this_hdr.sh_type == SHT_GROUP)
3551 	    {
3552 	      if (sec->flags & SEC_LINKER_CREATED)
3553 		{
3554 		  /* Remove the linker created SHT_GROUP sections.  */
3555 		  bfd_section_list_remove (abfd, sec);
3556 		  abfd->section_count--;
3557 		}
3558 	      else
3559 		d->this_idx = section_number++;
3560 	    }
3561 
3562 	  /* Count relocations.  */
3563 	  reloc_count += sec->reloc_count;
3564 	}
3565 
3566       /* Clear HAS_RELOC if there are no relocations.  */
3567       if (reloc_count == 0)
3568 	abfd->flags &= ~HAS_RELOC;
3569     }
3570 
3571   for (sec = abfd->sections; sec; sec = sec->next)
3572     {
3573       d = elf_section_data (sec);
3574 
3575       if (d->this_hdr.sh_type != SHT_GROUP)
3576 	d->this_idx = section_number++;
3577       if (d->this_hdr.sh_name != (unsigned int) -1)
3578 	_bfd_elf_strtab_addref (elf_shstrtab (abfd), d->this_hdr.sh_name);
3579       if (d->rel.hdr)
3580 	{
3581 	  d->rel.idx = section_number++;
3582 	  if (d->rel.hdr->sh_name != (unsigned int) -1)
3583 	    _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel.hdr->sh_name);
3584 	}
3585       else
3586 	d->rel.idx = 0;
3587 
3588       if (d->rela.hdr)
3589 	{
3590 	  d->rela.idx = section_number++;
3591 	  if (d->rela.hdr->sh_name != (unsigned int) -1)
3592 	    _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rela.hdr->sh_name);
3593 	}
3594       else
3595 	d->rela.idx = 0;
3596     }
3597 
3598   elf_shstrtab_sec (abfd) = section_number++;
3599   _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->shstrtab_hdr.sh_name);
3600   elf_elfheader (abfd)->e_shstrndx = elf_shstrtab_sec (abfd);
3601 
3602   need_symtab = (bfd_get_symcount (abfd) > 0
3603 		|| (link_info == NULL
3604 		    && ((abfd->flags & (EXEC_P | DYNAMIC | HAS_RELOC))
3605 			== HAS_RELOC)));
3606   if (need_symtab)
3607     {
3608       elf_onesymtab (abfd) = section_number++;
3609       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->symtab_hdr.sh_name);
3610       if (section_number > ((SHN_LORESERVE - 2) & 0xFFFF))
3611 	{
3612 	  elf_section_list * entry;
3613 
3614 	  BFD_ASSERT (elf_symtab_shndx_list (abfd) == NULL);
3615 
3616 	  entry = bfd_zalloc (abfd, sizeof * entry);
3617 	  entry->ndx = section_number++;
3618 	  elf_symtab_shndx_list (abfd) = entry;
3619 	  entry->hdr.sh_name
3620 	    = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
3621 						  ".symtab_shndx", FALSE);
3622 	  if (entry->hdr.sh_name == (unsigned int) -1)
3623 	    return FALSE;
3624 	}
3625       elf_strtab_sec (abfd) = section_number++;
3626       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->strtab_hdr.sh_name);
3627     }
3628 
3629   if (section_number >= SHN_LORESERVE)
3630     {
3631       _bfd_error_handler (_("%B: too many sections: %u"),
3632 			  abfd, section_number);
3633       return FALSE;
3634     }
3635 
3636   elf_numsections (abfd) = section_number;
3637   elf_elfheader (abfd)->e_shnum = section_number;
3638 
3639   /* Set up the list of section header pointers, in agreement with the
3640      indices.  */
3641   i_shdrp = (Elf_Internal_Shdr **) bfd_zalloc2 (abfd, section_number,
3642                                                 sizeof (Elf_Internal_Shdr *));
3643   if (i_shdrp == NULL)
3644     return FALSE;
3645 
3646   i_shdrp[0] = (Elf_Internal_Shdr *) bfd_zalloc (abfd,
3647                                                  sizeof (Elf_Internal_Shdr));
3648   if (i_shdrp[0] == NULL)
3649     {
3650       bfd_release (abfd, i_shdrp);
3651       return FALSE;
3652     }
3653 
3654   elf_elfsections (abfd) = i_shdrp;
3655 
3656   i_shdrp[elf_shstrtab_sec (abfd)] = &t->shstrtab_hdr;
3657   if (need_symtab)
3658     {
3659       i_shdrp[elf_onesymtab (abfd)] = &t->symtab_hdr;
3660       if (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF))
3661 	{
3662 	  elf_section_list * entry = elf_symtab_shndx_list (abfd);
3663 	  BFD_ASSERT (entry != NULL);
3664 	  i_shdrp[entry->ndx] = & entry->hdr;
3665 	  entry->hdr.sh_link = elf_onesymtab (abfd);
3666 	}
3667       i_shdrp[elf_strtab_sec (abfd)] = &t->strtab_hdr;
3668       t->symtab_hdr.sh_link = elf_strtab_sec (abfd);
3669     }
3670 
3671   for (sec = abfd->sections; sec; sec = sec->next)
3672     {
3673       asection *s;
3674 
3675       d = elf_section_data (sec);
3676 
3677       i_shdrp[d->this_idx] = &d->this_hdr;
3678       if (d->rel.idx != 0)
3679 	i_shdrp[d->rel.idx] = d->rel.hdr;
3680       if (d->rela.idx != 0)
3681 	i_shdrp[d->rela.idx] = d->rela.hdr;
3682 
3683       /* Fill in the sh_link and sh_info fields while we're at it.  */
3684 
3685       /* sh_link of a reloc section is the section index of the symbol
3686 	 table.  sh_info is the section index of the section to which
3687 	 the relocation entries apply.  */
3688       if (d->rel.idx != 0)
3689 	{
3690 	  d->rel.hdr->sh_link = elf_onesymtab (abfd);
3691 	  d->rel.hdr->sh_info = d->this_idx;
3692 	  d->rel.hdr->sh_flags |= SHF_INFO_LINK;
3693 	}
3694       if (d->rela.idx != 0)
3695 	{
3696 	  d->rela.hdr->sh_link = elf_onesymtab (abfd);
3697 	  d->rela.hdr->sh_info = d->this_idx;
3698 	  d->rela.hdr->sh_flags |= SHF_INFO_LINK;
3699 	}
3700 
3701       /* We need to set up sh_link for SHF_LINK_ORDER.  */
3702       if ((d->this_hdr.sh_flags & SHF_LINK_ORDER) != 0)
3703 	{
3704 	  s = elf_linked_to_section (sec);
3705 	  if (s)
3706 	    {
3707 	      /* elf_linked_to_section points to the input section.  */
3708 	      if (link_info != NULL)
3709 		{
3710 		  /* Check discarded linkonce section.  */
3711 		  if (discarded_section (s))
3712 		    {
3713 		      asection *kept;
3714 		      (*_bfd_error_handler)
3715 			(_("%B: sh_link of section `%A' points to discarded section `%A' of `%B'"),
3716 			 abfd, d->this_hdr.bfd_section,
3717 			 s, s->owner);
3718 		      /* Point to the kept section if it has the same
3719 			 size as the discarded one.  */
3720 		      kept = _bfd_elf_check_kept_section (s, link_info);
3721 		      if (kept == NULL)
3722 			{
3723 			  bfd_set_error (bfd_error_bad_value);
3724 			  return FALSE;
3725 			}
3726 		      s = kept;
3727 		    }
3728 
3729 		  s = s->output_section;
3730 		  BFD_ASSERT (s != NULL);
3731 		}
3732 	      else
3733 		{
3734 		  /* Handle objcopy. */
3735 		  if (s->output_section == NULL)
3736 		    {
3737 		      (*_bfd_error_handler)
3738 			(_("%B: sh_link of section `%A' points to removed section `%A' of `%B'"),
3739 			 abfd, d->this_hdr.bfd_section, s, s->owner);
3740 		      bfd_set_error (bfd_error_bad_value);
3741 		      return FALSE;
3742 		    }
3743 		  s = s->output_section;
3744 		}
3745 	      d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3746 	    }
3747 	  else
3748 	    {
3749 	      /* PR 290:
3750 		 The Intel C compiler generates SHT_IA_64_UNWIND with
3751 		 SHF_LINK_ORDER.  But it doesn't set the sh_link or
3752 		 sh_info fields.  Hence we could get the situation
3753 		 where s is NULL.  */
3754 	      const struct elf_backend_data *bed
3755 		= get_elf_backend_data (abfd);
3756 	      if (bed->link_order_error_handler)
3757 		bed->link_order_error_handler
3758 		  (_("%B: warning: sh_link not set for section `%A'"),
3759 		   abfd, sec);
3760 	    }
3761 	}
3762 
3763       switch (d->this_hdr.sh_type)
3764 	{
3765 	case SHT_REL:
3766 	case SHT_RELA:
3767 	  /* A reloc section which we are treating as a normal BFD
3768 	     section.  sh_link is the section index of the symbol
3769 	     table.  sh_info is the section index of the section to
3770 	     which the relocation entries apply.  We assume that an
3771 	     allocated reloc section uses the dynamic symbol table.
3772 	     FIXME: How can we be sure?  */
3773 	  s = bfd_get_section_by_name (abfd, ".dynsym");
3774 	  if (s != NULL)
3775 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3776 
3777 	  s = get_elf_backend_data (abfd)->get_reloc_section (sec);
3778 	  if (s != NULL)
3779 	    {
3780 	      d->this_hdr.sh_info = elf_section_data (s)->this_idx;
3781 	      d->this_hdr.sh_flags |= SHF_INFO_LINK;
3782 	    }
3783 	  break;
3784 
3785 	case SHT_STRTAB:
3786 	  /* We assume that a section named .stab*str is a stabs
3787 	     string section.  We look for a section with the same name
3788 	     but without the trailing ``str'', and set its sh_link
3789 	     field to point to this section.  */
3790 	  if (CONST_STRNEQ (sec->name, ".stab")
3791 	      && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
3792 	    {
3793 	      size_t len;
3794 	      char *alc;
3795 
3796 	      len = strlen (sec->name);
3797 	      alc = (char *) bfd_malloc (len - 2);
3798 	      if (alc == NULL)
3799 		return FALSE;
3800 	      memcpy (alc, sec->name, len - 3);
3801 	      alc[len - 3] = '\0';
3802 	      s = bfd_get_section_by_name (abfd, alc);
3803 	      free (alc);
3804 	      if (s != NULL)
3805 		{
3806 		  elf_section_data (s)->this_hdr.sh_link = d->this_idx;
3807 
3808 		  /* This is a .stab section.  */
3809 		  if (elf_section_data (s)->this_hdr.sh_entsize == 0)
3810 		    elf_section_data (s)->this_hdr.sh_entsize
3811 		      = 4 + 2 * bfd_get_arch_size (abfd) / 8;
3812 		}
3813 	    }
3814 	  break;
3815 
3816 	case SHT_DYNAMIC:
3817 	case SHT_DYNSYM:
3818 	case SHT_GNU_verneed:
3819 	case SHT_GNU_verdef:
3820 	  /* sh_link is the section header index of the string table
3821 	     used for the dynamic entries, or the symbol table, or the
3822 	     version strings.  */
3823 	  s = bfd_get_section_by_name (abfd, ".dynstr");
3824 	  if (s != NULL)
3825 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3826 	  break;
3827 
3828 	case SHT_GNU_LIBLIST:
3829 	  /* sh_link is the section header index of the prelink library
3830 	     list used for the dynamic entries, or the symbol table, or
3831 	     the version strings.  */
3832 	  s = bfd_get_section_by_name (abfd, (sec->flags & SEC_ALLOC)
3833 					     ? ".dynstr" : ".gnu.libstr");
3834 	  if (s != NULL)
3835 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3836 	  break;
3837 
3838 	case SHT_HASH:
3839 	case SHT_GNU_HASH:
3840 	case SHT_GNU_versym:
3841 	  /* sh_link is the section header index of the symbol table
3842 	     this hash table or version table is for.  */
3843 	  s = bfd_get_section_by_name (abfd, ".dynsym");
3844 	  if (s != NULL)
3845 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3846 	  break;
3847 
3848 	case SHT_GROUP:
3849 	  d->this_hdr.sh_link = elf_onesymtab (abfd);
3850 	}
3851     }
3852 
3853   /* Delay setting sh_name to _bfd_elf_write_object_contents so that
3854      _bfd_elf_assign_file_positions_for_non_load can convert DWARF
3855      debug section name from .debug_* to .zdebug_* if needed.  */
3856 
3857   return TRUE;
3858 }
3859 
3860 static bfd_boolean
3861 sym_is_global (bfd *abfd, asymbol *sym)
3862 {
3863   /* If the backend has a special mapping, use it.  */
3864   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3865   if (bed->elf_backend_sym_is_global)
3866     return (*bed->elf_backend_sym_is_global) (abfd, sym);
3867 
3868   return ((sym->flags & (BSF_GLOBAL | BSF_WEAK | BSF_GNU_UNIQUE)) != 0
3869 	  || bfd_is_und_section (bfd_get_section (sym))
3870 	  || bfd_is_com_section (bfd_get_section (sym)));
3871 }
3872 
3873 /* Don't output section symbols for sections that are not going to be
3874    output, that are duplicates or there is no BFD section.  */
3875 
3876 static bfd_boolean
3877 ignore_section_sym (bfd *abfd, asymbol *sym)
3878 {
3879   elf_symbol_type *type_ptr;
3880 
3881   if ((sym->flags & BSF_SECTION_SYM) == 0)
3882     return FALSE;
3883 
3884   type_ptr = elf_symbol_from (abfd, sym);
3885   return ((type_ptr != NULL
3886 	   && type_ptr->internal_elf_sym.st_shndx != 0
3887 	   && bfd_is_abs_section (sym->section))
3888 	  || !(sym->section->owner == abfd
3889 	       || (sym->section->output_section->owner == abfd
3890 		   && sym->section->output_offset == 0)
3891 	       || bfd_is_abs_section (sym->section)));
3892 }
3893 
3894 /* Map symbol from it's internal number to the external number, moving
3895    all local symbols to be at the head of the list.  */
3896 
3897 static bfd_boolean
3898 elf_map_symbols (bfd *abfd, unsigned int *pnum_locals)
3899 {
3900   unsigned int symcount = bfd_get_symcount (abfd);
3901   asymbol **syms = bfd_get_outsymbols (abfd);
3902   asymbol **sect_syms;
3903   unsigned int num_locals = 0;
3904   unsigned int num_globals = 0;
3905   unsigned int num_locals2 = 0;
3906   unsigned int num_globals2 = 0;
3907   unsigned int max_index = 0;
3908   unsigned int idx;
3909   asection *asect;
3910   asymbol **new_syms;
3911 
3912 #ifdef DEBUG
3913   fprintf (stderr, "elf_map_symbols\n");
3914   fflush (stderr);
3915 #endif
3916 
3917   for (asect = abfd->sections; asect; asect = asect->next)
3918     {
3919       if (max_index < asect->index)
3920 	max_index = asect->index;
3921     }
3922 
3923   max_index++;
3924   sect_syms = (asymbol **) bfd_zalloc2 (abfd, max_index, sizeof (asymbol *));
3925   if (sect_syms == NULL)
3926     return FALSE;
3927   elf_section_syms (abfd) = sect_syms;
3928   elf_num_section_syms (abfd) = max_index;
3929 
3930   /* Init sect_syms entries for any section symbols we have already
3931      decided to output.  */
3932   for (idx = 0; idx < symcount; idx++)
3933     {
3934       asymbol *sym = syms[idx];
3935 
3936       if ((sym->flags & BSF_SECTION_SYM) != 0
3937 	  && sym->value == 0
3938 	  && !ignore_section_sym (abfd, sym)
3939 	  && !bfd_is_abs_section (sym->section))
3940 	{
3941 	  asection *sec = sym->section;
3942 
3943 	  if (sec->owner != abfd)
3944 	    sec = sec->output_section;
3945 
3946 	  sect_syms[sec->index] = syms[idx];
3947 	}
3948     }
3949 
3950   /* Classify all of the symbols.  */
3951   for (idx = 0; idx < symcount; idx++)
3952     {
3953       if (sym_is_global (abfd, syms[idx]))
3954 	num_globals++;
3955       else if (!ignore_section_sym (abfd, syms[idx]))
3956 	num_locals++;
3957     }
3958 
3959   /* We will be adding a section symbol for each normal BFD section.  Most
3960      sections will already have a section symbol in outsymbols, but
3961      eg. SHT_GROUP sections will not, and we need the section symbol mapped
3962      at least in that case.  */
3963   for (asect = abfd->sections; asect; asect = asect->next)
3964     {
3965       if (sect_syms[asect->index] == NULL)
3966 	{
3967 	  if (!sym_is_global (abfd, asect->symbol))
3968 	    num_locals++;
3969 	  else
3970 	    num_globals++;
3971 	}
3972     }
3973 
3974   /* Now sort the symbols so the local symbols are first.  */
3975   new_syms = (asymbol **) bfd_alloc2 (abfd, num_locals + num_globals,
3976                                       sizeof (asymbol *));
3977 
3978   if (new_syms == NULL)
3979     return FALSE;
3980 
3981   for (idx = 0; idx < symcount; idx++)
3982     {
3983       asymbol *sym = syms[idx];
3984       unsigned int i;
3985 
3986       if (sym_is_global (abfd, sym))
3987 	i = num_locals + num_globals2++;
3988       else if (!ignore_section_sym (abfd, sym))
3989 	i = num_locals2++;
3990       else
3991 	continue;
3992       new_syms[i] = sym;
3993       sym->udata.i = i + 1;
3994     }
3995   for (asect = abfd->sections; asect; asect = asect->next)
3996     {
3997       if (sect_syms[asect->index] == NULL)
3998 	{
3999 	  asymbol *sym = asect->symbol;
4000 	  unsigned int i;
4001 
4002 	  sect_syms[asect->index] = sym;
4003 	  if (!sym_is_global (abfd, sym))
4004 	    i = num_locals2++;
4005 	  else
4006 	    i = num_locals + num_globals2++;
4007 	  new_syms[i] = sym;
4008 	  sym->udata.i = i + 1;
4009 	}
4010     }
4011 
4012   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
4013 
4014   *pnum_locals = num_locals;
4015   return TRUE;
4016 }
4017 
4018 /* Align to the maximum file alignment that could be required for any
4019    ELF data structure.  */
4020 
4021 static inline file_ptr
4022 align_file_position (file_ptr off, int align)
4023 {
4024   return (off + align - 1) & ~(align - 1);
4025 }
4026 
4027 /* Assign a file position to a section, optionally aligning to the
4028    required section alignment.  */
4029 
4030 file_ptr
4031 _bfd_elf_assign_file_position_for_section (Elf_Internal_Shdr *i_shdrp,
4032 					   file_ptr offset,
4033 					   bfd_boolean align)
4034 {
4035   if (align && i_shdrp->sh_addralign > 1)
4036     offset = BFD_ALIGN (offset, i_shdrp->sh_addralign);
4037   i_shdrp->sh_offset = offset;
4038   if (i_shdrp->bfd_section != NULL)
4039     i_shdrp->bfd_section->filepos = offset;
4040   if (i_shdrp->sh_type != SHT_NOBITS)
4041     offset += i_shdrp->sh_size;
4042   return offset;
4043 }
4044 
4045 /* Compute the file positions we are going to put the sections at, and
4046    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
4047    is not NULL, this is being called by the ELF backend linker.  */
4048 
4049 bfd_boolean
4050 _bfd_elf_compute_section_file_positions (bfd *abfd,
4051 					 struct bfd_link_info *link_info)
4052 {
4053   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4054   struct fake_section_arg fsargs;
4055   bfd_boolean failed;
4056   struct elf_strtab_hash *strtab = NULL;
4057   Elf_Internal_Shdr *shstrtab_hdr;
4058   bfd_boolean need_symtab;
4059 
4060   if (abfd->output_has_begun)
4061     return TRUE;
4062 
4063   /* Do any elf backend specific processing first.  */
4064   if (bed->elf_backend_begin_write_processing)
4065     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
4066 
4067   if (! prep_headers (abfd))
4068     return FALSE;
4069 
4070   /* Post process the headers if necessary.  */
4071   (*bed->elf_backend_post_process_headers) (abfd, link_info);
4072 
4073   fsargs.failed = FALSE;
4074   fsargs.link_info = link_info;
4075   bfd_map_over_sections (abfd, elf_fake_sections, &fsargs);
4076   if (fsargs.failed)
4077     return FALSE;
4078 
4079   if (!assign_section_numbers (abfd, link_info))
4080     return FALSE;
4081 
4082   /* The backend linker builds symbol table information itself.  */
4083   need_symtab = (link_info == NULL
4084 		 && (bfd_get_symcount (abfd) > 0
4085 		     || ((abfd->flags & (EXEC_P | DYNAMIC | HAS_RELOC))
4086 			 == HAS_RELOC)));
4087   if (need_symtab)
4088     {
4089       /* Non-zero if doing a relocatable link.  */
4090       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
4091 
4092       if (! swap_out_syms (abfd, &strtab, relocatable_p))
4093 	return FALSE;
4094     }
4095 
4096   failed = FALSE;
4097   if (link_info == NULL)
4098     {
4099       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
4100       if (failed)
4101 	return FALSE;
4102     }
4103 
4104   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
4105   /* sh_name was set in prep_headers.  */
4106   shstrtab_hdr->sh_type = SHT_STRTAB;
4107   shstrtab_hdr->sh_flags = bed->elf_strtab_flags;
4108   shstrtab_hdr->sh_addr = 0;
4109   /* sh_size is set in _bfd_elf_assign_file_positions_for_non_load.  */
4110   shstrtab_hdr->sh_entsize = 0;
4111   shstrtab_hdr->sh_link = 0;
4112   shstrtab_hdr->sh_info = 0;
4113   /* sh_offset is set in _bfd_elf_assign_file_positions_for_non_load.  */
4114   shstrtab_hdr->sh_addralign = 1;
4115 
4116   if (!assign_file_positions_except_relocs (abfd, link_info))
4117     return FALSE;
4118 
4119   if (need_symtab)
4120     {
4121       file_ptr off;
4122       Elf_Internal_Shdr *hdr;
4123 
4124       off = elf_next_file_pos (abfd);
4125 
4126       hdr = & elf_symtab_hdr (abfd);
4127       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4128 
4129       if (elf_symtab_shndx_list (abfd) != NULL)
4130 	{
4131 	  hdr = & elf_symtab_shndx_list (abfd)->hdr;
4132 	  if (hdr->sh_size != 0)
4133 	    off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4134 	  /* FIXME: What about other symtab_shndx sections in the list ?  */
4135 	}
4136 
4137       hdr = &elf_tdata (abfd)->strtab_hdr;
4138       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4139 
4140       elf_next_file_pos (abfd) = off;
4141 
4142       /* Now that we know where the .strtab section goes, write it
4143 	 out.  */
4144       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
4145 	  || ! _bfd_elf_strtab_emit (abfd, strtab))
4146 	return FALSE;
4147       _bfd_elf_strtab_free (strtab);
4148     }
4149 
4150   abfd->output_has_begun = TRUE;
4151 
4152   return TRUE;
4153 }
4154 
4155 /* Make an initial estimate of the size of the program header.  If we
4156    get the number wrong here, we'll redo section placement.  */
4157 
4158 static bfd_size_type
4159 get_program_header_size (bfd *abfd, struct bfd_link_info *info)
4160 {
4161   size_t segs;
4162   asection *s;
4163   const struct elf_backend_data *bed;
4164 
4165   /* Assume we will need exactly two PT_LOAD segments: one for text
4166      and one for data.  */
4167   segs = 2;
4168 
4169   s = bfd_get_section_by_name (abfd, ".interp");
4170   if (s != NULL && (s->flags & SEC_LOAD) != 0)
4171     {
4172       /* If we have a loadable interpreter section, we need a
4173 	 PT_INTERP segment.  In this case, assume we also need a
4174 	 PT_PHDR segment, although that may not be true for all
4175 	 targets.  */
4176       segs += 2;
4177     }
4178 
4179   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
4180     {
4181       /* We need a PT_DYNAMIC segment.  */
4182       ++segs;
4183     }
4184 
4185   if (info != NULL && info->relro)
4186     {
4187       /* We need a PT_GNU_RELRO segment.  */
4188       ++segs;
4189     }
4190 
4191   if (elf_eh_frame_hdr (abfd))
4192     {
4193       /* We need a PT_GNU_EH_FRAME segment.  */
4194       ++segs;
4195     }
4196 
4197   if (elf_stack_flags (abfd))
4198     {
4199       /* We need a PT_GNU_STACK segment.  */
4200       ++segs;
4201     }
4202 
4203   for (s = abfd->sections; s != NULL; s = s->next)
4204     {
4205       if ((s->flags & SEC_LOAD) != 0
4206 	  && CONST_STRNEQ (s->name, ".note"))
4207 	{
4208 	  /* We need a PT_NOTE segment.  */
4209 	  ++segs;
4210 	  /* Try to create just one PT_NOTE segment
4211 	     for all adjacent loadable .note* sections.
4212 	     gABI requires that within a PT_NOTE segment
4213 	     (and also inside of each SHT_NOTE section)
4214 	     each note is padded to a multiple of 4 size,
4215 	     so we check whether the sections are correctly
4216 	     aligned.  */
4217 	  if (s->alignment_power == 2)
4218 	    while (s->next != NULL
4219 		   && s->next->alignment_power == 2
4220 		   && (s->next->flags & SEC_LOAD) != 0
4221 		   && CONST_STRNEQ (s->next->name, ".note"))
4222 	      s = s->next;
4223 	}
4224     }
4225 
4226   for (s = abfd->sections; s != NULL; s = s->next)
4227     {
4228       if (s->flags & SEC_THREAD_LOCAL)
4229 	{
4230 	  /* We need a PT_TLS segment.  */
4231 	  ++segs;
4232 	  break;
4233 	}
4234     }
4235 
4236   /* Let the backend count up any program headers it might need.  */
4237   bed = get_elf_backend_data (abfd);
4238   if (bed->elf_backend_additional_program_headers)
4239     {
4240       int a;
4241 
4242       a = (*bed->elf_backend_additional_program_headers) (abfd, info);
4243       if (a == -1)
4244 	abort ();
4245       segs += a;
4246     }
4247 
4248   return segs * bed->s->sizeof_phdr;
4249 }
4250 
4251 /* Find the segment that contains the output_section of section.  */
4252 
4253 Elf_Internal_Phdr *
4254 _bfd_elf_find_segment_containing_section (bfd * abfd, asection * section)
4255 {
4256   struct elf_segment_map *m;
4257   Elf_Internal_Phdr *p;
4258 
4259   for (m = elf_seg_map (abfd), p = elf_tdata (abfd)->phdr;
4260        m != NULL;
4261        m = m->next, p++)
4262     {
4263       int i;
4264 
4265       for (i = m->count - 1; i >= 0; i--)
4266 	if (m->sections[i] == section)
4267 	  return p;
4268     }
4269 
4270   return NULL;
4271 }
4272 
4273 /* Create a mapping from a set of sections to a program segment.  */
4274 
4275 static struct elf_segment_map *
4276 make_mapping (bfd *abfd,
4277 	      asection **sections,
4278 	      unsigned int from,
4279 	      unsigned int to,
4280 	      bfd_boolean phdr)
4281 {
4282   struct elf_segment_map *m;
4283   unsigned int i;
4284   asection **hdrpp;
4285   bfd_size_type amt;
4286 
4287   amt = sizeof (struct elf_segment_map);
4288   amt += (to - from - 1) * sizeof (asection *);
4289   m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4290   if (m == NULL)
4291     return NULL;
4292   m->next = NULL;
4293   m->p_type = PT_LOAD;
4294   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
4295     m->sections[i - from] = *hdrpp;
4296   m->count = to - from;
4297 
4298   if (from == 0 && phdr)
4299     {
4300       /* Include the headers in the first PT_LOAD segment.  */
4301       m->includes_filehdr = 1;
4302       m->includes_phdrs = 1;
4303     }
4304 
4305   return m;
4306 }
4307 
4308 /* Create the PT_DYNAMIC segment, which includes DYNSEC.  Returns NULL
4309    on failure.  */
4310 
4311 struct elf_segment_map *
4312 _bfd_elf_make_dynamic_segment (bfd *abfd, asection *dynsec)
4313 {
4314   struct elf_segment_map *m;
4315 
4316   m = (struct elf_segment_map *) bfd_zalloc (abfd,
4317                                              sizeof (struct elf_segment_map));
4318   if (m == NULL)
4319     return NULL;
4320   m->next = NULL;
4321   m->p_type = PT_DYNAMIC;
4322   m->count = 1;
4323   m->sections[0] = dynsec;
4324 
4325   return m;
4326 }
4327 
4328 /* Possibly add or remove segments from the segment map.  */
4329 
4330 static bfd_boolean
4331 elf_modify_segment_map (bfd *abfd,
4332 			struct bfd_link_info *info,
4333 			bfd_boolean remove_empty_load)
4334 {
4335   struct elf_segment_map **m;
4336   const struct elf_backend_data *bed;
4337 
4338   /* The placement algorithm assumes that non allocated sections are
4339      not in PT_LOAD segments.  We ensure this here by removing such
4340      sections from the segment map.  We also remove excluded
4341      sections.  Finally, any PT_LOAD segment without sections is
4342      removed.  */
4343   m = &elf_seg_map (abfd);
4344   while (*m)
4345     {
4346       unsigned int i, new_count;
4347 
4348       for (new_count = 0, i = 0; i < (*m)->count; i++)
4349 	{
4350 	  if (((*m)->sections[i]->flags & SEC_EXCLUDE) == 0
4351 	      && (((*m)->sections[i]->flags & SEC_ALLOC) != 0
4352 		  || (*m)->p_type != PT_LOAD))
4353 	    {
4354 	      (*m)->sections[new_count] = (*m)->sections[i];
4355 	      new_count++;
4356 	    }
4357 	}
4358       (*m)->count = new_count;
4359 
4360       if (remove_empty_load && (*m)->p_type == PT_LOAD && (*m)->count == 0)
4361 	*m = (*m)->next;
4362       else
4363 	m = &(*m)->next;
4364     }
4365 
4366   bed = get_elf_backend_data (abfd);
4367   if (bed->elf_backend_modify_segment_map != NULL)
4368     {
4369       if (!(*bed->elf_backend_modify_segment_map) (abfd, info))
4370 	return FALSE;
4371     }
4372 
4373   return TRUE;
4374 }
4375 
4376 /* Set up a mapping from BFD sections to program segments.  */
4377 
4378 bfd_boolean
4379 _bfd_elf_map_sections_to_segments (bfd *abfd, struct bfd_link_info *info)
4380 {
4381   unsigned int count;
4382   struct elf_segment_map *m;
4383   asection **sections = NULL;
4384   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4385   bfd_boolean no_user_phdrs;
4386 
4387   no_user_phdrs = elf_seg_map (abfd) == NULL;
4388 
4389   if (info != NULL)
4390     info->user_phdrs = !no_user_phdrs;
4391 
4392   if (no_user_phdrs && bfd_count_sections (abfd) != 0)
4393     {
4394       asection *s;
4395       unsigned int i;
4396       struct elf_segment_map *mfirst;
4397       struct elf_segment_map **pm;
4398       asection *last_hdr;
4399       bfd_vma last_size;
4400       unsigned int phdr_index;
4401       bfd_vma maxpagesize;
4402       asection **hdrpp;
4403       bfd_boolean phdr_in_segment = TRUE;
4404       bfd_boolean writable;
4405       int tls_count = 0;
4406       asection *first_tls = NULL;
4407       asection *dynsec, *eh_frame_hdr;
4408       bfd_size_type amt;
4409       bfd_vma addr_mask, wrap_to = 0;
4410 
4411       /* Select the allocated sections, and sort them.  */
4412 
4413       sections = (asection **) bfd_malloc2 (bfd_count_sections (abfd),
4414                                             sizeof (asection *));
4415       if (sections == NULL)
4416 	goto error_return;
4417 
4418       /* Calculate top address, avoiding undefined behaviour of shift
4419 	 left operator when shift count is equal to size of type
4420 	 being shifted.  */
4421       addr_mask = ((bfd_vma) 1 << (bfd_arch_bits_per_address (abfd) - 1)) - 1;
4422       addr_mask = (addr_mask << 1) + 1;
4423 
4424       i = 0;
4425       for (s = abfd->sections; s != NULL; s = s->next)
4426 	{
4427 	  if ((s->flags & SEC_ALLOC) != 0)
4428 	    {
4429 	      sections[i] = s;
4430 	      ++i;
4431 	      /* A wrapping section potentially clashes with header.  */
4432 	      if (((s->lma + s->size) & addr_mask) < (s->lma & addr_mask))
4433 		wrap_to = (s->lma + s->size) & addr_mask;
4434 	    }
4435 	}
4436       BFD_ASSERT (i <= bfd_count_sections (abfd));
4437       count = i;
4438 
4439       qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
4440 
4441       /* Build the mapping.  */
4442 
4443       mfirst = NULL;
4444       pm = &mfirst;
4445 
4446       /* If we have a .interp section, then create a PT_PHDR segment for
4447 	 the program headers and a PT_INTERP segment for the .interp
4448 	 section.  */
4449       s = bfd_get_section_by_name (abfd, ".interp");
4450       if (s != NULL && (s->flags & SEC_LOAD) != 0)
4451 	{
4452 	  amt = sizeof (struct elf_segment_map);
4453 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4454 	  if (m == NULL)
4455 	    goto error_return;
4456 	  m->next = NULL;
4457 	  m->p_type = PT_PHDR;
4458 	  /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
4459 	  m->p_flags = PF_R | PF_X;
4460 	  m->p_flags_valid = 1;
4461 	  m->includes_phdrs = 1;
4462 
4463 	  *pm = m;
4464 	  pm = &m->next;
4465 
4466 	  amt = sizeof (struct elf_segment_map);
4467 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4468 	  if (m == NULL)
4469 	    goto error_return;
4470 	  m->next = NULL;
4471 	  m->p_type = PT_INTERP;
4472 	  m->count = 1;
4473 	  m->sections[0] = s;
4474 
4475 	  *pm = m;
4476 	  pm = &m->next;
4477 	}
4478 
4479       /* Look through the sections.  We put sections in the same program
4480 	 segment when the start of the second section can be placed within
4481 	 a few bytes of the end of the first section.  */
4482       last_hdr = NULL;
4483       last_size = 0;
4484       phdr_index = 0;
4485       maxpagesize = bed->maxpagesize;
4486       /* PR 17512: file: c8455299.
4487 	 Avoid divide-by-zero errors later on.
4488 	 FIXME: Should we abort if the maxpagesize is zero ?  */
4489       if (maxpagesize == 0)
4490 	maxpagesize = 1;
4491       writable = FALSE;
4492       dynsec = bfd_get_section_by_name (abfd, ".dynamic");
4493       if (dynsec != NULL
4494 	  && (dynsec->flags & SEC_LOAD) == 0)
4495 	dynsec = NULL;
4496 
4497       /* Deal with -Ttext or something similar such that the first section
4498 	 is not adjacent to the program headers.  This is an
4499 	 approximation, since at this point we don't know exactly how many
4500 	 program headers we will need.  */
4501       if (count > 0)
4502 	{
4503 	  bfd_size_type phdr_size = elf_program_header_size (abfd);
4504 
4505 	  if (phdr_size == (bfd_size_type) -1)
4506 	    phdr_size = get_program_header_size (abfd, info);
4507 	  phdr_size += bed->s->sizeof_ehdr;
4508 	  if ((abfd->flags & D_PAGED) == 0
4509 	      || (sections[0]->lma & addr_mask) < phdr_size
4510 	      || ((sections[0]->lma & addr_mask) % maxpagesize
4511 		  < phdr_size % maxpagesize)
4512 	      || (sections[0]->lma & addr_mask & -maxpagesize) < wrap_to)
4513 	    phdr_in_segment = FALSE;
4514 	}
4515 
4516       for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
4517 	{
4518 	  asection *hdr;
4519 	  bfd_boolean new_segment;
4520 
4521 	  hdr = *hdrpp;
4522 
4523 	  /* See if this section and the last one will fit in the same
4524 	     segment.  */
4525 
4526 	  if (last_hdr == NULL)
4527 	    {
4528 	      /* If we don't have a segment yet, then we don't need a new
4529 		 one (we build the last one after this loop).  */
4530 	      new_segment = FALSE;
4531 	    }
4532 	  else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
4533 	    {
4534 	      /* If this section has a different relation between the
4535 		 virtual address and the load address, then we need a new
4536 		 segment.  */
4537 	      new_segment = TRUE;
4538 	    }
4539 	  else if (hdr->lma < last_hdr->lma + last_size
4540 		   || last_hdr->lma + last_size < last_hdr->lma)
4541 	    {
4542 	      /* If this section has a load address that makes it overlap
4543 		 the previous section, then we need a new segment.  */
4544 	      new_segment = TRUE;
4545 	    }
4546 	  /* In the next test we have to be careful when last_hdr->lma is close
4547 	     to the end of the address space.  If the aligned address wraps
4548 	     around to the start of the address space, then there are no more
4549 	     pages left in memory and it is OK to assume that the current
4550 	     section can be included in the current segment.  */
4551 	  else if ((BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
4552 		    > last_hdr->lma)
4553 		   && (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
4554 		       <= hdr->lma))
4555 	    {
4556 	      /* If putting this section in this segment would force us to
4557 		 skip a page in the segment, then we need a new segment.  */
4558 	      new_segment = TRUE;
4559 	    }
4560 	  else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
4561 		   && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0
4562 		   && ((abfd->flags & D_PAGED) == 0
4563 		       || (((last_hdr->lma + last_size - 1) & -maxpagesize)
4564 			   != (hdr->lma & -maxpagesize))))
4565 	    {
4566 	      /* We don't want to put a loaded section after a
4567 		 nonloaded (ie. bss style) section in the same segment
4568 		 as that will force the non-loaded section to be loaded.
4569 		 Consider .tbss sections as loaded for this purpose.
4570 		 However, like the writable/non-writable case below,
4571 		 if they are on the same page then they must be put
4572 		 in the same segment.  */
4573 	      new_segment = TRUE;
4574 	    }
4575 	  else if ((abfd->flags & D_PAGED) == 0)
4576 	    {
4577 	      /* If the file is not demand paged, which means that we
4578 		 don't require the sections to be correctly aligned in the
4579 		 file, then there is no other reason for a new segment.  */
4580 	      new_segment = FALSE;
4581 	    }
4582 	  else if (! writable
4583 		   && (hdr->flags & SEC_READONLY) == 0
4584 		   && (((last_hdr->lma + last_size - 1) & -maxpagesize)
4585 		       != (hdr->lma & -maxpagesize)))
4586 	    {
4587 	      /* We don't want to put a writable section in a read only
4588 		 segment, unless they are on the same page in memory
4589 		 anyhow.  We already know that the last section does not
4590 		 bring us past the current section on the page, so the
4591 		 only case in which the new section is not on the same
4592 		 page as the previous section is when the previous section
4593 		 ends precisely on a page boundary.  */
4594 	      new_segment = TRUE;
4595 	    }
4596 	  else
4597 	    {
4598 	      /* Otherwise, we can use the same segment.  */
4599 	      new_segment = FALSE;
4600 	    }
4601 
4602 	  /* Allow interested parties a chance to override our decision.  */
4603 	  if (last_hdr != NULL
4604 	      && info != NULL
4605 	      && info->callbacks->override_segment_assignment != NULL)
4606 	    new_segment
4607 	      = info->callbacks->override_segment_assignment (info, abfd, hdr,
4608 							      last_hdr,
4609 							      new_segment);
4610 
4611 	  if (! new_segment)
4612 	    {
4613 	      if ((hdr->flags & SEC_READONLY) == 0)
4614 		writable = TRUE;
4615 	      last_hdr = hdr;
4616 	      /* .tbss sections effectively have zero size.  */
4617 	      if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
4618 		  != SEC_THREAD_LOCAL)
4619 		last_size = hdr->size;
4620 	      else
4621 		last_size = 0;
4622 	      continue;
4623 	    }
4624 
4625 	  /* We need a new program segment.  We must create a new program
4626 	     header holding all the sections from phdr_index until hdr.  */
4627 
4628 	  m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
4629 	  if (m == NULL)
4630 	    goto error_return;
4631 
4632 	  *pm = m;
4633 	  pm = &m->next;
4634 
4635 	  if ((hdr->flags & SEC_READONLY) == 0)
4636 	    writable = TRUE;
4637 	  else
4638 	    writable = FALSE;
4639 
4640 	  last_hdr = hdr;
4641 	  /* .tbss sections effectively have zero size.  */
4642 	  if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
4643 	    last_size = hdr->size;
4644 	  else
4645 	    last_size = 0;
4646 	  phdr_index = i;
4647 	  phdr_in_segment = FALSE;
4648 	}
4649 
4650       /* Create a final PT_LOAD program segment, but not if it's just
4651 	 for .tbss.  */
4652       if (last_hdr != NULL
4653 	  && (i - phdr_index != 1
4654 	      || ((last_hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
4655 		  != SEC_THREAD_LOCAL)))
4656 	{
4657 	  m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
4658 	  if (m == NULL)
4659 	    goto error_return;
4660 
4661 	  *pm = m;
4662 	  pm = &m->next;
4663 	}
4664 
4665       /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
4666       if (dynsec != NULL)
4667 	{
4668 	  m = _bfd_elf_make_dynamic_segment (abfd, dynsec);
4669 	  if (m == NULL)
4670 	    goto error_return;
4671 	  *pm = m;
4672 	  pm = &m->next;
4673 	}
4674 
4675       /* For each batch of consecutive loadable .note sections,
4676 	 add a PT_NOTE segment.  We don't use bfd_get_section_by_name,
4677 	 because if we link together nonloadable .note sections and
4678 	 loadable .note sections, we will generate two .note sections
4679 	 in the output file.  FIXME: Using names for section types is
4680 	 bogus anyhow.  */
4681       for (s = abfd->sections; s != NULL; s = s->next)
4682 	{
4683 	  if ((s->flags & SEC_LOAD) != 0
4684 	      && CONST_STRNEQ (s->name, ".note"))
4685 	    {
4686 	      asection *s2;
4687 
4688 	      count = 1;
4689 	      amt = sizeof (struct elf_segment_map);
4690 	      if (s->alignment_power == 2)
4691 		for (s2 = s; s2->next != NULL; s2 = s2->next)
4692 		  {
4693 		    if (s2->next->alignment_power == 2
4694 			&& (s2->next->flags & SEC_LOAD) != 0
4695 			&& CONST_STRNEQ (s2->next->name, ".note")
4696 			&& align_power (s2->lma + s2->size, 2)
4697 			   == s2->next->lma)
4698 		      count++;
4699 		    else
4700 		      break;
4701 		  }
4702 	      amt += (count - 1) * sizeof (asection *);
4703 	      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4704 	      if (m == NULL)
4705 		goto error_return;
4706 	      m->next = NULL;
4707 	      m->p_type = PT_NOTE;
4708 	      m->count = count;
4709 	      while (count > 1)
4710 		{
4711 		  m->sections[m->count - count--] = s;
4712 		  BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
4713 		  s = s->next;
4714 		}
4715 	      m->sections[m->count - 1] = s;
4716 	      BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
4717 	      *pm = m;
4718 	      pm = &m->next;
4719 	    }
4720 	  if (s->flags & SEC_THREAD_LOCAL)
4721 	    {
4722 	      if (! tls_count)
4723 		first_tls = s;
4724 	      tls_count++;
4725 	    }
4726 	}
4727 
4728       /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
4729       if (tls_count > 0)
4730 	{
4731 	  amt = sizeof (struct elf_segment_map);
4732 	  amt += (tls_count - 1) * sizeof (asection *);
4733 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4734 	  if (m == NULL)
4735 	    goto error_return;
4736 	  m->next = NULL;
4737 	  m->p_type = PT_TLS;
4738 	  m->count = tls_count;
4739 	  /* Mandated PF_R.  */
4740 	  m->p_flags = PF_R;
4741 	  m->p_flags_valid = 1;
4742 	  s = first_tls;
4743 	  for (i = 0; i < (unsigned int) tls_count; ++i)
4744 	    {
4745 	      if ((s->flags & SEC_THREAD_LOCAL) == 0)
4746 		{
4747 		  _bfd_error_handler
4748 		    (_("%B: TLS sections are not adjacent:"), abfd);
4749 		  s = first_tls;
4750 		  i = 0;
4751 		  while (i < (unsigned int) tls_count)
4752 		    {
4753 		      if ((s->flags & SEC_THREAD_LOCAL) != 0)
4754 			{
4755 			  _bfd_error_handler (_("	    TLS: %A"), s);
4756 			  i++;
4757 			}
4758 		      else
4759 			_bfd_error_handler (_("	non-TLS: %A"), s);
4760 		      s = s->next;
4761 		    }
4762 		  bfd_set_error (bfd_error_bad_value);
4763 		  goto error_return;
4764 		}
4765 	      m->sections[i] = s;
4766 	      s = s->next;
4767 	    }
4768 
4769 	  *pm = m;
4770 	  pm = &m->next;
4771 	}
4772 
4773       /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
4774 	 segment.  */
4775       eh_frame_hdr = elf_eh_frame_hdr (abfd);
4776       if (eh_frame_hdr != NULL
4777 	  && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
4778 	{
4779 	  amt = sizeof (struct elf_segment_map);
4780 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4781 	  if (m == NULL)
4782 	    goto error_return;
4783 	  m->next = NULL;
4784 	  m->p_type = PT_GNU_EH_FRAME;
4785 	  m->count = 1;
4786 	  m->sections[0] = eh_frame_hdr->output_section;
4787 
4788 	  *pm = m;
4789 	  pm = &m->next;
4790 	}
4791 
4792       if (elf_stack_flags (abfd))
4793 	{
4794 	  amt = sizeof (struct elf_segment_map);
4795 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4796 	  if (m == NULL)
4797 	    goto error_return;
4798 	  m->next = NULL;
4799 	  m->p_type = PT_GNU_STACK;
4800 	  m->p_flags = elf_stack_flags (abfd);
4801 	  m->p_align = bed->stack_align;
4802 	  m->p_flags_valid = 1;
4803 	  m->p_align_valid = m->p_align != 0;
4804 	  if (info->stacksize > 0)
4805 	    {
4806 	      m->p_size = info->stacksize;
4807 	      m->p_size_valid = 1;
4808 	    }
4809 
4810 	  *pm = m;
4811 	  pm = &m->next;
4812 	}
4813 
4814       if (info != NULL && info->relro)
4815 	{
4816 	  for (m = mfirst; m != NULL; m = m->next)
4817 	    {
4818 	      if (m->p_type == PT_LOAD
4819 		  && m->count != 0
4820 		  && m->sections[0]->vma >= info->relro_start
4821 		  && m->sections[0]->vma < info->relro_end)
4822 		{
4823 		  i = m->count;
4824 		  while (--i != (unsigned) -1)
4825 		    if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS))
4826 			== (SEC_LOAD | SEC_HAS_CONTENTS))
4827 		      break;
4828 
4829 		  if (i != (unsigned) -1)
4830 		    break;
4831 		}
4832 	    }
4833 
4834 	  /* Make a PT_GNU_RELRO segment only when it isn't empty.  */
4835 	  if (m != NULL)
4836 	    {
4837 	      amt = sizeof (struct elf_segment_map);
4838 	      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4839 	      if (m == NULL)
4840 		goto error_return;
4841 	      m->next = NULL;
4842 	      m->p_type = PT_GNU_RELRO;
4843 	      *pm = m;
4844 	      pm = &m->next;
4845 	    }
4846 	}
4847 
4848       free (sections);
4849       elf_seg_map (abfd) = mfirst;
4850     }
4851 
4852   if (!elf_modify_segment_map (abfd, info, no_user_phdrs))
4853     return FALSE;
4854 
4855   for (count = 0, m = elf_seg_map (abfd); m != NULL; m = m->next)
4856     ++count;
4857   elf_program_header_size (abfd) = count * bed->s->sizeof_phdr;
4858 
4859   return TRUE;
4860 
4861  error_return:
4862   if (sections != NULL)
4863     free (sections);
4864   return FALSE;
4865 }
4866 
4867 /* Sort sections by address.  */
4868 
4869 static int
4870 elf_sort_sections (const void *arg1, const void *arg2)
4871 {
4872   const asection *sec1 = *(const asection **) arg1;
4873   const asection *sec2 = *(const asection **) arg2;
4874   bfd_size_type size1, size2;
4875 
4876   /* Sort by LMA first, since this is the address used to
4877      place the section into a segment.  */
4878   if (sec1->lma < sec2->lma)
4879     return -1;
4880   else if (sec1->lma > sec2->lma)
4881     return 1;
4882 
4883   /* Then sort by VMA.  Normally the LMA and the VMA will be
4884      the same, and this will do nothing.  */
4885   if (sec1->vma < sec2->vma)
4886     return -1;
4887   else if (sec1->vma > sec2->vma)
4888     return 1;
4889 
4890   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
4891 
4892 #define TOEND(x) (((x)->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0)
4893 
4894   if (TOEND (sec1))
4895     {
4896       if (TOEND (sec2))
4897 	{
4898 	  /* If the indicies are the same, do not return 0
4899 	     here, but continue to try the next comparison.  */
4900 	  if (sec1->target_index - sec2->target_index != 0)
4901 	    return sec1->target_index - sec2->target_index;
4902 	}
4903       else
4904 	return 1;
4905     }
4906   else if (TOEND (sec2))
4907     return -1;
4908 
4909 #undef TOEND
4910 
4911   /* Sort by size, to put zero sized sections
4912      before others at the same address.  */
4913 
4914   size1 = (sec1->flags & SEC_LOAD) ? sec1->size : 0;
4915   size2 = (sec2->flags & SEC_LOAD) ? sec2->size : 0;
4916 
4917   if (size1 < size2)
4918     return -1;
4919   if (size1 > size2)
4920     return 1;
4921 
4922   return sec1->target_index - sec2->target_index;
4923 }
4924 
4925 /* Ian Lance Taylor writes:
4926 
4927    We shouldn't be using % with a negative signed number.  That's just
4928    not good.  We have to make sure either that the number is not
4929    negative, or that the number has an unsigned type.  When the types
4930    are all the same size they wind up as unsigned.  When file_ptr is a
4931    larger signed type, the arithmetic winds up as signed long long,
4932    which is wrong.
4933 
4934    What we're trying to say here is something like ``increase OFF by
4935    the least amount that will cause it to be equal to the VMA modulo
4936    the page size.''  */
4937 /* In other words, something like:
4938 
4939    vma_offset = m->sections[0]->vma % bed->maxpagesize;
4940    off_offset = off % bed->maxpagesize;
4941    if (vma_offset < off_offset)
4942      adjustment = vma_offset + bed->maxpagesize - off_offset;
4943    else
4944      adjustment = vma_offset - off_offset;
4945 
4946    which can can be collapsed into the expression below.  */
4947 
4948 static file_ptr
4949 vma_page_aligned_bias (bfd_vma vma, ufile_ptr off, bfd_vma maxpagesize)
4950 {
4951   /* PR binutils/16199: Handle an alignment of zero.  */
4952   if (maxpagesize == 0)
4953     maxpagesize = 1;
4954   return ((vma - off) % maxpagesize);
4955 }
4956 
4957 static void
4958 print_segment_map (const struct elf_segment_map *m)
4959 {
4960   unsigned int j;
4961   const char *pt = get_segment_type (m->p_type);
4962   char buf[32];
4963 
4964   if (pt == NULL)
4965     {
4966       if (m->p_type >= PT_LOPROC && m->p_type <= PT_HIPROC)
4967 	sprintf (buf, "LOPROC+%7.7x",
4968 		 (unsigned int) (m->p_type - PT_LOPROC));
4969       else if (m->p_type >= PT_LOOS && m->p_type <= PT_HIOS)
4970 	sprintf (buf, "LOOS+%7.7x",
4971 		 (unsigned int) (m->p_type - PT_LOOS));
4972       else
4973 	snprintf (buf, sizeof (buf), "%8.8x",
4974 		  (unsigned int) m->p_type);
4975       pt = buf;
4976     }
4977   fflush (stdout);
4978   fprintf (stderr, "%s:", pt);
4979   for (j = 0; j < m->count; j++)
4980     fprintf (stderr, " %s", m->sections [j]->name);
4981   putc ('\n',stderr);
4982   fflush (stderr);
4983 }
4984 
4985 static bfd_boolean
4986 write_zeros (bfd *abfd, file_ptr pos, bfd_size_type len)
4987 {
4988   void *buf;
4989   bfd_boolean ret;
4990 
4991   if (bfd_seek (abfd, pos, SEEK_SET) != 0)
4992     return FALSE;
4993   buf = bfd_zmalloc (len);
4994   if (buf == NULL)
4995     return FALSE;
4996   ret = bfd_bwrite (buf, len, abfd) == len;
4997   free (buf);
4998   return ret;
4999 }
5000 
5001 /* Assign file positions to the sections based on the mapping from
5002    sections to segments.  This function also sets up some fields in
5003    the file header.  */
5004 
5005 static bfd_boolean
5006 assign_file_positions_for_load_sections (bfd *abfd,
5007 					 struct bfd_link_info *link_info)
5008 {
5009   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5010   struct elf_segment_map *m;
5011   Elf_Internal_Phdr *phdrs;
5012   Elf_Internal_Phdr *p;
5013   file_ptr off;
5014   bfd_size_type maxpagesize;
5015   unsigned int alloc;
5016   unsigned int i, j;
5017   bfd_vma header_pad = 0;
5018 
5019   if (link_info == NULL
5020       && !_bfd_elf_map_sections_to_segments (abfd, link_info))
5021     return FALSE;
5022 
5023   alloc = 0;
5024   for (m = elf_seg_map (abfd); m != NULL; m = m->next)
5025     {
5026       ++alloc;
5027       if (m->header_size)
5028 	header_pad = m->header_size;
5029     }
5030 
5031   if (alloc)
5032     {
5033       elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
5034       elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
5035     }
5036   else
5037     {
5038       /* PR binutils/12467.  */
5039       elf_elfheader (abfd)->e_phoff = 0;
5040       elf_elfheader (abfd)->e_phentsize = 0;
5041     }
5042 
5043   elf_elfheader (abfd)->e_phnum = alloc;
5044 
5045   if (elf_program_header_size (abfd) == (bfd_size_type) -1)
5046     elf_program_header_size (abfd) = alloc * bed->s->sizeof_phdr;
5047   else
5048     BFD_ASSERT (elf_program_header_size (abfd)
5049 		>= alloc * bed->s->sizeof_phdr);
5050 
5051   if (alloc == 0)
5052     {
5053       elf_next_file_pos (abfd) = bed->s->sizeof_ehdr;
5054       return TRUE;
5055     }
5056 
5057   /* We're writing the size in elf_program_header_size (abfd),
5058      see assign_file_positions_except_relocs, so make sure we have
5059      that amount allocated, with trailing space cleared.
5060      The variable alloc contains the computed need, while
5061      elf_program_header_size (abfd) contains the size used for the
5062      layout.
5063      See ld/emultempl/elf-generic.em:gld${EMULATION_NAME}_map_segments
5064      where the layout is forced to according to a larger size in the
5065      last iterations for the testcase ld-elf/header.  */
5066   BFD_ASSERT (elf_program_header_size (abfd) % bed->s->sizeof_phdr
5067 	      == 0);
5068   phdrs = (Elf_Internal_Phdr *)
5069      bfd_zalloc2 (abfd,
5070                   (elf_program_header_size (abfd) / bed->s->sizeof_phdr),
5071                   sizeof (Elf_Internal_Phdr));
5072   elf_tdata (abfd)->phdr = phdrs;
5073   if (phdrs == NULL)
5074     return FALSE;
5075 
5076   maxpagesize = 1;
5077   if ((abfd->flags & D_PAGED) != 0)
5078     maxpagesize = bed->maxpagesize;
5079 
5080   off = bed->s->sizeof_ehdr;
5081   off += alloc * bed->s->sizeof_phdr;
5082   if (header_pad < (bfd_vma) off)
5083     header_pad = 0;
5084   else
5085     header_pad -= off;
5086   off += header_pad;
5087 
5088   for (m = elf_seg_map (abfd), p = phdrs, j = 0;
5089        m != NULL;
5090        m = m->next, p++, j++)
5091     {
5092       asection **secpp;
5093       bfd_vma off_adjust;
5094       bfd_boolean no_contents;
5095 
5096       /* If elf_segment_map is not from map_sections_to_segments, the
5097 	 sections may not be correctly ordered.  NOTE: sorting should
5098 	 not be done to the PT_NOTE section of a corefile, which may
5099 	 contain several pseudo-sections artificially created by bfd.
5100 	 Sorting these pseudo-sections breaks things badly.  */
5101       if (m->count > 1
5102 	  && !(elf_elfheader (abfd)->e_type == ET_CORE
5103 	       && m->p_type == PT_NOTE))
5104 	qsort (m->sections, (size_t) m->count, sizeof (asection *),
5105 	       elf_sort_sections);
5106 
5107       /* An ELF segment (described by Elf_Internal_Phdr) may contain a
5108 	 number of sections with contents contributing to both p_filesz
5109 	 and p_memsz, followed by a number of sections with no contents
5110 	 that just contribute to p_memsz.  In this loop, OFF tracks next
5111 	 available file offset for PT_LOAD and PT_NOTE segments.  */
5112       p->p_type = m->p_type;
5113       p->p_flags = m->p_flags;
5114 
5115       if (m->count == 0)
5116 	p->p_vaddr = 0;
5117       else
5118 	p->p_vaddr = m->sections[0]->vma - m->p_vaddr_offset;
5119 
5120       if (m->p_paddr_valid)
5121 	p->p_paddr = m->p_paddr;
5122       else if (m->count == 0)
5123 	p->p_paddr = 0;
5124       else
5125 	p->p_paddr = m->sections[0]->lma - m->p_vaddr_offset;
5126 
5127       if (p->p_type == PT_LOAD
5128 	  && (abfd->flags & D_PAGED) != 0)
5129 	{
5130 	  /* p_align in demand paged PT_LOAD segments effectively stores
5131 	     the maximum page size.  When copying an executable with
5132 	     objcopy, we set m->p_align from the input file.  Use this
5133 	     value for maxpagesize rather than bed->maxpagesize, which
5134 	     may be different.  Note that we use maxpagesize for PT_TLS
5135 	     segment alignment later in this function, so we are relying
5136 	     on at least one PT_LOAD segment appearing before a PT_TLS
5137 	     segment.  */
5138 	  if (m->p_align_valid)
5139 	    maxpagesize = m->p_align;
5140 
5141 	  p->p_align = maxpagesize;
5142 	}
5143       else if (m->p_align_valid)
5144 	p->p_align = m->p_align;
5145       else if (m->count == 0)
5146 	p->p_align = 1 << bed->s->log_file_align;
5147       else
5148 	p->p_align = 0;
5149 
5150       no_contents = FALSE;
5151       off_adjust = 0;
5152       if (p->p_type == PT_LOAD
5153 	  && m->count > 0)
5154 	{
5155 	  bfd_size_type align;
5156 	  unsigned int align_power = 0;
5157 
5158 	  if (m->p_align_valid)
5159 	    align = p->p_align;
5160 	  else
5161 	    {
5162 	      for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
5163 		{
5164 		  unsigned int secalign;
5165 
5166 		  secalign = bfd_get_section_alignment (abfd, *secpp);
5167 		  if (secalign > align_power)
5168 		    align_power = secalign;
5169 		}
5170 	      align = (bfd_size_type) 1 << align_power;
5171 	      if (align < maxpagesize)
5172 		align = maxpagesize;
5173 	    }
5174 
5175 	  for (i = 0; i < m->count; i++)
5176 	    if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
5177 	      /* If we aren't making room for this section, then
5178 		 it must be SHT_NOBITS regardless of what we've
5179 		 set via struct bfd_elf_special_section.  */
5180 	      elf_section_type (m->sections[i]) = SHT_NOBITS;
5181 
5182 	  /* Find out whether this segment contains any loadable
5183 	     sections.  */
5184 	  no_contents = TRUE;
5185 	  for (i = 0; i < m->count; i++)
5186 	    if (elf_section_type (m->sections[i]) != SHT_NOBITS)
5187 	      {
5188 		no_contents = FALSE;
5189 		break;
5190 	      }
5191 
5192 	  off_adjust = vma_page_aligned_bias (p->p_vaddr, off, align);
5193 	  off += off_adjust;
5194 	  if (no_contents)
5195 	    {
5196 	      /* We shouldn't need to align the segment on disk since
5197 		 the segment doesn't need file space, but the gABI
5198 		 arguably requires the alignment and glibc ld.so
5199 		 checks it.  So to comply with the alignment
5200 		 requirement but not waste file space, we adjust
5201 		 p_offset for just this segment.  (OFF_ADJUST is
5202 		 subtracted from OFF later.)  This may put p_offset
5203 		 past the end of file, but that shouldn't matter.  */
5204 	    }
5205 	  else
5206 	    off_adjust = 0;
5207 	}
5208       /* Make sure the .dynamic section is the first section in the
5209 	 PT_DYNAMIC segment.  */
5210       else if (p->p_type == PT_DYNAMIC
5211 	       && m->count > 1
5212 	       && strcmp (m->sections[0]->name, ".dynamic") != 0)
5213 	{
5214 	  _bfd_error_handler
5215 	    (_("%B: The first section in the PT_DYNAMIC segment is not the .dynamic section"),
5216 	     abfd);
5217 	  bfd_set_error (bfd_error_bad_value);
5218 	  return FALSE;
5219 	}
5220       /* Set the note section type to SHT_NOTE.  */
5221       else if (p->p_type == PT_NOTE)
5222 	for (i = 0; i < m->count; i++)
5223 	  elf_section_type (m->sections[i]) = SHT_NOTE;
5224 
5225       p->p_offset = 0;
5226       p->p_filesz = 0;
5227       p->p_memsz = 0;
5228 
5229       if (m->includes_filehdr)
5230 	{
5231 	  if (!m->p_flags_valid)
5232 	    p->p_flags |= PF_R;
5233 	  p->p_filesz = bed->s->sizeof_ehdr;
5234 	  p->p_memsz = bed->s->sizeof_ehdr;
5235 	  if (m->count > 0)
5236 	    {
5237 	      if (p->p_vaddr < (bfd_vma) off)
5238 		{
5239 		  (*_bfd_error_handler)
5240 		    (_("%B: Not enough room for program headers, try linking with -N"),
5241 		     abfd);
5242 		  bfd_set_error (bfd_error_bad_value);
5243 		  return FALSE;
5244 		}
5245 
5246 	      p->p_vaddr -= off;
5247 	      if (!m->p_paddr_valid)
5248 		p->p_paddr -= off;
5249 	    }
5250 	}
5251 
5252       if (m->includes_phdrs)
5253 	{
5254 	  if (!m->p_flags_valid)
5255 	    p->p_flags |= PF_R;
5256 
5257 	  if (!m->includes_filehdr)
5258 	    {
5259 	      p->p_offset = bed->s->sizeof_ehdr;
5260 
5261 	      if (m->count > 0)
5262 		{
5263 		  p->p_vaddr -= off - p->p_offset;
5264 		  if (!m->p_paddr_valid)
5265 		    p->p_paddr -= off - p->p_offset;
5266 		}
5267 	    }
5268 
5269 	  p->p_filesz += alloc * bed->s->sizeof_phdr;
5270 	  p->p_memsz += alloc * bed->s->sizeof_phdr;
5271 	  if (m->count)
5272 	    {
5273 	      p->p_filesz += header_pad;
5274 	      p->p_memsz += header_pad;
5275 	    }
5276 	}
5277 
5278       if (p->p_type == PT_LOAD
5279 	  || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
5280 	{
5281 	  if (!m->includes_filehdr && !m->includes_phdrs)
5282 	    p->p_offset = off;
5283 	  else
5284 	    {
5285 	      file_ptr adjust;
5286 
5287 	      adjust = off - (p->p_offset + p->p_filesz);
5288 	      if (!no_contents)
5289 		p->p_filesz += adjust;
5290 	      p->p_memsz += adjust;
5291 	    }
5292 	}
5293 
5294       /* Set up p_filesz, p_memsz, p_align and p_flags from the section
5295 	 maps.  Set filepos for sections in PT_LOAD segments, and in
5296 	 core files, for sections in PT_NOTE segments.
5297 	 assign_file_positions_for_non_load_sections will set filepos
5298 	 for other sections and update p_filesz for other segments.  */
5299       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
5300 	{
5301 	  asection *sec;
5302 	  bfd_size_type align;
5303 	  Elf_Internal_Shdr *this_hdr;
5304 
5305 	  sec = *secpp;
5306 	  this_hdr = &elf_section_data (sec)->this_hdr;
5307 	  align = (bfd_size_type) 1 << bfd_get_section_alignment (abfd, sec);
5308 
5309 	  if ((p->p_type == PT_LOAD
5310 	       || p->p_type == PT_TLS)
5311 	      && (this_hdr->sh_type != SHT_NOBITS
5312 		  || ((this_hdr->sh_flags & SHF_ALLOC) != 0
5313 		      && ((this_hdr->sh_flags & SHF_TLS) == 0
5314 			  || p->p_type == PT_TLS))))
5315 	    {
5316 	      bfd_vma p_start = p->p_paddr;
5317 	      bfd_vma p_end = p_start + p->p_memsz;
5318 	      bfd_vma s_start = sec->lma;
5319 	      bfd_vma adjust = s_start - p_end;
5320 
5321 	      if (adjust != 0
5322 		  && (s_start < p_end
5323 		      || p_end < p_start))
5324 		{
5325 		  (*_bfd_error_handler)
5326 		    (_("%B: section %A lma %#lx adjusted to %#lx"), abfd, sec,
5327 		     (unsigned long) s_start, (unsigned long) p_end);
5328 		  adjust = 0;
5329 		  sec->lma = p_end;
5330 		}
5331 	      p->p_memsz += adjust;
5332 
5333 	      if (this_hdr->sh_type != SHT_NOBITS)
5334 		{
5335 		  if (p->p_filesz + adjust < p->p_memsz)
5336 		    {
5337 		      /* We have a PROGBITS section following NOBITS ones.
5338 		         Allocate file space for the NOBITS section(s) and
5339 			 zero it.  */
5340 		      adjust = p->p_memsz - p->p_filesz;
5341 		      if (!write_zeros (abfd, off, adjust))
5342 			return FALSE;
5343 		    }
5344 		  off += adjust;
5345 		  p->p_filesz += adjust;
5346 		}
5347 	    }
5348 
5349 	  if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
5350 	    {
5351 	      /* The section at i == 0 is the one that actually contains
5352 		 everything.  */
5353 	      if (i == 0)
5354 		{
5355 		  this_hdr->sh_offset = sec->filepos = off;
5356 		  off += this_hdr->sh_size;
5357 		  p->p_filesz = this_hdr->sh_size;
5358 		  p->p_memsz = 0;
5359 		  p->p_align = 1;
5360 		}
5361 	      else
5362 		{
5363 		  /* The rest are fake sections that shouldn't be written.  */
5364 		  sec->filepos = 0;
5365 		  sec->size = 0;
5366 		  sec->flags = 0;
5367 		  continue;
5368 		}
5369 	    }
5370 	  else
5371 	    {
5372 	      if (p->p_type == PT_LOAD)
5373 		{
5374 		  this_hdr->sh_offset = sec->filepos = off;
5375 		  if (this_hdr->sh_type != SHT_NOBITS)
5376 		    off += this_hdr->sh_size;
5377 		}
5378 	      else if (this_hdr->sh_type == SHT_NOBITS
5379 		       && (this_hdr->sh_flags & SHF_TLS) != 0
5380 		       && this_hdr->sh_offset == 0)
5381 		{
5382 		  /* This is a .tbss section that didn't get a PT_LOAD.
5383 		     (See _bfd_elf_map_sections_to_segments "Create a
5384 		     final PT_LOAD".)  Set sh_offset to the value it
5385 		     would have if we had created a zero p_filesz and
5386 		     p_memsz PT_LOAD header for the section.  This
5387 		     also makes the PT_TLS header have the same
5388 		     p_offset value.  */
5389 		  bfd_vma adjust = vma_page_aligned_bias (this_hdr->sh_addr,
5390 							  off, align);
5391 		  this_hdr->sh_offset = sec->filepos = off + adjust;
5392 		}
5393 
5394 	      if (this_hdr->sh_type != SHT_NOBITS)
5395 		{
5396 		  p->p_filesz += this_hdr->sh_size;
5397 		  /* A load section without SHF_ALLOC is something like
5398 		     a note section in a PT_NOTE segment.  These take
5399 		     file space but are not loaded into memory.  */
5400 		  if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
5401 		    p->p_memsz += this_hdr->sh_size;
5402 		}
5403 	      else if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
5404 		{
5405 		  if (p->p_type == PT_TLS)
5406 		    p->p_memsz += this_hdr->sh_size;
5407 
5408 		  /* .tbss is special.  It doesn't contribute to p_memsz of
5409 		     normal segments.  */
5410 		  else if ((this_hdr->sh_flags & SHF_TLS) == 0)
5411 		    p->p_memsz += this_hdr->sh_size;
5412 		}
5413 
5414 	      if (align > p->p_align
5415 		  && !m->p_align_valid
5416 		  && (p->p_type != PT_LOAD
5417 		      || (abfd->flags & D_PAGED) == 0))
5418 		p->p_align = align;
5419 	    }
5420 
5421 	  if (!m->p_flags_valid)
5422 	    {
5423 	      p->p_flags |= PF_R;
5424 	      if ((this_hdr->sh_flags & SHF_EXECINSTR) != 0)
5425 		p->p_flags |= PF_X;
5426 	      if ((this_hdr->sh_flags & SHF_WRITE) != 0)
5427 		p->p_flags |= PF_W;
5428 	    }
5429 	}
5430 
5431       off -= off_adjust;
5432 
5433       /* Check that all sections are in a PT_LOAD segment.
5434 	 Don't check funky gdb generated core files.  */
5435       if (p->p_type == PT_LOAD && bfd_get_format (abfd) != bfd_core)
5436 	{
5437 	  bfd_boolean check_vma = TRUE;
5438 
5439 	  for (i = 1; i < m->count; i++)
5440 	    if (m->sections[i]->vma == m->sections[i - 1]->vma
5441 		&& ELF_SECTION_SIZE (&(elf_section_data (m->sections[i])
5442 				       ->this_hdr), p) != 0
5443 		&& ELF_SECTION_SIZE (&(elf_section_data (m->sections[i - 1])
5444 				       ->this_hdr), p) != 0)
5445 	      {
5446 		/* Looks like we have overlays packed into the segment.  */
5447 		check_vma = FALSE;
5448 		break;
5449 	      }
5450 
5451 	  for (i = 0; i < m->count; i++)
5452 	    {
5453 	      Elf_Internal_Shdr *this_hdr;
5454 	      asection *sec;
5455 
5456 	      sec = m->sections[i];
5457 	      this_hdr = &(elf_section_data(sec)->this_hdr);
5458 	      if (!ELF_SECTION_IN_SEGMENT_1 (this_hdr, p, check_vma, 0)
5459 		  && !ELF_TBSS_SPECIAL (this_hdr, p))
5460 		{
5461 		  (*_bfd_error_handler)
5462 		    (_("%B: section `%A' can't be allocated in segment %d"),
5463 		     abfd, sec, j);
5464 		  print_segment_map (m);
5465 		}
5466 	    }
5467 	}
5468     }
5469 
5470   elf_next_file_pos (abfd) = off;
5471   return TRUE;
5472 }
5473 
5474 /* Assign file positions for the other sections.  */
5475 
5476 static bfd_boolean
5477 assign_file_positions_for_non_load_sections (bfd *abfd,
5478 					     struct bfd_link_info *link_info)
5479 {
5480   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5481   Elf_Internal_Shdr **i_shdrpp;
5482   Elf_Internal_Shdr **hdrpp, **end_hdrpp;
5483   Elf_Internal_Phdr *phdrs;
5484   Elf_Internal_Phdr *p;
5485   struct elf_segment_map *m;
5486   struct elf_segment_map *hdrs_segment;
5487   bfd_vma filehdr_vaddr, filehdr_paddr;
5488   bfd_vma phdrs_vaddr, phdrs_paddr;
5489   file_ptr off;
5490   unsigned int count;
5491 
5492   i_shdrpp = elf_elfsections (abfd);
5493   end_hdrpp = i_shdrpp + elf_numsections (abfd);
5494   off = elf_next_file_pos (abfd);
5495   for (hdrpp = i_shdrpp + 1; hdrpp < end_hdrpp; hdrpp++)
5496     {
5497       Elf_Internal_Shdr *hdr;
5498 
5499       hdr = *hdrpp;
5500       if (hdr->bfd_section != NULL
5501 	  && (hdr->bfd_section->filepos != 0
5502 	      || (hdr->sh_type == SHT_NOBITS
5503 		  && hdr->contents == NULL)))
5504 	BFD_ASSERT (hdr->sh_offset == hdr->bfd_section->filepos);
5505       else if ((hdr->sh_flags & SHF_ALLOC) != 0)
5506 	{
5507 	  if (hdr->sh_size != 0)
5508 	    (*_bfd_error_handler)
5509 	      (_("%B: warning: allocated section `%s' not in segment"),
5510 	       abfd,
5511 	       (hdr->bfd_section == NULL
5512 		? "*unknown*"
5513 		: hdr->bfd_section->name));
5514 	  /* We don't need to page align empty sections.  */
5515 	  if ((abfd->flags & D_PAGED) != 0 && hdr->sh_size != 0)
5516 	    off += vma_page_aligned_bias (hdr->sh_addr, off,
5517 					  bed->maxpagesize);
5518 	  else
5519 	    off += vma_page_aligned_bias (hdr->sh_addr, off,
5520 					  hdr->sh_addralign);
5521 	  off = _bfd_elf_assign_file_position_for_section (hdr, off,
5522 							   FALSE);
5523 	}
5524       else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
5525 		&& hdr->bfd_section == NULL)
5526 	       || (hdr->bfd_section != NULL
5527 		   && (hdr->bfd_section->flags & SEC_ELF_COMPRESS))
5528 		   /* Compress DWARF debug sections.  */
5529 	       || hdr == i_shdrpp[elf_onesymtab (abfd)]
5530 	       || (elf_symtab_shndx_list (abfd) != NULL
5531 		   && hdr == i_shdrpp[elf_symtab_shndx_list (abfd)->ndx])
5532 	       || hdr == i_shdrpp[elf_strtab_sec (abfd)]
5533 	       || hdr == i_shdrpp[elf_shstrtab_sec (abfd)])
5534 	hdr->sh_offset = -1;
5535       else
5536 	off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
5537     }
5538 
5539   /* Now that we have set the section file positions, we can set up
5540      the file positions for the non PT_LOAD segments.  */
5541   count = 0;
5542   filehdr_vaddr = 0;
5543   filehdr_paddr = 0;
5544   phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
5545   phdrs_paddr = 0;
5546   hdrs_segment = NULL;
5547   phdrs = elf_tdata (abfd)->phdr;
5548   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
5549     {
5550       ++count;
5551       if (p->p_type != PT_LOAD)
5552 	continue;
5553 
5554       if (m->includes_filehdr)
5555 	{
5556 	  filehdr_vaddr = p->p_vaddr;
5557 	  filehdr_paddr = p->p_paddr;
5558 	}
5559       if (m->includes_phdrs)
5560 	{
5561 	  phdrs_vaddr = p->p_vaddr;
5562 	  phdrs_paddr = p->p_paddr;
5563 	  if (m->includes_filehdr)
5564 	    {
5565 	      hdrs_segment = m;
5566 	      phdrs_vaddr += bed->s->sizeof_ehdr;
5567 	      phdrs_paddr += bed->s->sizeof_ehdr;
5568 	    }
5569 	}
5570     }
5571 
5572   if (hdrs_segment != NULL && link_info != NULL)
5573     {
5574       /* There is a segment that contains both the file headers and the
5575 	 program headers, so provide a symbol __ehdr_start pointing there.
5576 	 A program can use this to examine itself robustly.  */
5577 
5578       struct elf_link_hash_entry *hash
5579 	= elf_link_hash_lookup (elf_hash_table (link_info), "__ehdr_start",
5580 				FALSE, FALSE, TRUE);
5581       /* If the symbol was referenced and not defined, define it.  */
5582       if (hash != NULL
5583 	  && (hash->root.type == bfd_link_hash_new
5584 	      || hash->root.type == bfd_link_hash_undefined
5585 	      || hash->root.type == bfd_link_hash_undefweak
5586 	      || hash->root.type == bfd_link_hash_common))
5587 	{
5588 	  asection *s = NULL;
5589 	  if (hdrs_segment->count != 0)
5590 	    /* The segment contains sections, so use the first one.  */
5591 	    s = hdrs_segment->sections[0];
5592 	  else
5593 	    /* Use the first (i.e. lowest-addressed) section in any segment.  */
5594 	    for (m = elf_seg_map (abfd); m != NULL; m = m->next)
5595 	      if (m->count != 0)
5596 		{
5597 		  s = m->sections[0];
5598 		  break;
5599 		}
5600 
5601 	  if (s != NULL)
5602 	    {
5603 	      hash->root.u.def.value = filehdr_vaddr - s->vma;
5604 	      hash->root.u.def.section = s;
5605 	    }
5606 	  else
5607 	    {
5608 	      hash->root.u.def.value = filehdr_vaddr;
5609 	      hash->root.u.def.section = bfd_abs_section_ptr;
5610 	    }
5611 
5612 	  hash->root.type = bfd_link_hash_defined;
5613 	  hash->def_regular = 1;
5614 	  hash->non_elf = 0;
5615 	}
5616     }
5617 
5618   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
5619     {
5620       if (p->p_type == PT_GNU_RELRO)
5621 	{
5622 	  const Elf_Internal_Phdr *lp;
5623 	  struct elf_segment_map *lm;
5624 
5625 	  if (link_info != NULL)
5626 	    {
5627 	      /* During linking the range of the RELRO segment is passed
5628 		 in link_info.  */
5629 	      for (lm = elf_seg_map (abfd), lp = phdrs;
5630 		   lm != NULL;
5631 		   lm = lm->next, lp++)
5632 		{
5633 		  if (lp->p_type == PT_LOAD
5634 		      && lp->p_vaddr < link_info->relro_end
5635 		      && lm->count != 0
5636 		      && lm->sections[0]->vma >= link_info->relro_start)
5637 		    break;
5638 		}
5639 
5640 	      BFD_ASSERT (lm != NULL);
5641 	    }
5642 	  else
5643 	    {
5644 	      /* Otherwise we are copying an executable or shared
5645 		 library, but we need to use the same linker logic.  */
5646 	      for (lp = phdrs; lp < phdrs + count; ++lp)
5647 		{
5648 		  if (lp->p_type == PT_LOAD
5649 		      && lp->p_paddr == p->p_paddr)
5650 		    break;
5651 		}
5652 	    }
5653 
5654 	  if (lp < phdrs + count)
5655 	    {
5656 	      p->p_vaddr = lp->p_vaddr;
5657 	      p->p_paddr = lp->p_paddr;
5658 	      p->p_offset = lp->p_offset;
5659 	      if (link_info != NULL)
5660 		p->p_filesz = link_info->relro_end - lp->p_vaddr;
5661 	      else if (m->p_size_valid)
5662 		p->p_filesz = m->p_size;
5663 	      else
5664 		abort ();
5665 	      p->p_memsz = p->p_filesz;
5666 	      /* Preserve the alignment and flags if they are valid. The
5667 	         gold linker generates RW/4 for the PT_GNU_RELRO section.
5668 		 It is better for objcopy/strip to honor these attributes
5669 		 otherwise gdb will choke when using separate debug files.
5670 	       */
5671 	      if (!m->p_align_valid)
5672 		p->p_align = 1;
5673 	      if (!m->p_flags_valid)
5674 		p->p_flags = PF_R;
5675 	    }
5676 	  else
5677 	    {
5678 	      memset (p, 0, sizeof *p);
5679 	      p->p_type = PT_NULL;
5680 	    }
5681 	}
5682       else if (p->p_type == PT_GNU_STACK)
5683 	{
5684 	  if (m->p_size_valid)
5685 	    p->p_memsz = m->p_size;
5686 	}
5687       else if (m->count != 0)
5688 	{
5689 	  unsigned int i;
5690 	  if (p->p_type != PT_LOAD
5691 	      && (p->p_type != PT_NOTE
5692 		  || bfd_get_format (abfd) != bfd_core))
5693 	    {
5694 	      if (m->includes_filehdr || m->includes_phdrs)
5695 		{
5696 		  /* PR 17512: file: 2195325e.  */
5697 		  (*_bfd_error_handler)
5698 		    (_("%B: warning: non-load segment includes file header and/or program header"),
5699 		     abfd);
5700 		  return FALSE;
5701 		}
5702 
5703 	      p->p_filesz = 0;
5704 	      p->p_offset = m->sections[0]->filepos;
5705 	      for (i = m->count; i-- != 0;)
5706 		{
5707 		  asection *sect = m->sections[i];
5708 		  Elf_Internal_Shdr *hdr = &elf_section_data (sect)->this_hdr;
5709 		  if (hdr->sh_type != SHT_NOBITS)
5710 		    {
5711 		      p->p_filesz = (sect->filepos - m->sections[0]->filepos
5712 				     + hdr->sh_size);
5713 		      break;
5714 		    }
5715 		}
5716 	    }
5717 	}
5718       else if (m->includes_filehdr)
5719 	{
5720 	  p->p_vaddr = filehdr_vaddr;
5721 	  if (! m->p_paddr_valid)
5722 	    p->p_paddr = filehdr_paddr;
5723 	}
5724       else if (m->includes_phdrs)
5725 	{
5726 	  p->p_vaddr = phdrs_vaddr;
5727 	  if (! m->p_paddr_valid)
5728 	    p->p_paddr = phdrs_paddr;
5729 	}
5730     }
5731 
5732   elf_next_file_pos (abfd) = off;
5733 
5734   return TRUE;
5735 }
5736 
5737 static elf_section_list *
5738 find_section_in_list (unsigned int i, elf_section_list * list)
5739 {
5740   for (;list != NULL; list = list->next)
5741     if (list->ndx == i)
5742       break;
5743   return list;
5744 }
5745 
5746 /* Work out the file positions of all the sections.  This is called by
5747    _bfd_elf_compute_section_file_positions.  All the section sizes and
5748    VMAs must be known before this is called.
5749 
5750    Reloc sections come in two flavours: Those processed specially as
5751    "side-channel" data attached to a section to which they apply, and
5752    those that bfd doesn't process as relocations.  The latter sort are
5753    stored in a normal bfd section by bfd_section_from_shdr.   We don't
5754    consider the former sort here, unless they form part of the loadable
5755    image.  Reloc sections not assigned here will be handled later by
5756    assign_file_positions_for_relocs.
5757 
5758    We also don't set the positions of the .symtab and .strtab here.  */
5759 
5760 static bfd_boolean
5761 assign_file_positions_except_relocs (bfd *abfd,
5762 				     struct bfd_link_info *link_info)
5763 {
5764   struct elf_obj_tdata *tdata = elf_tdata (abfd);
5765   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
5766   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5767 
5768   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
5769       && bfd_get_format (abfd) != bfd_core)
5770     {
5771       Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
5772       unsigned int num_sec = elf_numsections (abfd);
5773       Elf_Internal_Shdr **hdrpp;
5774       unsigned int i;
5775       file_ptr off;
5776 
5777       /* Start after the ELF header.  */
5778       off = i_ehdrp->e_ehsize;
5779 
5780       /* We are not creating an executable, which means that we are
5781 	 not creating a program header, and that the actual order of
5782 	 the sections in the file is unimportant.  */
5783       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
5784 	{
5785 	  Elf_Internal_Shdr *hdr;
5786 
5787 	  hdr = *hdrpp;
5788 	  if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
5789 	       && hdr->bfd_section == NULL)
5790 	      || (hdr->bfd_section != NULL
5791 		  && (hdr->bfd_section->flags & SEC_ELF_COMPRESS))
5792 		  /* Compress DWARF debug sections.  */
5793 	      || i == elf_onesymtab (abfd)
5794 	      || (elf_symtab_shndx_list (abfd) != NULL
5795 		  && hdr == i_shdrpp[elf_symtab_shndx_list (abfd)->ndx])
5796 	      || i == elf_strtab_sec (abfd)
5797 	      || i == elf_shstrtab_sec (abfd))
5798 	    {
5799 	      hdr->sh_offset = -1;
5800 	    }
5801 	  else
5802 	    off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
5803 	}
5804 
5805       elf_next_file_pos (abfd) = off;
5806     }
5807   else
5808     {
5809       unsigned int alloc;
5810 
5811       /* Assign file positions for the loaded sections based on the
5812 	 assignment of sections to segments.  */
5813       if (!assign_file_positions_for_load_sections (abfd, link_info))
5814 	return FALSE;
5815 
5816       /* And for non-load sections.  */
5817       if (!assign_file_positions_for_non_load_sections (abfd, link_info))
5818 	return FALSE;
5819 
5820       if (bed->elf_backend_modify_program_headers != NULL)
5821 	{
5822 	  if (!(*bed->elf_backend_modify_program_headers) (abfd, link_info))
5823 	    return FALSE;
5824 	}
5825 
5826       /* Set e_type in ELF header to ET_EXEC for -pie -Ttext-segment=.  */
5827       if (link_info != NULL && bfd_link_pie (link_info))
5828 	{
5829 	  unsigned int num_segments = elf_elfheader (abfd)->e_phnum;
5830 	  Elf_Internal_Phdr *segment = elf_tdata (abfd)->phdr;
5831 	  Elf_Internal_Phdr *end_segment = &segment[num_segments];
5832 
5833 	  /* Find the lowest p_vaddr in PT_LOAD segments.  */
5834 	  bfd_vma p_vaddr = (bfd_vma) -1;
5835 	  for (; segment < end_segment; segment++)
5836 	    if (segment->p_type == PT_LOAD && p_vaddr > segment->p_vaddr)
5837 	      p_vaddr = segment->p_vaddr;
5838 
5839 	  /* Set e_type to ET_EXEC if the lowest p_vaddr in PT_LOAD
5840 	     segments is non-zero.  */
5841 	  if (p_vaddr)
5842 	    i_ehdrp->e_type = ET_EXEC;
5843 	}
5844 
5845       /* Write out the program headers.  */
5846       alloc = elf_program_header_size (abfd) / bed->s->sizeof_phdr;
5847       if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
5848 	  || bed->s->write_out_phdrs (abfd, tdata->phdr, alloc) != 0)
5849 	return FALSE;
5850     }
5851 
5852   return TRUE;
5853 }
5854 
5855 static bfd_boolean
5856 prep_headers (bfd *abfd)
5857 {
5858   Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form.  */
5859   struct elf_strtab_hash *shstrtab;
5860   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5861 
5862   i_ehdrp = elf_elfheader (abfd);
5863 
5864   shstrtab = _bfd_elf_strtab_init ();
5865   if (shstrtab == NULL)
5866     return FALSE;
5867 
5868   elf_shstrtab (abfd) = shstrtab;
5869 
5870   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
5871   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
5872   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
5873   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
5874 
5875   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
5876   i_ehdrp->e_ident[EI_DATA] =
5877     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
5878   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
5879 
5880   if ((abfd->flags & DYNAMIC) != 0)
5881     i_ehdrp->e_type = ET_DYN;
5882   else if ((abfd->flags & EXEC_P) != 0)
5883     i_ehdrp->e_type = ET_EXEC;
5884   else if (bfd_get_format (abfd) == bfd_core)
5885     i_ehdrp->e_type = ET_CORE;
5886   else
5887     i_ehdrp->e_type = ET_REL;
5888 
5889   switch (bfd_get_arch (abfd))
5890     {
5891     case bfd_arch_unknown:
5892       i_ehdrp->e_machine = EM_NONE;
5893       break;
5894 
5895       /* There used to be a long list of cases here, each one setting
5896 	 e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
5897 	 in the corresponding bfd definition.  To avoid duplication,
5898 	 the switch was removed.  Machines that need special handling
5899 	 can generally do it in elf_backend_final_write_processing(),
5900 	 unless they need the information earlier than the final write.
5901 	 Such need can generally be supplied by replacing the tests for
5902 	 e_machine with the conditions used to determine it.  */
5903     default:
5904       i_ehdrp->e_machine = bed->elf_machine_code;
5905     }
5906 
5907   i_ehdrp->e_version = bed->s->ev_current;
5908   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
5909 
5910   /* No program header, for now.  */
5911   i_ehdrp->e_phoff = 0;
5912   i_ehdrp->e_phentsize = 0;
5913   i_ehdrp->e_phnum = 0;
5914 
5915   /* Each bfd section is section header entry.  */
5916   i_ehdrp->e_entry = bfd_get_start_address (abfd);
5917   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
5918 
5919   /* If we're building an executable, we'll need a program header table.  */
5920   if (abfd->flags & EXEC_P)
5921     /* It all happens later.  */
5922     ;
5923   else
5924     {
5925       i_ehdrp->e_phentsize = 0;
5926       i_ehdrp->e_phoff = 0;
5927     }
5928 
5929   elf_tdata (abfd)->symtab_hdr.sh_name =
5930     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", FALSE);
5931   elf_tdata (abfd)->strtab_hdr.sh_name =
5932     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", FALSE);
5933   elf_tdata (abfd)->shstrtab_hdr.sh_name =
5934     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", FALSE);
5935   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
5936       || elf_tdata (abfd)->strtab_hdr.sh_name == (unsigned int) -1
5937       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
5938     return FALSE;
5939 
5940   return TRUE;
5941 }
5942 
5943 /* Assign file positions for all the reloc sections which are not part
5944    of the loadable file image, and the file position of section headers.  */
5945 
5946 static bfd_boolean
5947 _bfd_elf_assign_file_positions_for_non_load (bfd *abfd)
5948 {
5949   file_ptr off;
5950   Elf_Internal_Shdr **shdrpp, **end_shdrpp;
5951   Elf_Internal_Shdr *shdrp;
5952   Elf_Internal_Ehdr *i_ehdrp;
5953   const struct elf_backend_data *bed;
5954 
5955   off = elf_next_file_pos (abfd);
5956 
5957   shdrpp = elf_elfsections (abfd);
5958   end_shdrpp = shdrpp + elf_numsections (abfd);
5959   for (shdrpp++; shdrpp < end_shdrpp; shdrpp++)
5960     {
5961       shdrp = *shdrpp;
5962       if (shdrp->sh_offset == -1)
5963 	{
5964 	  asection *sec = shdrp->bfd_section;
5965 	  bfd_boolean is_rel = (shdrp->sh_type == SHT_REL
5966 				|| shdrp->sh_type == SHT_RELA);
5967 	  if (is_rel
5968 	      || (sec != NULL && (sec->flags & SEC_ELF_COMPRESS)))
5969 	    {
5970 	      if (!is_rel)
5971 		{
5972 		  const char *name = sec->name;
5973 		  struct bfd_elf_section_data *d;
5974 
5975 		  /* Compress DWARF debug sections.  */
5976 		  if (!bfd_compress_section (abfd, sec,
5977 					     shdrp->contents))
5978 		    return FALSE;
5979 
5980 		  if (sec->compress_status == COMPRESS_SECTION_DONE
5981 		      && (abfd->flags & BFD_COMPRESS_GABI) == 0)
5982 		    {
5983 		      /* If section is compressed with zlib-gnu, convert
5984 			 section name from .debug_* to .zdebug_*.  */
5985 		      char *new_name
5986 			= convert_debug_to_zdebug (abfd, name);
5987 		      if (new_name == NULL)
5988 			return FALSE;
5989 		      name = new_name;
5990 		    }
5991 		  /* Add setion name to section name section.  */
5992 		  if (shdrp->sh_name != (unsigned int) -1)
5993 		    abort ();
5994 		  shdrp->sh_name
5995 		    = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
5996 							  name, FALSE);
5997 		  d = elf_section_data (sec);
5998 
5999 		  /* Add reloc setion name to section name section.  */
6000 		  if (d->rel.hdr
6001 		      && !_bfd_elf_set_reloc_sh_name (abfd,
6002 						      d->rel.hdr,
6003 						      name, FALSE))
6004 		    return FALSE;
6005 		  if (d->rela.hdr
6006 		      && !_bfd_elf_set_reloc_sh_name (abfd,
6007 						      d->rela.hdr,
6008 						      name, TRUE))
6009 		    return FALSE;
6010 
6011 		  /* Update section size and contents.  */
6012 		  shdrp->sh_size = sec->size;
6013 		  shdrp->contents = sec->contents;
6014 		  shdrp->bfd_section->contents = NULL;
6015 		}
6016 	      off = _bfd_elf_assign_file_position_for_section (shdrp,
6017 							       off,
6018 							       TRUE);
6019 	    }
6020 	}
6021     }
6022 
6023   /* Place section name section after DWARF debug sections have been
6024      compressed.  */
6025   _bfd_elf_strtab_finalize (elf_shstrtab (abfd));
6026   shdrp = &elf_tdata (abfd)->shstrtab_hdr;
6027   shdrp->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
6028   off = _bfd_elf_assign_file_position_for_section (shdrp, off, TRUE);
6029 
6030   /* Place the section headers.  */
6031   i_ehdrp = elf_elfheader (abfd);
6032   bed = get_elf_backend_data (abfd);
6033   off = align_file_position (off, 1 << bed->s->log_file_align);
6034   i_ehdrp->e_shoff = off;
6035   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
6036   elf_next_file_pos (abfd) = off;
6037 
6038   return TRUE;
6039 }
6040 
6041 bfd_boolean
6042 _bfd_elf_write_object_contents (bfd *abfd)
6043 {
6044   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6045   Elf_Internal_Shdr **i_shdrp;
6046   bfd_boolean failed;
6047   unsigned int count, num_sec;
6048   struct elf_obj_tdata *t;
6049 
6050   if (! abfd->output_has_begun
6051       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
6052     return FALSE;
6053 
6054   i_shdrp = elf_elfsections (abfd);
6055 
6056   failed = FALSE;
6057   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
6058   if (failed)
6059     return FALSE;
6060 
6061   if (!_bfd_elf_assign_file_positions_for_non_load (abfd))
6062     return FALSE;
6063 
6064   /* After writing the headers, we need to write the sections too...  */
6065   num_sec = elf_numsections (abfd);
6066   for (count = 1; count < num_sec; count++)
6067     {
6068       i_shdrp[count]->sh_name
6069 	= _bfd_elf_strtab_offset (elf_shstrtab (abfd),
6070 				  i_shdrp[count]->sh_name);
6071       if (bed->elf_backend_section_processing)
6072 	(*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
6073       if (i_shdrp[count]->contents)
6074 	{
6075 	  bfd_size_type amt = i_shdrp[count]->sh_size;
6076 
6077 	  if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
6078 	      || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
6079 	    return FALSE;
6080 	}
6081     }
6082 
6083   /* Write out the section header names.  */
6084   t = elf_tdata (abfd);
6085   if (elf_shstrtab (abfd) != NULL
6086       && (bfd_seek (abfd, t->shstrtab_hdr.sh_offset, SEEK_SET) != 0
6087 	  || !_bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd))))
6088     return FALSE;
6089 
6090   if (bed->elf_backend_final_write_processing)
6091     (*bed->elf_backend_final_write_processing) (abfd, elf_linker (abfd));
6092 
6093   if (!bed->s->write_shdrs_and_ehdr (abfd))
6094     return FALSE;
6095 
6096   /* This is last since write_shdrs_and_ehdr can touch i_shdrp[0].  */
6097   if (t->o->build_id.after_write_object_contents != NULL)
6098     return (*t->o->build_id.after_write_object_contents) (abfd);
6099 
6100   return TRUE;
6101 }
6102 
6103 bfd_boolean
6104 _bfd_elf_write_corefile_contents (bfd *abfd)
6105 {
6106   /* Hopefully this can be done just like an object file.  */
6107   return _bfd_elf_write_object_contents (abfd);
6108 }
6109 
6110 /* Given a section, search the header to find them.  */
6111 
6112 unsigned int
6113 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
6114 {
6115   const struct elf_backend_data *bed;
6116   unsigned int sec_index;
6117 
6118   if (elf_section_data (asect) != NULL
6119       && elf_section_data (asect)->this_idx != 0)
6120     return elf_section_data (asect)->this_idx;
6121 
6122   if (bfd_is_abs_section (asect))
6123     sec_index = SHN_ABS;
6124   else if (bfd_is_com_section (asect))
6125     sec_index = SHN_COMMON;
6126   else if (bfd_is_und_section (asect))
6127     sec_index = SHN_UNDEF;
6128   else
6129     sec_index = SHN_BAD;
6130 
6131   bed = get_elf_backend_data (abfd);
6132   if (bed->elf_backend_section_from_bfd_section)
6133     {
6134       int retval = sec_index;
6135 
6136       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
6137 	return retval;
6138     }
6139 
6140   if (sec_index == SHN_BAD)
6141     bfd_set_error (bfd_error_nonrepresentable_section);
6142 
6143   return sec_index;
6144 }
6145 
6146 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
6147    on error.  */
6148 
6149 int
6150 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
6151 {
6152   asymbol *asym_ptr = *asym_ptr_ptr;
6153   int idx;
6154   flagword flags = asym_ptr->flags;
6155 
6156   /* When gas creates relocations against local labels, it creates its
6157      own symbol for the section, but does put the symbol into the
6158      symbol chain, so udata is 0.  When the linker is generating
6159      relocatable output, this section symbol may be for one of the
6160      input sections rather than the output section.  */
6161   if (asym_ptr->udata.i == 0
6162       && (flags & BSF_SECTION_SYM)
6163       && asym_ptr->section)
6164     {
6165       asection *sec;
6166       int indx;
6167 
6168       sec = asym_ptr->section;
6169       if (sec->owner != abfd && sec->output_section != NULL)
6170 	sec = sec->output_section;
6171       if (sec->owner == abfd
6172 	  && (indx = sec->index) < elf_num_section_syms (abfd)
6173 	  && elf_section_syms (abfd)[indx] != NULL)
6174 	asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
6175     }
6176 
6177   idx = asym_ptr->udata.i;
6178 
6179   if (idx == 0)
6180     {
6181       /* This case can occur when using --strip-symbol on a symbol
6182 	 which is used in a relocation entry.  */
6183       (*_bfd_error_handler)
6184 	(_("%B: symbol `%s' required but not present"),
6185 	 abfd, bfd_asymbol_name (asym_ptr));
6186       bfd_set_error (bfd_error_no_symbols);
6187       return -1;
6188     }
6189 
6190 #if DEBUG & 4
6191   {
6192     fprintf (stderr,
6193 	     "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx\n",
6194 	     (long) asym_ptr, asym_ptr->name, idx, (long) flags);
6195     fflush (stderr);
6196   }
6197 #endif
6198 
6199   return idx;
6200 }
6201 
6202 /* Rewrite program header information.  */
6203 
6204 static bfd_boolean
6205 rewrite_elf_program_header (bfd *ibfd, bfd *obfd)
6206 {
6207   Elf_Internal_Ehdr *iehdr;
6208   struct elf_segment_map *map;
6209   struct elf_segment_map *map_first;
6210   struct elf_segment_map **pointer_to_map;
6211   Elf_Internal_Phdr *segment;
6212   asection *section;
6213   unsigned int i;
6214   unsigned int num_segments;
6215   bfd_boolean phdr_included = FALSE;
6216   bfd_boolean p_paddr_valid;
6217   bfd_vma maxpagesize;
6218   struct elf_segment_map *phdr_adjust_seg = NULL;
6219   unsigned int phdr_adjust_num = 0;
6220   const struct elf_backend_data *bed;
6221 
6222   bed = get_elf_backend_data (ibfd);
6223   iehdr = elf_elfheader (ibfd);
6224 
6225   map_first = NULL;
6226   pointer_to_map = &map_first;
6227 
6228   num_segments = elf_elfheader (ibfd)->e_phnum;
6229   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
6230 
6231   /* Returns the end address of the segment + 1.  */
6232 #define SEGMENT_END(segment, start)					\
6233   (start + (segment->p_memsz > segment->p_filesz			\
6234 	    ? segment->p_memsz : segment->p_filesz))
6235 
6236 #define SECTION_SIZE(section, segment)					\
6237   (((section->flags & (SEC_HAS_CONTENTS | SEC_THREAD_LOCAL))		\
6238     != SEC_THREAD_LOCAL || segment->p_type == PT_TLS)			\
6239    ? section->size : 0)
6240 
6241   /* Returns TRUE if the given section is contained within
6242      the given segment.  VMA addresses are compared.  */
6243 #define IS_CONTAINED_BY_VMA(section, segment)				\
6244   (section->vma >= segment->p_vaddr					\
6245    && (section->vma + SECTION_SIZE (section, segment)			\
6246        <= (SEGMENT_END (segment, segment->p_vaddr))))
6247 
6248   /* Returns TRUE if the given section is contained within
6249      the given segment.  LMA addresses are compared.  */
6250 #define IS_CONTAINED_BY_LMA(section, segment, base)			\
6251   (section->lma >= base							\
6252    && (section->lma + SECTION_SIZE (section, segment)			\
6253        <= SEGMENT_END (segment, base)))
6254 
6255   /* Handle PT_NOTE segment.  */
6256 #define IS_NOTE(p, s)							\
6257   (p->p_type == PT_NOTE							\
6258    && elf_section_type (s) == SHT_NOTE					\
6259    && (bfd_vma) s->filepos >= p->p_offset				\
6260    && ((bfd_vma) s->filepos + s->size					\
6261        <= p->p_offset + p->p_filesz))
6262 
6263   /* Special case: corefile "NOTE" section containing regs, prpsinfo
6264      etc.  */
6265 #define IS_COREFILE_NOTE(p, s)						\
6266   (IS_NOTE (p, s)							\
6267    && bfd_get_format (ibfd) == bfd_core					\
6268    && s->vma == 0							\
6269    && s->lma == 0)
6270 
6271   /* The complicated case when p_vaddr is 0 is to handle the Solaris
6272      linker, which generates a PT_INTERP section with p_vaddr and
6273      p_memsz set to 0.  */
6274 #define IS_SOLARIS_PT_INTERP(p, s)					\
6275   (p->p_vaddr == 0							\
6276    && p->p_paddr == 0							\
6277    && p->p_memsz == 0							\
6278    && p->p_filesz > 0							\
6279    && (s->flags & SEC_HAS_CONTENTS) != 0				\
6280    && s->size > 0							\
6281    && (bfd_vma) s->filepos >= p->p_offset				\
6282    && ((bfd_vma) s->filepos + s->size					\
6283        <= p->p_offset + p->p_filesz))
6284 
6285   /* Decide if the given section should be included in the given segment.
6286      A section will be included if:
6287        1. It is within the address space of the segment -- we use the LMA
6288 	  if that is set for the segment and the VMA otherwise,
6289        2. It is an allocated section or a NOTE section in a PT_NOTE
6290 	  segment.
6291        3. There is an output section associated with it,
6292        4. The section has not already been allocated to a previous segment.
6293        5. PT_GNU_STACK segments do not include any sections.
6294        6. PT_TLS segment includes only SHF_TLS sections.
6295        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.
6296        8. PT_DYNAMIC should not contain empty sections at the beginning
6297 	  (with the possible exception of .dynamic).  */
6298 #define IS_SECTION_IN_INPUT_SEGMENT(section, segment, bed)		\
6299   ((((segment->p_paddr							\
6300       ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)	\
6301       : IS_CONTAINED_BY_VMA (section, segment))				\
6302      && (section->flags & SEC_ALLOC) != 0)				\
6303     || IS_NOTE (segment, section))					\
6304    && segment->p_type != PT_GNU_STACK					\
6305    && (segment->p_type != PT_TLS					\
6306        || (section->flags & SEC_THREAD_LOCAL))				\
6307    && (segment->p_type == PT_LOAD					\
6308        || segment->p_type == PT_TLS					\
6309        || (section->flags & SEC_THREAD_LOCAL) == 0)			\
6310    && (segment->p_type != PT_DYNAMIC					\
6311        || SECTION_SIZE (section, segment) > 0				\
6312        || (segment->p_paddr						\
6313 	   ? segment->p_paddr != section->lma				\
6314 	   : segment->p_vaddr != section->vma)				\
6315        || (strcmp (bfd_get_section_name (ibfd, section), ".dynamic")	\
6316 	   == 0))							\
6317    && !section->segment_mark)
6318 
6319 /* If the output section of a section in the input segment is NULL,
6320    it is removed from the corresponding output segment.   */
6321 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)		\
6322   (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed)		\
6323    && section->output_section != NULL)
6324 
6325   /* Returns TRUE iff seg1 starts after the end of seg2.  */
6326 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)			\
6327   (seg1->field >= SEGMENT_END (seg2, seg2->field))
6328 
6329   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
6330      their VMA address ranges and their LMA address ranges overlap.
6331      It is possible to have overlapping VMA ranges without overlapping LMA
6332      ranges.  RedBoot images for example can have both .data and .bss mapped
6333      to the same VMA range, but with the .data section mapped to a different
6334      LMA.  */
6335 #define SEGMENT_OVERLAPS(seg1, seg2)					\
6336   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)			\
6337 	|| SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))			\
6338    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)			\
6339 	|| SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
6340 
6341   /* Initialise the segment mark field.  */
6342   for (section = ibfd->sections; section != NULL; section = section->next)
6343     section->segment_mark = FALSE;
6344 
6345   /* The Solaris linker creates program headers in which all the
6346      p_paddr fields are zero.  When we try to objcopy or strip such a
6347      file, we get confused.  Check for this case, and if we find it
6348      don't set the p_paddr_valid fields.  */
6349   p_paddr_valid = FALSE;
6350   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6351        i < num_segments;
6352        i++, segment++)
6353     if (segment->p_paddr != 0)
6354       {
6355 	p_paddr_valid = TRUE;
6356 	break;
6357       }
6358 
6359   /* Scan through the segments specified in the program header
6360      of the input BFD.  For this first scan we look for overlaps
6361      in the loadable segments.  These can be created by weird
6362      parameters to objcopy.  Also, fix some solaris weirdness.  */
6363   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6364        i < num_segments;
6365        i++, segment++)
6366     {
6367       unsigned int j;
6368       Elf_Internal_Phdr *segment2;
6369 
6370       if (segment->p_type == PT_INTERP)
6371 	for (section = ibfd->sections; section; section = section->next)
6372 	  if (IS_SOLARIS_PT_INTERP (segment, section))
6373 	    {
6374 	      /* Mininal change so that the normal section to segment
6375 		 assignment code will work.  */
6376 	      segment->p_vaddr = section->vma;
6377 	      break;
6378 	    }
6379 
6380       if (segment->p_type != PT_LOAD)
6381 	{
6382 	  /* Remove PT_GNU_RELRO segment.  */
6383 	  if (segment->p_type == PT_GNU_RELRO)
6384 	    segment->p_type = PT_NULL;
6385 	  continue;
6386 	}
6387 
6388       /* Determine if this segment overlaps any previous segments.  */
6389       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2++)
6390 	{
6391 	  bfd_signed_vma extra_length;
6392 
6393 	  if (segment2->p_type != PT_LOAD
6394 	      || !SEGMENT_OVERLAPS (segment, segment2))
6395 	    continue;
6396 
6397 	  /* Merge the two segments together.  */
6398 	  if (segment2->p_vaddr < segment->p_vaddr)
6399 	    {
6400 	      /* Extend SEGMENT2 to include SEGMENT and then delete
6401 		 SEGMENT.  */
6402 	      extra_length = (SEGMENT_END (segment, segment->p_vaddr)
6403 			      - SEGMENT_END (segment2, segment2->p_vaddr));
6404 
6405 	      if (extra_length > 0)
6406 		{
6407 		  segment2->p_memsz += extra_length;
6408 		  segment2->p_filesz += extra_length;
6409 		}
6410 
6411 	      segment->p_type = PT_NULL;
6412 
6413 	      /* Since we have deleted P we must restart the outer loop.  */
6414 	      i = 0;
6415 	      segment = elf_tdata (ibfd)->phdr;
6416 	      break;
6417 	    }
6418 	  else
6419 	    {
6420 	      /* Extend SEGMENT to include SEGMENT2 and then delete
6421 		 SEGMENT2.  */
6422 	      extra_length = (SEGMENT_END (segment2, segment2->p_vaddr)
6423 			      - SEGMENT_END (segment, segment->p_vaddr));
6424 
6425 	      if (extra_length > 0)
6426 		{
6427 		  segment->p_memsz += extra_length;
6428 		  segment->p_filesz += extra_length;
6429 		}
6430 
6431 	      segment2->p_type = PT_NULL;
6432 	    }
6433 	}
6434     }
6435 
6436   /* The second scan attempts to assign sections to segments.  */
6437   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6438        i < num_segments;
6439        i++, segment++)
6440     {
6441       unsigned int section_count;
6442       asection **sections;
6443       asection *output_section;
6444       unsigned int isec;
6445       bfd_vma matching_lma;
6446       bfd_vma suggested_lma;
6447       unsigned int j;
6448       bfd_size_type amt;
6449       asection *first_section;
6450       bfd_boolean first_matching_lma;
6451       bfd_boolean first_suggested_lma;
6452 
6453       if (segment->p_type == PT_NULL)
6454 	continue;
6455 
6456       first_section = NULL;
6457       /* Compute how many sections might be placed into this segment.  */
6458       for (section = ibfd->sections, section_count = 0;
6459 	   section != NULL;
6460 	   section = section->next)
6461 	{
6462 	  /* Find the first section in the input segment, which may be
6463 	     removed from the corresponding output segment.   */
6464 	  if (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed))
6465 	    {
6466 	      if (first_section == NULL)
6467 		first_section = section;
6468 	      if (section->output_section != NULL)
6469 		++section_count;
6470 	    }
6471 	}
6472 
6473       /* Allocate a segment map big enough to contain
6474 	 all of the sections we have selected.  */
6475       amt = sizeof (struct elf_segment_map);
6476       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
6477       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
6478       if (map == NULL)
6479 	return FALSE;
6480 
6481       /* Initialise the fields of the segment map.  Default to
6482 	 using the physical address of the segment in the input BFD.  */
6483       map->next = NULL;
6484       map->p_type = segment->p_type;
6485       map->p_flags = segment->p_flags;
6486       map->p_flags_valid = 1;
6487 
6488       /* If the first section in the input segment is removed, there is
6489 	 no need to preserve segment physical address in the corresponding
6490 	 output segment.  */
6491       if (!first_section || first_section->output_section != NULL)
6492 	{
6493 	  map->p_paddr = segment->p_paddr;
6494 	  map->p_paddr_valid = p_paddr_valid;
6495 	}
6496 
6497       /* Determine if this segment contains the ELF file header
6498 	 and if it contains the program headers themselves.  */
6499       map->includes_filehdr = (segment->p_offset == 0
6500 			       && segment->p_filesz >= iehdr->e_ehsize);
6501       map->includes_phdrs = 0;
6502 
6503       if (!phdr_included || segment->p_type != PT_LOAD)
6504 	{
6505 	  map->includes_phdrs =
6506 	    (segment->p_offset <= (bfd_vma) iehdr->e_phoff
6507 	     && (segment->p_offset + segment->p_filesz
6508 		 >= ((bfd_vma) iehdr->e_phoff
6509 		     + iehdr->e_phnum * iehdr->e_phentsize)));
6510 
6511 	  if (segment->p_type == PT_LOAD && map->includes_phdrs)
6512 	    phdr_included = TRUE;
6513 	}
6514 
6515       if (section_count == 0)
6516 	{
6517 	  /* Special segments, such as the PT_PHDR segment, may contain
6518 	     no sections, but ordinary, loadable segments should contain
6519 	     something.  They are allowed by the ELF spec however, so only
6520 	     a warning is produced.  */
6521 	  if (segment->p_type == PT_LOAD)
6522 	    (*_bfd_error_handler) (_("\
6523 %B: warning: Empty loadable segment detected, is this intentional ?"),
6524 				   ibfd);
6525 
6526 	  map->count = 0;
6527 	  *pointer_to_map = map;
6528 	  pointer_to_map = &map->next;
6529 
6530 	  continue;
6531 	}
6532 
6533       /* Now scan the sections in the input BFD again and attempt
6534 	 to add their corresponding output sections to the segment map.
6535 	 The problem here is how to handle an output section which has
6536 	 been moved (ie had its LMA changed).  There are four possibilities:
6537 
6538 	 1. None of the sections have been moved.
6539 	    In this case we can continue to use the segment LMA from the
6540 	    input BFD.
6541 
6542 	 2. All of the sections have been moved by the same amount.
6543 	    In this case we can change the segment's LMA to match the LMA
6544 	    of the first section.
6545 
6546 	 3. Some of the sections have been moved, others have not.
6547 	    In this case those sections which have not been moved can be
6548 	    placed in the current segment which will have to have its size,
6549 	    and possibly its LMA changed, and a new segment or segments will
6550 	    have to be created to contain the other sections.
6551 
6552 	 4. The sections have been moved, but not by the same amount.
6553 	    In this case we can change the segment's LMA to match the LMA
6554 	    of the first section and we will have to create a new segment
6555 	    or segments to contain the other sections.
6556 
6557 	 In order to save time, we allocate an array to hold the section
6558 	 pointers that we are interested in.  As these sections get assigned
6559 	 to a segment, they are removed from this array.  */
6560 
6561       sections = (asection **) bfd_malloc2 (section_count, sizeof (asection *));
6562       if (sections == NULL)
6563 	return FALSE;
6564 
6565       /* Step One: Scan for segment vs section LMA conflicts.
6566 	 Also add the sections to the section array allocated above.
6567 	 Also add the sections to the current segment.  In the common
6568 	 case, where the sections have not been moved, this means that
6569 	 we have completely filled the segment, and there is nothing
6570 	 more to do.  */
6571       isec = 0;
6572       matching_lma = 0;
6573       suggested_lma = 0;
6574       first_matching_lma = TRUE;
6575       first_suggested_lma = TRUE;
6576 
6577       for (section = first_section, j = 0;
6578 	   section != NULL;
6579 	   section = section->next)
6580 	{
6581 	  if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
6582 	    {
6583 	      output_section = section->output_section;
6584 
6585 	      sections[j++] = section;
6586 
6587 	      /* The Solaris native linker always sets p_paddr to 0.
6588 		 We try to catch that case here, and set it to the
6589 		 correct value.  Note - some backends require that
6590 		 p_paddr be left as zero.  */
6591 	      if (!p_paddr_valid
6592 		  && segment->p_vaddr != 0
6593 		  && !bed->want_p_paddr_set_to_zero
6594 		  && isec == 0
6595 		  && output_section->lma != 0
6596 		  && output_section->vma == (segment->p_vaddr
6597 					     + (map->includes_filehdr
6598 						? iehdr->e_ehsize
6599 						: 0)
6600 					     + (map->includes_phdrs
6601 						? (iehdr->e_phnum
6602 						   * iehdr->e_phentsize)
6603 						: 0)))
6604 		map->p_paddr = segment->p_vaddr;
6605 
6606 	      /* Match up the physical address of the segment with the
6607 		 LMA address of the output section.  */
6608 	      if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
6609 		  || IS_COREFILE_NOTE (segment, section)
6610 		  || (bed->want_p_paddr_set_to_zero
6611 		      && IS_CONTAINED_BY_VMA (output_section, segment)))
6612 		{
6613 		  if (first_matching_lma || output_section->lma < matching_lma)
6614 		    {
6615 		      matching_lma = output_section->lma;
6616 		      first_matching_lma = FALSE;
6617 		    }
6618 
6619 		  /* We assume that if the section fits within the segment
6620 		     then it does not overlap any other section within that
6621 		     segment.  */
6622 		  map->sections[isec++] = output_section;
6623 		}
6624 	      else if (first_suggested_lma)
6625 		{
6626 		  suggested_lma = output_section->lma;
6627 		  first_suggested_lma = FALSE;
6628 		}
6629 
6630 	      if (j == section_count)
6631 		break;
6632 	    }
6633 	}
6634 
6635       BFD_ASSERT (j == section_count);
6636 
6637       /* Step Two: Adjust the physical address of the current segment,
6638 	 if necessary.  */
6639       if (isec == section_count)
6640 	{
6641 	  /* All of the sections fitted within the segment as currently
6642 	     specified.  This is the default case.  Add the segment to
6643 	     the list of built segments and carry on to process the next
6644 	     program header in the input BFD.  */
6645 	  map->count = section_count;
6646 	  *pointer_to_map = map;
6647 	  pointer_to_map = &map->next;
6648 
6649 	  if (p_paddr_valid
6650 	      && !bed->want_p_paddr_set_to_zero
6651 	      && matching_lma != map->p_paddr
6652 	      && !map->includes_filehdr
6653 	      && !map->includes_phdrs)
6654 	    /* There is some padding before the first section in the
6655 	       segment.  So, we must account for that in the output
6656 	       segment's vma.  */
6657 	    map->p_vaddr_offset = matching_lma - map->p_paddr;
6658 
6659 	  free (sections);
6660 	  continue;
6661 	}
6662       else
6663 	{
6664 	  if (!first_matching_lma)
6665 	    {
6666 	      /* At least one section fits inside the current segment.
6667 		 Keep it, but modify its physical address to match the
6668 		 LMA of the first section that fitted.  */
6669 	      map->p_paddr = matching_lma;
6670 	    }
6671 	  else
6672 	    {
6673 	      /* None of the sections fitted inside the current segment.
6674 		 Change the current segment's physical address to match
6675 		 the LMA of the first section.  */
6676 	      map->p_paddr = suggested_lma;
6677 	    }
6678 
6679 	  /* Offset the segment physical address from the lma
6680 	     to allow for space taken up by elf headers.  */
6681 	  if (map->includes_filehdr)
6682 	    {
6683 	      if (map->p_paddr >= iehdr->e_ehsize)
6684 		map->p_paddr -= iehdr->e_ehsize;
6685 	      else
6686 		{
6687 		  map->includes_filehdr = FALSE;
6688 		  map->includes_phdrs = FALSE;
6689 		}
6690 	    }
6691 
6692 	  if (map->includes_phdrs)
6693 	    {
6694 	      if (map->p_paddr >= iehdr->e_phnum * iehdr->e_phentsize)
6695 		{
6696 		  map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
6697 
6698 		  /* iehdr->e_phnum is just an estimate of the number
6699 		     of program headers that we will need.  Make a note
6700 		     here of the number we used and the segment we chose
6701 		     to hold these headers, so that we can adjust the
6702 		     offset when we know the correct value.  */
6703 		  phdr_adjust_num = iehdr->e_phnum;
6704 		  phdr_adjust_seg = map;
6705 		}
6706 	      else
6707 		map->includes_phdrs = FALSE;
6708 	    }
6709 	}
6710 
6711       /* Step Three: Loop over the sections again, this time assigning
6712 	 those that fit to the current segment and removing them from the
6713 	 sections array; but making sure not to leave large gaps.  Once all
6714 	 possible sections have been assigned to the current segment it is
6715 	 added to the list of built segments and if sections still remain
6716 	 to be assigned, a new segment is constructed before repeating
6717 	 the loop.  */
6718       isec = 0;
6719       do
6720 	{
6721 	  map->count = 0;
6722 	  suggested_lma = 0;
6723 	  first_suggested_lma = TRUE;
6724 
6725 	  /* Fill the current segment with sections that fit.  */
6726 	  for (j = 0; j < section_count; j++)
6727 	    {
6728 	      section = sections[j];
6729 
6730 	      if (section == NULL)
6731 		continue;
6732 
6733 	      output_section = section->output_section;
6734 
6735 	      BFD_ASSERT (output_section != NULL);
6736 
6737 	      if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
6738 		  || IS_COREFILE_NOTE (segment, section))
6739 		{
6740 		  if (map->count == 0)
6741 		    {
6742 		      /* If the first section in a segment does not start at
6743 			 the beginning of the segment, then something is
6744 			 wrong.  */
6745 		      if (output_section->lma
6746 			  != (map->p_paddr
6747 			      + (map->includes_filehdr ? iehdr->e_ehsize : 0)
6748 			      + (map->includes_phdrs
6749 				 ? iehdr->e_phnum * iehdr->e_phentsize
6750 				 : 0)))
6751 			abort ();
6752 		    }
6753 		  else
6754 		    {
6755 		      asection *prev_sec;
6756 
6757 		      prev_sec = map->sections[map->count - 1];
6758 
6759 		      /* If the gap between the end of the previous section
6760 			 and the start of this section is more than
6761 			 maxpagesize then we need to start a new segment.  */
6762 		      if ((BFD_ALIGN (prev_sec->lma + prev_sec->size,
6763 				      maxpagesize)
6764 			   < BFD_ALIGN (output_section->lma, maxpagesize))
6765 			  || (prev_sec->lma + prev_sec->size
6766 			      > output_section->lma))
6767 			{
6768 			  if (first_suggested_lma)
6769 			    {
6770 			      suggested_lma = output_section->lma;
6771 			      first_suggested_lma = FALSE;
6772 			    }
6773 
6774 			  continue;
6775 			}
6776 		    }
6777 
6778 		  map->sections[map->count++] = output_section;
6779 		  ++isec;
6780 		  sections[j] = NULL;
6781 		  section->segment_mark = TRUE;
6782 		}
6783 	      else if (first_suggested_lma)
6784 		{
6785 		  suggested_lma = output_section->lma;
6786 		  first_suggested_lma = FALSE;
6787 		}
6788 	    }
6789 
6790 	  BFD_ASSERT (map->count > 0);
6791 
6792 	  /* Add the current segment to the list of built segments.  */
6793 	  *pointer_to_map = map;
6794 	  pointer_to_map = &map->next;
6795 
6796 	  if (isec < section_count)
6797 	    {
6798 	      /* We still have not allocated all of the sections to
6799 		 segments.  Create a new segment here, initialise it
6800 		 and carry on looping.  */
6801 	      amt = sizeof (struct elf_segment_map);
6802 	      amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
6803 	      map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
6804 	      if (map == NULL)
6805 		{
6806 		  free (sections);
6807 		  return FALSE;
6808 		}
6809 
6810 	      /* Initialise the fields of the segment map.  Set the physical
6811 		 physical address to the LMA of the first section that has
6812 		 not yet been assigned.  */
6813 	      map->next = NULL;
6814 	      map->p_type = segment->p_type;
6815 	      map->p_flags = segment->p_flags;
6816 	      map->p_flags_valid = 1;
6817 	      map->p_paddr = suggested_lma;
6818 	      map->p_paddr_valid = p_paddr_valid;
6819 	      map->includes_filehdr = 0;
6820 	      map->includes_phdrs = 0;
6821 	    }
6822 	}
6823       while (isec < section_count);
6824 
6825       free (sections);
6826     }
6827 
6828   elf_seg_map (obfd) = map_first;
6829 
6830   /* If we had to estimate the number of program headers that were
6831      going to be needed, then check our estimate now and adjust
6832      the offset if necessary.  */
6833   if (phdr_adjust_seg != NULL)
6834     {
6835       unsigned int count;
6836 
6837       for (count = 0, map = map_first; map != NULL; map = map->next)
6838 	count++;
6839 
6840       if (count > phdr_adjust_num)
6841 	phdr_adjust_seg->p_paddr
6842 	  -= (count - phdr_adjust_num) * iehdr->e_phentsize;
6843     }
6844 
6845 #undef SEGMENT_END
6846 #undef SECTION_SIZE
6847 #undef IS_CONTAINED_BY_VMA
6848 #undef IS_CONTAINED_BY_LMA
6849 #undef IS_NOTE
6850 #undef IS_COREFILE_NOTE
6851 #undef IS_SOLARIS_PT_INTERP
6852 #undef IS_SECTION_IN_INPUT_SEGMENT
6853 #undef INCLUDE_SECTION_IN_SEGMENT
6854 #undef SEGMENT_AFTER_SEGMENT
6855 #undef SEGMENT_OVERLAPS
6856   return TRUE;
6857 }
6858 
6859 /* Copy ELF program header information.  */
6860 
6861 static bfd_boolean
6862 copy_elf_program_header (bfd *ibfd, bfd *obfd)
6863 {
6864   Elf_Internal_Ehdr *iehdr;
6865   struct elf_segment_map *map;
6866   struct elf_segment_map *map_first;
6867   struct elf_segment_map **pointer_to_map;
6868   Elf_Internal_Phdr *segment;
6869   unsigned int i;
6870   unsigned int num_segments;
6871   bfd_boolean phdr_included = FALSE;
6872   bfd_boolean p_paddr_valid;
6873 
6874   iehdr = elf_elfheader (ibfd);
6875 
6876   map_first = NULL;
6877   pointer_to_map = &map_first;
6878 
6879   /* If all the segment p_paddr fields are zero, don't set
6880      map->p_paddr_valid.  */
6881   p_paddr_valid = FALSE;
6882   num_segments = elf_elfheader (ibfd)->e_phnum;
6883   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6884        i < num_segments;
6885        i++, segment++)
6886     if (segment->p_paddr != 0)
6887       {
6888 	p_paddr_valid = TRUE;
6889 	break;
6890       }
6891 
6892   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6893        i < num_segments;
6894        i++, segment++)
6895     {
6896       asection *section;
6897       unsigned int section_count;
6898       bfd_size_type amt;
6899       Elf_Internal_Shdr *this_hdr;
6900       asection *first_section = NULL;
6901       asection *lowest_section;
6902 
6903       /* Compute how many sections are in this segment.  */
6904       for (section = ibfd->sections, section_count = 0;
6905 	   section != NULL;
6906 	   section = section->next)
6907 	{
6908 	  this_hdr = &(elf_section_data(section)->this_hdr);
6909 	  if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
6910 	    {
6911 	      if (first_section == NULL)
6912 		first_section = section;
6913 	      section_count++;
6914 	    }
6915 	}
6916 
6917       /* Allocate a segment map big enough to contain
6918 	 all of the sections we have selected.  */
6919       amt = sizeof (struct elf_segment_map);
6920       if (section_count != 0)
6921 	amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
6922       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
6923       if (map == NULL)
6924 	return FALSE;
6925 
6926       /* Initialize the fields of the output segment map with the
6927 	 input segment.  */
6928       map->next = NULL;
6929       map->p_type = segment->p_type;
6930       map->p_flags = segment->p_flags;
6931       map->p_flags_valid = 1;
6932       map->p_paddr = segment->p_paddr;
6933       map->p_paddr_valid = p_paddr_valid;
6934       map->p_align = segment->p_align;
6935       map->p_align_valid = 1;
6936       map->p_vaddr_offset = 0;
6937 
6938       if (map->p_type == PT_GNU_RELRO
6939 	  || map->p_type == PT_GNU_STACK)
6940 	{
6941 	  /* The PT_GNU_RELRO segment may contain the first a few
6942 	     bytes in the .got.plt section even if the whole .got.plt
6943 	     section isn't in the PT_GNU_RELRO segment.  We won't
6944 	     change the size of the PT_GNU_RELRO segment.
6945 	     Similarly, PT_GNU_STACK size is significant on uclinux
6946 	     systems.    */
6947 	  map->p_size = segment->p_memsz;
6948 	  map->p_size_valid = 1;
6949 	}
6950 
6951       /* Determine if this segment contains the ELF file header
6952 	 and if it contains the program headers themselves.  */
6953       map->includes_filehdr = (segment->p_offset == 0
6954 			       && segment->p_filesz >= iehdr->e_ehsize);
6955 
6956       map->includes_phdrs = 0;
6957       if (! phdr_included || segment->p_type != PT_LOAD)
6958 	{
6959 	  map->includes_phdrs =
6960 	    (segment->p_offset <= (bfd_vma) iehdr->e_phoff
6961 	     && (segment->p_offset + segment->p_filesz
6962 		 >= ((bfd_vma) iehdr->e_phoff
6963 		     + iehdr->e_phnum * iehdr->e_phentsize)));
6964 
6965 	  if (segment->p_type == PT_LOAD && map->includes_phdrs)
6966 	    phdr_included = TRUE;
6967 	}
6968 
6969       lowest_section = NULL;
6970       if (section_count != 0)
6971 	{
6972 	  unsigned int isec = 0;
6973 
6974 	  for (section = first_section;
6975 	       section != NULL;
6976 	       section = section->next)
6977 	    {
6978 	      this_hdr = &(elf_section_data(section)->this_hdr);
6979 	      if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
6980 		{
6981 		  map->sections[isec++] = section->output_section;
6982 		  if ((section->flags & SEC_ALLOC) != 0)
6983 		    {
6984 		      bfd_vma seg_off;
6985 
6986 		      if (lowest_section == NULL
6987 			  || section->lma < lowest_section->lma)
6988 			lowest_section = section;
6989 
6990 		      /* Section lmas are set up from PT_LOAD header
6991 			 p_paddr in _bfd_elf_make_section_from_shdr.
6992 			 If this header has a p_paddr that disagrees
6993 			 with the section lma, flag the p_paddr as
6994 			 invalid.  */
6995 		      if ((section->flags & SEC_LOAD) != 0)
6996 			seg_off = this_hdr->sh_offset - segment->p_offset;
6997 		      else
6998 			seg_off = this_hdr->sh_addr - segment->p_vaddr;
6999 		      if (section->lma - segment->p_paddr != seg_off)
7000 			map->p_paddr_valid = FALSE;
7001 		    }
7002 		  if (isec == section_count)
7003 		    break;
7004 		}
7005 	    }
7006 	}
7007 
7008       if (map->includes_filehdr && lowest_section != NULL)
7009 	/* We need to keep the space used by the headers fixed.  */
7010 	map->header_size = lowest_section->vma - segment->p_vaddr;
7011 
7012       if (!map->includes_phdrs
7013 	  && !map->includes_filehdr
7014 	  && map->p_paddr_valid)
7015 	/* There is some other padding before the first section.  */
7016 	map->p_vaddr_offset = ((lowest_section ? lowest_section->lma : 0)
7017 			       - segment->p_paddr);
7018 
7019       map->count = section_count;
7020       *pointer_to_map = map;
7021       pointer_to_map = &map->next;
7022     }
7023 
7024   elf_seg_map (obfd) = map_first;
7025   return TRUE;
7026 }
7027 
7028 /* Copy private BFD data.  This copies or rewrites ELF program header
7029    information.  */
7030 
7031 static bfd_boolean
7032 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
7033 {
7034   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
7035       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
7036     return TRUE;
7037 
7038   if (elf_tdata (ibfd)->phdr == NULL)
7039     return TRUE;
7040 
7041   if (ibfd->xvec == obfd->xvec)
7042     {
7043       /* Check to see if any sections in the input BFD
7044 	 covered by ELF program header have changed.  */
7045       Elf_Internal_Phdr *segment;
7046       asection *section, *osec;
7047       unsigned int i, num_segments;
7048       Elf_Internal_Shdr *this_hdr;
7049       const struct elf_backend_data *bed;
7050 
7051       bed = get_elf_backend_data (ibfd);
7052 
7053       /* Regenerate the segment map if p_paddr is set to 0.  */
7054       if (bed->want_p_paddr_set_to_zero)
7055 	goto rewrite;
7056 
7057       /* Initialize the segment mark field.  */
7058       for (section = obfd->sections; section != NULL;
7059 	   section = section->next)
7060 	section->segment_mark = FALSE;
7061 
7062       num_segments = elf_elfheader (ibfd)->e_phnum;
7063       for (i = 0, segment = elf_tdata (ibfd)->phdr;
7064 	   i < num_segments;
7065 	   i++, segment++)
7066 	{
7067 	  /* PR binutils/3535.  The Solaris linker always sets the p_paddr
7068 	     and p_memsz fields of special segments (DYNAMIC, INTERP) to 0
7069 	     which severly confuses things, so always regenerate the segment
7070 	     map in this case.  */
7071 	  if (segment->p_paddr == 0
7072 	      && segment->p_memsz == 0
7073 	      && (segment->p_type == PT_INTERP || segment->p_type == PT_DYNAMIC))
7074 	    goto rewrite;
7075 
7076 	  for (section = ibfd->sections;
7077 	       section != NULL; section = section->next)
7078 	    {
7079 	      /* We mark the output section so that we know it comes
7080 		 from the input BFD.  */
7081 	      osec = section->output_section;
7082 	      if (osec)
7083 		osec->segment_mark = TRUE;
7084 
7085 	      /* Check if this section is covered by the segment.  */
7086 	      this_hdr = &(elf_section_data(section)->this_hdr);
7087 	      if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
7088 		{
7089 		  /* FIXME: Check if its output section is changed or
7090 		     removed.  What else do we need to check?  */
7091 		  if (osec == NULL
7092 		      || section->flags != osec->flags
7093 		      || section->lma != osec->lma
7094 		      || section->vma != osec->vma
7095 		      || section->size != osec->size
7096 		      || section->rawsize != osec->rawsize
7097 		      || section->alignment_power != osec->alignment_power)
7098 		    goto rewrite;
7099 		}
7100 	    }
7101 	}
7102 
7103       /* Check to see if any output section do not come from the
7104 	 input BFD.  */
7105       for (section = obfd->sections; section != NULL;
7106 	   section = section->next)
7107 	{
7108 	  if (section->segment_mark == FALSE)
7109 	    goto rewrite;
7110 	  else
7111 	    section->segment_mark = FALSE;
7112 	}
7113 
7114       return copy_elf_program_header (ibfd, obfd);
7115     }
7116 
7117 rewrite:
7118   if (ibfd->xvec == obfd->xvec)
7119     {
7120       /* When rewriting program header, set the output maxpagesize to
7121 	 the maximum alignment of input PT_LOAD segments.  */
7122       Elf_Internal_Phdr *segment;
7123       unsigned int i;
7124       unsigned int num_segments = elf_elfheader (ibfd)->e_phnum;
7125       bfd_vma maxpagesize = 0;
7126 
7127       for (i = 0, segment = elf_tdata (ibfd)->phdr;
7128 	   i < num_segments;
7129 	   i++, segment++)
7130 	if (segment->p_type == PT_LOAD
7131 	    && maxpagesize < segment->p_align)
7132 	  {
7133 	    /* PR 17512: file: f17299af.  */
7134 	    if (segment->p_align > (bfd_vma) 1 << ((sizeof (bfd_vma) * 8) - 2))
7135 	      (*_bfd_error_handler) (_("\
7136 %B: warning: segment alignment of 0x%llx is too large"),
7137 				     ibfd, (long long) segment->p_align);
7138 	    else
7139 	      maxpagesize = segment->p_align;
7140 	  }
7141 
7142       if (maxpagesize != get_elf_backend_data (obfd)->maxpagesize)
7143 	bfd_emul_set_maxpagesize (bfd_get_target (obfd), maxpagesize);
7144     }
7145 
7146   return rewrite_elf_program_header (ibfd, obfd);
7147 }
7148 
7149 /* Initialize private output section information from input section.  */
7150 
7151 bfd_boolean
7152 _bfd_elf_init_private_section_data (bfd *ibfd,
7153 				    asection *isec,
7154 				    bfd *obfd,
7155 				    asection *osec,
7156 				    struct bfd_link_info *link_info)
7157 
7158 {
7159   Elf_Internal_Shdr *ihdr, *ohdr;
7160   bfd_boolean final_link = (link_info != NULL
7161 			    && !bfd_link_relocatable (link_info));
7162 
7163   if (ibfd->xvec->flavour != bfd_target_elf_flavour
7164       || obfd->xvec->flavour != bfd_target_elf_flavour)
7165     return TRUE;
7166 
7167   BFD_ASSERT (elf_section_data (osec) != NULL);
7168 
7169   /* For objcopy and relocatable link, don't copy the output ELF
7170      section type from input if the output BFD section flags have been
7171      set to something different.  For a final link allow some flags
7172      that the linker clears to differ.  */
7173   if (elf_section_type (osec) == SHT_NULL
7174       && (osec->flags == isec->flags
7175 	  || (final_link
7176 	      && ((osec->flags ^ isec->flags)
7177 		  & ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC)) == 0)))
7178     elf_section_type (osec) = elf_section_type (isec);
7179 
7180   /* FIXME: Is this correct for all OS/PROC specific flags?  */
7181   elf_section_flags (osec) |= (elf_section_flags (isec)
7182 			       & (SHF_MASKOS | SHF_MASKPROC));
7183 
7184   /* Set things up for objcopy and relocatable link.  The output
7185      SHT_GROUP section will have its elf_next_in_group pointing back
7186      to the input group members.  Ignore linker created group section.
7187      See elfNN_ia64_object_p in elfxx-ia64.c.  */
7188   if (!final_link)
7189     {
7190       if (elf_sec_group (isec) == NULL
7191 	  || (elf_sec_group (isec)->flags & SEC_LINKER_CREATED) == 0)
7192 	{
7193 	  if (elf_section_flags (isec) & SHF_GROUP)
7194 	    elf_section_flags (osec) |= SHF_GROUP;
7195 	  elf_next_in_group (osec) = elf_next_in_group (isec);
7196 	  elf_section_data (osec)->group = elf_section_data (isec)->group;
7197 	}
7198 
7199       /* If not decompress, preserve SHF_COMPRESSED.  */
7200       if ((ibfd->flags & BFD_DECOMPRESS) == 0)
7201 	elf_section_flags (osec) |= (elf_section_flags (isec)
7202 				     & SHF_COMPRESSED);
7203     }
7204 
7205   ihdr = &elf_section_data (isec)->this_hdr;
7206 
7207   /* We need to handle elf_linked_to_section for SHF_LINK_ORDER. We
7208      don't use the output section of the linked-to section since it
7209      may be NULL at this point.  */
7210   if ((ihdr->sh_flags & SHF_LINK_ORDER) != 0)
7211     {
7212       ohdr = &elf_section_data (osec)->this_hdr;
7213       ohdr->sh_flags |= SHF_LINK_ORDER;
7214       elf_linked_to_section (osec) = elf_linked_to_section (isec);
7215     }
7216 
7217   osec->use_rela_p = isec->use_rela_p;
7218 
7219   return TRUE;
7220 }
7221 
7222 /* Copy private section information.  This copies over the entsize
7223    field, and sometimes the info field.  */
7224 
7225 bfd_boolean
7226 _bfd_elf_copy_private_section_data (bfd *ibfd,
7227 				    asection *isec,
7228 				    bfd *obfd,
7229 				    asection *osec)
7230 {
7231   Elf_Internal_Shdr *ihdr, *ohdr;
7232 
7233   if (ibfd->xvec->flavour != bfd_target_elf_flavour
7234       || obfd->xvec->flavour != bfd_target_elf_flavour)
7235     return TRUE;
7236 
7237   ihdr = &elf_section_data (isec)->this_hdr;
7238   ohdr = &elf_section_data (osec)->this_hdr;
7239 
7240   ohdr->sh_entsize = ihdr->sh_entsize;
7241 
7242   if (ihdr->sh_type == SHT_SYMTAB
7243       || ihdr->sh_type == SHT_DYNSYM
7244       || ihdr->sh_type == SHT_GNU_verneed
7245       || ihdr->sh_type == SHT_GNU_verdef)
7246     ohdr->sh_info = ihdr->sh_info;
7247 
7248   return _bfd_elf_init_private_section_data (ibfd, isec, obfd, osec,
7249 					     NULL);
7250 }
7251 
7252 /* Look at all the SHT_GROUP sections in IBFD, making any adjustments
7253    necessary if we are removing either the SHT_GROUP section or any of
7254    the group member sections.  DISCARDED is the value that a section's
7255    output_section has if the section will be discarded, NULL when this
7256    function is called from objcopy, bfd_abs_section_ptr when called
7257    from the linker.  */
7258 
7259 bfd_boolean
7260 _bfd_elf_fixup_group_sections (bfd *ibfd, asection *discarded)
7261 {
7262   asection *isec;
7263 
7264   for (isec = ibfd->sections; isec != NULL; isec = isec->next)
7265     if (elf_section_type (isec) == SHT_GROUP)
7266       {
7267 	asection *first = elf_next_in_group (isec);
7268 	asection *s = first;
7269 	bfd_size_type removed = 0;
7270 
7271 	while (s != NULL)
7272 	  {
7273 	    /* If this member section is being output but the
7274 	       SHT_GROUP section is not, then clear the group info
7275 	       set up by _bfd_elf_copy_private_section_data.  */
7276 	    if (s->output_section != discarded
7277 		&& isec->output_section == discarded)
7278 	      {
7279 		elf_section_flags (s->output_section) &= ~SHF_GROUP;
7280 		elf_group_name (s->output_section) = NULL;
7281 	      }
7282 	    /* Conversely, if the member section is not being output
7283 	       but the SHT_GROUP section is, then adjust its size.  */
7284 	    else if (s->output_section == discarded
7285 		     && isec->output_section != discarded)
7286 	      removed += 4;
7287 	    s = elf_next_in_group (s);
7288 	    if (s == first)
7289 	      break;
7290 	  }
7291 	if (removed != 0)
7292 	  {
7293 	    if (discarded != NULL)
7294 	      {
7295 		/* If we've been called for ld -r, then we need to
7296 		   adjust the input section size.  This function may
7297 		   be called multiple times, so save the original
7298 		   size.  */
7299 		if (isec->rawsize == 0)
7300 		  isec->rawsize = isec->size;
7301 		isec->size = isec->rawsize - removed;
7302 	      }
7303 	    else
7304 	      {
7305 		/* Adjust the output section size when called from
7306 		   objcopy. */
7307 		isec->output_section->size -= removed;
7308 	      }
7309 	  }
7310       }
7311 
7312   return TRUE;
7313 }
7314 
7315 /* Copy private header information.  */
7316 
7317 bfd_boolean
7318 _bfd_elf_copy_private_header_data (bfd *ibfd, bfd *obfd)
7319 {
7320   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
7321       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
7322     return TRUE;
7323 
7324   /* Copy over private BFD data if it has not already been copied.
7325      This must be done here, rather than in the copy_private_bfd_data
7326      entry point, because the latter is called after the section
7327      contents have been set, which means that the program headers have
7328      already been worked out.  */
7329   if (elf_seg_map (obfd) == NULL && elf_tdata (ibfd)->phdr != NULL)
7330     {
7331       if (! copy_private_bfd_data (ibfd, obfd))
7332 	return FALSE;
7333     }
7334 
7335   return _bfd_elf_fixup_group_sections (ibfd, NULL);
7336 }
7337 
7338 /* Copy private symbol information.  If this symbol is in a section
7339    which we did not map into a BFD section, try to map the section
7340    index correctly.  We use special macro definitions for the mapped
7341    section indices; these definitions are interpreted by the
7342    swap_out_syms function.  */
7343 
7344 #define MAP_ONESYMTAB (SHN_HIOS + 1)
7345 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
7346 #define MAP_STRTAB    (SHN_HIOS + 3)
7347 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
7348 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
7349 
7350 bfd_boolean
7351 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
7352 				   asymbol *isymarg,
7353 				   bfd *obfd,
7354 				   asymbol *osymarg)
7355 {
7356   elf_symbol_type *isym, *osym;
7357 
7358   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
7359       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
7360     return TRUE;
7361 
7362   isym = elf_symbol_from (ibfd, isymarg);
7363   osym = elf_symbol_from (obfd, osymarg);
7364 
7365   if (isym != NULL
7366       && isym->internal_elf_sym.st_shndx != 0
7367       && osym != NULL
7368       && bfd_is_abs_section (isym->symbol.section))
7369     {
7370       unsigned int shndx;
7371 
7372       shndx = isym->internal_elf_sym.st_shndx;
7373       if (shndx == elf_onesymtab (ibfd))
7374 	shndx = MAP_ONESYMTAB;
7375       else if (shndx == elf_dynsymtab (ibfd))
7376 	shndx = MAP_DYNSYMTAB;
7377       else if (shndx == elf_strtab_sec (ibfd))
7378 	shndx = MAP_STRTAB;
7379       else if (shndx == elf_shstrtab_sec (ibfd))
7380 	shndx = MAP_SHSTRTAB;
7381       else if (find_section_in_list (shndx, elf_symtab_shndx_list (ibfd)))
7382 	shndx = MAP_SYM_SHNDX;
7383       osym->internal_elf_sym.st_shndx = shndx;
7384     }
7385 
7386   return TRUE;
7387 }
7388 
7389 /* Swap out the symbols.  */
7390 
7391 static bfd_boolean
7392 swap_out_syms (bfd *abfd,
7393 	       struct elf_strtab_hash **sttp,
7394 	       int relocatable_p)
7395 {
7396   const struct elf_backend_data *bed;
7397   int symcount;
7398   asymbol **syms;
7399   struct elf_strtab_hash *stt;
7400   Elf_Internal_Shdr *symtab_hdr;
7401   Elf_Internal_Shdr *symtab_shndx_hdr;
7402   Elf_Internal_Shdr *symstrtab_hdr;
7403   struct elf_sym_strtab *symstrtab;
7404   bfd_byte *outbound_syms;
7405   bfd_byte *outbound_shndx;
7406   unsigned long outbound_syms_index;
7407   unsigned long outbound_shndx_index;
7408   int idx;
7409   unsigned int num_locals;
7410   bfd_size_type amt;
7411   bfd_boolean name_local_sections;
7412 
7413   if (!elf_map_symbols (abfd, &num_locals))
7414     return FALSE;
7415 
7416   /* Dump out the symtabs.  */
7417   stt = _bfd_elf_strtab_init ();
7418   if (stt == NULL)
7419     return FALSE;
7420 
7421   bed = get_elf_backend_data (abfd);
7422   symcount = bfd_get_symcount (abfd);
7423   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7424   symtab_hdr->sh_type = SHT_SYMTAB;
7425   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
7426   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
7427   symtab_hdr->sh_info = num_locals + 1;
7428   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
7429 
7430   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
7431   symstrtab_hdr->sh_type = SHT_STRTAB;
7432 
7433   /* Allocate buffer to swap out the .strtab section.  */
7434   symstrtab = (struct elf_sym_strtab *) bfd_malloc ((symcount + 1)
7435 						    * sizeof (*symstrtab));
7436   if (symstrtab == NULL)
7437     {
7438       _bfd_elf_strtab_free (stt);
7439       return FALSE;
7440     }
7441 
7442   outbound_syms = (bfd_byte *) bfd_alloc2 (abfd, 1 + symcount,
7443                                            bed->s->sizeof_sym);
7444   if (outbound_syms == NULL)
7445     {
7446 error_return:
7447       _bfd_elf_strtab_free (stt);
7448       free (symstrtab);
7449       return FALSE;
7450     }
7451   symtab_hdr->contents = outbound_syms;
7452   outbound_syms_index = 0;
7453 
7454   outbound_shndx = NULL;
7455   outbound_shndx_index = 0;
7456 
7457   if (elf_symtab_shndx_list (abfd))
7458     {
7459       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
7460       if (symtab_shndx_hdr->sh_name != 0)
7461 	{
7462 	  amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
7463 	  outbound_shndx =  (bfd_byte *)
7464 	    bfd_zalloc2 (abfd, 1 + symcount, sizeof (Elf_External_Sym_Shndx));
7465 	  if (outbound_shndx == NULL)
7466 	    goto error_return;
7467 
7468 	  symtab_shndx_hdr->contents = outbound_shndx;
7469 	  symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
7470 	  symtab_shndx_hdr->sh_size = amt;
7471 	  symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
7472 	  symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
7473 	}
7474       /* FIXME: What about any other headers in the list ?  */
7475     }
7476 
7477   /* Now generate the data (for "contents").  */
7478   {
7479     /* Fill in zeroth symbol and swap it out.  */
7480     Elf_Internal_Sym sym;
7481     sym.st_name = 0;
7482     sym.st_value = 0;
7483     sym.st_size = 0;
7484     sym.st_info = 0;
7485     sym.st_other = 0;
7486     sym.st_shndx = SHN_UNDEF;
7487     sym.st_target_internal = 0;
7488     symstrtab[0].sym = sym;
7489     symstrtab[0].dest_index = outbound_syms_index;
7490     symstrtab[0].destshndx_index = outbound_shndx_index;
7491     outbound_syms_index++;
7492     if (outbound_shndx != NULL)
7493       outbound_shndx_index++;
7494   }
7495 
7496   name_local_sections
7497     = (bed->elf_backend_name_local_section_symbols
7498        && bed->elf_backend_name_local_section_symbols (abfd));
7499 
7500   syms = bfd_get_outsymbols (abfd);
7501   for (idx = 0; idx < symcount;)
7502     {
7503       Elf_Internal_Sym sym;
7504       bfd_vma value = syms[idx]->value;
7505       elf_symbol_type *type_ptr;
7506       flagword flags = syms[idx]->flags;
7507       int type;
7508 
7509       if (!name_local_sections
7510 	  && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
7511 	{
7512 	  /* Local section symbols have no name.  */
7513 	  sym.st_name = (unsigned long) -1;
7514 	}
7515       else
7516 	{
7517 	  /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
7518 	     to get the final offset for st_name.  */
7519 	  sym.st_name
7520 	    = (unsigned long) _bfd_elf_strtab_add (stt, syms[idx]->name,
7521 						   FALSE);
7522 	  if (sym.st_name == (unsigned long) -1)
7523 	    goto error_return;
7524 	}
7525 
7526       type_ptr = elf_symbol_from (abfd, syms[idx]);
7527 
7528       if ((flags & BSF_SECTION_SYM) == 0
7529 	  && bfd_is_com_section (syms[idx]->section))
7530 	{
7531 	  /* ELF common symbols put the alignment into the `value' field,
7532 	     and the size into the `size' field.  This is backwards from
7533 	     how BFD handles it, so reverse it here.  */
7534 	  sym.st_size = value;
7535 	  if (type_ptr == NULL
7536 	      || type_ptr->internal_elf_sym.st_value == 0)
7537 	    sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
7538 	  else
7539 	    sym.st_value = type_ptr->internal_elf_sym.st_value;
7540 	  sym.st_shndx = _bfd_elf_section_from_bfd_section
7541 	    (abfd, syms[idx]->section);
7542 	}
7543       else
7544 	{
7545 	  asection *sec = syms[idx]->section;
7546 	  unsigned int shndx;
7547 
7548 	  if (sec->output_section)
7549 	    {
7550 	      value += sec->output_offset;
7551 	      sec = sec->output_section;
7552 	    }
7553 
7554 	  /* Don't add in the section vma for relocatable output.  */
7555 	  if (! relocatable_p)
7556 	    value += sec->vma;
7557 	  sym.st_value = value;
7558 	  sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
7559 
7560 	  if (bfd_is_abs_section (sec)
7561 	      && type_ptr != NULL
7562 	      && type_ptr->internal_elf_sym.st_shndx != 0)
7563 	    {
7564 	      /* This symbol is in a real ELF section which we did
7565 		 not create as a BFD section.  Undo the mapping done
7566 		 by copy_private_symbol_data.  */
7567 	      shndx = type_ptr->internal_elf_sym.st_shndx;
7568 	      switch (shndx)
7569 		{
7570 		case MAP_ONESYMTAB:
7571 		  shndx = elf_onesymtab (abfd);
7572 		  break;
7573 		case MAP_DYNSYMTAB:
7574 		  shndx = elf_dynsymtab (abfd);
7575 		  break;
7576 		case MAP_STRTAB:
7577 		  shndx = elf_strtab_sec (abfd);
7578 		  break;
7579 		case MAP_SHSTRTAB:
7580 		  shndx = elf_shstrtab_sec (abfd);
7581 		  break;
7582 		case MAP_SYM_SHNDX:
7583 		  if (elf_symtab_shndx_list (abfd))
7584 		    shndx = elf_symtab_shndx_list (abfd)->ndx;
7585 		  break;
7586 		default:
7587 		  shndx = SHN_ABS;
7588 		  break;
7589 		}
7590 	    }
7591 	  else
7592 	    {
7593 	      shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
7594 
7595 	      if (shndx == SHN_BAD)
7596 		{
7597 		  asection *sec2;
7598 
7599 		  /* Writing this would be a hell of a lot easier if
7600 		     we had some decent documentation on bfd, and
7601 		     knew what to expect of the library, and what to
7602 		     demand of applications.  For example, it
7603 		     appears that `objcopy' might not set the
7604 		     section of a symbol to be a section that is
7605 		     actually in the output file.  */
7606 		  sec2 = bfd_get_section_by_name (abfd, sec->name);
7607 		  if (sec2 == NULL)
7608 		    {
7609 		      _bfd_error_handler (_("\
7610 Unable to find equivalent output section for symbol '%s' from section '%s'"),
7611 					  syms[idx]->name ? syms[idx]->name : "<Local sym>",
7612 					  sec->name);
7613 		      bfd_set_error (bfd_error_invalid_operation);
7614 		      goto error_return;
7615 		    }
7616 
7617 		  shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
7618 		  BFD_ASSERT (shndx != SHN_BAD);
7619 		}
7620 	    }
7621 
7622 	  sym.st_shndx = shndx;
7623 	}
7624 
7625       if ((flags & BSF_THREAD_LOCAL) != 0)
7626 	type = STT_TLS;
7627       else if ((flags & BSF_GNU_INDIRECT_FUNCTION) != 0)
7628 	type = STT_GNU_IFUNC;
7629       else if ((flags & BSF_FUNCTION) != 0)
7630 	type = STT_FUNC;
7631       else if ((flags & BSF_OBJECT) != 0)
7632 	type = STT_OBJECT;
7633       else if ((flags & BSF_RELC) != 0)
7634 	type = STT_RELC;
7635       else if ((flags & BSF_SRELC) != 0)
7636 	type = STT_SRELC;
7637       else
7638 	type = STT_NOTYPE;
7639 
7640       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
7641 	type = STT_TLS;
7642 
7643       /* Processor-specific types.  */
7644       if (type_ptr != NULL
7645 	  && bed->elf_backend_get_symbol_type)
7646 	type = ((*bed->elf_backend_get_symbol_type)
7647 		(&type_ptr->internal_elf_sym, type));
7648 
7649       if (flags & BSF_SECTION_SYM)
7650 	{
7651 	  if (flags & BSF_GLOBAL)
7652 	    sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
7653 	  else
7654 	    sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
7655 	}
7656       else if (bfd_is_com_section (syms[idx]->section))
7657 	{
7658 	  if (type != STT_TLS)
7659 	    {
7660 	      if ((abfd->flags & BFD_CONVERT_ELF_COMMON))
7661 		type = ((abfd->flags & BFD_USE_ELF_STT_COMMON)
7662 			? STT_COMMON : STT_OBJECT);
7663 	      else
7664 		type = ((flags & BSF_ELF_COMMON) != 0
7665 			? STT_COMMON : STT_OBJECT);
7666 	    }
7667 	  sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
7668 	}
7669       else if (bfd_is_und_section (syms[idx]->section))
7670 	sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
7671 				    ? STB_WEAK
7672 				    : STB_GLOBAL),
7673 				   type);
7674       else if (flags & BSF_FILE)
7675 	sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
7676       else
7677 	{
7678 	  int bind = STB_LOCAL;
7679 
7680 	  if (flags & BSF_LOCAL)
7681 	    bind = STB_LOCAL;
7682 	  else if (flags & BSF_GNU_UNIQUE)
7683 	    bind = STB_GNU_UNIQUE;
7684 	  else if (flags & BSF_WEAK)
7685 	    bind = STB_WEAK;
7686 	  else if (flags & BSF_GLOBAL)
7687 	    bind = STB_GLOBAL;
7688 
7689 	  sym.st_info = ELF_ST_INFO (bind, type);
7690 	}
7691 
7692       if (type_ptr != NULL)
7693 	{
7694 	  sym.st_other = type_ptr->internal_elf_sym.st_other;
7695 	  sym.st_target_internal
7696 	    = type_ptr->internal_elf_sym.st_target_internal;
7697 	}
7698       else
7699 	{
7700 	  sym.st_other = 0;
7701 	  sym.st_target_internal = 0;
7702 	}
7703 
7704       idx++;
7705       symstrtab[idx].sym = sym;
7706       symstrtab[idx].dest_index = outbound_syms_index;
7707       symstrtab[idx].destshndx_index = outbound_shndx_index;
7708 
7709       outbound_syms_index++;
7710       if (outbound_shndx != NULL)
7711 	outbound_shndx_index++;
7712     }
7713 
7714   /* Finalize the .strtab section.  */
7715   _bfd_elf_strtab_finalize (stt);
7716 
7717   /* Swap out the .strtab section.  */
7718   for (idx = 0; idx <= symcount; idx++)
7719     {
7720       struct elf_sym_strtab *elfsym = &symstrtab[idx];
7721       if (elfsym->sym.st_name == (unsigned long) -1)
7722 	elfsym->sym.st_name = 0;
7723       else
7724 	elfsym->sym.st_name = _bfd_elf_strtab_offset (stt,
7725 						      elfsym->sym.st_name);
7726       bed->s->swap_symbol_out (abfd, &elfsym->sym,
7727 			       (outbound_syms
7728 				+ (elfsym->dest_index
7729 				   * bed->s->sizeof_sym)),
7730 			       (outbound_shndx
7731 				+ (elfsym->destshndx_index
7732 				   * sizeof (Elf_External_Sym_Shndx))));
7733     }
7734   free (symstrtab);
7735 
7736   *sttp = stt;
7737   symstrtab_hdr->sh_size = _bfd_elf_strtab_size (stt);
7738   symstrtab_hdr->sh_type = SHT_STRTAB;
7739   symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
7740   symstrtab_hdr->sh_addr = 0;
7741   symstrtab_hdr->sh_entsize = 0;
7742   symstrtab_hdr->sh_link = 0;
7743   symstrtab_hdr->sh_info = 0;
7744   symstrtab_hdr->sh_addralign = 1;
7745 
7746   return TRUE;
7747 }
7748 
7749 /* Return the number of bytes required to hold the symtab vector.
7750 
7751    Note that we base it on the count plus 1, since we will null terminate
7752    the vector allocated based on this size.  However, the ELF symbol table
7753    always has a dummy entry as symbol #0, so it ends up even.  */
7754 
7755 long
7756 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
7757 {
7758   long symcount;
7759   long symtab_size;
7760   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
7761 
7762   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
7763   symtab_size = (symcount + 1) * (sizeof (asymbol *));
7764   if (symcount > 0)
7765     symtab_size -= sizeof (asymbol *);
7766 
7767   return symtab_size;
7768 }
7769 
7770 long
7771 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
7772 {
7773   long symcount;
7774   long symtab_size;
7775   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
7776 
7777   if (elf_dynsymtab (abfd) == 0)
7778     {
7779       bfd_set_error (bfd_error_invalid_operation);
7780       return -1;
7781     }
7782 
7783   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
7784   symtab_size = (symcount + 1) * (sizeof (asymbol *));
7785   if (symcount > 0)
7786     symtab_size -= sizeof (asymbol *);
7787 
7788   return symtab_size;
7789 }
7790 
7791 long
7792 _bfd_elf_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
7793 				sec_ptr asect)
7794 {
7795   return (asect->reloc_count + 1) * sizeof (arelent *);
7796 }
7797 
7798 /* Canonicalize the relocs.  */
7799 
7800 long
7801 _bfd_elf_canonicalize_reloc (bfd *abfd,
7802 			     sec_ptr section,
7803 			     arelent **relptr,
7804 			     asymbol **symbols)
7805 {
7806   arelent *tblptr;
7807   unsigned int i;
7808   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7809 
7810   if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
7811     return -1;
7812 
7813   tblptr = section->relocation;
7814   for (i = 0; i < section->reloc_count; i++)
7815     *relptr++ = tblptr++;
7816 
7817   *relptr = NULL;
7818 
7819   return section->reloc_count;
7820 }
7821 
7822 long
7823 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
7824 {
7825   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7826   long symcount = bed->s->slurp_symbol_table (abfd, allocation, FALSE);
7827 
7828   if (symcount >= 0)
7829     bfd_get_symcount (abfd) = symcount;
7830   return symcount;
7831 }
7832 
7833 long
7834 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
7835 				      asymbol **allocation)
7836 {
7837   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7838   long symcount = bed->s->slurp_symbol_table (abfd, allocation, TRUE);
7839 
7840   if (symcount >= 0)
7841     bfd_get_dynamic_symcount (abfd) = symcount;
7842   return symcount;
7843 }
7844 
7845 /* Return the size required for the dynamic reloc entries.  Any loadable
7846    section that was actually installed in the BFD, and has type SHT_REL
7847    or SHT_RELA, and uses the dynamic symbol table, is considered to be a
7848    dynamic reloc section.  */
7849 
7850 long
7851 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
7852 {
7853   long ret;
7854   asection *s;
7855 
7856   if (elf_dynsymtab (abfd) == 0)
7857     {
7858       bfd_set_error (bfd_error_invalid_operation);
7859       return -1;
7860     }
7861 
7862   ret = sizeof (arelent *);
7863   for (s = abfd->sections; s != NULL; s = s->next)
7864     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
7865 	&& (elf_section_data (s)->this_hdr.sh_type == SHT_REL
7866 	    || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
7867       ret += ((s->size / elf_section_data (s)->this_hdr.sh_entsize)
7868 	      * sizeof (arelent *));
7869 
7870   return ret;
7871 }
7872 
7873 /* Canonicalize the dynamic relocation entries.  Note that we return the
7874    dynamic relocations as a single block, although they are actually
7875    associated with particular sections; the interface, which was
7876    designed for SunOS style shared libraries, expects that there is only
7877    one set of dynamic relocs.  Any loadable section that was actually
7878    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses the
7879    dynamic symbol table, is considered to be a dynamic reloc section.  */
7880 
7881 long
7882 _bfd_elf_canonicalize_dynamic_reloc (bfd *abfd,
7883 				     arelent **storage,
7884 				     asymbol **syms)
7885 {
7886   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
7887   asection *s;
7888   long ret;
7889 
7890   if (elf_dynsymtab (abfd) == 0)
7891     {
7892       bfd_set_error (bfd_error_invalid_operation);
7893       return -1;
7894     }
7895 
7896   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
7897   ret = 0;
7898   for (s = abfd->sections; s != NULL; s = s->next)
7899     {
7900       if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
7901 	  && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
7902 	      || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
7903 	{
7904 	  arelent *p;
7905 	  long count, i;
7906 
7907 	  if (! (*slurp_relocs) (abfd, s, syms, TRUE))
7908 	    return -1;
7909 	  count = s->size / elf_section_data (s)->this_hdr.sh_entsize;
7910 	  p = s->relocation;
7911 	  for (i = 0; i < count; i++)
7912 	    *storage++ = p++;
7913 	  ret += count;
7914 	}
7915     }
7916 
7917   *storage = NULL;
7918 
7919   return ret;
7920 }
7921 
7922 /* Read in the version information.  */
7923 
7924 bfd_boolean
7925 _bfd_elf_slurp_version_tables (bfd *abfd, bfd_boolean default_imported_symver)
7926 {
7927   bfd_byte *contents = NULL;
7928   unsigned int freeidx = 0;
7929 
7930   if (elf_dynverref (abfd) != 0)
7931     {
7932       Elf_Internal_Shdr *hdr;
7933       Elf_External_Verneed *everneed;
7934       Elf_Internal_Verneed *iverneed;
7935       unsigned int i;
7936       bfd_byte *contents_end;
7937 
7938       hdr = &elf_tdata (abfd)->dynverref_hdr;
7939 
7940       if (hdr->sh_info == 0 || hdr->sh_size < sizeof (Elf_External_Verneed))
7941 	{
7942 error_return_bad_verref:
7943 	  (*_bfd_error_handler)
7944 	    (_("%B: .gnu.version_r invalid entry"), abfd);
7945 	  bfd_set_error (bfd_error_bad_value);
7946 error_return_verref:
7947 	  elf_tdata (abfd)->verref = NULL;
7948 	  elf_tdata (abfd)->cverrefs = 0;
7949 	  goto error_return;
7950 	}
7951 
7952       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
7953       if (contents == NULL)
7954 	goto error_return_verref;
7955 
7956       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
7957 	  || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
7958 	goto error_return_verref;
7959 
7960       elf_tdata (abfd)->verref = (Elf_Internal_Verneed *)
7961 	bfd_zalloc2 (abfd, hdr->sh_info, sizeof (Elf_Internal_Verneed));
7962 
7963       if (elf_tdata (abfd)->verref == NULL)
7964 	goto error_return_verref;
7965 
7966       BFD_ASSERT (sizeof (Elf_External_Verneed)
7967 		  == sizeof (Elf_External_Vernaux));
7968       contents_end = contents + hdr->sh_size - sizeof (Elf_External_Verneed);
7969       everneed = (Elf_External_Verneed *) contents;
7970       iverneed = elf_tdata (abfd)->verref;
7971       for (i = 0; i < hdr->sh_info; i++, iverneed++)
7972 	{
7973 	  Elf_External_Vernaux *evernaux;
7974 	  Elf_Internal_Vernaux *ivernaux;
7975 	  unsigned int j;
7976 
7977 	  _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
7978 
7979 	  iverneed->vn_bfd = abfd;
7980 
7981 	  iverneed->vn_filename =
7982 	    bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
7983 					     iverneed->vn_file);
7984 	  if (iverneed->vn_filename == NULL)
7985 	    goto error_return_bad_verref;
7986 
7987 	  if (iverneed->vn_cnt == 0)
7988 	    iverneed->vn_auxptr = NULL;
7989 	  else
7990 	    {
7991 	      iverneed->vn_auxptr = (struct elf_internal_vernaux *)
7992                   bfd_alloc2 (abfd, iverneed->vn_cnt,
7993                               sizeof (Elf_Internal_Vernaux));
7994 	      if (iverneed->vn_auxptr == NULL)
7995 		goto error_return_verref;
7996 	    }
7997 
7998 	  if (iverneed->vn_aux
7999 	      > (size_t) (contents_end - (bfd_byte *) everneed))
8000 	    goto error_return_bad_verref;
8001 
8002 	  evernaux = ((Elf_External_Vernaux *)
8003 		      ((bfd_byte *) everneed + iverneed->vn_aux));
8004 	  ivernaux = iverneed->vn_auxptr;
8005 	  for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
8006 	    {
8007 	      _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
8008 
8009 	      ivernaux->vna_nodename =
8010 		bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
8011 						 ivernaux->vna_name);
8012 	      if (ivernaux->vna_nodename == NULL)
8013 		goto error_return_bad_verref;
8014 
8015 	      if (ivernaux->vna_other > freeidx)
8016 		freeidx = ivernaux->vna_other;
8017 
8018 	      ivernaux->vna_nextptr = NULL;
8019 	      if (ivernaux->vna_next == 0)
8020 		{
8021 		  iverneed->vn_cnt = j + 1;
8022 		  break;
8023 		}
8024 	      if (j + 1 < iverneed->vn_cnt)
8025 		ivernaux->vna_nextptr = ivernaux + 1;
8026 
8027 	      if (ivernaux->vna_next
8028 		  > (size_t) (contents_end - (bfd_byte *) evernaux))
8029 		goto error_return_bad_verref;
8030 
8031 	      evernaux = ((Elf_External_Vernaux *)
8032 			  ((bfd_byte *) evernaux + ivernaux->vna_next));
8033 	    }
8034 
8035 	  iverneed->vn_nextref = NULL;
8036 	  if (iverneed->vn_next == 0)
8037 	    break;
8038 	  if (i + 1 < hdr->sh_info)
8039 	    iverneed->vn_nextref = iverneed + 1;
8040 
8041 	  if (iverneed->vn_next
8042 	      > (size_t) (contents_end - (bfd_byte *) everneed))
8043 	    goto error_return_bad_verref;
8044 
8045 	  everneed = ((Elf_External_Verneed *)
8046 		      ((bfd_byte *) everneed + iverneed->vn_next));
8047 	}
8048       elf_tdata (abfd)->cverrefs = i;
8049 
8050       free (contents);
8051       contents = NULL;
8052     }
8053 
8054   if (elf_dynverdef (abfd) != 0)
8055     {
8056       Elf_Internal_Shdr *hdr;
8057       Elf_External_Verdef *everdef;
8058       Elf_Internal_Verdef *iverdef;
8059       Elf_Internal_Verdef *iverdefarr;
8060       Elf_Internal_Verdef iverdefmem;
8061       unsigned int i;
8062       unsigned int maxidx;
8063       bfd_byte *contents_end_def, *contents_end_aux;
8064 
8065       hdr = &elf_tdata (abfd)->dynverdef_hdr;
8066 
8067       if (hdr->sh_info == 0 || hdr->sh_size < sizeof (Elf_External_Verdef))
8068 	{
8069 	error_return_bad_verdef:
8070 	  (*_bfd_error_handler)
8071 	    (_("%B: .gnu.version_d invalid entry"), abfd);
8072 	  bfd_set_error (bfd_error_bad_value);
8073 	error_return_verdef:
8074 	  elf_tdata (abfd)->verdef = NULL;
8075 	  elf_tdata (abfd)->cverdefs = 0;
8076 	  goto error_return;
8077 	}
8078 
8079       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
8080       if (contents == NULL)
8081 	goto error_return_verdef;
8082       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
8083 	  || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
8084 	goto error_return_verdef;
8085 
8086       BFD_ASSERT (sizeof (Elf_External_Verdef)
8087 		  >= sizeof (Elf_External_Verdaux));
8088       contents_end_def = contents + hdr->sh_size
8089 			 - sizeof (Elf_External_Verdef);
8090       contents_end_aux = contents + hdr->sh_size
8091 			 - sizeof (Elf_External_Verdaux);
8092 
8093       /* We know the number of entries in the section but not the maximum
8094 	 index.  Therefore we have to run through all entries and find
8095 	 the maximum.  */
8096       everdef = (Elf_External_Verdef *) contents;
8097       maxidx = 0;
8098       for (i = 0; i < hdr->sh_info; ++i)
8099 	{
8100 	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
8101 
8102 	  if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) == 0)
8103 	    goto error_return_bad_verdef;
8104 	  if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
8105 	    maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
8106 
8107 	  if (iverdefmem.vd_next == 0)
8108 	    break;
8109 
8110 	  if (iverdefmem.vd_next
8111 	      > (size_t) (contents_end_def - (bfd_byte *) everdef))
8112 	    goto error_return_bad_verdef;
8113 
8114 	  everdef = ((Elf_External_Verdef *)
8115 		     ((bfd_byte *) everdef + iverdefmem.vd_next));
8116 	}
8117 
8118       if (default_imported_symver)
8119 	{
8120 	  if (freeidx > maxidx)
8121 	    maxidx = ++freeidx;
8122 	  else
8123 	    freeidx = ++maxidx;
8124 	}
8125 
8126       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *)
8127 	bfd_zalloc2 (abfd, maxidx, sizeof (Elf_Internal_Verdef));
8128       if (elf_tdata (abfd)->verdef == NULL)
8129 	goto error_return_verdef;
8130 
8131       elf_tdata (abfd)->cverdefs = maxidx;
8132 
8133       everdef = (Elf_External_Verdef *) contents;
8134       iverdefarr = elf_tdata (abfd)->verdef;
8135       for (i = 0; i < hdr->sh_info; i++)
8136 	{
8137 	  Elf_External_Verdaux *everdaux;
8138 	  Elf_Internal_Verdaux *iverdaux;
8139 	  unsigned int j;
8140 
8141 	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
8142 
8143 	  if ((iverdefmem.vd_ndx & VERSYM_VERSION) == 0)
8144 	    goto error_return_bad_verdef;
8145 
8146 	  iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
8147 	  memcpy (iverdef, &iverdefmem, offsetof (Elf_Internal_Verdef, vd_bfd));
8148 
8149 	  iverdef->vd_bfd = abfd;
8150 
8151 	  if (iverdef->vd_cnt == 0)
8152 	    iverdef->vd_auxptr = NULL;
8153 	  else
8154 	    {
8155 	      iverdef->vd_auxptr = (struct elf_internal_verdaux *)
8156                   bfd_alloc2 (abfd, iverdef->vd_cnt,
8157                               sizeof (Elf_Internal_Verdaux));
8158 	      if (iverdef->vd_auxptr == NULL)
8159 		goto error_return_verdef;
8160 	    }
8161 
8162 	  if (iverdef->vd_aux
8163 	      > (size_t) (contents_end_aux - (bfd_byte *) everdef))
8164 	    goto error_return_bad_verdef;
8165 
8166 	  everdaux = ((Elf_External_Verdaux *)
8167 		      ((bfd_byte *) everdef + iverdef->vd_aux));
8168 	  iverdaux = iverdef->vd_auxptr;
8169 	  for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
8170 	    {
8171 	      _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
8172 
8173 	      iverdaux->vda_nodename =
8174 		bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
8175 						 iverdaux->vda_name);
8176 	      if (iverdaux->vda_nodename == NULL)
8177 		goto error_return_bad_verdef;
8178 
8179 	      iverdaux->vda_nextptr = NULL;
8180 	      if (iverdaux->vda_next == 0)
8181 		{
8182 		  iverdef->vd_cnt = j + 1;
8183 		  break;
8184 		}
8185 	      if (j + 1 < iverdef->vd_cnt)
8186 		iverdaux->vda_nextptr = iverdaux + 1;
8187 
8188 	      if (iverdaux->vda_next
8189 		  > (size_t) (contents_end_aux - (bfd_byte *) everdaux))
8190 		goto error_return_bad_verdef;
8191 
8192 	      everdaux = ((Elf_External_Verdaux *)
8193 			  ((bfd_byte *) everdaux + iverdaux->vda_next));
8194 	    }
8195 
8196 	  iverdef->vd_nodename = NULL;
8197 	  if (iverdef->vd_cnt)
8198 	    iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
8199 
8200 	  iverdef->vd_nextdef = NULL;
8201 	  if (iverdef->vd_next == 0)
8202 	    break;
8203 	  if ((size_t) (iverdef - iverdefarr) + 1 < maxidx)
8204 	    iverdef->vd_nextdef = iverdef + 1;
8205 
8206 	  everdef = ((Elf_External_Verdef *)
8207 		     ((bfd_byte *) everdef + iverdef->vd_next));
8208 	}
8209 
8210       free (contents);
8211       contents = NULL;
8212     }
8213   else if (default_imported_symver)
8214     {
8215       if (freeidx < 3)
8216 	freeidx = 3;
8217       else
8218 	freeidx++;
8219 
8220       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *)
8221           bfd_zalloc2 (abfd, freeidx, sizeof (Elf_Internal_Verdef));
8222       if (elf_tdata (abfd)->verdef == NULL)
8223 	goto error_return;
8224 
8225       elf_tdata (abfd)->cverdefs = freeidx;
8226     }
8227 
8228   /* Create a default version based on the soname.  */
8229   if (default_imported_symver)
8230     {
8231       Elf_Internal_Verdef *iverdef;
8232       Elf_Internal_Verdaux *iverdaux;
8233 
8234       iverdef = &elf_tdata (abfd)->verdef[freeidx - 1];
8235 
8236       iverdef->vd_version = VER_DEF_CURRENT;
8237       iverdef->vd_flags = 0;
8238       iverdef->vd_ndx = freeidx;
8239       iverdef->vd_cnt = 1;
8240 
8241       iverdef->vd_bfd = abfd;
8242 
8243       iverdef->vd_nodename = bfd_elf_get_dt_soname (abfd);
8244       if (iverdef->vd_nodename == NULL)
8245 	goto error_return_verdef;
8246       iverdef->vd_nextdef = NULL;
8247       iverdef->vd_auxptr = ((struct elf_internal_verdaux *)
8248 			    bfd_zalloc (abfd, sizeof (Elf_Internal_Verdaux)));
8249       if (iverdef->vd_auxptr == NULL)
8250 	goto error_return_verdef;
8251 
8252       iverdaux = iverdef->vd_auxptr;
8253       iverdaux->vda_nodename = iverdef->vd_nodename;
8254     }
8255 
8256   return TRUE;
8257 
8258  error_return:
8259   if (contents != NULL)
8260     free (contents);
8261   return FALSE;
8262 }
8263 
8264 asymbol *
8265 _bfd_elf_make_empty_symbol (bfd *abfd)
8266 {
8267   elf_symbol_type *newsym;
8268 
8269   newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof * newsym);
8270   if (!newsym)
8271     return NULL;
8272   newsym->symbol.the_bfd = abfd;
8273   return &newsym->symbol;
8274 }
8275 
8276 void
8277 _bfd_elf_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
8278 			  asymbol *symbol,
8279 			  symbol_info *ret)
8280 {
8281   bfd_symbol_info (symbol, ret);
8282 }
8283 
8284 /* Return whether a symbol name implies a local symbol.  Most targets
8285    use this function for the is_local_label_name entry point, but some
8286    override it.  */
8287 
8288 bfd_boolean
8289 _bfd_elf_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
8290 			      const char *name)
8291 {
8292   /* Normal local symbols start with ``.L''.  */
8293   if (name[0] == '.' && name[1] == 'L')
8294     return TRUE;
8295 
8296   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
8297      DWARF debugging symbols starting with ``..''.  */
8298   if (name[0] == '.' && name[1] == '.')
8299     return TRUE;
8300 
8301   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
8302      emitting DWARF debugging output.  I suspect this is actually a
8303      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
8304      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
8305      underscore to be emitted on some ELF targets).  For ease of use,
8306      we treat such symbols as local.  */
8307   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
8308     return TRUE;
8309 
8310   /* Treat assembler generated fake symbols, dollar local labels and
8311      forward-backward labels (aka local labels) as locals.
8312      These labels have the form:
8313 
8314        L0^A.*                                  (fake symbols)
8315 
8316        [.]?L[0123456789]+{^A|^B}[0123456789]*  (local labels)
8317 
8318      Versions which start with .L will have already been matched above,
8319      so we only need to match the rest.  */
8320   if (name[0] == 'L' && ISDIGIT (name[1]))
8321     {
8322       bfd_boolean ret = FALSE;
8323       const char * p;
8324       char c;
8325 
8326       for (p = name + 2; (c = *p); p++)
8327 	{
8328 	  if (c == 1 || c == 2)
8329 	    {
8330 	      if (c == 1 && p == name + 2)
8331 		/* A fake symbol.  */
8332 		return TRUE;
8333 
8334 	      /* FIXME: We are being paranoid here and treating symbols like
8335 		 L0^Bfoo as if there were non-local, on the grounds that the
8336 		 assembler will never generate them.  But can any symbol
8337 		 containing an ASCII value in the range 1-31 ever be anything
8338 		 other than some kind of local ?  */
8339 	      ret = TRUE;
8340 	    }
8341 
8342 	  if (! ISDIGIT (c))
8343 	    {
8344 	      ret = FALSE;
8345 	      break;
8346 	    }
8347 	}
8348       return ret;
8349     }
8350 
8351   return FALSE;
8352 }
8353 
8354 alent *
8355 _bfd_elf_get_lineno (bfd *abfd ATTRIBUTE_UNUSED,
8356 		     asymbol *symbol ATTRIBUTE_UNUSED)
8357 {
8358   abort ();
8359   return NULL;
8360 }
8361 
8362 bfd_boolean
8363 _bfd_elf_set_arch_mach (bfd *abfd,
8364 			enum bfd_architecture arch,
8365 			unsigned long machine)
8366 {
8367   /* If this isn't the right architecture for this backend, and this
8368      isn't the generic backend, fail.  */
8369   if (arch != get_elf_backend_data (abfd)->arch
8370       && arch != bfd_arch_unknown
8371       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
8372     return FALSE;
8373 
8374   return bfd_default_set_arch_mach (abfd, arch, machine);
8375 }
8376 
8377 /* Find the nearest line to a particular section and offset,
8378    for error reporting.  */
8379 
8380 bfd_boolean
8381 _bfd_elf_find_nearest_line (bfd *abfd,
8382 			    asymbol **symbols,
8383 			    asection *section,
8384 			    bfd_vma offset,
8385 			    const char **filename_ptr,
8386 			    const char **functionname_ptr,
8387 			    unsigned int *line_ptr,
8388 			    unsigned int *discriminator_ptr)
8389 {
8390   bfd_boolean found;
8391 
8392   if (_bfd_dwarf2_find_nearest_line (abfd, symbols, NULL, section, offset,
8393 				     filename_ptr, functionname_ptr,
8394 				     line_ptr, discriminator_ptr,
8395 				     dwarf_debug_sections, 0,
8396 				     &elf_tdata (abfd)->dwarf2_find_line_info)
8397       || _bfd_dwarf1_find_nearest_line (abfd, symbols, section, offset,
8398 					filename_ptr, functionname_ptr,
8399 					line_ptr))
8400     {
8401       if (!*functionname_ptr)
8402 	_bfd_elf_find_function (abfd, symbols, section, offset,
8403 				*filename_ptr ? NULL : filename_ptr,
8404 				functionname_ptr);
8405       return TRUE;
8406     }
8407 
8408   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
8409 					     &found, filename_ptr,
8410 					     functionname_ptr, line_ptr,
8411 					     &elf_tdata (abfd)->line_info))
8412     return FALSE;
8413   if (found && (*functionname_ptr || *line_ptr))
8414     return TRUE;
8415 
8416   if (symbols == NULL)
8417     return FALSE;
8418 
8419   if (! _bfd_elf_find_function (abfd, symbols, section, offset,
8420 				filename_ptr, functionname_ptr))
8421     return FALSE;
8422 
8423   *line_ptr = 0;
8424   return TRUE;
8425 }
8426 
8427 /* Find the line for a symbol.  */
8428 
8429 bfd_boolean
8430 _bfd_elf_find_line (bfd *abfd, asymbol **symbols, asymbol *symbol,
8431 		    const char **filename_ptr, unsigned int *line_ptr)
8432 {
8433   return _bfd_dwarf2_find_nearest_line (abfd, symbols, symbol, NULL, 0,
8434 					filename_ptr, NULL, line_ptr, NULL,
8435 					dwarf_debug_sections, 0,
8436 					&elf_tdata (abfd)->dwarf2_find_line_info);
8437 }
8438 
8439 /* After a call to bfd_find_nearest_line, successive calls to
8440    bfd_find_inliner_info can be used to get source information about
8441    each level of function inlining that terminated at the address
8442    passed to bfd_find_nearest_line.  Currently this is only supported
8443    for DWARF2 with appropriate DWARF3 extensions. */
8444 
8445 bfd_boolean
8446 _bfd_elf_find_inliner_info (bfd *abfd,
8447 			    const char **filename_ptr,
8448 			    const char **functionname_ptr,
8449 			    unsigned int *line_ptr)
8450 {
8451   bfd_boolean found;
8452   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
8453 					 functionname_ptr, line_ptr,
8454 					 & elf_tdata (abfd)->dwarf2_find_line_info);
8455   return found;
8456 }
8457 
8458 int
8459 _bfd_elf_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
8460 {
8461   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8462   int ret = bed->s->sizeof_ehdr;
8463 
8464   if (!bfd_link_relocatable (info))
8465     {
8466       bfd_size_type phdr_size = elf_program_header_size (abfd);
8467 
8468       if (phdr_size == (bfd_size_type) -1)
8469 	{
8470 	  struct elf_segment_map *m;
8471 
8472 	  phdr_size = 0;
8473 	  for (m = elf_seg_map (abfd); m != NULL; m = m->next)
8474 	    phdr_size += bed->s->sizeof_phdr;
8475 
8476 	  if (phdr_size == 0)
8477 	    phdr_size = get_program_header_size (abfd, info);
8478 	}
8479 
8480       elf_program_header_size (abfd) = phdr_size;
8481       ret += phdr_size;
8482     }
8483 
8484   return ret;
8485 }
8486 
8487 bfd_boolean
8488 _bfd_elf_set_section_contents (bfd *abfd,
8489 			       sec_ptr section,
8490 			       const void *location,
8491 			       file_ptr offset,
8492 			       bfd_size_type count)
8493 {
8494   Elf_Internal_Shdr *hdr;
8495   file_ptr pos;
8496 
8497   if (! abfd->output_has_begun
8498       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
8499     return FALSE;
8500 
8501   if (!count)
8502     return TRUE;
8503 
8504   hdr = &elf_section_data (section)->this_hdr;
8505   if (hdr->sh_offset == (file_ptr) -1)
8506     {
8507       /* We must compress this section.  Write output to the buffer.  */
8508       unsigned char *contents = hdr->contents;
8509       if ((offset + count) > hdr->sh_size
8510 	  || (section->flags & SEC_ELF_COMPRESS) == 0
8511 	  || contents == NULL)
8512 	abort ();
8513       memcpy (contents + offset, location, count);
8514       return TRUE;
8515     }
8516   pos = hdr->sh_offset + offset;
8517   if (bfd_seek (abfd, pos, SEEK_SET) != 0
8518       || bfd_bwrite (location, count, abfd) != count)
8519     return FALSE;
8520 
8521   return TRUE;
8522 }
8523 
8524 void
8525 _bfd_elf_no_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
8526 			   arelent *cache_ptr ATTRIBUTE_UNUSED,
8527 			   Elf_Internal_Rela *dst ATTRIBUTE_UNUSED)
8528 {
8529   abort ();
8530 }
8531 
8532 /* Try to convert a non-ELF reloc into an ELF one.  */
8533 
8534 bfd_boolean
8535 _bfd_elf_validate_reloc (bfd *abfd, arelent *areloc)
8536 {
8537   /* Check whether we really have an ELF howto.  */
8538 
8539   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
8540     {
8541       bfd_reloc_code_real_type code;
8542       reloc_howto_type *howto;
8543 
8544       /* Alien reloc: Try to determine its type to replace it with an
8545 	 equivalent ELF reloc.  */
8546 
8547       if (areloc->howto->pc_relative)
8548 	{
8549 	  switch (areloc->howto->bitsize)
8550 	    {
8551 	    case 8:
8552 	      code = BFD_RELOC_8_PCREL;
8553 	      break;
8554 	    case 12:
8555 	      code = BFD_RELOC_12_PCREL;
8556 	      break;
8557 	    case 16:
8558 	      code = BFD_RELOC_16_PCREL;
8559 	      break;
8560 	    case 24:
8561 	      code = BFD_RELOC_24_PCREL;
8562 	      break;
8563 	    case 32:
8564 	      code = BFD_RELOC_32_PCREL;
8565 	      break;
8566 	    case 64:
8567 	      code = BFD_RELOC_64_PCREL;
8568 	      break;
8569 	    default:
8570 	      goto fail;
8571 	    }
8572 
8573 	  howto = bfd_reloc_type_lookup (abfd, code);
8574 
8575 	  if (areloc->howto->pcrel_offset != howto->pcrel_offset)
8576 	    {
8577 	      if (howto->pcrel_offset)
8578 		areloc->addend += areloc->address;
8579 	      else
8580 		areloc->addend -= areloc->address; /* addend is unsigned!! */
8581 	    }
8582 	}
8583       else
8584 	{
8585 	  switch (areloc->howto->bitsize)
8586 	    {
8587 	    case 8:
8588 	      code = BFD_RELOC_8;
8589 	      break;
8590 	    case 14:
8591 	      code = BFD_RELOC_14;
8592 	      break;
8593 	    case 16:
8594 	      code = BFD_RELOC_16;
8595 	      break;
8596 	    case 26:
8597 	      code = BFD_RELOC_26;
8598 	      break;
8599 	    case 32:
8600 	      code = BFD_RELOC_32;
8601 	      break;
8602 	    case 64:
8603 	      code = BFD_RELOC_64;
8604 	      break;
8605 	    default:
8606 	      goto fail;
8607 	    }
8608 
8609 	  howto = bfd_reloc_type_lookup (abfd, code);
8610 	}
8611 
8612       if (howto)
8613 	areloc->howto = howto;
8614       else
8615 	goto fail;
8616     }
8617 
8618   return TRUE;
8619 
8620  fail:
8621   (*_bfd_error_handler)
8622     (_("%B: unsupported relocation type %s"),
8623      abfd, areloc->howto->name);
8624   bfd_set_error (bfd_error_bad_value);
8625   return FALSE;
8626 }
8627 
8628 bfd_boolean
8629 _bfd_elf_close_and_cleanup (bfd *abfd)
8630 {
8631   struct elf_obj_tdata *tdata = elf_tdata (abfd);
8632   if (bfd_get_format (abfd) == bfd_object && tdata != NULL)
8633     {
8634       if (elf_tdata (abfd)->o != NULL && elf_shstrtab (abfd) != NULL)
8635 	_bfd_elf_strtab_free (elf_shstrtab (abfd));
8636       _bfd_dwarf2_cleanup_debug_info (abfd, &tdata->dwarf2_find_line_info);
8637     }
8638 
8639   return _bfd_generic_close_and_cleanup (abfd);
8640 }
8641 
8642 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
8643    in the relocation's offset.  Thus we cannot allow any sort of sanity
8644    range-checking to interfere.  There is nothing else to do in processing
8645    this reloc.  */
8646 
8647 bfd_reloc_status_type
8648 _bfd_elf_rel_vtable_reloc_fn
8649   (bfd *abfd ATTRIBUTE_UNUSED, arelent *re ATTRIBUTE_UNUSED,
8650    struct bfd_symbol *symbol ATTRIBUTE_UNUSED,
8651    void *data ATTRIBUTE_UNUSED, asection *is ATTRIBUTE_UNUSED,
8652    bfd *obfd ATTRIBUTE_UNUSED, char **errmsg ATTRIBUTE_UNUSED)
8653 {
8654   return bfd_reloc_ok;
8655 }
8656 
8657 /* Elf core file support.  Much of this only works on native
8658    toolchains, since we rely on knowing the
8659    machine-dependent procfs structure in order to pick
8660    out details about the corefile.  */
8661 
8662 #ifdef HAVE_SYS_PROCFS_H
8663 /* Needed for new procfs interface on sparc-solaris.  */
8664 # define _STRUCTURED_PROC 1
8665 # include <sys/procfs.h>
8666 #endif
8667 
8668 /* Return a PID that identifies a "thread" for threaded cores, or the
8669    PID of the main process for non-threaded cores.  */
8670 
8671 static int
8672 elfcore_make_pid (bfd *abfd)
8673 {
8674   int pid;
8675 
8676   pid = elf_tdata (abfd)->core->lwpid;
8677   if (pid == 0)
8678     pid = elf_tdata (abfd)->core->pid;
8679 
8680   return pid;
8681 }
8682 
8683 /* If there isn't a section called NAME, make one, using
8684    data from SECT.  Note, this function will generate a
8685    reference to NAME, so you shouldn't deallocate or
8686    overwrite it.  */
8687 
8688 static bfd_boolean
8689 elfcore_maybe_make_sect (bfd *abfd, char *name, asection *sect)
8690 {
8691   asection *sect2;
8692 
8693   if (bfd_get_section_by_name (abfd, name) != NULL)
8694     return TRUE;
8695 
8696   sect2 = bfd_make_section_with_flags (abfd, name, sect->flags);
8697   if (sect2 == NULL)
8698     return FALSE;
8699 
8700   sect2->size = sect->size;
8701   sect2->filepos = sect->filepos;
8702   sect2->alignment_power = sect->alignment_power;
8703   return TRUE;
8704 }
8705 
8706 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
8707    actually creates up to two pseudosections:
8708    - For the single-threaded case, a section named NAME, unless
8709      such a section already exists.
8710    - For the multi-threaded case, a section named "NAME/PID", where
8711      PID is elfcore_make_pid (abfd).
8712    Both pseudosections have identical contents. */
8713 bfd_boolean
8714 _bfd_elfcore_make_pseudosection (bfd *abfd,
8715 				 char *name,
8716 				 size_t size,
8717 				 ufile_ptr filepos)
8718 {
8719   char buf[100];
8720   char *threaded_name;
8721   size_t len;
8722   asection *sect;
8723 
8724   /* Build the section name.  */
8725 
8726   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
8727   len = strlen (buf) + 1;
8728   threaded_name = (char *) bfd_alloc (abfd, len);
8729   if (threaded_name == NULL)
8730     return FALSE;
8731   memcpy (threaded_name, buf, len);
8732 
8733   sect = bfd_make_section_anyway_with_flags (abfd, threaded_name,
8734 					     SEC_HAS_CONTENTS);
8735   if (sect == NULL)
8736     return FALSE;
8737   sect->size = size;
8738   sect->filepos = filepos;
8739   sect->alignment_power = 2;
8740 
8741   return elfcore_maybe_make_sect (abfd, name, sect);
8742 }
8743 
8744 /* prstatus_t exists on:
8745      solaris 2.5+
8746      linux 2.[01] + glibc
8747      unixware 4.2
8748 */
8749 
8750 #if defined (HAVE_PRSTATUS_T)
8751 
8752 static bfd_boolean
8753 elfcore_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
8754 {
8755   size_t size;
8756   int offset;
8757 
8758   if (note->descsz == sizeof (prstatus_t))
8759     {
8760       prstatus_t prstat;
8761 
8762       size = sizeof (prstat.pr_reg);
8763       offset   = offsetof (prstatus_t, pr_reg);
8764       memcpy (&prstat, note->descdata, sizeof (prstat));
8765 
8766       /* Do not overwrite the core signal if it
8767 	 has already been set by another thread.  */
8768       if (elf_tdata (abfd)->core->signal == 0)
8769 	elf_tdata (abfd)->core->signal = prstat.pr_cursig;
8770       if (elf_tdata (abfd)->core->pid == 0)
8771 	elf_tdata (abfd)->core->pid = prstat.pr_pid;
8772 
8773       /* pr_who exists on:
8774 	 solaris 2.5+
8775 	 unixware 4.2
8776 	 pr_who doesn't exist on:
8777 	 linux 2.[01]
8778 	 */
8779 #if defined (HAVE_PRSTATUS_T_PR_WHO)
8780       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
8781 #else
8782       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
8783 #endif
8784     }
8785 #if defined (HAVE_PRSTATUS32_T)
8786   else if (note->descsz == sizeof (prstatus32_t))
8787     {
8788       /* 64-bit host, 32-bit corefile */
8789       prstatus32_t prstat;
8790 
8791       size = sizeof (prstat.pr_reg);
8792       offset   = offsetof (prstatus32_t, pr_reg);
8793       memcpy (&prstat, note->descdata, sizeof (prstat));
8794 
8795       /* Do not overwrite the core signal if it
8796 	 has already been set by another thread.  */
8797       if (elf_tdata (abfd)->core->signal == 0)
8798 	elf_tdata (abfd)->core->signal = prstat.pr_cursig;
8799       if (elf_tdata (abfd)->core->pid == 0)
8800 	elf_tdata (abfd)->core->pid = prstat.pr_pid;
8801 
8802       /* pr_who exists on:
8803 	 solaris 2.5+
8804 	 unixware 4.2
8805 	 pr_who doesn't exist on:
8806 	 linux 2.[01]
8807 	 */
8808 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
8809       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
8810 #else
8811       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
8812 #endif
8813     }
8814 #endif /* HAVE_PRSTATUS32_T */
8815   else
8816     {
8817       /* Fail - we don't know how to handle any other
8818 	 note size (ie. data object type).  */
8819       return TRUE;
8820     }
8821 
8822   /* Make a ".reg/999" section and a ".reg" section.  */
8823   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
8824 					  size, note->descpos + offset);
8825 }
8826 #endif /* defined (HAVE_PRSTATUS_T) */
8827 
8828 /* Create a pseudosection containing the exact contents of NOTE.  */
8829 static bfd_boolean
8830 elfcore_make_note_pseudosection (bfd *abfd,
8831 				 char *name,
8832 				 Elf_Internal_Note *note)
8833 {
8834   return _bfd_elfcore_make_pseudosection (abfd, name,
8835 					  note->descsz, note->descpos);
8836 }
8837 
8838 /* There isn't a consistent prfpregset_t across platforms,
8839    but it doesn't matter, because we don't have to pick this
8840    data structure apart.  */
8841 
8842 static bfd_boolean
8843 elfcore_grok_prfpreg (bfd *abfd, Elf_Internal_Note *note)
8844 {
8845   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
8846 }
8847 
8848 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
8849    type of NT_PRXFPREG.  Just include the whole note's contents
8850    literally.  */
8851 
8852 static bfd_boolean
8853 elfcore_grok_prxfpreg (bfd *abfd, Elf_Internal_Note *note)
8854 {
8855   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
8856 }
8857 
8858 /* Linux dumps the Intel XSAVE extended state in a note named "LINUX"
8859    with a note type of NT_X86_XSTATE.  Just include the whole note's
8860    contents literally.  */
8861 
8862 static bfd_boolean
8863 elfcore_grok_xstatereg (bfd *abfd, Elf_Internal_Note *note)
8864 {
8865   return elfcore_make_note_pseudosection (abfd, ".reg-xstate", note);
8866 }
8867 
8868 static bfd_boolean
8869 elfcore_grok_ppc_vmx (bfd *abfd, Elf_Internal_Note *note)
8870 {
8871   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vmx", note);
8872 }
8873 
8874 static bfd_boolean
8875 elfcore_grok_ppc_vsx (bfd *abfd, Elf_Internal_Note *note)
8876 {
8877   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vsx", note);
8878 }
8879 
8880 static bfd_boolean
8881 elfcore_grok_s390_high_gprs (bfd *abfd, Elf_Internal_Note *note)
8882 {
8883   return elfcore_make_note_pseudosection (abfd, ".reg-s390-high-gprs", note);
8884 }
8885 
8886 static bfd_boolean
8887 elfcore_grok_s390_timer (bfd *abfd, Elf_Internal_Note *note)
8888 {
8889   return elfcore_make_note_pseudosection (abfd, ".reg-s390-timer", note);
8890 }
8891 
8892 static bfd_boolean
8893 elfcore_grok_s390_todcmp (bfd *abfd, Elf_Internal_Note *note)
8894 {
8895   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todcmp", note);
8896 }
8897 
8898 static bfd_boolean
8899 elfcore_grok_s390_todpreg (bfd *abfd, Elf_Internal_Note *note)
8900 {
8901   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todpreg", note);
8902 }
8903 
8904 static bfd_boolean
8905 elfcore_grok_s390_ctrs (bfd *abfd, Elf_Internal_Note *note)
8906 {
8907   return elfcore_make_note_pseudosection (abfd, ".reg-s390-ctrs", note);
8908 }
8909 
8910 static bfd_boolean
8911 elfcore_grok_s390_prefix (bfd *abfd, Elf_Internal_Note *note)
8912 {
8913   return elfcore_make_note_pseudosection (abfd, ".reg-s390-prefix", note);
8914 }
8915 
8916 static bfd_boolean
8917 elfcore_grok_s390_last_break (bfd *abfd, Elf_Internal_Note *note)
8918 {
8919   return elfcore_make_note_pseudosection (abfd, ".reg-s390-last-break", note);
8920 }
8921 
8922 static bfd_boolean
8923 elfcore_grok_s390_system_call (bfd *abfd, Elf_Internal_Note *note)
8924 {
8925   return elfcore_make_note_pseudosection (abfd, ".reg-s390-system-call", note);
8926 }
8927 
8928 static bfd_boolean
8929 elfcore_grok_s390_tdb (bfd *abfd, Elf_Internal_Note *note)
8930 {
8931   return elfcore_make_note_pseudosection (abfd, ".reg-s390-tdb", note);
8932 }
8933 
8934 static bfd_boolean
8935 elfcore_grok_s390_vxrs_low (bfd *abfd, Elf_Internal_Note *note)
8936 {
8937   return elfcore_make_note_pseudosection (abfd, ".reg-s390-vxrs-low", note);
8938 }
8939 
8940 static bfd_boolean
8941 elfcore_grok_s390_vxrs_high (bfd *abfd, Elf_Internal_Note *note)
8942 {
8943   return elfcore_make_note_pseudosection (abfd, ".reg-s390-vxrs-high", note);
8944 }
8945 
8946 static bfd_boolean
8947 elfcore_grok_arm_vfp (bfd *abfd, Elf_Internal_Note *note)
8948 {
8949   return elfcore_make_note_pseudosection (abfd, ".reg-arm-vfp", note);
8950 }
8951 
8952 static bfd_boolean
8953 elfcore_grok_aarch_tls (bfd *abfd, Elf_Internal_Note *note)
8954 {
8955   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-tls", note);
8956 }
8957 
8958 static bfd_boolean
8959 elfcore_grok_aarch_hw_break (bfd *abfd, Elf_Internal_Note *note)
8960 {
8961   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-break", note);
8962 }
8963 
8964 static bfd_boolean
8965 elfcore_grok_aarch_hw_watch (bfd *abfd, Elf_Internal_Note *note)
8966 {
8967   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-watch", note);
8968 }
8969 
8970 #if defined (HAVE_PRPSINFO_T)
8971 typedef prpsinfo_t   elfcore_psinfo_t;
8972 #if defined (HAVE_PRPSINFO32_T)		/* Sparc64 cross Sparc32 */
8973 typedef prpsinfo32_t elfcore_psinfo32_t;
8974 #endif
8975 #endif
8976 
8977 #if defined (HAVE_PSINFO_T)
8978 typedef psinfo_t   elfcore_psinfo_t;
8979 #if defined (HAVE_PSINFO32_T)		/* Sparc64 cross Sparc32 */
8980 typedef psinfo32_t elfcore_psinfo32_t;
8981 #endif
8982 #endif
8983 
8984 /* return a malloc'ed copy of a string at START which is at
8985    most MAX bytes long, possibly without a terminating '\0'.
8986    the copy will always have a terminating '\0'.  */
8987 
8988 char *
8989 _bfd_elfcore_strndup (bfd *abfd, char *start, size_t max)
8990 {
8991   char *dups;
8992   char *end = (char *) memchr (start, '\0', max);
8993   size_t len;
8994 
8995   if (end == NULL)
8996     len = max;
8997   else
8998     len = end - start;
8999 
9000   dups = (char *) bfd_alloc (abfd, len + 1);
9001   if (dups == NULL)
9002     return NULL;
9003 
9004   memcpy (dups, start, len);
9005   dups[len] = '\0';
9006 
9007   return dups;
9008 }
9009 
9010 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
9011 static bfd_boolean
9012 elfcore_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
9013 {
9014   if (note->descsz == sizeof (elfcore_psinfo_t))
9015     {
9016       elfcore_psinfo_t psinfo;
9017 
9018       memcpy (&psinfo, note->descdata, sizeof (psinfo));
9019 
9020 #if defined (HAVE_PSINFO_T_PR_PID) || defined (HAVE_PRPSINFO_T_PR_PID)
9021       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
9022 #endif
9023       elf_tdata (abfd)->core->program
9024 	= _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
9025 				sizeof (psinfo.pr_fname));
9026 
9027       elf_tdata (abfd)->core->command
9028 	= _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
9029 				sizeof (psinfo.pr_psargs));
9030     }
9031 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
9032   else if (note->descsz == sizeof (elfcore_psinfo32_t))
9033     {
9034       /* 64-bit host, 32-bit corefile */
9035       elfcore_psinfo32_t psinfo;
9036 
9037       memcpy (&psinfo, note->descdata, sizeof (psinfo));
9038 
9039 #if defined (HAVE_PSINFO32_T_PR_PID) || defined (HAVE_PRPSINFO32_T_PR_PID)
9040       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
9041 #endif
9042       elf_tdata (abfd)->core->program
9043 	= _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
9044 				sizeof (psinfo.pr_fname));
9045 
9046       elf_tdata (abfd)->core->command
9047 	= _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
9048 				sizeof (psinfo.pr_psargs));
9049     }
9050 #endif
9051 
9052   else
9053     {
9054       /* Fail - we don't know how to handle any other
9055 	 note size (ie. data object type).  */
9056       return TRUE;
9057     }
9058 
9059   /* Note that for some reason, a spurious space is tacked
9060      onto the end of the args in some (at least one anyway)
9061      implementations, so strip it off if it exists.  */
9062 
9063   {
9064     char *command = elf_tdata (abfd)->core->command;
9065     int n = strlen (command);
9066 
9067     if (0 < n && command[n - 1] == ' ')
9068       command[n - 1] = '\0';
9069   }
9070 
9071   return TRUE;
9072 }
9073 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
9074 
9075 #if defined (HAVE_PSTATUS_T)
9076 static bfd_boolean
9077 elfcore_grok_pstatus (bfd *abfd, Elf_Internal_Note *note)
9078 {
9079   if (note->descsz == sizeof (pstatus_t)
9080 #if defined (HAVE_PXSTATUS_T)
9081       || note->descsz == sizeof (pxstatus_t)
9082 #endif
9083       )
9084     {
9085       pstatus_t pstat;
9086 
9087       memcpy (&pstat, note->descdata, sizeof (pstat));
9088 
9089       elf_tdata (abfd)->core->pid = pstat.pr_pid;
9090     }
9091 #if defined (HAVE_PSTATUS32_T)
9092   else if (note->descsz == sizeof (pstatus32_t))
9093     {
9094       /* 64-bit host, 32-bit corefile */
9095       pstatus32_t pstat;
9096 
9097       memcpy (&pstat, note->descdata, sizeof (pstat));
9098 
9099       elf_tdata (abfd)->core->pid = pstat.pr_pid;
9100     }
9101 #endif
9102   /* Could grab some more details from the "representative"
9103      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
9104      NT_LWPSTATUS note, presumably.  */
9105 
9106   return TRUE;
9107 }
9108 #endif /* defined (HAVE_PSTATUS_T) */
9109 
9110 #if defined (HAVE_LWPSTATUS_T)
9111 static bfd_boolean
9112 elfcore_grok_lwpstatus (bfd *abfd, Elf_Internal_Note *note)
9113 {
9114   lwpstatus_t lwpstat;
9115   char buf[100];
9116   char *name;
9117   size_t len;
9118   asection *sect;
9119 
9120   if (note->descsz != sizeof (lwpstat)
9121 #if defined (HAVE_LWPXSTATUS_T)
9122       && note->descsz != sizeof (lwpxstatus_t)
9123 #endif
9124       )
9125     return TRUE;
9126 
9127   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
9128 
9129   elf_tdata (abfd)->core->lwpid = lwpstat.pr_lwpid;
9130   /* Do not overwrite the core signal if it has already been set by
9131      another thread.  */
9132   if (elf_tdata (abfd)->core->signal == 0)
9133     elf_tdata (abfd)->core->signal = lwpstat.pr_cursig;
9134 
9135   /* Make a ".reg/999" section.  */
9136 
9137   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
9138   len = strlen (buf) + 1;
9139   name = bfd_alloc (abfd, len);
9140   if (name == NULL)
9141     return FALSE;
9142   memcpy (name, buf, len);
9143 
9144   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9145   if (sect == NULL)
9146     return FALSE;
9147 
9148 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
9149   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
9150   sect->filepos = note->descpos
9151     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
9152 #endif
9153 
9154 #if defined (HAVE_LWPSTATUS_T_PR_REG)
9155   sect->size = sizeof (lwpstat.pr_reg);
9156   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
9157 #endif
9158 
9159   sect->alignment_power = 2;
9160 
9161   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
9162     return FALSE;
9163 
9164   /* Make a ".reg2/999" section */
9165 
9166   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
9167   len = strlen (buf) + 1;
9168   name = bfd_alloc (abfd, len);
9169   if (name == NULL)
9170     return FALSE;
9171   memcpy (name, buf, len);
9172 
9173   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9174   if (sect == NULL)
9175     return FALSE;
9176 
9177 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
9178   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
9179   sect->filepos = note->descpos
9180     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
9181 #endif
9182 
9183 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
9184   sect->size = sizeof (lwpstat.pr_fpreg);
9185   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
9186 #endif
9187 
9188   sect->alignment_power = 2;
9189 
9190   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
9191 }
9192 #endif /* defined (HAVE_LWPSTATUS_T) */
9193 
9194 static bfd_boolean
9195 elfcore_grok_win32pstatus (bfd *abfd, Elf_Internal_Note *note)
9196 {
9197   char buf[30];
9198   char *name;
9199   size_t len;
9200   asection *sect;
9201   int type;
9202   int is_active_thread;
9203   bfd_vma base_addr;
9204 
9205   if (note->descsz < 728)
9206     return TRUE;
9207 
9208   if (! CONST_STRNEQ (note->namedata, "win32"))
9209     return TRUE;
9210 
9211   type = bfd_get_32 (abfd, note->descdata);
9212 
9213   switch (type)
9214     {
9215     case 1 /* NOTE_INFO_PROCESS */:
9216       /* FIXME: need to add ->core->command.  */
9217       /* process_info.pid */
9218       elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, note->descdata + 8);
9219       /* process_info.signal */
9220       elf_tdata (abfd)->core->signal = bfd_get_32 (abfd, note->descdata + 12);
9221       break;
9222 
9223     case 2 /* NOTE_INFO_THREAD */:
9224       /* Make a ".reg/999" section.  */
9225       /* thread_info.tid */
9226       sprintf (buf, ".reg/%ld", (long) bfd_get_32 (abfd, note->descdata + 8));
9227 
9228       len = strlen (buf) + 1;
9229       name = (char *) bfd_alloc (abfd, len);
9230       if (name == NULL)
9231 	return FALSE;
9232 
9233       memcpy (name, buf, len);
9234 
9235       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9236       if (sect == NULL)
9237 	return FALSE;
9238 
9239       /* sizeof (thread_info.thread_context) */
9240       sect->size = 716;
9241       /* offsetof (thread_info.thread_context) */
9242       sect->filepos = note->descpos + 12;
9243       sect->alignment_power = 2;
9244 
9245       /* thread_info.is_active_thread */
9246       is_active_thread = bfd_get_32 (abfd, note->descdata + 8);
9247 
9248       if (is_active_thread)
9249 	if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
9250 	  return FALSE;
9251       break;
9252 
9253     case 3 /* NOTE_INFO_MODULE */:
9254       /* Make a ".module/xxxxxxxx" section.  */
9255       /* module_info.base_address */
9256       base_addr = bfd_get_32 (abfd, note->descdata + 4);
9257       sprintf (buf, ".module/%08lx", (unsigned long) base_addr);
9258 
9259       len = strlen (buf) + 1;
9260       name = (char *) bfd_alloc (abfd, len);
9261       if (name == NULL)
9262 	return FALSE;
9263 
9264       memcpy (name, buf, len);
9265 
9266       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9267 
9268       if (sect == NULL)
9269 	return FALSE;
9270 
9271       sect->size = note->descsz;
9272       sect->filepos = note->descpos;
9273       sect->alignment_power = 2;
9274       break;
9275 
9276     default:
9277       return TRUE;
9278     }
9279 
9280   return TRUE;
9281 }
9282 
9283 static bfd_boolean
9284 elfcore_grok_note (bfd *abfd, Elf_Internal_Note *note)
9285 {
9286   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9287 
9288   switch (note->type)
9289     {
9290     default:
9291       return TRUE;
9292 
9293     case NT_PRSTATUS:
9294       if (bed->elf_backend_grok_prstatus)
9295 	if ((*bed->elf_backend_grok_prstatus) (abfd, note))
9296 	  return TRUE;
9297 #if defined (HAVE_PRSTATUS_T)
9298       return elfcore_grok_prstatus (abfd, note);
9299 #else
9300       return TRUE;
9301 #endif
9302 
9303 #if defined (HAVE_PSTATUS_T)
9304     case NT_PSTATUS:
9305       return elfcore_grok_pstatus (abfd, note);
9306 #endif
9307 
9308 #if defined (HAVE_LWPSTATUS_T)
9309     case NT_LWPSTATUS:
9310       return elfcore_grok_lwpstatus (abfd, note);
9311 #endif
9312 
9313     case NT_FPREGSET:		/* FIXME: rename to NT_PRFPREG */
9314       return elfcore_grok_prfpreg (abfd, note);
9315 
9316     case NT_WIN32PSTATUS:
9317       return elfcore_grok_win32pstatus (abfd, note);
9318 
9319     case NT_PRXFPREG:		/* Linux SSE extension */
9320       if (note->namesz == 6
9321 	  && strcmp (note->namedata, "LINUX") == 0)
9322 	return elfcore_grok_prxfpreg (abfd, note);
9323       else
9324 	return TRUE;
9325 
9326     case NT_X86_XSTATE:		/* Linux XSAVE extension */
9327       if (note->namesz == 6
9328 	  && strcmp (note->namedata, "LINUX") == 0)
9329 	return elfcore_grok_xstatereg (abfd, note);
9330       else
9331 	return TRUE;
9332 
9333     case NT_PPC_VMX:
9334       if (note->namesz == 6
9335 	  && strcmp (note->namedata, "LINUX") == 0)
9336 	return elfcore_grok_ppc_vmx (abfd, note);
9337       else
9338 	return TRUE;
9339 
9340     case NT_PPC_VSX:
9341       if (note->namesz == 6
9342           && strcmp (note->namedata, "LINUX") == 0)
9343         return elfcore_grok_ppc_vsx (abfd, note);
9344       else
9345         return TRUE;
9346 
9347     case NT_S390_HIGH_GPRS:
9348       if (note->namesz == 6
9349           && strcmp (note->namedata, "LINUX") == 0)
9350         return elfcore_grok_s390_high_gprs (abfd, note);
9351       else
9352         return TRUE;
9353 
9354     case NT_S390_TIMER:
9355       if (note->namesz == 6
9356           && strcmp (note->namedata, "LINUX") == 0)
9357         return elfcore_grok_s390_timer (abfd, note);
9358       else
9359         return TRUE;
9360 
9361     case NT_S390_TODCMP:
9362       if (note->namesz == 6
9363           && strcmp (note->namedata, "LINUX") == 0)
9364         return elfcore_grok_s390_todcmp (abfd, note);
9365       else
9366         return TRUE;
9367 
9368     case NT_S390_TODPREG:
9369       if (note->namesz == 6
9370           && strcmp (note->namedata, "LINUX") == 0)
9371         return elfcore_grok_s390_todpreg (abfd, note);
9372       else
9373         return TRUE;
9374 
9375     case NT_S390_CTRS:
9376       if (note->namesz == 6
9377           && strcmp (note->namedata, "LINUX") == 0)
9378         return elfcore_grok_s390_ctrs (abfd, note);
9379       else
9380         return TRUE;
9381 
9382     case NT_S390_PREFIX:
9383       if (note->namesz == 6
9384           && strcmp (note->namedata, "LINUX") == 0)
9385         return elfcore_grok_s390_prefix (abfd, note);
9386       else
9387         return TRUE;
9388 
9389     case NT_S390_LAST_BREAK:
9390       if (note->namesz == 6
9391           && strcmp (note->namedata, "LINUX") == 0)
9392         return elfcore_grok_s390_last_break (abfd, note);
9393       else
9394         return TRUE;
9395 
9396     case NT_S390_SYSTEM_CALL:
9397       if (note->namesz == 6
9398           && strcmp (note->namedata, "LINUX") == 0)
9399         return elfcore_grok_s390_system_call (abfd, note);
9400       else
9401         return TRUE;
9402 
9403     case NT_S390_TDB:
9404       if (note->namesz == 6
9405           && strcmp (note->namedata, "LINUX") == 0)
9406         return elfcore_grok_s390_tdb (abfd, note);
9407       else
9408         return TRUE;
9409 
9410     case NT_S390_VXRS_LOW:
9411       if (note->namesz == 6
9412 	  && strcmp (note->namedata, "LINUX") == 0)
9413 	return elfcore_grok_s390_vxrs_low (abfd, note);
9414       else
9415 	return TRUE;
9416 
9417     case NT_S390_VXRS_HIGH:
9418       if (note->namesz == 6
9419 	  && strcmp (note->namedata, "LINUX") == 0)
9420 	return elfcore_grok_s390_vxrs_high (abfd, note);
9421       else
9422 	return TRUE;
9423 
9424     case NT_ARM_VFP:
9425       if (note->namesz == 6
9426 	  && strcmp (note->namedata, "LINUX") == 0)
9427 	return elfcore_grok_arm_vfp (abfd, note);
9428       else
9429 	return TRUE;
9430 
9431     case NT_ARM_TLS:
9432       if (note->namesz == 6
9433 	  && strcmp (note->namedata, "LINUX") == 0)
9434 	return elfcore_grok_aarch_tls (abfd, note);
9435       else
9436 	return TRUE;
9437 
9438     case NT_ARM_HW_BREAK:
9439       if (note->namesz == 6
9440 	  && strcmp (note->namedata, "LINUX") == 0)
9441 	return elfcore_grok_aarch_hw_break (abfd, note);
9442       else
9443 	return TRUE;
9444 
9445     case NT_ARM_HW_WATCH:
9446       if (note->namesz == 6
9447 	  && strcmp (note->namedata, "LINUX") == 0)
9448 	return elfcore_grok_aarch_hw_watch (abfd, note);
9449       else
9450 	return TRUE;
9451 
9452     case NT_PRPSINFO:
9453     case NT_PSINFO:
9454       if (bed->elf_backend_grok_psinfo)
9455 	if ((*bed->elf_backend_grok_psinfo) (abfd, note))
9456 	  return TRUE;
9457 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
9458       return elfcore_grok_psinfo (abfd, note);
9459 #else
9460       return TRUE;
9461 #endif
9462 
9463     case NT_AUXV:
9464       {
9465 	asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
9466 							     SEC_HAS_CONTENTS);
9467 
9468 	if (sect == NULL)
9469 	  return FALSE;
9470 	sect->size = note->descsz;
9471 	sect->filepos = note->descpos;
9472 	sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
9473 
9474 	return TRUE;
9475       }
9476 
9477     case NT_FILE:
9478       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.file",
9479 					      note);
9480 
9481     case NT_SIGINFO:
9482       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.siginfo",
9483 					      note);
9484 
9485     }
9486 }
9487 
9488 static bfd_boolean
9489 elfobj_grok_gnu_build_id (bfd *abfd, Elf_Internal_Note *note)
9490 {
9491   struct bfd_build_id* build_id;
9492 
9493   if (note->descsz == 0)
9494     return FALSE;
9495 
9496   build_id = bfd_alloc (abfd, sizeof (struct bfd_build_id) - 1 + note->descsz);
9497   if (build_id == NULL)
9498     return FALSE;
9499 
9500   build_id->size = note->descsz;
9501   memcpy (build_id->data, note->descdata, note->descsz);
9502   abfd->build_id = build_id;
9503 
9504   return TRUE;
9505 }
9506 
9507 static bfd_boolean
9508 elfobj_grok_gnu_note (bfd *abfd, Elf_Internal_Note *note)
9509 {
9510   switch (note->type)
9511     {
9512     default:
9513       return TRUE;
9514 
9515     case NT_GNU_BUILD_ID:
9516       return elfobj_grok_gnu_build_id (abfd, note);
9517     }
9518 }
9519 
9520 static bfd_boolean
9521 elfobj_grok_stapsdt_note_1 (bfd *abfd, Elf_Internal_Note *note)
9522 {
9523   struct sdt_note *cur =
9524     (struct sdt_note *) bfd_alloc (abfd, sizeof (struct sdt_note)
9525 				   + note->descsz);
9526 
9527   cur->next = (struct sdt_note *) (elf_tdata (abfd))->sdt_note_head;
9528   cur->size = (bfd_size_type) note->descsz;
9529   memcpy (cur->data, note->descdata, note->descsz);
9530 
9531   elf_tdata (abfd)->sdt_note_head = cur;
9532 
9533   return TRUE;
9534 }
9535 
9536 static bfd_boolean
9537 elfobj_grok_stapsdt_note (bfd *abfd, Elf_Internal_Note *note)
9538 {
9539   switch (note->type)
9540     {
9541     case NT_STAPSDT:
9542       return elfobj_grok_stapsdt_note_1 (abfd, note);
9543 
9544     default:
9545       return TRUE;
9546     }
9547 }
9548 
9549 static bfd_boolean
9550 elfcore_grok_freebsd_psinfo (bfd *abfd, Elf_Internal_Note *note)
9551 {
9552   size_t offset;
9553 
9554   /* Check for version 1 in pr_version. */
9555   if (bfd_h_get_32 (abfd, (bfd_byte *) note->descdata) != 1)
9556     return FALSE;
9557   offset = 4;
9558 
9559   /* Skip over pr_psinfosz. */
9560   switch (abfd->arch_info->bits_per_word)
9561     {
9562     case 32:
9563       offset += 4;
9564       break;
9565 
9566     case 64:
9567       offset += 4;	/* Padding before pr_psinfosz. */
9568       offset += 8;
9569       break;
9570 
9571     default:
9572       return FALSE;
9573     }
9574 
9575   /* pr_fname is PRFNAMESZ (16) + 1 bytes in size.  */
9576   elf_tdata (abfd)->core->program
9577     = _bfd_elfcore_strndup (abfd, note->descdata + offset, 17);
9578   offset += 17;
9579 
9580   /* pr_psargs is PRARGSZ (80) + 1 bytes in size.  */
9581   elf_tdata (abfd)->core->command
9582     = _bfd_elfcore_strndup (abfd, note->descdata + offset, 81);
9583 
9584   return TRUE;
9585 }
9586 
9587 static bfd_boolean
9588 elfcore_grok_freebsd_prstatus (bfd *abfd, Elf_Internal_Note *note)
9589 {
9590   size_t offset;
9591   size_t size;
9592 
9593   /* Check for version 1 in pr_version. */
9594   if (bfd_h_get_32 (abfd, (bfd_byte *) note->descdata) != 1)
9595     return FALSE;
9596   offset = 4;
9597 
9598   /* Skip over pr_statussz.  */
9599   switch (abfd->arch_info->bits_per_word)
9600     {
9601     case 32:
9602       offset += 4;
9603       break;
9604 
9605     case 64:
9606       offset += 4;	/* Padding before pr_statussz. */
9607       offset += 8;
9608       break;
9609 
9610     default:
9611       return FALSE;
9612     }
9613 
9614   /* Extract size of pr_reg from pr_gregsetsz.  */
9615   if (abfd->arch_info->bits_per_word == 32)
9616     size = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
9617   else
9618     size = bfd_h_get_64 (abfd, (bfd_byte *) note->descdata + offset);
9619 
9620   /* Skip over pr_gregsetsz and pr_fpregsetsz. */
9621   offset += (abfd->arch_info->bits_per_word / 8) * 2;
9622 
9623   /* Skip over pr_osreldate. */
9624   offset += 4;
9625 
9626   /* Read signal from pr_cursig. */
9627   if (elf_tdata (abfd)->core->signal == 0)
9628     elf_tdata (abfd)->core->signal
9629       = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
9630   offset += 4;
9631 
9632   /* Read TID from pr_pid. */
9633   elf_tdata (abfd)->core->lwpid
9634       = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
9635   offset += 4;
9636 
9637   /* Padding before pr_reg. */
9638   if (abfd->arch_info->bits_per_word == 64)
9639     offset += 4;
9640 
9641   /* Make a ".reg/999" section and a ".reg" section.  */
9642   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
9643 					  size, note->descpos + offset);
9644 }
9645 
9646 static bfd_boolean
9647 elfcore_grok_freebsd_note (bfd *abfd, Elf_Internal_Note *note)
9648 {
9649   switch (note->type)
9650     {
9651     case NT_PRSTATUS:
9652       return elfcore_grok_freebsd_prstatus (abfd, note);
9653 
9654     case NT_FPREGSET:
9655       return elfcore_grok_prfpreg (abfd, note);
9656 
9657     case NT_PRPSINFO:
9658       return elfcore_grok_freebsd_psinfo (abfd, note);
9659 
9660     case NT_FREEBSD_THRMISC:
9661       if (note->namesz == 8)
9662 	return elfcore_make_note_pseudosection (abfd, ".thrmisc", note);
9663       else
9664 	return TRUE;
9665 
9666     case NT_FREEBSD_PROCSTAT_AUXV:
9667       {
9668 	asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
9669 							     SEC_HAS_CONTENTS);
9670 
9671 	if (sect == NULL)
9672 	  return FALSE;
9673 	sect->size = note->descsz - 4;
9674 	sect->filepos = note->descpos + 4;
9675 	sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
9676 
9677 	return TRUE;
9678       }
9679 
9680     case NT_X86_XSTATE:
9681       if (note->namesz == 8)
9682 	return elfcore_grok_xstatereg (abfd, note);
9683       else
9684 	return TRUE;
9685 
9686     default:
9687       return TRUE;
9688     }
9689 }
9690 
9691 static bfd_boolean
9692 elfcore_netbsd_get_lwpid (Elf_Internal_Note *note, int *lwpidp)
9693 {
9694   char *cp;
9695 
9696   cp = strchr (note->namedata, '@');
9697   if (cp != NULL)
9698     {
9699       *lwpidp = atoi(cp + 1);
9700       return TRUE;
9701     }
9702   return FALSE;
9703 }
9704 
9705 static bfd_boolean
9706 elfcore_grok_netbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
9707 {
9708   /* Signal number at offset 0x08. */
9709   elf_tdata (abfd)->core->signal
9710     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
9711 
9712   /* Process ID at offset 0x50. */
9713   elf_tdata (abfd)->core->pid
9714     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
9715 
9716   /* Command name at 0x7c (max 32 bytes, including nul). */
9717   elf_tdata (abfd)->core->command
9718     = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
9719 
9720   return elfcore_make_note_pseudosection (abfd, ".note.netbsdcore.procinfo",
9721 					  note);
9722 }
9723 
9724 static bfd_boolean
9725 elfcore_grok_netbsd_note (bfd *abfd, Elf_Internal_Note *note)
9726 {
9727   int lwp;
9728 
9729   if (elfcore_netbsd_get_lwpid (note, &lwp))
9730     elf_tdata (abfd)->core->lwpid = lwp;
9731 
9732   if (note->type == NT_NETBSDCORE_PROCINFO)
9733     {
9734       /* NetBSD-specific core "procinfo".  Note that we expect to
9735 	 find this note before any of the others, which is fine,
9736 	 since the kernel writes this note out first when it
9737 	 creates a core file.  */
9738 
9739       return elfcore_grok_netbsd_procinfo (abfd, note);
9740     }
9741 
9742   /* As of Jan 2002 there are no other machine-independent notes
9743      defined for NetBSD core files.  If the note type is less
9744      than the start of the machine-dependent note types, we don't
9745      understand it.  */
9746 
9747   if (note->type < NT_NETBSDCORE_FIRSTMACH)
9748     return TRUE;
9749 
9750 
9751   switch (bfd_get_arch (abfd))
9752     {
9753       /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
9754 	 PT_GETFPREGS == mach+2.  */
9755 
9756     case bfd_arch_alpha:
9757     case bfd_arch_sparc:
9758       switch (note->type)
9759 	{
9760 	case NT_NETBSDCORE_FIRSTMACH+0:
9761 	  return elfcore_make_note_pseudosection (abfd, ".reg", note);
9762 
9763 	case NT_NETBSDCORE_FIRSTMACH+2:
9764 	  return elfcore_make_note_pseudosection (abfd, ".reg2", note);
9765 
9766 	default:
9767 	  return TRUE;
9768 	}
9769 
9770       /* On all other arch's, PT_GETREGS == mach+1 and
9771 	 PT_GETFPREGS == mach+3.  */
9772 
9773     default:
9774       switch (note->type)
9775 	{
9776 	case NT_NETBSDCORE_FIRSTMACH+1:
9777 	  return elfcore_make_note_pseudosection (abfd, ".reg", note);
9778 
9779 	case NT_NETBSDCORE_FIRSTMACH+3:
9780 	  return elfcore_make_note_pseudosection (abfd, ".reg2", note);
9781 
9782 	default:
9783 	  return TRUE;
9784 	}
9785     }
9786     /* NOTREACHED */
9787 }
9788 
9789 static bfd_boolean
9790 elfcore_grok_openbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
9791 {
9792   /* Signal number at offset 0x08. */
9793   elf_tdata (abfd)->core->signal
9794     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
9795 
9796   /* Process ID at offset 0x20. */
9797   elf_tdata (abfd)->core->pid
9798     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x20);
9799 
9800   /* Command name at 0x48 (max 32 bytes, including nul). */
9801   elf_tdata (abfd)->core->command
9802     = _bfd_elfcore_strndup (abfd, note->descdata + 0x48, 31);
9803 
9804   return TRUE;
9805 }
9806 
9807 static bfd_boolean
9808 elfcore_grok_openbsd_note (bfd *abfd, Elf_Internal_Note *note)
9809 {
9810   if (note->type == NT_OPENBSD_PROCINFO)
9811     return elfcore_grok_openbsd_procinfo (abfd, note);
9812 
9813   if (note->type == NT_OPENBSD_REGS)
9814     return elfcore_make_note_pseudosection (abfd, ".reg", note);
9815 
9816   if (note->type == NT_OPENBSD_FPREGS)
9817     return elfcore_make_note_pseudosection (abfd, ".reg2", note);
9818 
9819   if (note->type == NT_OPENBSD_XFPREGS)
9820     return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
9821 
9822   if (note->type == NT_OPENBSD_AUXV)
9823     {
9824       asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
9825 							   SEC_HAS_CONTENTS);
9826 
9827       if (sect == NULL)
9828 	return FALSE;
9829       sect->size = note->descsz;
9830       sect->filepos = note->descpos;
9831       sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
9832 
9833       return TRUE;
9834     }
9835 
9836   if (note->type == NT_OPENBSD_WCOOKIE)
9837     {
9838       asection *sect = bfd_make_section_anyway_with_flags (abfd, ".wcookie",
9839 							   SEC_HAS_CONTENTS);
9840 
9841       if (sect == NULL)
9842 	return FALSE;
9843       sect->size = note->descsz;
9844       sect->filepos = note->descpos;
9845       sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
9846 
9847       return TRUE;
9848     }
9849 
9850   return TRUE;
9851 }
9852 
9853 static bfd_boolean
9854 elfcore_grok_nto_status (bfd *abfd, Elf_Internal_Note *note, long *tid)
9855 {
9856   void *ddata = note->descdata;
9857   char buf[100];
9858   char *name;
9859   asection *sect;
9860   short sig;
9861   unsigned flags;
9862 
9863   /* nto_procfs_status 'pid' field is at offset 0.  */
9864   elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, (bfd_byte *) ddata);
9865 
9866   /* nto_procfs_status 'tid' field is at offset 4.  Pass it back.  */
9867   *tid = bfd_get_32 (abfd, (bfd_byte *) ddata + 4);
9868 
9869   /* nto_procfs_status 'flags' field is at offset 8.  */
9870   flags = bfd_get_32 (abfd, (bfd_byte *) ddata + 8);
9871 
9872   /* nto_procfs_status 'what' field is at offset 14.  */
9873   if ((sig = bfd_get_16 (abfd, (bfd_byte *) ddata + 14)) > 0)
9874     {
9875       elf_tdata (abfd)->core->signal = sig;
9876       elf_tdata (abfd)->core->lwpid = *tid;
9877     }
9878 
9879   /* _DEBUG_FLAG_CURTID (current thread) is 0x80.  Some cores
9880      do not come from signals so we make sure we set the current
9881      thread just in case.  */
9882   if (flags & 0x00000080)
9883     elf_tdata (abfd)->core->lwpid = *tid;
9884 
9885   /* Make a ".qnx_core_status/%d" section.  */
9886   sprintf (buf, ".qnx_core_status/%ld", *tid);
9887 
9888   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
9889   if (name == NULL)
9890     return FALSE;
9891   strcpy (name, buf);
9892 
9893   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9894   if (sect == NULL)
9895     return FALSE;
9896 
9897   sect->size            = note->descsz;
9898   sect->filepos         = note->descpos;
9899   sect->alignment_power = 2;
9900 
9901   return (elfcore_maybe_make_sect (abfd, ".qnx_core_status", sect));
9902 }
9903 
9904 static bfd_boolean
9905 elfcore_grok_nto_regs (bfd *abfd,
9906 		       Elf_Internal_Note *note,
9907 		       long tid,
9908 		       char *base)
9909 {
9910   char buf[100];
9911   char *name;
9912   asection *sect;
9913 
9914   /* Make a "(base)/%d" section.  */
9915   sprintf (buf, "%s/%ld", base, tid);
9916 
9917   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
9918   if (name == NULL)
9919     return FALSE;
9920   strcpy (name, buf);
9921 
9922   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9923   if (sect == NULL)
9924     return FALSE;
9925 
9926   sect->size            = note->descsz;
9927   sect->filepos         = note->descpos;
9928   sect->alignment_power = 2;
9929 
9930   /* This is the current thread.  */
9931   if (elf_tdata (abfd)->core->lwpid == tid)
9932     return elfcore_maybe_make_sect (abfd, base, sect);
9933 
9934   return TRUE;
9935 }
9936 
9937 #define BFD_QNT_CORE_INFO	7
9938 #define BFD_QNT_CORE_STATUS	8
9939 #define BFD_QNT_CORE_GREG	9
9940 #define BFD_QNT_CORE_FPREG	10
9941 
9942 static bfd_boolean
9943 elfcore_grok_nto_note (bfd *abfd, Elf_Internal_Note *note)
9944 {
9945   /* Every GREG section has a STATUS section before it.  Store the
9946      tid from the previous call to pass down to the next gregs
9947      function.  */
9948   static long tid = 1;
9949 
9950   switch (note->type)
9951     {
9952     case BFD_QNT_CORE_INFO:
9953       return elfcore_make_note_pseudosection (abfd, ".qnx_core_info", note);
9954     case BFD_QNT_CORE_STATUS:
9955       return elfcore_grok_nto_status (abfd, note, &tid);
9956     case BFD_QNT_CORE_GREG:
9957       return elfcore_grok_nto_regs (abfd, note, tid, ".reg");
9958     case BFD_QNT_CORE_FPREG:
9959       return elfcore_grok_nto_regs (abfd, note, tid, ".reg2");
9960     default:
9961       return TRUE;
9962     }
9963 }
9964 
9965 static bfd_boolean
9966 elfcore_grok_spu_note (bfd *abfd, Elf_Internal_Note *note)
9967 {
9968   char *name;
9969   asection *sect;
9970   size_t len;
9971 
9972   /* Use note name as section name.  */
9973   len = note->namesz;
9974   name = (char *) bfd_alloc (abfd, len);
9975   if (name == NULL)
9976     return FALSE;
9977   memcpy (name, note->namedata, len);
9978   name[len - 1] = '\0';
9979 
9980   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9981   if (sect == NULL)
9982     return FALSE;
9983 
9984   sect->size            = note->descsz;
9985   sect->filepos         = note->descpos;
9986   sect->alignment_power = 1;
9987 
9988   return TRUE;
9989 }
9990 
9991 /* Function: elfcore_write_note
9992 
9993    Inputs:
9994      buffer to hold note, and current size of buffer
9995      name of note
9996      type of note
9997      data for note
9998      size of data for note
9999 
10000    Writes note to end of buffer.  ELF64 notes are written exactly as
10001    for ELF32, despite the current (as of 2006) ELF gabi specifying
10002    that they ought to have 8-byte namesz and descsz field, and have
10003    8-byte alignment.  Other writers, eg. Linux kernel, do the same.
10004 
10005    Return:
10006    Pointer to realloc'd buffer, *BUFSIZ updated.  */
10007 
10008 char *
10009 elfcore_write_note (bfd *abfd,
10010 		    char *buf,
10011 		    int *bufsiz,
10012 		    const char *name,
10013 		    int type,
10014 		    const void *input,
10015 		    int size)
10016 {
10017   Elf_External_Note *xnp;
10018   size_t namesz;
10019   size_t newspace;
10020   char *dest;
10021 
10022   namesz = 0;
10023   if (name != NULL)
10024     namesz = strlen (name) + 1;
10025 
10026   newspace = 12 + ((namesz + 3) & -4) + ((size + 3) & -4);
10027 
10028   buf = (char *) realloc (buf, *bufsiz + newspace);
10029   if (buf == NULL)
10030     return buf;
10031   dest = buf + *bufsiz;
10032   *bufsiz += newspace;
10033   xnp = (Elf_External_Note *) dest;
10034   H_PUT_32 (abfd, namesz, xnp->namesz);
10035   H_PUT_32 (abfd, size, xnp->descsz);
10036   H_PUT_32 (abfd, type, xnp->type);
10037   dest = xnp->name;
10038   if (name != NULL)
10039     {
10040       memcpy (dest, name, namesz);
10041       dest += namesz;
10042       while (namesz & 3)
10043 	{
10044 	  *dest++ = '\0';
10045 	  ++namesz;
10046 	}
10047     }
10048   memcpy (dest, input, size);
10049   dest += size;
10050   while (size & 3)
10051     {
10052       *dest++ = '\0';
10053       ++size;
10054     }
10055   return buf;
10056 }
10057 
10058 char *
10059 elfcore_write_prpsinfo (bfd  *abfd,
10060 			char *buf,
10061 			int  *bufsiz,
10062 			const char *fname,
10063 			const char *psargs)
10064 {
10065   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10066 
10067   if (bed->elf_backend_write_core_note != NULL)
10068     {
10069       char *ret;
10070       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
10071 						 NT_PRPSINFO, fname, psargs);
10072       if (ret != NULL)
10073 	return ret;
10074     }
10075 
10076 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
10077 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
10078   if (bed->s->elfclass == ELFCLASS32)
10079     {
10080 #if defined (HAVE_PSINFO32_T)
10081       psinfo32_t data;
10082       int note_type = NT_PSINFO;
10083 #else
10084       prpsinfo32_t data;
10085       int note_type = NT_PRPSINFO;
10086 #endif
10087 
10088       memset (&data, 0, sizeof (data));
10089       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
10090       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
10091       return elfcore_write_note (abfd, buf, bufsiz,
10092 				 "CORE", note_type, &data, sizeof (data));
10093     }
10094   else
10095 #endif
10096     {
10097 #if defined (HAVE_PSINFO_T)
10098       psinfo_t data;
10099       int note_type = NT_PSINFO;
10100 #else
10101       prpsinfo_t data;
10102       int note_type = NT_PRPSINFO;
10103 #endif
10104 
10105       memset (&data, 0, sizeof (data));
10106       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
10107       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
10108       return elfcore_write_note (abfd, buf, bufsiz,
10109 				 "CORE", note_type, &data, sizeof (data));
10110     }
10111 #endif	/* PSINFO_T or PRPSINFO_T */
10112 
10113   free (buf);
10114   return NULL;
10115 }
10116 
10117 char *
10118 elfcore_write_linux_prpsinfo32
10119   (bfd *abfd, char *buf, int *bufsiz,
10120    const struct elf_internal_linux_prpsinfo *prpsinfo)
10121 {
10122   struct elf_external_linux_prpsinfo32 data;
10123 
10124   swap_linux_prpsinfo32_out (abfd, prpsinfo, &data);
10125   return elfcore_write_note (abfd, buf, bufsiz, "CORE", NT_PRPSINFO,
10126 			     &data, sizeof (data));
10127 }
10128 
10129 char *
10130 elfcore_write_linux_prpsinfo64
10131   (bfd *abfd, char *buf, int *bufsiz,
10132    const struct elf_internal_linux_prpsinfo *prpsinfo)
10133 {
10134   struct elf_external_linux_prpsinfo64 data;
10135 
10136   swap_linux_prpsinfo64_out (abfd, prpsinfo, &data);
10137   return elfcore_write_note (abfd, buf, bufsiz,
10138 			     "CORE", NT_PRPSINFO, &data, sizeof (data));
10139 }
10140 
10141 char *
10142 elfcore_write_prstatus (bfd *abfd,
10143 			char *buf,
10144 			int *bufsiz,
10145 			long pid,
10146 			int cursig,
10147 			const void *gregs)
10148 {
10149   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10150 
10151   if (bed->elf_backend_write_core_note != NULL)
10152     {
10153       char *ret;
10154       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
10155 						 NT_PRSTATUS,
10156 						 pid, cursig, gregs);
10157       if (ret != NULL)
10158 	return ret;
10159     }
10160 
10161 #if defined (HAVE_PRSTATUS_T)
10162 #if defined (HAVE_PRSTATUS32_T)
10163   if (bed->s->elfclass == ELFCLASS32)
10164     {
10165       prstatus32_t prstat;
10166 
10167       memset (&prstat, 0, sizeof (prstat));
10168       prstat.pr_pid = pid;
10169       prstat.pr_cursig = cursig;
10170       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
10171       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
10172 				 NT_PRSTATUS, &prstat, sizeof (prstat));
10173     }
10174   else
10175 #endif
10176     {
10177       prstatus_t prstat;
10178 
10179       memset (&prstat, 0, sizeof (prstat));
10180       prstat.pr_pid = pid;
10181       prstat.pr_cursig = cursig;
10182       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
10183       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
10184 				 NT_PRSTATUS, &prstat, sizeof (prstat));
10185     }
10186 #endif /* HAVE_PRSTATUS_T */
10187 
10188   free (buf);
10189   return NULL;
10190 }
10191 
10192 #if defined (HAVE_LWPSTATUS_T)
10193 char *
10194 elfcore_write_lwpstatus (bfd *abfd,
10195 			 char *buf,
10196 			 int *bufsiz,
10197 			 long pid,
10198 			 int cursig,
10199 			 const void *gregs)
10200 {
10201   lwpstatus_t lwpstat;
10202   const char *note_name = "CORE";
10203 
10204   memset (&lwpstat, 0, sizeof (lwpstat));
10205   lwpstat.pr_lwpid  = pid >> 16;
10206   lwpstat.pr_cursig = cursig;
10207 #if defined (HAVE_LWPSTATUS_T_PR_REG)
10208   memcpy (&lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
10209 #elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
10210 #if !defined(gregs)
10211   memcpy (lwpstat.pr_context.uc_mcontext.gregs,
10212 	  gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
10213 #else
10214   memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
10215 	  gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
10216 #endif
10217 #endif
10218   return elfcore_write_note (abfd, buf, bufsiz, note_name,
10219 			     NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
10220 }
10221 #endif /* HAVE_LWPSTATUS_T */
10222 
10223 #if defined (HAVE_PSTATUS_T)
10224 char *
10225 elfcore_write_pstatus (bfd *abfd,
10226 		       char *buf,
10227 		       int *bufsiz,
10228 		       long pid,
10229 		       int cursig ATTRIBUTE_UNUSED,
10230 		       const void *gregs ATTRIBUTE_UNUSED)
10231 {
10232   const char *note_name = "CORE";
10233 #if defined (HAVE_PSTATUS32_T)
10234   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10235 
10236   if (bed->s->elfclass == ELFCLASS32)
10237     {
10238       pstatus32_t pstat;
10239 
10240       memset (&pstat, 0, sizeof (pstat));
10241       pstat.pr_pid = pid & 0xffff;
10242       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
10243 				NT_PSTATUS, &pstat, sizeof (pstat));
10244       return buf;
10245     }
10246   else
10247 #endif
10248     {
10249       pstatus_t pstat;
10250 
10251       memset (&pstat, 0, sizeof (pstat));
10252       pstat.pr_pid = pid & 0xffff;
10253       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
10254 				NT_PSTATUS, &pstat, sizeof (pstat));
10255       return buf;
10256     }
10257 }
10258 #endif /* HAVE_PSTATUS_T */
10259 
10260 char *
10261 elfcore_write_prfpreg (bfd *abfd,
10262 		       char *buf,
10263 		       int *bufsiz,
10264 		       const void *fpregs,
10265 		       int size)
10266 {
10267   const char *note_name = "CORE";
10268   return elfcore_write_note (abfd, buf, bufsiz,
10269 			     note_name, NT_FPREGSET, fpregs, size);
10270 }
10271 
10272 char *
10273 elfcore_write_prxfpreg (bfd *abfd,
10274 			char *buf,
10275 			int *bufsiz,
10276 			const void *xfpregs,
10277 			int size)
10278 {
10279   char *note_name = "LINUX";
10280   return elfcore_write_note (abfd, buf, bufsiz,
10281 			     note_name, NT_PRXFPREG, xfpregs, size);
10282 }
10283 
10284 char *
10285 elfcore_write_xstatereg (bfd *abfd, char *buf, int *bufsiz,
10286 			 const void *xfpregs, int size)
10287 {
10288   char *note_name;
10289   if (get_elf_backend_data (abfd)->elf_osabi == ELFOSABI_FREEBSD)
10290     note_name = "FreeBSD";
10291   else
10292     note_name = "LINUX";
10293   return elfcore_write_note (abfd, buf, bufsiz,
10294 			     note_name, NT_X86_XSTATE, xfpregs, size);
10295 }
10296 
10297 char *
10298 elfcore_write_ppc_vmx (bfd *abfd,
10299 		       char *buf,
10300 		       int *bufsiz,
10301 		       const void *ppc_vmx,
10302 		       int size)
10303 {
10304   char *note_name = "LINUX";
10305   return elfcore_write_note (abfd, buf, bufsiz,
10306 			     note_name, NT_PPC_VMX, ppc_vmx, size);
10307 }
10308 
10309 char *
10310 elfcore_write_ppc_vsx (bfd *abfd,
10311                        char *buf,
10312                        int *bufsiz,
10313                        const void *ppc_vsx,
10314                        int size)
10315 {
10316   char *note_name = "LINUX";
10317   return elfcore_write_note (abfd, buf, bufsiz,
10318                              note_name, NT_PPC_VSX, ppc_vsx, size);
10319 }
10320 
10321 static char *
10322 elfcore_write_s390_high_gprs (bfd *abfd,
10323 			      char *buf,
10324 			      int *bufsiz,
10325 			      const void *s390_high_gprs,
10326 			      int size)
10327 {
10328   char *note_name = "LINUX";
10329   return elfcore_write_note (abfd, buf, bufsiz,
10330                              note_name, NT_S390_HIGH_GPRS,
10331 			     s390_high_gprs, size);
10332 }
10333 
10334 char *
10335 elfcore_write_s390_timer (bfd *abfd,
10336                           char *buf,
10337                           int *bufsiz,
10338                           const void *s390_timer,
10339                           int size)
10340 {
10341   char *note_name = "LINUX";
10342   return elfcore_write_note (abfd, buf, bufsiz,
10343                              note_name, NT_S390_TIMER, s390_timer, size);
10344 }
10345 
10346 char *
10347 elfcore_write_s390_todcmp (bfd *abfd,
10348                            char *buf,
10349                            int *bufsiz,
10350                            const void *s390_todcmp,
10351                            int size)
10352 {
10353   char *note_name = "LINUX";
10354   return elfcore_write_note (abfd, buf, bufsiz,
10355                              note_name, NT_S390_TODCMP, s390_todcmp, size);
10356 }
10357 
10358 char *
10359 elfcore_write_s390_todpreg (bfd *abfd,
10360                             char *buf,
10361                             int *bufsiz,
10362                             const void *s390_todpreg,
10363                             int size)
10364 {
10365   char *note_name = "LINUX";
10366   return elfcore_write_note (abfd, buf, bufsiz,
10367                              note_name, NT_S390_TODPREG, s390_todpreg, size);
10368 }
10369 
10370 char *
10371 elfcore_write_s390_ctrs (bfd *abfd,
10372                          char *buf,
10373                          int *bufsiz,
10374                          const void *s390_ctrs,
10375                          int size)
10376 {
10377   char *note_name = "LINUX";
10378   return elfcore_write_note (abfd, buf, bufsiz,
10379                              note_name, NT_S390_CTRS, s390_ctrs, size);
10380 }
10381 
10382 char *
10383 elfcore_write_s390_prefix (bfd *abfd,
10384                            char *buf,
10385                            int *bufsiz,
10386                            const void *s390_prefix,
10387                            int size)
10388 {
10389   char *note_name = "LINUX";
10390   return elfcore_write_note (abfd, buf, bufsiz,
10391                              note_name, NT_S390_PREFIX, s390_prefix, size);
10392 }
10393 
10394 char *
10395 elfcore_write_s390_last_break (bfd *abfd,
10396 			       char *buf,
10397 			       int *bufsiz,
10398 			       const void *s390_last_break,
10399 			       int size)
10400 {
10401   char *note_name = "LINUX";
10402   return elfcore_write_note (abfd, buf, bufsiz,
10403                              note_name, NT_S390_LAST_BREAK,
10404 			     s390_last_break, size);
10405 }
10406 
10407 char *
10408 elfcore_write_s390_system_call (bfd *abfd,
10409 				char *buf,
10410 				int *bufsiz,
10411 				const void *s390_system_call,
10412 				int size)
10413 {
10414   char *note_name = "LINUX";
10415   return elfcore_write_note (abfd, buf, bufsiz,
10416                              note_name, NT_S390_SYSTEM_CALL,
10417 			     s390_system_call, size);
10418 }
10419 
10420 char *
10421 elfcore_write_s390_tdb (bfd *abfd,
10422 			char *buf,
10423 			int *bufsiz,
10424 			const void *s390_tdb,
10425 			int size)
10426 {
10427   char *note_name = "LINUX";
10428   return elfcore_write_note (abfd, buf, bufsiz,
10429                              note_name, NT_S390_TDB, s390_tdb, size);
10430 }
10431 
10432 char *
10433 elfcore_write_s390_vxrs_low (bfd *abfd,
10434 			     char *buf,
10435 			     int *bufsiz,
10436 			     const void *s390_vxrs_low,
10437 			     int size)
10438 {
10439   char *note_name = "LINUX";
10440   return elfcore_write_note (abfd, buf, bufsiz,
10441 			     note_name, NT_S390_VXRS_LOW, s390_vxrs_low, size);
10442 }
10443 
10444 char *
10445 elfcore_write_s390_vxrs_high (bfd *abfd,
10446 			     char *buf,
10447 			     int *bufsiz,
10448 			     const void *s390_vxrs_high,
10449 			     int size)
10450 {
10451   char *note_name = "LINUX";
10452   return elfcore_write_note (abfd, buf, bufsiz,
10453 			     note_name, NT_S390_VXRS_HIGH,
10454 			     s390_vxrs_high, size);
10455 }
10456 
10457 char *
10458 elfcore_write_arm_vfp (bfd *abfd,
10459 		       char *buf,
10460 		       int *bufsiz,
10461 		       const void *arm_vfp,
10462 		       int size)
10463 {
10464   char *note_name = "LINUX";
10465   return elfcore_write_note (abfd, buf, bufsiz,
10466 			     note_name, NT_ARM_VFP, arm_vfp, size);
10467 }
10468 
10469 char *
10470 elfcore_write_aarch_tls (bfd *abfd,
10471 		       char *buf,
10472 		       int *bufsiz,
10473 		       const void *aarch_tls,
10474 		       int size)
10475 {
10476   char *note_name = "LINUX";
10477   return elfcore_write_note (abfd, buf, bufsiz,
10478 			     note_name, NT_ARM_TLS, aarch_tls, size);
10479 }
10480 
10481 char *
10482 elfcore_write_aarch_hw_break (bfd *abfd,
10483 			    char *buf,
10484 			    int *bufsiz,
10485 			    const void *aarch_hw_break,
10486 			    int size)
10487 {
10488   char *note_name = "LINUX";
10489   return elfcore_write_note (abfd, buf, bufsiz,
10490 			     note_name, NT_ARM_HW_BREAK, aarch_hw_break, size);
10491 }
10492 
10493 char *
10494 elfcore_write_aarch_hw_watch (bfd *abfd,
10495 			    char *buf,
10496 			    int *bufsiz,
10497 			    const void *aarch_hw_watch,
10498 			    int size)
10499 {
10500   char *note_name = "LINUX";
10501   return elfcore_write_note (abfd, buf, bufsiz,
10502 			     note_name, NT_ARM_HW_WATCH, aarch_hw_watch, size);
10503 }
10504 
10505 char *
10506 elfcore_write_register_note (bfd *abfd,
10507 			     char *buf,
10508 			     int *bufsiz,
10509 			     const char *section,
10510 			     const void *data,
10511 			     int size)
10512 {
10513   if (strcmp (section, ".reg2") == 0)
10514     return elfcore_write_prfpreg (abfd, buf, bufsiz, data, size);
10515   if (strcmp (section, ".reg-xfp") == 0)
10516     return elfcore_write_prxfpreg (abfd, buf, bufsiz, data, size);
10517   if (strcmp (section, ".reg-xstate") == 0)
10518     return elfcore_write_xstatereg (abfd, buf, bufsiz, data, size);
10519   if (strcmp (section, ".reg-ppc-vmx") == 0)
10520     return elfcore_write_ppc_vmx (abfd, buf, bufsiz, data, size);
10521   if (strcmp (section, ".reg-ppc-vsx") == 0)
10522     return elfcore_write_ppc_vsx (abfd, buf, bufsiz, data, size);
10523   if (strcmp (section, ".reg-s390-high-gprs") == 0)
10524     return elfcore_write_s390_high_gprs (abfd, buf, bufsiz, data, size);
10525   if (strcmp (section, ".reg-s390-timer") == 0)
10526     return elfcore_write_s390_timer (abfd, buf, bufsiz, data, size);
10527   if (strcmp (section, ".reg-s390-todcmp") == 0)
10528     return elfcore_write_s390_todcmp (abfd, buf, bufsiz, data, size);
10529   if (strcmp (section, ".reg-s390-todpreg") == 0)
10530     return elfcore_write_s390_todpreg (abfd, buf, bufsiz, data, size);
10531   if (strcmp (section, ".reg-s390-ctrs") == 0)
10532     return elfcore_write_s390_ctrs (abfd, buf, bufsiz, data, size);
10533   if (strcmp (section, ".reg-s390-prefix") == 0)
10534     return elfcore_write_s390_prefix (abfd, buf, bufsiz, data, size);
10535   if (strcmp (section, ".reg-s390-last-break") == 0)
10536     return elfcore_write_s390_last_break (abfd, buf, bufsiz, data, size);
10537   if (strcmp (section, ".reg-s390-system-call") == 0)
10538     return elfcore_write_s390_system_call (abfd, buf, bufsiz, data, size);
10539   if (strcmp (section, ".reg-s390-tdb") == 0)
10540     return elfcore_write_s390_tdb (abfd, buf, bufsiz, data, size);
10541   if (strcmp (section, ".reg-s390-vxrs-low") == 0)
10542     return elfcore_write_s390_vxrs_low (abfd, buf, bufsiz, data, size);
10543   if (strcmp (section, ".reg-s390-vxrs-high") == 0)
10544     return elfcore_write_s390_vxrs_high (abfd, buf, bufsiz, data, size);
10545   if (strcmp (section, ".reg-arm-vfp") == 0)
10546     return elfcore_write_arm_vfp (abfd, buf, bufsiz, data, size);
10547   if (strcmp (section, ".reg-aarch-tls") == 0)
10548     return elfcore_write_aarch_tls (abfd, buf, bufsiz, data, size);
10549   if (strcmp (section, ".reg-aarch-hw-break") == 0)
10550     return elfcore_write_aarch_hw_break (abfd, buf, bufsiz, data, size);
10551   if (strcmp (section, ".reg-aarch-hw-watch") == 0)
10552     return elfcore_write_aarch_hw_watch (abfd, buf, bufsiz, data, size);
10553   return NULL;
10554 }
10555 
10556 static bfd_boolean
10557 elf_parse_notes (bfd *abfd, char *buf, size_t size, file_ptr offset)
10558 {
10559   char *p;
10560 
10561   p = buf;
10562   while (p < buf + size)
10563     {
10564       /* FIXME: bad alignment assumption.  */
10565       Elf_External_Note *xnp = (Elf_External_Note *) p;
10566       Elf_Internal_Note in;
10567 
10568       if (offsetof (Elf_External_Note, name) > buf - p + size)
10569 	return FALSE;
10570 
10571       in.type = H_GET_32 (abfd, xnp->type);
10572 
10573       in.namesz = H_GET_32 (abfd, xnp->namesz);
10574       in.namedata = xnp->name;
10575       if (in.namesz > buf - in.namedata + size)
10576 	return FALSE;
10577 
10578       in.descsz = H_GET_32 (abfd, xnp->descsz);
10579       in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
10580       in.descpos = offset + (in.descdata - buf);
10581       if (in.descsz != 0
10582 	  && (in.descdata >= buf + size
10583 	      || in.descsz > buf - in.descdata + size))
10584 	return FALSE;
10585 
10586       switch (bfd_get_format (abfd))
10587         {
10588 	default:
10589 	  return TRUE;
10590 
10591 	case bfd_core:
10592 	  {
10593 #define GROKER_ELEMENT(S,F) {S, sizeof (S) - 1, F}
10594 	    struct
10595 	    {
10596 	      const char * string;
10597 	      size_t len;
10598 	      bfd_boolean (* func)(bfd *, Elf_Internal_Note *);
10599 	    }
10600 	    grokers[] =
10601 	    {
10602 	      GROKER_ELEMENT ("", elfcore_grok_note),
10603 	      GROKER_ELEMENT ("FreeBSD", elfcore_grok_freebsd_note),
10604 	      GROKER_ELEMENT ("NetBSD-CORE", elfcore_grok_netbsd_note),
10605 	      GROKER_ELEMENT ( "OpenBSD", elfcore_grok_openbsd_note),
10606 	      GROKER_ELEMENT ("QNX", elfcore_grok_nto_note),
10607 	      GROKER_ELEMENT ("SPU/", elfcore_grok_spu_note)
10608 	    };
10609 #undef GROKER_ELEMENT
10610 	    int i;
10611 
10612 	    for (i = ARRAY_SIZE (grokers); i--;)
10613 	      {
10614 		if (in.namesz >= grokers[i].len
10615 		    && strncmp (in.namedata, grokers[i].string,
10616 				grokers[i].len) == 0)
10617 		  {
10618 		    if (! grokers[i].func (abfd, & in))
10619 		      return FALSE;
10620 		    break;
10621 		  }
10622 	      }
10623 	    break;
10624 	  }
10625 
10626 	case bfd_object:
10627 	  if (in.namesz == sizeof "GNU" && strcmp (in.namedata, "GNU") == 0)
10628 	    {
10629 	      if (! elfobj_grok_gnu_note (abfd, &in))
10630 		return FALSE;
10631 	    }
10632 	  else if (in.namesz == sizeof "stapsdt"
10633 		   && strcmp (in.namedata, "stapsdt") == 0)
10634 	    {
10635 	      if (! elfobj_grok_stapsdt_note (abfd, &in))
10636 		return FALSE;
10637 	    }
10638 	  break;
10639 	}
10640 
10641       p = in.descdata + BFD_ALIGN (in.descsz, 4);
10642     }
10643 
10644   return TRUE;
10645 }
10646 
10647 static bfd_boolean
10648 elf_read_notes (bfd *abfd, file_ptr offset, bfd_size_type size)
10649 {
10650   char *buf;
10651 
10652   if (size <= 0)
10653     return TRUE;
10654 
10655   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
10656     return FALSE;
10657 
10658   buf = (char *) bfd_malloc (size + 1);
10659   if (buf == NULL)
10660     return FALSE;
10661 
10662   /* PR 17512: file: ec08f814
10663      0-termintate the buffer so that string searches will not overflow.  */
10664   buf[size] = 0;
10665 
10666   if (bfd_bread (buf, size, abfd) != size
10667       || !elf_parse_notes (abfd, buf, size, offset))
10668     {
10669       free (buf);
10670       return FALSE;
10671     }
10672 
10673   free (buf);
10674   return TRUE;
10675 }
10676 
10677 /* Providing external access to the ELF program header table.  */
10678 
10679 /* Return an upper bound on the number of bytes required to store a
10680    copy of ABFD's program header table entries.  Return -1 if an error
10681    occurs; bfd_get_error will return an appropriate code.  */
10682 
10683 long
10684 bfd_get_elf_phdr_upper_bound (bfd *abfd)
10685 {
10686   if (abfd->xvec->flavour != bfd_target_elf_flavour)
10687     {
10688       bfd_set_error (bfd_error_wrong_format);
10689       return -1;
10690     }
10691 
10692   return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
10693 }
10694 
10695 /* Copy ABFD's program header table entries to *PHDRS.  The entries
10696    will be stored as an array of Elf_Internal_Phdr structures, as
10697    defined in include/elf/internal.h.  To find out how large the
10698    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
10699 
10700    Return the number of program header table entries read, or -1 if an
10701    error occurs; bfd_get_error will return an appropriate code.  */
10702 
10703 int
10704 bfd_get_elf_phdrs (bfd *abfd, void *phdrs)
10705 {
10706   int num_phdrs;
10707 
10708   if (abfd->xvec->flavour != bfd_target_elf_flavour)
10709     {
10710       bfd_set_error (bfd_error_wrong_format);
10711       return -1;
10712     }
10713 
10714   num_phdrs = elf_elfheader (abfd)->e_phnum;
10715   memcpy (phdrs, elf_tdata (abfd)->phdr,
10716 	  num_phdrs * sizeof (Elf_Internal_Phdr));
10717 
10718   return num_phdrs;
10719 }
10720 
10721 enum elf_reloc_type_class
10722 _bfd_elf_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
10723 			   const asection *rel_sec ATTRIBUTE_UNUSED,
10724 			   const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED)
10725 {
10726   return reloc_class_normal;
10727 }
10728 
10729 /* For RELA architectures, return the relocation value for a
10730    relocation against a local symbol.  */
10731 
10732 bfd_vma
10733 _bfd_elf_rela_local_sym (bfd *abfd,
10734 			 Elf_Internal_Sym *sym,
10735 			 asection **psec,
10736 			 Elf_Internal_Rela *rel)
10737 {
10738   asection *sec = *psec;
10739   bfd_vma relocation;
10740 
10741   relocation = (sec->output_section->vma
10742 		+ sec->output_offset
10743 		+ sym->st_value);
10744   if ((sec->flags & SEC_MERGE)
10745       && ELF_ST_TYPE (sym->st_info) == STT_SECTION
10746       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
10747     {
10748       rel->r_addend =
10749 	_bfd_merged_section_offset (abfd, psec,
10750 				    elf_section_data (sec)->sec_info,
10751 				    sym->st_value + rel->r_addend);
10752       if (sec != *psec)
10753 	{
10754 	  /* If we have changed the section, and our original section is
10755 	     marked with SEC_EXCLUDE, it means that the original
10756 	     SEC_MERGE section has been completely subsumed in some
10757 	     other SEC_MERGE section.  In this case, we need to leave
10758 	     some info around for --emit-relocs.  */
10759 	  if ((sec->flags & SEC_EXCLUDE) != 0)
10760 	    sec->kept_section = *psec;
10761 	  sec = *psec;
10762 	}
10763       rel->r_addend -= relocation;
10764       rel->r_addend += sec->output_section->vma + sec->output_offset;
10765     }
10766   return relocation;
10767 }
10768 
10769 bfd_vma
10770 _bfd_elf_rel_local_sym (bfd *abfd,
10771 			Elf_Internal_Sym *sym,
10772 			asection **psec,
10773 			bfd_vma addend)
10774 {
10775   asection *sec = *psec;
10776 
10777   if (sec->sec_info_type != SEC_INFO_TYPE_MERGE)
10778     return sym->st_value + addend;
10779 
10780   return _bfd_merged_section_offset (abfd, psec,
10781 				     elf_section_data (sec)->sec_info,
10782 				     sym->st_value + addend);
10783 }
10784 
10785 /* Adjust an address within a section.  Given OFFSET within SEC, return
10786    the new offset within the section, based upon changes made to the
10787    section.  Returns -1 if the offset is now invalid.
10788    The offset (in abnd out) is in target sized bytes, however big a
10789    byte may be.  */
10790 
10791 bfd_vma
10792 _bfd_elf_section_offset (bfd *abfd,
10793 			 struct bfd_link_info *info,
10794 			 asection *sec,
10795 			 bfd_vma offset)
10796 {
10797   switch (sec->sec_info_type)
10798     {
10799     case SEC_INFO_TYPE_STABS:
10800       return _bfd_stab_section_offset (sec, elf_section_data (sec)->sec_info,
10801 				       offset);
10802     case SEC_INFO_TYPE_EH_FRAME:
10803       return _bfd_elf_eh_frame_section_offset (abfd, info, sec, offset);
10804 
10805     default:
10806       if ((sec->flags & SEC_ELF_REVERSE_COPY) != 0)
10807 	{
10808 	  /* Reverse the offset.  */
10809 	  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10810 	  bfd_size_type address_size = bed->s->arch_size / 8;
10811 
10812 	  /* address_size and sec->size are in octets.  Convert
10813 	     to bytes before subtracting the original offset.  */
10814 	  offset = (sec->size - address_size) / bfd_octets_per_byte (abfd) - offset;
10815 	}
10816       return offset;
10817     }
10818 }
10819 
10820 /* Create a new BFD as if by bfd_openr.  Rather than opening a file,
10821    reconstruct an ELF file by reading the segments out of remote memory
10822    based on the ELF file header at EHDR_VMA and the ELF program headers it
10823    points to.  If not null, *LOADBASEP is filled in with the difference
10824    between the VMAs from which the segments were read, and the VMAs the
10825    file headers (and hence BFD's idea of each section's VMA) put them at.
10826 
10827    The function TARGET_READ_MEMORY is called to copy LEN bytes from the
10828    remote memory at target address VMA into the local buffer at MYADDR; it
10829    should return zero on success or an `errno' code on failure.  TEMPL must
10830    be a BFD for an ELF target with the word size and byte order found in
10831    the remote memory.  */
10832 
10833 bfd *
10834 bfd_elf_bfd_from_remote_memory
10835   (bfd *templ,
10836    bfd_vma ehdr_vma,
10837    bfd_size_type size,
10838    bfd_vma *loadbasep,
10839    int (*target_read_memory) (bfd_vma, bfd_byte *, bfd_size_type))
10840 {
10841   return (*get_elf_backend_data (templ)->elf_backend_bfd_from_remote_memory)
10842     (templ, ehdr_vma, size, loadbasep, target_read_memory);
10843 }
10844 
10845 long
10846 _bfd_elf_get_synthetic_symtab (bfd *abfd,
10847 			       long symcount ATTRIBUTE_UNUSED,
10848 			       asymbol **syms ATTRIBUTE_UNUSED,
10849 			       long dynsymcount,
10850 			       asymbol **dynsyms,
10851 			       asymbol **ret)
10852 {
10853   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10854   asection *relplt;
10855   asymbol *s;
10856   const char *relplt_name;
10857   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
10858   arelent *p;
10859   long count, i, n;
10860   size_t size;
10861   Elf_Internal_Shdr *hdr;
10862   char *names;
10863   asection *plt;
10864 
10865   *ret = NULL;
10866 
10867   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0)
10868     return 0;
10869 
10870   if (dynsymcount <= 0)
10871     return 0;
10872 
10873   if (!bed->plt_sym_val)
10874     return 0;
10875 
10876   relplt_name = bed->relplt_name;
10877   if (relplt_name == NULL)
10878     relplt_name = bed->rela_plts_and_copies_p ? ".rela.plt" : ".rel.plt";
10879   relplt = bfd_get_section_by_name (abfd, relplt_name);
10880   if (relplt == NULL)
10881     return 0;
10882 
10883   hdr = &elf_section_data (relplt)->this_hdr;
10884   if (hdr->sh_link != elf_dynsymtab (abfd)
10885       || (hdr->sh_type != SHT_REL && hdr->sh_type != SHT_RELA))
10886     return 0;
10887 
10888   plt = bfd_get_section_by_name (abfd, ".plt");
10889   if (plt == NULL)
10890     return 0;
10891 
10892   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
10893   if (! (*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
10894     return -1;
10895 
10896   count = relplt->size / hdr->sh_entsize;
10897   size = count * sizeof (asymbol);
10898   p = relplt->relocation;
10899   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
10900     {
10901       size += strlen ((*p->sym_ptr_ptr)->name) + sizeof ("@plt");
10902       if (p->addend != 0)
10903 	{
10904 #ifdef BFD64
10905 	  size += sizeof ("+0x") - 1 + 8 + 8 * (bed->s->elfclass == ELFCLASS64);
10906 #else
10907 	  size += sizeof ("+0x") - 1 + 8;
10908 #endif
10909 	}
10910     }
10911 
10912   s = *ret = (asymbol *) bfd_malloc (size);
10913   if (s == NULL)
10914     return -1;
10915 
10916   names = (char *) (s + count);
10917   p = relplt->relocation;
10918   n = 0;
10919   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
10920     {
10921       size_t len;
10922       bfd_vma addr;
10923 
10924       addr = bed->plt_sym_val (i, plt, p);
10925       if (addr == (bfd_vma) -1)
10926 	continue;
10927 
10928       *s = **p->sym_ptr_ptr;
10929       /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
10930 	 we are defining a symbol, ensure one of them is set.  */
10931       if ((s->flags & BSF_LOCAL) == 0)
10932 	s->flags |= BSF_GLOBAL;
10933       s->flags |= BSF_SYNTHETIC;
10934       s->section = plt;
10935       s->value = addr - plt->vma;
10936       s->name = names;
10937       s->udata.p = NULL;
10938       len = strlen ((*p->sym_ptr_ptr)->name);
10939       memcpy (names, (*p->sym_ptr_ptr)->name, len);
10940       names += len;
10941       if (p->addend != 0)
10942 	{
10943 	  char buf[30], *a;
10944 
10945 	  memcpy (names, "+0x", sizeof ("+0x") - 1);
10946 	  names += sizeof ("+0x") - 1;
10947 	  bfd_sprintf_vma (abfd, buf, p->addend);
10948 	  for (a = buf; *a == '0'; ++a)
10949 	    ;
10950 	  len = strlen (a);
10951 	  memcpy (names, a, len);
10952 	  names += len;
10953 	}
10954       memcpy (names, "@plt", sizeof ("@plt"));
10955       names += sizeof ("@plt");
10956       ++s, ++n;
10957     }
10958 
10959   return n;
10960 }
10961 
10962 /* It is only used by x86-64 so far.  */
10963 asection _bfd_elf_large_com_section
10964   = BFD_FAKE_SECTION (_bfd_elf_large_com_section,
10965 		      SEC_IS_COMMON, NULL, "LARGE_COMMON", 0);
10966 
10967 void
10968 _bfd_elf_post_process_headers (bfd * abfd,
10969 			       struct bfd_link_info * link_info ATTRIBUTE_UNUSED)
10970 {
10971   Elf_Internal_Ehdr * i_ehdrp;	/* ELF file header, internal form.  */
10972 
10973   i_ehdrp = elf_elfheader (abfd);
10974 
10975   i_ehdrp->e_ident[EI_OSABI] = get_elf_backend_data (abfd)->elf_osabi;
10976 
10977   /* To make things simpler for the loader on Linux systems we set the
10978      osabi field to ELFOSABI_GNU if the binary contains symbols of
10979      the STT_GNU_IFUNC type or STB_GNU_UNIQUE binding.  */
10980   if (i_ehdrp->e_ident[EI_OSABI] == ELFOSABI_NONE
10981       && elf_tdata (abfd)->has_gnu_symbols)
10982     i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_GNU;
10983 }
10984 
10985 
10986 /* Return TRUE for ELF symbol types that represent functions.
10987    This is the default version of this function, which is sufficient for
10988    most targets.  It returns true if TYPE is STT_FUNC or STT_GNU_IFUNC.  */
10989 
10990 bfd_boolean
10991 _bfd_elf_is_function_type (unsigned int type)
10992 {
10993   return (type == STT_FUNC
10994 	  || type == STT_GNU_IFUNC);
10995 }
10996 
10997 /* If the ELF symbol SYM might be a function in SEC, return the
10998    function size and set *CODE_OFF to the function's entry point,
10999    otherwise return zero.  */
11000 
11001 bfd_size_type
11002 _bfd_elf_maybe_function_sym (const asymbol *sym, asection *sec,
11003 			     bfd_vma *code_off)
11004 {
11005   bfd_size_type size;
11006 
11007   if ((sym->flags & (BSF_SECTION_SYM | BSF_FILE | BSF_OBJECT
11008 		     | BSF_THREAD_LOCAL | BSF_RELC | BSF_SRELC)) != 0
11009       || sym->section != sec)
11010     return 0;
11011 
11012   *code_off = sym->value;
11013   size = 0;
11014   if (!(sym->flags & BSF_SYNTHETIC))
11015     size = ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
11016   if (size == 0)
11017     size = 1;
11018   return size;
11019 }
11020