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