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