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