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