elf.c revision 107496
118334Speter/* ELF executable support for BFD.
2132718Skan   Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002
390075Sobrien   Free Software Foundation, Inc.
418334Speter
5132718SkanThis file is part of BFD, the Binary File Descriptor library.
618334Speter
7132718SkanThis program is free software; you can redistribute it and/or modify
818334Speterit under the terms of the GNU General Public License as published by
918334Speterthe Free Software Foundation; either version 2 of the License, or
1018334Speter(at your option) any later version.
1118334Speter
12132718SkanThis program is distributed in the hope that it will be useful,
1318334Speterbut WITHOUT ANY WARRANTY; without even the implied warranty of
1418334SpeterMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1518334SpeterGNU General Public License for more details.
1618334Speter
1718334SpeterYou should have received a copy of the GNU General Public License
18132718Skanalong with this program; if not, write to the Free Software
1918334SpeterFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
2018334Speter
2118334Speter
2218334Speter/* $FreeBSD: head/contrib/binutils/bfd/elf.c 107496 2002-12-02 09:17:49Z obrien $ */
2318334Speter
2418334Speter
2518334Speter/*  SECTION
2618334Speter
2718334Speter	ELF backends
2818334Speter
2918334Speter	BFD support for ELF formats is being worked on.
3018334Speter	Currently, the best supported back ends are for sparc and i386
3118334Speter	(running svr4 or Solaris 2).
3218334Speter
3318334Speter	Documentation of the internals of the support code still needs
3418334Speter	to be written.  The code is changing quickly enough that we
35132718Skan	haven't bothered yet.  */
36117395Skan
37132718Skan/* For sparc64-cross-sparc32.  */
38#define _SYSCALL32
39#include "bfd.h"
40#include "sysdep.h"
41#include "bfdlink.h"
42#include "libbfd.h"
43#define ARCH_SIZE 0
44#include "elf-bfd.h"
45#include "libiberty.h"
46
47static INLINE struct elf_segment_map *make_mapping
48  PARAMS ((bfd *, asection **, unsigned int, unsigned int, boolean));
49static boolean map_sections_to_segments PARAMS ((bfd *));
50static int elf_sort_sections PARAMS ((const PTR, const PTR));
51static boolean assign_file_positions_for_segments PARAMS ((bfd *));
52static boolean assign_file_positions_except_relocs PARAMS ((bfd *));
53static boolean prep_headers PARAMS ((bfd *));
54static boolean swap_out_syms PARAMS ((bfd *, struct bfd_strtab_hash **, int));
55static boolean copy_private_bfd_data PARAMS ((bfd *, bfd *));
56static char *elf_read PARAMS ((bfd *, file_ptr, bfd_size_type));
57static const char *group_signature PARAMS ((bfd *, Elf_Internal_Shdr *));
58static boolean setup_group PARAMS ((bfd *, Elf_Internal_Shdr *, asection *));
59static void merge_sections_remove_hook PARAMS ((bfd *, asection *));
60static void elf_fake_sections PARAMS ((bfd *, asection *, PTR));
61static boolean assign_section_numbers PARAMS ((bfd *));
62static INLINE int sym_is_global PARAMS ((bfd *, asymbol *));
63static boolean elf_map_symbols PARAMS ((bfd *));
64static bfd_size_type get_program_header_size PARAMS ((bfd *));
65static boolean elfcore_read_notes PARAMS ((bfd *, file_ptr, bfd_size_type));
66static boolean elf_find_function PARAMS ((bfd *, asection *, asymbol **,
67					  bfd_vma, const char **,
68					  const char **));
69static int elfcore_make_pid PARAMS ((bfd *));
70static boolean elfcore_maybe_make_sect PARAMS ((bfd *, char *, asection *));
71static boolean elfcore_make_note_pseudosection PARAMS ((bfd *, char *,
72							Elf_Internal_Note *));
73static boolean elfcore_grok_prfpreg PARAMS ((bfd *, Elf_Internal_Note *));
74static boolean elfcore_grok_prxfpreg PARAMS ((bfd *, Elf_Internal_Note *));
75static boolean elfcore_grok_note PARAMS ((bfd *, Elf_Internal_Note *));
76
77static boolean elfcore_netbsd_get_lwpid PARAMS ((Elf_Internal_Note *, int *));
78static boolean elfcore_grok_netbsd_procinfo PARAMS ((bfd *,
79						     Elf_Internal_Note *));
80static boolean elfcore_grok_netbsd_note PARAMS ((bfd *, Elf_Internal_Note *));
81
82/* Swap version information in and out.  The version information is
83   currently size independent.  If that ever changes, this code will
84   need to move into elfcode.h.  */
85
86/* Swap in a Verdef structure.  */
87
88void
89_bfd_elf_swap_verdef_in (abfd, src, dst)
90     bfd *abfd;
91     const Elf_External_Verdef *src;
92     Elf_Internal_Verdef *dst;
93{
94  dst->vd_version = H_GET_16 (abfd, src->vd_version);
95  dst->vd_flags   = H_GET_16 (abfd, src->vd_flags);
96  dst->vd_ndx     = H_GET_16 (abfd, src->vd_ndx);
97  dst->vd_cnt     = H_GET_16 (abfd, src->vd_cnt);
98  dst->vd_hash    = H_GET_32 (abfd, src->vd_hash);
99  dst->vd_aux     = H_GET_32 (abfd, src->vd_aux);
100  dst->vd_next    = H_GET_32 (abfd, src->vd_next);
101}
102
103/* Swap out a Verdef structure.  */
104
105void
106_bfd_elf_swap_verdef_out (abfd, src, dst)
107     bfd *abfd;
108     const Elf_Internal_Verdef *src;
109     Elf_External_Verdef *dst;
110{
111  H_PUT_16 (abfd, src->vd_version, dst->vd_version);
112  H_PUT_16 (abfd, src->vd_flags, dst->vd_flags);
113  H_PUT_16 (abfd, src->vd_ndx, dst->vd_ndx);
114  H_PUT_16 (abfd, src->vd_cnt, dst->vd_cnt);
115  H_PUT_32 (abfd, src->vd_hash, dst->vd_hash);
116  H_PUT_32 (abfd, src->vd_aux, dst->vd_aux);
117  H_PUT_32 (abfd, src->vd_next, dst->vd_next);
118}
119
120/* Swap in a Verdaux structure.  */
121
122void
123_bfd_elf_swap_verdaux_in (abfd, src, dst)
124     bfd *abfd;
125     const Elf_External_Verdaux *src;
126     Elf_Internal_Verdaux *dst;
127{
128  dst->vda_name = H_GET_32 (abfd, src->vda_name);
129  dst->vda_next = H_GET_32 (abfd, src->vda_next);
130}
131
132/* Swap out a Verdaux structure.  */
133
134void
135_bfd_elf_swap_verdaux_out (abfd, src, dst)
136     bfd *abfd;
137     const Elf_Internal_Verdaux *src;
138     Elf_External_Verdaux *dst;
139{
140  H_PUT_32 (abfd, src->vda_name, dst->vda_name);
141  H_PUT_32 (abfd, src->vda_next, dst->vda_next);
142}
143
144/* Swap in a Verneed structure.  */
145
146void
147_bfd_elf_swap_verneed_in (abfd, src, dst)
148     bfd *abfd;
149     const Elf_External_Verneed *src;
150     Elf_Internal_Verneed *dst;
151{
152  dst->vn_version = H_GET_16 (abfd, src->vn_version);
153  dst->vn_cnt     = H_GET_16 (abfd, src->vn_cnt);
154  dst->vn_file    = H_GET_32 (abfd, src->vn_file);
155  dst->vn_aux     = H_GET_32 (abfd, src->vn_aux);
156  dst->vn_next    = H_GET_32 (abfd, src->vn_next);
157}
158
159/* Swap out a Verneed structure.  */
160
161void
162_bfd_elf_swap_verneed_out (abfd, src, dst)
163     bfd *abfd;
164     const Elf_Internal_Verneed *src;
165     Elf_External_Verneed *dst;
166{
167  H_PUT_16 (abfd, src->vn_version, dst->vn_version);
168  H_PUT_16 (abfd, src->vn_cnt, dst->vn_cnt);
169  H_PUT_32 (abfd, src->vn_file, dst->vn_file);
170  H_PUT_32 (abfd, src->vn_aux, dst->vn_aux);
171  H_PUT_32 (abfd, src->vn_next, dst->vn_next);
172}
173
174/* Swap in a Vernaux structure.  */
175
176void
177_bfd_elf_swap_vernaux_in (abfd, src, dst)
178     bfd *abfd;
179     const Elf_External_Vernaux *src;
180     Elf_Internal_Vernaux *dst;
181{
182  dst->vna_hash  = H_GET_32 (abfd, src->vna_hash);
183  dst->vna_flags = H_GET_16 (abfd, src->vna_flags);
184  dst->vna_other = H_GET_16 (abfd, src->vna_other);
185  dst->vna_name  = H_GET_32 (abfd, src->vna_name);
186  dst->vna_next  = H_GET_32 (abfd, src->vna_next);
187}
188
189/* Swap out a Vernaux structure.  */
190
191void
192_bfd_elf_swap_vernaux_out (abfd, src, dst)
193     bfd *abfd;
194     const Elf_Internal_Vernaux *src;
195     Elf_External_Vernaux *dst;
196{
197  H_PUT_32 (abfd, src->vna_hash, dst->vna_hash);
198  H_PUT_16 (abfd, src->vna_flags, dst->vna_flags);
199  H_PUT_16 (abfd, src->vna_other, dst->vna_other);
200  H_PUT_32 (abfd, src->vna_name, dst->vna_name);
201  H_PUT_32 (abfd, src->vna_next, dst->vna_next);
202}
203
204/* Swap in a Versym structure.  */
205
206void
207_bfd_elf_swap_versym_in (abfd, src, dst)
208     bfd *abfd;
209     const Elf_External_Versym *src;
210     Elf_Internal_Versym *dst;
211{
212  dst->vs_vers = H_GET_16 (abfd, src->vs_vers);
213}
214
215/* Swap out a Versym structure.  */
216
217void
218_bfd_elf_swap_versym_out (abfd, src, dst)
219     bfd *abfd;
220     const Elf_Internal_Versym *src;
221     Elf_External_Versym *dst;
222{
223  H_PUT_16 (abfd, src->vs_vers, dst->vs_vers);
224}
225
226/* Standard ELF hash function.  Do not change this function; you will
227   cause invalid hash tables to be generated.  */
228
229unsigned long
230bfd_elf_hash (namearg)
231     const char *namearg;
232{
233  const unsigned char *name = (const unsigned char *) namearg;
234  unsigned long h = 0;
235  unsigned long g;
236  int ch;
237
238  while ((ch = *name++) != '\0')
239    {
240      h = (h << 4) + ch;
241      if ((g = (h & 0xf0000000)) != 0)
242	{
243	  h ^= g >> 24;
244	  /* The ELF ABI says `h &= ~g', but this is equivalent in
245	     this case and on some machines one insn instead of two.  */
246	  h ^= g;
247	}
248    }
249  return h;
250}
251
252/* Read a specified number of bytes at a specified offset in an ELF
253   file, into a newly allocated buffer, and return a pointer to the
254   buffer.  */
255
256static char *
257elf_read (abfd, offset, size)
258     bfd *abfd;
259     file_ptr offset;
260     bfd_size_type size;
261{
262  char *buf;
263
264  if ((buf = bfd_alloc (abfd, size)) == NULL)
265    return NULL;
266  if (bfd_seek (abfd, offset, SEEK_SET) != 0)
267    return NULL;
268  if (bfd_bread ((PTR) buf, size, abfd) != size)
269    {
270      if (bfd_get_error () != bfd_error_system_call)
271	bfd_set_error (bfd_error_file_truncated);
272      return NULL;
273    }
274  return buf;
275}
276
277boolean
278bfd_elf_mkobject (abfd)
279     bfd *abfd;
280{
281  /* This just does initialization.  */
282  /* coff_mkobject zalloc's space for tdata.coff_obj_data ...  */
283  bfd_size_type amt = sizeof (struct elf_obj_tdata);
284  elf_tdata (abfd) = (struct elf_obj_tdata *) bfd_zalloc (abfd, amt);
285  if (elf_tdata (abfd) == 0)
286    return false;
287  /* Since everything is done at close time, do we need any
288     initialization?  */
289
290  return true;
291}
292
293boolean
294bfd_elf_mkcorefile (abfd)
295     bfd *abfd;
296{
297  /* I think this can be done just like an object file.  */
298  return bfd_elf_mkobject (abfd);
299}
300
301char *
302bfd_elf_get_str_section (abfd, shindex)
303     bfd *abfd;
304     unsigned int shindex;
305{
306  Elf_Internal_Shdr **i_shdrp;
307  char *shstrtab = NULL;
308  file_ptr offset;
309  bfd_size_type shstrtabsize;
310
311  i_shdrp = elf_elfsections (abfd);
312  if (i_shdrp == 0 || i_shdrp[shindex] == 0)
313    return 0;
314
315  shstrtab = (char *) i_shdrp[shindex]->contents;
316  if (shstrtab == NULL)
317    {
318      /* No cached one, attempt to read, and cache what we read.  */
319      offset = i_shdrp[shindex]->sh_offset;
320      shstrtabsize = i_shdrp[shindex]->sh_size;
321      shstrtab = elf_read (abfd, offset, shstrtabsize);
322      i_shdrp[shindex]->contents = (PTR) shstrtab;
323    }
324  return shstrtab;
325}
326
327char *
328bfd_elf_string_from_elf_section (abfd, shindex, strindex)
329     bfd *abfd;
330     unsigned int shindex;
331     unsigned int strindex;
332{
333  Elf_Internal_Shdr *hdr;
334
335  if (strindex == 0)
336    return "";
337
338  hdr = elf_elfsections (abfd)[shindex];
339
340  if (hdr->contents == NULL
341      && bfd_elf_get_str_section (abfd, shindex) == NULL)
342    return NULL;
343
344  if (strindex >= hdr->sh_size)
345    {
346      (*_bfd_error_handler)
347	(_("%s: invalid string offset %u >= %lu for section `%s'"),
348	 bfd_archive_filename (abfd), strindex, (unsigned long) hdr->sh_size,
349	 ((shindex == elf_elfheader(abfd)->e_shstrndx
350	   && strindex == hdr->sh_name)
351	  ? ".shstrtab"
352	  : elf_string_from_elf_strtab (abfd, hdr->sh_name)));
353      return "";
354    }
355
356  return ((char *) hdr->contents) + strindex;
357}
358
359/* Read and convert symbols to internal format.
360   SYMCOUNT specifies the number of symbols to read, starting from
361   symbol SYMOFFSET.  If any of INTSYM_BUF, EXTSYM_BUF or EXTSHNDX_BUF
362   are non-NULL, they are used to store the internal symbols, external
363   symbols, and symbol section index extensions, respectively.  */
364
365Elf_Internal_Sym *
366bfd_elf_get_elf_syms (ibfd, symtab_hdr, symcount, symoffset,
367		      intsym_buf, extsym_buf, extshndx_buf)
368     bfd *ibfd;
369     Elf_Internal_Shdr *symtab_hdr;
370     size_t symcount;
371     size_t symoffset;
372     Elf_Internal_Sym *intsym_buf;
373     PTR extsym_buf;
374     Elf_External_Sym_Shndx *extshndx_buf;
375{
376  Elf_Internal_Shdr *shndx_hdr;
377  PTR alloc_ext;
378  const bfd_byte *esym;
379  Elf_External_Sym_Shndx *alloc_extshndx;
380  Elf_External_Sym_Shndx *shndx;
381  Elf_Internal_Sym *isym;
382  Elf_Internal_Sym *isymend;
383  struct elf_backend_data *bed;
384  size_t extsym_size;
385  bfd_size_type amt;
386  file_ptr pos;
387
388  if (symcount == 0)
389    return intsym_buf;
390
391  /* Normal syms might have section extension entries.  */
392  shndx_hdr = NULL;
393  if (symtab_hdr == &elf_tdata (ibfd)->symtab_hdr)
394    shndx_hdr = &elf_tdata (ibfd)->symtab_shndx_hdr;
395
396  /* Read the symbols.  */
397  alloc_ext = NULL;
398  alloc_extshndx = NULL;
399  bed = get_elf_backend_data (ibfd);
400  extsym_size = bed->s->sizeof_sym;
401  amt = symcount * extsym_size;
402  pos = symtab_hdr->sh_offset + symoffset * extsym_size;
403  if (extsym_buf == NULL)
404    {
405      alloc_ext = bfd_malloc (amt);
406      extsym_buf = alloc_ext;
407    }
408  if (extsym_buf == NULL
409      || bfd_seek (ibfd, pos, SEEK_SET) != 0
410      || bfd_bread (extsym_buf, amt, ibfd) != amt)
411    {
412      intsym_buf = NULL;
413      goto out;
414    }
415
416  if (shndx_hdr == NULL || shndx_hdr->sh_size == 0)
417    extshndx_buf = NULL;
418  else
419    {
420      amt = symcount * sizeof (Elf_External_Sym_Shndx);
421      pos = shndx_hdr->sh_offset + symoffset * sizeof (Elf_External_Sym_Shndx);
422      if (extshndx_buf == NULL)
423	{
424	  alloc_extshndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
425	  extshndx_buf = alloc_extshndx;
426	}
427      if (extshndx_buf == NULL
428	  || bfd_seek (ibfd, pos, SEEK_SET) != 0
429	  || bfd_bread (extshndx_buf, amt, ibfd) != amt)
430	{
431	  intsym_buf = NULL;
432	  goto out;
433	}
434    }
435
436  if (intsym_buf == NULL)
437    {
438      bfd_size_type amt = symcount * sizeof (Elf_Internal_Sym);
439      intsym_buf = (Elf_Internal_Sym *) bfd_malloc (amt);
440      if (intsym_buf == NULL)
441	goto out;
442    }
443
444  /* Convert the symbols to internal form.  */
445  isymend = intsym_buf + symcount;
446  for (esym = extsym_buf, isym = intsym_buf, shndx = extshndx_buf;
447       isym < isymend;
448       esym += extsym_size, isym++, shndx = shndx != NULL ? shndx + 1 : NULL)
449    (*bed->s->swap_symbol_in) (ibfd, esym, (const PTR) shndx, isym);
450
451 out:
452  if (alloc_ext != NULL)
453    free (alloc_ext);
454  if (alloc_extshndx != NULL)
455    free (alloc_extshndx);
456
457  return intsym_buf;
458}
459
460/* Elf_Internal_Shdr->contents is an array of these for SHT_GROUP
461   sections.  The first element is the flags, the rest are section
462   pointers.  */
463
464typedef union elf_internal_group {
465  Elf_Internal_Shdr *shdr;
466  unsigned int flags;
467} Elf_Internal_Group;
468
469/* Return the name of the group signature symbol.  Why isn't the
470   signature just a string?  */
471
472static const char *
473group_signature (abfd, ghdr)
474     bfd *abfd;
475     Elf_Internal_Shdr *ghdr;
476{
477  Elf_Internal_Shdr *hdr;
478  unsigned char esym[sizeof (Elf64_External_Sym)];
479  Elf_External_Sym_Shndx eshndx;
480  Elf_Internal_Sym isym;
481  unsigned int iname;
482  unsigned int shindex;
483
484  /* First we need to ensure the symbol table is available.  */
485  if (! bfd_section_from_shdr (abfd, ghdr->sh_link))
486    return NULL;
487
488  /* Go read the symbol.  */
489  hdr = &elf_tdata (abfd)->symtab_hdr;
490  if (bfd_elf_get_elf_syms (abfd, hdr, 1, ghdr->sh_info,
491			    &isym, esym, &eshndx) == NULL)
492    return NULL;
493
494  /* Look up the symbol name.  */
495  iname = isym.st_name;
496  shindex = hdr->sh_link;
497  if (iname == 0 && ELF_ST_TYPE (isym.st_info) == STT_SECTION)
498    {
499      iname = elf_elfsections (abfd)[isym.st_shndx]->sh_name;
500      shindex = elf_elfheader (abfd)->e_shstrndx;
501    }
502
503  return bfd_elf_string_from_elf_section (abfd, shindex, iname);
504}
505
506/* Set next_in_group list pointer, and group name for NEWSECT.  */
507
508static boolean
509setup_group (abfd, hdr, newsect)
510     bfd *abfd;
511     Elf_Internal_Shdr *hdr;
512     asection *newsect;
513{
514  unsigned int num_group = elf_tdata (abfd)->num_group;
515
516  /* If num_group is zero, read in all SHT_GROUP sections.  The count
517     is set to -1 if there are no SHT_GROUP sections.  */
518  if (num_group == 0)
519    {
520      unsigned int i, shnum;
521
522      /* First count the number of groups.  If we have a SHT_GROUP
523	 section with just a flag word (ie. sh_size is 4), ignore it.  */
524      shnum = elf_numsections (abfd);
525      num_group = 0;
526      for (i = 0; i < shnum; i++)
527	{
528	  Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
529	  if (shdr->sh_type == SHT_GROUP && shdr->sh_size >= 8)
530	    num_group += 1;
531	}
532
533      if (num_group == 0)
534	num_group = (unsigned) -1;
535      elf_tdata (abfd)->num_group = num_group;
536
537      if (num_group > 0)
538	{
539	  /* We keep a list of elf section headers for group sections,
540	     so we can find them quickly.  */
541	  bfd_size_type amt = num_group * sizeof (Elf_Internal_Shdr *);
542	  elf_tdata (abfd)->group_sect_ptr = bfd_alloc (abfd, amt);
543	  if (elf_tdata (abfd)->group_sect_ptr == NULL)
544	    return false;
545
546	  num_group = 0;
547	  for (i = 0; i < shnum; i++)
548	    {
549	      Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
550	      if (shdr->sh_type == SHT_GROUP && shdr->sh_size >= 8)
551		{
552		  unsigned char *src;
553		  Elf_Internal_Group *dest;
554
555		  /* Add to list of sections.  */
556		  elf_tdata (abfd)->group_sect_ptr[num_group] = shdr;
557		  num_group += 1;
558
559		  /* Read the raw contents.  */
560		  BFD_ASSERT (sizeof (*dest) >= 4);
561		  amt = shdr->sh_size * sizeof (*dest) / 4;
562		  shdr->contents = bfd_alloc (abfd, amt);
563		  if (shdr->contents == NULL
564		      || bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0
565		      || (bfd_bread (shdr->contents, shdr->sh_size, abfd)
566			  != shdr->sh_size))
567		    return false;
568
569		  /* Translate raw contents, a flag word followed by an
570		     array of elf section indices all in target byte order,
571		     to the flag word followed by an array of elf section
572		     pointers.  */
573		  src = shdr->contents + shdr->sh_size;
574		  dest = (Elf_Internal_Group *) (shdr->contents + amt);
575		  while (1)
576		    {
577		      unsigned int idx;
578
579		      src -= 4;
580		      --dest;
581		      idx = H_GET_32 (abfd, src);
582		      if (src == shdr->contents)
583			{
584			  dest->flags = idx;
585			  if (shdr->bfd_section != NULL && (idx & GRP_COMDAT))
586			    shdr->bfd_section->flags
587			      |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
588			  break;
589			}
590		      if (idx >= shnum)
591			{
592			  ((*_bfd_error_handler)
593			   (_("%s: invalid SHT_GROUP entry"),
594			    bfd_archive_filename (abfd)));
595			  idx = 0;
596			}
597		      dest->shdr = elf_elfsections (abfd)[idx];
598		    }
599		}
600	    }
601	}
602    }
603
604  if (num_group != (unsigned) -1)
605    {
606      unsigned int i;
607
608      for (i = 0; i < num_group; i++)
609	{
610	  Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
611	  Elf_Internal_Group *idx = (Elf_Internal_Group *) shdr->contents;
612	  unsigned int n_elt = shdr->sh_size / 4;
613
614	  /* Look through this group's sections to see if current
615	     section is a member.  */
616	  while (--n_elt != 0)
617	    if ((++idx)->shdr == hdr)
618	      {
619		asection *s = NULL;
620
621		/* We are a member of this group.  Go looking through
622		   other members to see if any others are linked via
623		   next_in_group.  */
624		idx = (Elf_Internal_Group *) shdr->contents;
625		n_elt = shdr->sh_size / 4;
626		while (--n_elt != 0)
627		  if ((s = (++idx)->shdr->bfd_section) != NULL
628		      && elf_next_in_group (s) != NULL)
629		    break;
630		if (n_elt != 0)
631		  {
632		    /* Snarf the group name from other member, and
633		       insert current section in circular list.  */
634		    elf_group_name (newsect) = elf_group_name (s);
635		    elf_next_in_group (newsect) = elf_next_in_group (s);
636		    elf_next_in_group (s) = newsect;
637		  }
638		else
639		  {
640		    const char *gname;
641
642		    gname = group_signature (abfd, shdr);
643		    if (gname == NULL)
644		      return false;
645		    elf_group_name (newsect) = gname;
646
647		    /* Start a circular list with one element.  */
648		    elf_next_in_group (newsect) = newsect;
649		  }
650
651		/* If the group section has been created, point to the
652		   new member.  */
653		if (shdr->bfd_section != NULL)
654		  elf_next_in_group (shdr->bfd_section) = newsect;
655
656		i = num_group - 1;
657		break;
658	      }
659	}
660    }
661
662  if (elf_group_name (newsect) == NULL)
663    {
664      (*_bfd_error_handler) (_("%s: no group info for section %s"),
665			     bfd_archive_filename (abfd), newsect->name);
666    }
667  return true;
668}
669
670boolean
671bfd_elf_discard_group (abfd, group)
672     bfd *abfd ATTRIBUTE_UNUSED;
673     asection *group;
674{
675  asection *first = elf_next_in_group (group);
676  asection *s = first;
677
678  while (s != NULL)
679    {
680      s->output_section = bfd_abs_section_ptr;
681      s = elf_next_in_group (s);
682      /* These lists are circular.  */
683      if (s == first)
684	break;
685    }
686  return true;
687}
688
689/* Make a BFD section from an ELF section.  We store a pointer to the
690   BFD section in the bfd_section field of the header.  */
691
692boolean
693_bfd_elf_make_section_from_shdr (abfd, hdr, name)
694     bfd *abfd;
695     Elf_Internal_Shdr *hdr;
696     const char *name;
697{
698  asection *newsect;
699  flagword flags;
700  struct elf_backend_data *bed;
701
702  if (hdr->bfd_section != NULL)
703    {
704      BFD_ASSERT (strcmp (name,
705			  bfd_get_section_name (abfd, hdr->bfd_section)) == 0);
706      return true;
707    }
708
709  newsect = bfd_make_section_anyway (abfd, name);
710  if (newsect == NULL)
711    return false;
712
713  newsect->filepos = hdr->sh_offset;
714
715  if (! bfd_set_section_vma (abfd, newsect, hdr->sh_addr)
716      || ! bfd_set_section_size (abfd, newsect, hdr->sh_size)
717      || ! bfd_set_section_alignment (abfd, newsect,
718				      bfd_log2 ((bfd_vma) hdr->sh_addralign)))
719    return false;
720
721  flags = SEC_NO_FLAGS;
722  if (hdr->sh_type != SHT_NOBITS)
723    flags |= SEC_HAS_CONTENTS;
724  if (hdr->sh_type == SHT_GROUP)
725    flags |= SEC_GROUP | SEC_EXCLUDE;
726  if ((hdr->sh_flags & SHF_ALLOC) != 0)
727    {
728      flags |= SEC_ALLOC;
729      if (hdr->sh_type != SHT_NOBITS)
730	flags |= SEC_LOAD;
731    }
732  if ((hdr->sh_flags & SHF_WRITE) == 0)
733    flags |= SEC_READONLY;
734  if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
735    flags |= SEC_CODE;
736  else if ((flags & SEC_LOAD) != 0)
737    flags |= SEC_DATA;
738  if ((hdr->sh_flags & SHF_MERGE) != 0)
739    {
740      flags |= SEC_MERGE;
741      newsect->entsize = hdr->sh_entsize;
742      if ((hdr->sh_flags & SHF_STRINGS) != 0)
743	flags |= SEC_STRINGS;
744    }
745  if (hdr->sh_flags & SHF_GROUP)
746    if (!setup_group (abfd, hdr, newsect))
747      return false;
748  if ((hdr->sh_flags & SHF_TLS) != 0)
749    flags |= SEC_THREAD_LOCAL;
750
751  /* The debugging sections appear to be recognized only by name, not
752     any sort of flag.  */
753  {
754    static const char *debug_sec_names [] =
755    {
756      ".debug",
757      ".gnu.linkonce.wi.",
758      ".line",
759      ".stab"
760    };
761    int i;
762
763    for (i = ARRAY_SIZE (debug_sec_names); i--;)
764      if (strncmp (name, debug_sec_names[i], strlen (debug_sec_names[i])) == 0)
765	break;
766
767    if (i >= 0)
768      flags |= SEC_DEBUGGING;
769  }
770
771  /* As a GNU extension, if the name begins with .gnu.linkonce, we
772     only link a single copy of the section.  This is used to support
773     g++.  g++ will emit each template expansion in its own section.
774     The symbols will be defined as weak, so that multiple definitions
775     are permitted.  The GNU linker extension is to actually discard
776     all but one of the sections.  */
777  if (strncmp (name, ".gnu.linkonce", sizeof ".gnu.linkonce" - 1) == 0
778      && elf_next_in_group (newsect) == NULL)
779    flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
780
781  bed = get_elf_backend_data (abfd);
782  if (bed->elf_backend_section_flags)
783    if (! bed->elf_backend_section_flags (&flags, hdr))
784      return false;
785
786  if (! bfd_set_section_flags (abfd, newsect, flags))
787    return false;
788
789  if ((flags & SEC_ALLOC) != 0)
790    {
791      Elf_Internal_Phdr *phdr;
792      unsigned int i;
793
794      /* Look through the phdrs to see if we need to adjust the lma.
795         If all the p_paddr fields are zero, we ignore them, since
796         some ELF linkers produce such output.  */
797      phdr = elf_tdata (abfd)->phdr;
798      for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
799	{
800	  if (phdr->p_paddr != 0)
801	    break;
802	}
803      if (i < elf_elfheader (abfd)->e_phnum)
804	{
805	  phdr = elf_tdata (abfd)->phdr;
806	  for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
807	    {
808	      /* This section is part of this segment if its file
809		 offset plus size lies within the segment's memory
810		 span and, if the section is loaded, the extent of the
811		 loaded data lies within the extent of the segment.
812
813		 Note - we used to check the p_paddr field as well, and
814		 refuse to set the LMA if it was 0.  This is wrong
815		 though, as a perfectly valid initialised segment can
816		 have a p_paddr of zero.  Some architectures, eg ARM,
817	         place special significance on the address 0 and
818	         executables need to be able to have a segment which
819	         covers this address.  */
820	      if (phdr->p_type == PT_LOAD
821		  && (bfd_vma) hdr->sh_offset >= phdr->p_offset
822		  && (hdr->sh_offset + hdr->sh_size
823		      <= phdr->p_offset + phdr->p_memsz)
824		  && ((flags & SEC_LOAD) == 0
825		      || (hdr->sh_offset + hdr->sh_size
826			  <= phdr->p_offset + phdr->p_filesz)))
827		{
828		  if ((flags & SEC_LOAD) == 0)
829		    newsect->lma = (phdr->p_paddr
830				    + hdr->sh_addr - phdr->p_vaddr);
831		  else
832		    /* We used to use the same adjustment for SEC_LOAD
833		       sections, but that doesn't work if the segment
834		       is packed with code from multiple VMAs.
835		       Instead we calculate the section LMA based on
836		       the segment LMA.  It is assumed that the
837		       segment will contain sections with contiguous
838		       LMAs, even if the VMAs are not.  */
839		    newsect->lma = (phdr->p_paddr
840				    + hdr->sh_offset - phdr->p_offset);
841
842		  /* With contiguous segments, we can't tell from file
843		     offsets whether a section with zero size should
844		     be placed at the end of one segment or the
845		     beginning of the next.  Decide based on vaddr.  */
846		  if (hdr->sh_addr >= phdr->p_vaddr
847		      && (hdr->sh_addr + hdr->sh_size
848			  <= phdr->p_vaddr + phdr->p_memsz))
849		    break;
850		}
851	    }
852	}
853    }
854
855  hdr->bfd_section = newsect;
856  elf_section_data (newsect)->this_hdr = *hdr;
857
858  return true;
859}
860
861/*
862INTERNAL_FUNCTION
863	bfd_elf_find_section
864
865SYNOPSIS
866	struct elf_internal_shdr *bfd_elf_find_section (bfd *abfd, char *name);
867
868DESCRIPTION
869	Helper functions for GDB to locate the string tables.
870	Since BFD hides string tables from callers, GDB needs to use an
871	internal hook to find them.  Sun's .stabstr, in particular,
872	isn't even pointed to by the .stab section, so ordinary
873	mechanisms wouldn't work to find it, even if we had some.
874*/
875
876struct elf_internal_shdr *
877bfd_elf_find_section (abfd, name)
878     bfd *abfd;
879     char *name;
880{
881  Elf_Internal_Shdr **i_shdrp;
882  char *shstrtab;
883  unsigned int max;
884  unsigned int i;
885
886  i_shdrp = elf_elfsections (abfd);
887  if (i_shdrp != NULL)
888    {
889      shstrtab = bfd_elf_get_str_section (abfd,
890					  elf_elfheader (abfd)->e_shstrndx);
891      if (shstrtab != NULL)
892	{
893	  max = elf_numsections (abfd);
894	  for (i = 1; i < max; i++)
895	    if (!strcmp (&shstrtab[i_shdrp[i]->sh_name], name))
896	      return i_shdrp[i];
897	}
898    }
899  return 0;
900}
901
902const char *const bfd_elf_section_type_names[] = {
903  "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB",
904  "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE",
905  "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM",
906};
907
908/* ELF relocs are against symbols.  If we are producing relocateable
909   output, and the reloc is against an external symbol, and nothing
910   has given us any additional addend, the resulting reloc will also
911   be against the same symbol.  In such a case, we don't want to
912   change anything about the way the reloc is handled, since it will
913   all be done at final link time.  Rather than put special case code
914   into bfd_perform_relocation, all the reloc types use this howto
915   function.  It just short circuits the reloc if producing
916   relocateable output against an external symbol.  */
917
918bfd_reloc_status_type
919bfd_elf_generic_reloc (abfd,
920		       reloc_entry,
921		       symbol,
922		       data,
923		       input_section,
924		       output_bfd,
925		       error_message)
926     bfd *abfd ATTRIBUTE_UNUSED;
927     arelent *reloc_entry;
928     asymbol *symbol;
929     PTR data ATTRIBUTE_UNUSED;
930     asection *input_section;
931     bfd *output_bfd;
932     char **error_message ATTRIBUTE_UNUSED;
933{
934  if (output_bfd != (bfd *) NULL
935      && (symbol->flags & BSF_SECTION_SYM) == 0
936      && (! reloc_entry->howto->partial_inplace
937	  || reloc_entry->addend == 0))
938    {
939      reloc_entry->address += input_section->output_offset;
940      return bfd_reloc_ok;
941    }
942
943  return bfd_reloc_continue;
944}
945
946/* Make sure sec_info_type is cleared if sec_info is cleared too.  */
947
948static void
949merge_sections_remove_hook (abfd, sec)
950     bfd *abfd ATTRIBUTE_UNUSED;
951     asection *sec;
952{
953  struct bfd_elf_section_data *sec_data;
954
955  sec_data = elf_section_data (sec);
956  BFD_ASSERT (sec_data->sec_info_type == ELF_INFO_TYPE_MERGE);
957  sec_data->sec_info_type = ELF_INFO_TYPE_NONE;
958}
959
960/* Finish SHF_MERGE section merging.  */
961
962boolean
963_bfd_elf_merge_sections (abfd, info)
964     bfd *abfd;
965     struct bfd_link_info *info;
966{
967  if (!is_elf_hash_table (info))
968    return false;
969  if (elf_hash_table (info)->merge_info)
970    _bfd_merge_sections (abfd, elf_hash_table (info)->merge_info,
971			 merge_sections_remove_hook);
972  return true;
973}
974
975void
976_bfd_elf_link_just_syms (sec, info)
977     asection *sec;
978     struct bfd_link_info *info;
979{
980  sec->output_section = bfd_abs_section_ptr;
981  sec->output_offset = sec->vma;
982  if (!is_elf_hash_table (info))
983    return;
984
985  elf_section_data (sec)->sec_info_type = ELF_INFO_TYPE_JUST_SYMS;
986}
987
988/* Copy the program header and other data from one object module to
989   another.  */
990
991boolean
992_bfd_elf_copy_private_bfd_data (ibfd, obfd)
993     bfd *ibfd;
994     bfd *obfd;
995{
996  if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
997      || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
998    return true;
999
1000  BFD_ASSERT (!elf_flags_init (obfd)
1001	      || (elf_elfheader (obfd)->e_flags
1002		  == elf_elfheader (ibfd)->e_flags));
1003
1004  elf_gp (obfd) = elf_gp (ibfd);
1005  elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags;
1006  elf_flags_init (obfd) = true;
1007  return true;
1008}
1009
1010/* Print out the program headers.  */
1011
1012boolean
1013_bfd_elf_print_private_bfd_data (abfd, farg)
1014     bfd *abfd;
1015     PTR farg;
1016{
1017  FILE *f = (FILE *) farg;
1018  Elf_Internal_Phdr *p;
1019  asection *s;
1020  bfd_byte *dynbuf = NULL;
1021
1022  p = elf_tdata (abfd)->phdr;
1023  if (p != NULL)
1024    {
1025      unsigned int i, c;
1026
1027      fprintf (f, _("\nProgram Header:\n"));
1028      c = elf_elfheader (abfd)->e_phnum;
1029      for (i = 0; i < c; i++, p++)
1030	{
1031	  const char *pt;
1032	  char buf[20];
1033
1034	  switch (p->p_type)
1035	    {
1036	    case PT_NULL: pt = "NULL"; break;
1037	    case PT_LOAD: pt = "LOAD"; break;
1038	    case PT_DYNAMIC: pt = "DYNAMIC"; break;
1039	    case PT_INTERP: pt = "INTERP"; break;
1040	    case PT_NOTE: pt = "NOTE"; break;
1041	    case PT_SHLIB: pt = "SHLIB"; break;
1042	    case PT_PHDR: pt = "PHDR"; break;
1043	    case PT_TLS: pt = "TLS"; break;
1044	    case PT_GNU_EH_FRAME: pt = "EH_FRAME"; break;
1045	    default: sprintf (buf, "0x%lx", p->p_type); pt = buf; break;
1046	    }
1047	  fprintf (f, "%8s off    0x", pt);
1048	  bfd_fprintf_vma (abfd, f, p->p_offset);
1049	  fprintf (f, " vaddr 0x");
1050	  bfd_fprintf_vma (abfd, f, p->p_vaddr);
1051	  fprintf (f, " paddr 0x");
1052	  bfd_fprintf_vma (abfd, f, p->p_paddr);
1053	  fprintf (f, " align 2**%u\n", bfd_log2 (p->p_align));
1054	  fprintf (f, "         filesz 0x");
1055	  bfd_fprintf_vma (abfd, f, p->p_filesz);
1056	  fprintf (f, " memsz 0x");
1057	  bfd_fprintf_vma (abfd, f, p->p_memsz);
1058	  fprintf (f, " flags %c%c%c",
1059		   (p->p_flags & PF_R) != 0 ? 'r' : '-',
1060		   (p->p_flags & PF_W) != 0 ? 'w' : '-',
1061		   (p->p_flags & PF_X) != 0 ? 'x' : '-');
1062	  if ((p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X)) != 0)
1063	    fprintf (f, " %lx", p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X));
1064	  fprintf (f, "\n");
1065	}
1066    }
1067
1068  s = bfd_get_section_by_name (abfd, ".dynamic");
1069  if (s != NULL)
1070    {
1071      int elfsec;
1072      unsigned long shlink;
1073      bfd_byte *extdyn, *extdynend;
1074      size_t extdynsize;
1075      void (*swap_dyn_in) PARAMS ((bfd *, const PTR, Elf_Internal_Dyn *));
1076
1077      fprintf (f, _("\nDynamic Section:\n"));
1078
1079      dynbuf = (bfd_byte *) bfd_malloc (s->_raw_size);
1080      if (dynbuf == NULL)
1081	goto error_return;
1082      if (! bfd_get_section_contents (abfd, s, (PTR) dynbuf, (file_ptr) 0,
1083				      s->_raw_size))
1084	goto error_return;
1085
1086      elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
1087      if (elfsec == -1)
1088	goto error_return;
1089      shlink = elf_elfsections (abfd)[elfsec]->sh_link;
1090
1091      extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
1092      swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
1093
1094      extdyn = dynbuf;
1095      extdynend = extdyn + s->_raw_size;
1096      for (; extdyn < extdynend; extdyn += extdynsize)
1097	{
1098	  Elf_Internal_Dyn dyn;
1099	  const char *name;
1100	  char ab[20];
1101	  boolean stringp;
1102
1103	  (*swap_dyn_in) (abfd, (PTR) extdyn, &dyn);
1104
1105	  if (dyn.d_tag == DT_NULL)
1106	    break;
1107
1108	  stringp = false;
1109	  switch (dyn.d_tag)
1110	    {
1111	    default:
1112	      sprintf (ab, "0x%lx", (unsigned long) dyn.d_tag);
1113	      name = ab;
1114	      break;
1115
1116	    case DT_NEEDED: name = "NEEDED"; stringp = true; break;
1117	    case DT_PLTRELSZ: name = "PLTRELSZ"; break;
1118	    case DT_PLTGOT: name = "PLTGOT"; break;
1119	    case DT_HASH: name = "HASH"; break;
1120	    case DT_STRTAB: name = "STRTAB"; break;
1121	    case DT_SYMTAB: name = "SYMTAB"; break;
1122	    case DT_RELA: name = "RELA"; break;
1123	    case DT_RELASZ: name = "RELASZ"; break;
1124	    case DT_RELAENT: name = "RELAENT"; break;
1125	    case DT_STRSZ: name = "STRSZ"; break;
1126	    case DT_SYMENT: name = "SYMENT"; break;
1127	    case DT_INIT: name = "INIT"; break;
1128	    case DT_FINI: name = "FINI"; break;
1129	    case DT_SONAME: name = "SONAME"; stringp = true; break;
1130	    case DT_RPATH: name = "RPATH"; stringp = true; break;
1131	    case DT_SYMBOLIC: name = "SYMBOLIC"; break;
1132	    case DT_REL: name = "REL"; break;
1133	    case DT_RELSZ: name = "RELSZ"; break;
1134	    case DT_RELENT: name = "RELENT"; break;
1135	    case DT_PLTREL: name = "PLTREL"; break;
1136	    case DT_DEBUG: name = "DEBUG"; break;
1137	    case DT_TEXTREL: name = "TEXTREL"; break;
1138	    case DT_JMPREL: name = "JMPREL"; break;
1139	    case DT_BIND_NOW: name = "BIND_NOW"; break;
1140	    case DT_INIT_ARRAY: name = "INIT_ARRAY"; break;
1141	    case DT_FINI_ARRAY: name = "FINI_ARRAY"; break;
1142	    case DT_INIT_ARRAYSZ: name = "INIT_ARRAYSZ"; break;
1143	    case DT_FINI_ARRAYSZ: name = "FINI_ARRAYSZ"; break;
1144	    case DT_RUNPATH: name = "RUNPATH"; stringp = true; break;
1145	    case DT_FLAGS: name = "FLAGS"; break;
1146	    case DT_PREINIT_ARRAY: name = "PREINIT_ARRAY"; break;
1147	    case DT_PREINIT_ARRAYSZ: name = "PREINIT_ARRAYSZ"; break;
1148	    case DT_CHECKSUM: name = "CHECKSUM"; break;
1149	    case DT_PLTPADSZ: name = "PLTPADSZ"; break;
1150	    case DT_MOVEENT: name = "MOVEENT"; break;
1151	    case DT_MOVESZ: name = "MOVESZ"; break;
1152	    case DT_FEATURE: name = "FEATURE"; break;
1153	    case DT_POSFLAG_1: name = "POSFLAG_1"; break;
1154	    case DT_SYMINSZ: name = "SYMINSZ"; break;
1155	    case DT_SYMINENT: name = "SYMINENT"; break;
1156	    case DT_CONFIG: name = "CONFIG"; stringp = true; break;
1157	    case DT_DEPAUDIT: name = "DEPAUDIT"; stringp = true; break;
1158	    case DT_AUDIT: name = "AUDIT"; stringp = true; break;
1159	    case DT_PLTPAD: name = "PLTPAD"; break;
1160	    case DT_MOVETAB: name = "MOVETAB"; break;
1161	    case DT_SYMINFO: name = "SYMINFO"; break;
1162	    case DT_RELACOUNT: name = "RELACOUNT"; break;
1163	    case DT_RELCOUNT: name = "RELCOUNT"; break;
1164	    case DT_FLAGS_1: name = "FLAGS_1"; break;
1165	    case DT_VERSYM: name = "VERSYM"; break;
1166	    case DT_VERDEF: name = "VERDEF"; break;
1167	    case DT_VERDEFNUM: name = "VERDEFNUM"; break;
1168	    case DT_VERNEED: name = "VERNEED"; break;
1169	    case DT_VERNEEDNUM: name = "VERNEEDNUM"; break;
1170	    case DT_AUXILIARY: name = "AUXILIARY"; stringp = true; break;
1171	    case DT_USED: name = "USED"; break;
1172	    case DT_FILTER: name = "FILTER"; stringp = true; break;
1173	    }
1174
1175	  fprintf (f, "  %-11s ", name);
1176	  if (! stringp)
1177	    fprintf (f, "0x%lx", (unsigned long) dyn.d_un.d_val);
1178	  else
1179	    {
1180	      const char *string;
1181	      unsigned int tagv = dyn.d_un.d_val;
1182
1183	      string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
1184	      if (string == NULL)
1185		goto error_return;
1186	      fprintf (f, "%s", string);
1187	    }
1188	  fprintf (f, "\n");
1189	}
1190
1191      free (dynbuf);
1192      dynbuf = NULL;
1193    }
1194
1195  if ((elf_dynverdef (abfd) != 0 && elf_tdata (abfd)->verdef == NULL)
1196      || (elf_dynverref (abfd) != 0 && elf_tdata (abfd)->verref == NULL))
1197    {
1198      if (! _bfd_elf_slurp_version_tables (abfd))
1199	return false;
1200    }
1201
1202  if (elf_dynverdef (abfd) != 0)
1203    {
1204      Elf_Internal_Verdef *t;
1205
1206      fprintf (f, _("\nVersion definitions:\n"));
1207      for (t = elf_tdata (abfd)->verdef; t != NULL; t = t->vd_nextdef)
1208	{
1209	  fprintf (f, "%d 0x%2.2x 0x%8.8lx %s\n", t->vd_ndx,
1210		   t->vd_flags, t->vd_hash, t->vd_nodename);
1211	  if (t->vd_auxptr->vda_nextptr != NULL)
1212	    {
1213	      Elf_Internal_Verdaux *a;
1214
1215	      fprintf (f, "\t");
1216	      for (a = t->vd_auxptr->vda_nextptr;
1217		   a != NULL;
1218		   a = a->vda_nextptr)
1219		fprintf (f, "%s ", a->vda_nodename);
1220	      fprintf (f, "\n");
1221	    }
1222	}
1223    }
1224
1225  if (elf_dynverref (abfd) != 0)
1226    {
1227      Elf_Internal_Verneed *t;
1228
1229      fprintf (f, _("\nVersion References:\n"));
1230      for (t = elf_tdata (abfd)->verref; t != NULL; t = t->vn_nextref)
1231	{
1232	  Elf_Internal_Vernaux *a;
1233
1234	  fprintf (f, _("  required from %s:\n"), t->vn_filename);
1235	  for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1236	    fprintf (f, "    0x%8.8lx 0x%2.2x %2.2d %s\n", a->vna_hash,
1237		     a->vna_flags, a->vna_other, a->vna_nodename);
1238	}
1239    }
1240
1241  return true;
1242
1243 error_return:
1244  if (dynbuf != NULL)
1245    free (dynbuf);
1246  return false;
1247}
1248
1249/* Display ELF-specific fields of a symbol.  */
1250
1251void
1252bfd_elf_print_symbol (abfd, filep, symbol, how)
1253     bfd *abfd;
1254     PTR filep;
1255     asymbol *symbol;
1256     bfd_print_symbol_type how;
1257{
1258  FILE *file = (FILE *) filep;
1259  switch (how)
1260    {
1261    case bfd_print_symbol_name:
1262      fprintf (file, "%s", symbol->name);
1263      break;
1264    case bfd_print_symbol_more:
1265      fprintf (file, "elf ");
1266      bfd_fprintf_vma (abfd, file, symbol->value);
1267      fprintf (file, " %lx", (long) symbol->flags);
1268      break;
1269    case bfd_print_symbol_all:
1270      {
1271	const char *section_name;
1272	const char *name = NULL;
1273	struct elf_backend_data *bed;
1274	unsigned char st_other;
1275	bfd_vma val;
1276
1277	section_name = symbol->section ? symbol->section->name : "(*none*)";
1278
1279	bed = get_elf_backend_data (abfd);
1280	if (bed->elf_backend_print_symbol_all)
1281	  name = (*bed->elf_backend_print_symbol_all) (abfd, filep, symbol);
1282
1283	if (name == NULL)
1284	  {
1285	    name = symbol->name;
1286	    bfd_print_symbol_vandf (abfd, (PTR) file, symbol);
1287	  }
1288
1289	fprintf (file, " %s\t", section_name);
1290	/* Print the "other" value for a symbol.  For common symbols,
1291	   we've already printed the size; now print the alignment.
1292	   For other symbols, we have no specified alignment, and
1293	   we've printed the address; now print the size.  */
1294	if (bfd_is_com_section (symbol->section))
1295	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_value;
1296	else
1297	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_size;
1298	bfd_fprintf_vma (abfd, file, val);
1299
1300	/* If we have version information, print it.  */
1301	if (elf_tdata (abfd)->dynversym_section != 0
1302	    && (elf_tdata (abfd)->dynverdef_section != 0
1303		|| elf_tdata (abfd)->dynverref_section != 0))
1304	  {
1305	    unsigned int vernum;
1306	    const char *version_string;
1307
1308	    vernum = ((elf_symbol_type *) symbol)->version & VERSYM_VERSION;
1309
1310	    if (vernum == 0)
1311	      version_string = "";
1312	    else if (vernum == 1)
1313	      version_string = "Base";
1314	    else if (vernum <= elf_tdata (abfd)->cverdefs)
1315	      version_string =
1316		elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
1317	    else
1318	      {
1319		Elf_Internal_Verneed *t;
1320
1321		version_string = "";
1322		for (t = elf_tdata (abfd)->verref;
1323		     t != NULL;
1324		     t = t->vn_nextref)
1325		  {
1326		    Elf_Internal_Vernaux *a;
1327
1328		    for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1329		      {
1330			if (a->vna_other == vernum)
1331			  {
1332			    version_string = a->vna_nodename;
1333			    break;
1334			  }
1335		      }
1336		  }
1337	      }
1338
1339	    if ((((elf_symbol_type *) symbol)->version & VERSYM_HIDDEN) == 0)
1340	      fprintf (file, "  %-11s", version_string);
1341	    else
1342	      {
1343		int i;
1344
1345		fprintf (file, " (%s)", version_string);
1346		for (i = 10 - strlen (version_string); i > 0; --i)
1347		  putc (' ', file);
1348	      }
1349	  }
1350
1351	/* If the st_other field is not zero, print it.  */
1352	st_other = ((elf_symbol_type *) symbol)->internal_elf_sym.st_other;
1353
1354	switch (st_other)
1355	  {
1356	  case 0: break;
1357	  case STV_INTERNAL:  fprintf (file, " .internal");  break;
1358	  case STV_HIDDEN:    fprintf (file, " .hidden");    break;
1359	  case STV_PROTECTED: fprintf (file, " .protected"); break;
1360	  default:
1361	    /* Some other non-defined flags are also present, so print
1362	       everything hex.  */
1363	    fprintf (file, " 0x%02x", (unsigned int) st_other);
1364	  }
1365
1366	fprintf (file, " %s", name);
1367      }
1368      break;
1369    }
1370}
1371
1372/* Create an entry in an ELF linker hash table.  */
1373
1374struct bfd_hash_entry *
1375_bfd_elf_link_hash_newfunc (entry, table, string)
1376     struct bfd_hash_entry *entry;
1377     struct bfd_hash_table *table;
1378     const char *string;
1379{
1380  /* Allocate the structure if it has not already been allocated by a
1381     subclass.  */
1382  if (entry == NULL)
1383    {
1384      entry = bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
1385      if (entry == NULL)
1386	return entry;
1387    }
1388
1389  /* Call the allocation method of the superclass.  */
1390  entry = _bfd_link_hash_newfunc (entry, table, string);
1391  if (entry != NULL)
1392    {
1393      struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
1394      struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
1395
1396      /* Set local fields.  */
1397      ret->indx = -1;
1398      ret->size = 0;
1399      ret->dynindx = -1;
1400      ret->dynstr_index = 0;
1401      ret->weakdef = NULL;
1402      ret->got.refcount = htab->init_refcount;
1403      ret->plt.refcount = htab->init_refcount;
1404      ret->linker_section_pointer = NULL;
1405      ret->verinfo.verdef = NULL;
1406      ret->vtable_entries_used = NULL;
1407      ret->vtable_entries_size = 0;
1408      ret->vtable_parent = NULL;
1409      ret->type = STT_NOTYPE;
1410      ret->other = 0;
1411      /* Assume that we have been called by a non-ELF symbol reader.
1412         This flag is then reset by the code which reads an ELF input
1413         file.  This ensures that a symbol created by a non-ELF symbol
1414         reader will have the flag set correctly.  */
1415      ret->elf_link_hash_flags = ELF_LINK_NON_ELF;
1416    }
1417
1418  return entry;
1419}
1420
1421/* Copy data from an indirect symbol to its direct symbol, hiding the
1422   old indirect symbol.  Also used for copying flags to a weakdef.  */
1423
1424void
1425_bfd_elf_link_hash_copy_indirect (bed, dir, ind)
1426     struct elf_backend_data *bed;
1427     struct elf_link_hash_entry *dir, *ind;
1428{
1429  bfd_signed_vma tmp;
1430  bfd_signed_vma lowest_valid = bed->can_refcount;
1431
1432  /* Copy down any references that we may have already seen to the
1433     symbol which just became indirect.  */
1434
1435  dir->elf_link_hash_flags |=
1436    (ind->elf_link_hash_flags
1437     & (ELF_LINK_HASH_REF_DYNAMIC
1438	| ELF_LINK_HASH_REF_REGULAR
1439	| ELF_LINK_HASH_REF_REGULAR_NONWEAK
1440	| ELF_LINK_NON_GOT_REF));
1441
1442  if (ind->root.type != bfd_link_hash_indirect)
1443    return;
1444
1445  /* Copy over the global and procedure linkage table refcount entries.
1446     These may have been already set up by a check_relocs routine.  */
1447  tmp = dir->got.refcount;
1448  if (tmp < lowest_valid)
1449    {
1450      dir->got.refcount = ind->got.refcount;
1451      ind->got.refcount = tmp;
1452    }
1453  else
1454    BFD_ASSERT (ind->got.refcount < lowest_valid);
1455
1456  tmp = dir->plt.refcount;
1457  if (tmp < lowest_valid)
1458    {
1459      dir->plt.refcount = ind->plt.refcount;
1460      ind->plt.refcount = tmp;
1461    }
1462  else
1463    BFD_ASSERT (ind->plt.refcount < lowest_valid);
1464
1465  if (dir->dynindx == -1)
1466    {
1467      dir->dynindx = ind->dynindx;
1468      dir->dynstr_index = ind->dynstr_index;
1469      ind->dynindx = -1;
1470      ind->dynstr_index = 0;
1471    }
1472  else
1473    BFD_ASSERT (ind->dynindx == -1);
1474}
1475
1476void
1477_bfd_elf_link_hash_hide_symbol (info, h, force_local)
1478     struct bfd_link_info *info;
1479     struct elf_link_hash_entry *h;
1480     boolean force_local;
1481{
1482  h->plt.offset = (bfd_vma) -1;
1483  h->elf_link_hash_flags &= ~ELF_LINK_HASH_NEEDS_PLT;
1484  if (force_local)
1485    {
1486      h->elf_link_hash_flags |= ELF_LINK_FORCED_LOCAL;
1487      if (h->dynindx != -1)
1488	{
1489	  h->dynindx = -1;
1490	  _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
1491				  h->dynstr_index);
1492	}
1493    }
1494}
1495
1496/* Initialize an ELF linker hash table.  */
1497
1498boolean
1499_bfd_elf_link_hash_table_init (table, abfd, newfunc)
1500     struct elf_link_hash_table *table;
1501     bfd *abfd;
1502     struct bfd_hash_entry *(*newfunc) PARAMS ((struct bfd_hash_entry *,
1503						struct bfd_hash_table *,
1504						const char *));
1505{
1506  boolean ret;
1507
1508  table->dynamic_sections_created = false;
1509  table->dynobj = NULL;
1510  table->init_refcount = get_elf_backend_data (abfd)->can_refcount - 1;
1511  /* The first dynamic symbol is a dummy.  */
1512  table->dynsymcount = 1;
1513  table->dynstr = NULL;
1514  table->bucketcount = 0;
1515  table->needed = NULL;
1516  table->runpath = NULL;
1517  table->loaded = NULL;
1518  table->hgot = NULL;
1519  table->stab_info = NULL;
1520  table->merge_info = NULL;
1521  table->dynlocal = NULL;
1522  ret = _bfd_link_hash_table_init (& table->root, abfd, newfunc);
1523  table->root.type = bfd_link_elf_hash_table;
1524
1525  return ret;
1526}
1527
1528/* Create an ELF linker hash table.  */
1529
1530struct bfd_link_hash_table *
1531_bfd_elf_link_hash_table_create (abfd)
1532     bfd *abfd;
1533{
1534  struct elf_link_hash_table *ret;
1535  bfd_size_type amt = sizeof (struct elf_link_hash_table);
1536
1537  ret = (struct elf_link_hash_table *) bfd_malloc (amt);
1538  if (ret == (struct elf_link_hash_table *) NULL)
1539    return NULL;
1540
1541  if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc))
1542    {
1543      free (ret);
1544      return NULL;
1545    }
1546
1547  return &ret->root;
1548}
1549
1550/* This is a hook for the ELF emulation code in the generic linker to
1551   tell the backend linker what file name to use for the DT_NEEDED
1552   entry for a dynamic object.  The generic linker passes name as an
1553   empty string to indicate that no DT_NEEDED entry should be made.  */
1554
1555void
1556bfd_elf_set_dt_needed_name (abfd, name)
1557     bfd *abfd;
1558     const char *name;
1559{
1560  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1561      && bfd_get_format (abfd) == bfd_object)
1562    elf_dt_name (abfd) = name;
1563}
1564
1565void
1566bfd_elf_set_dt_needed_soname (abfd, name)
1567     bfd *abfd;
1568     const char *name;
1569{
1570  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1571      && bfd_get_format (abfd) == bfd_object)
1572    elf_dt_soname (abfd) = name;
1573}
1574
1575/* Get the list of DT_NEEDED entries for a link.  This is a hook for
1576   the linker ELF emulation code.  */
1577
1578struct bfd_link_needed_list *
1579bfd_elf_get_needed_list (abfd, info)
1580     bfd *abfd ATTRIBUTE_UNUSED;
1581     struct bfd_link_info *info;
1582{
1583  if (info->hash->creator->flavour != bfd_target_elf_flavour)
1584    return NULL;
1585  return elf_hash_table (info)->needed;
1586}
1587
1588/* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
1589   hook for the linker ELF emulation code.  */
1590
1591struct bfd_link_needed_list *
1592bfd_elf_get_runpath_list (abfd, info)
1593     bfd *abfd ATTRIBUTE_UNUSED;
1594     struct bfd_link_info *info;
1595{
1596  if (info->hash->creator->flavour != bfd_target_elf_flavour)
1597    return NULL;
1598  return elf_hash_table (info)->runpath;
1599}
1600
1601/* Get the name actually used for a dynamic object for a link.  This
1602   is the SONAME entry if there is one.  Otherwise, it is the string
1603   passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
1604
1605const char *
1606bfd_elf_get_dt_soname (abfd)
1607     bfd *abfd;
1608{
1609  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1610      && bfd_get_format (abfd) == bfd_object)
1611    return elf_dt_name (abfd);
1612  return NULL;
1613}
1614
1615/* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
1616   the ELF linker emulation code.  */
1617
1618boolean
1619bfd_elf_get_bfd_needed_list (abfd, pneeded)
1620     bfd *abfd;
1621     struct bfd_link_needed_list **pneeded;
1622{
1623  asection *s;
1624  bfd_byte *dynbuf = NULL;
1625  int elfsec;
1626  unsigned long shlink;
1627  bfd_byte *extdyn, *extdynend;
1628  size_t extdynsize;
1629  void (*swap_dyn_in) PARAMS ((bfd *, const PTR, Elf_Internal_Dyn *));
1630
1631  *pneeded = NULL;
1632
1633  if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
1634      || bfd_get_format (abfd) != bfd_object)
1635    return true;
1636
1637  s = bfd_get_section_by_name (abfd, ".dynamic");
1638  if (s == NULL || s->_raw_size == 0)
1639    return true;
1640
1641  dynbuf = (bfd_byte *) bfd_malloc (s->_raw_size);
1642  if (dynbuf == NULL)
1643    goto error_return;
1644
1645  if (! bfd_get_section_contents (abfd, s, (PTR) dynbuf, (file_ptr) 0,
1646				  s->_raw_size))
1647    goto error_return;
1648
1649  elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
1650  if (elfsec == -1)
1651    goto error_return;
1652
1653  shlink = elf_elfsections (abfd)[elfsec]->sh_link;
1654
1655  extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
1656  swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
1657
1658  extdyn = dynbuf;
1659  extdynend = extdyn + s->_raw_size;
1660  for (; extdyn < extdynend; extdyn += extdynsize)
1661    {
1662      Elf_Internal_Dyn dyn;
1663
1664      (*swap_dyn_in) (abfd, (PTR) extdyn, &dyn);
1665
1666      if (dyn.d_tag == DT_NULL)
1667	break;
1668
1669      if (dyn.d_tag == DT_NEEDED)
1670	{
1671	  const char *string;
1672	  struct bfd_link_needed_list *l;
1673	  unsigned int tagv = dyn.d_un.d_val;
1674	  bfd_size_type amt;
1675
1676	  string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
1677	  if (string == NULL)
1678	    goto error_return;
1679
1680	  amt = sizeof *l;
1681	  l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
1682	  if (l == NULL)
1683	    goto error_return;
1684
1685	  l->by = abfd;
1686	  l->name = string;
1687	  l->next = *pneeded;
1688	  *pneeded = l;
1689	}
1690    }
1691
1692  free (dynbuf);
1693
1694  return true;
1695
1696 error_return:
1697  if (dynbuf != NULL)
1698    free (dynbuf);
1699  return false;
1700}
1701
1702/* Allocate an ELF string table--force the first byte to be zero.  */
1703
1704struct bfd_strtab_hash *
1705_bfd_elf_stringtab_init ()
1706{
1707  struct bfd_strtab_hash *ret;
1708
1709  ret = _bfd_stringtab_init ();
1710  if (ret != NULL)
1711    {
1712      bfd_size_type loc;
1713
1714      loc = _bfd_stringtab_add (ret, "", true, false);
1715      BFD_ASSERT (loc == 0 || loc == (bfd_size_type) -1);
1716      if (loc == (bfd_size_type) -1)
1717	{
1718	  _bfd_stringtab_free (ret);
1719	  ret = NULL;
1720	}
1721    }
1722  return ret;
1723}
1724
1725/* ELF .o/exec file reading */
1726
1727/* Create a new bfd section from an ELF section header.  */
1728
1729boolean
1730bfd_section_from_shdr (abfd, shindex)
1731     bfd *abfd;
1732     unsigned int shindex;
1733{
1734  Elf_Internal_Shdr *hdr = elf_elfsections (abfd)[shindex];
1735  Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
1736  struct elf_backend_data *bed = get_elf_backend_data (abfd);
1737  const char *name;
1738
1739  name = elf_string_from_elf_strtab (abfd, hdr->sh_name);
1740
1741  switch (hdr->sh_type)
1742    {
1743    case SHT_NULL:
1744      /* Inactive section. Throw it away.  */
1745      return true;
1746
1747    case SHT_PROGBITS:	/* Normal section with contents.  */
1748    case SHT_NOBITS:	/* .bss section.  */
1749    case SHT_HASH:	/* .hash section.  */
1750    case SHT_NOTE:	/* .note section.  */
1751    case SHT_INIT_ARRAY:	/* .init_array section.  */
1752    case SHT_FINI_ARRAY:	/* .fini_array section.  */
1753    case SHT_PREINIT_ARRAY:	/* .preinit_array section.  */
1754      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1755
1756    case SHT_DYNAMIC:	/* Dynamic linking information.  */
1757      if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name))
1758	return false;
1759      if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_STRTAB)
1760	{
1761	  Elf_Internal_Shdr *dynsymhdr;
1762
1763	  /* The shared libraries distributed with hpux11 have a bogus
1764	     sh_link field for the ".dynamic" section.  Find the
1765	     string table for the ".dynsym" section instead.  */
1766	  if (elf_dynsymtab (abfd) != 0)
1767	    {
1768	      dynsymhdr = elf_elfsections (abfd)[elf_dynsymtab (abfd)];
1769	      hdr->sh_link = dynsymhdr->sh_link;
1770	    }
1771	  else
1772	    {
1773	      unsigned int i, num_sec;
1774
1775	      num_sec = elf_numsections (abfd);
1776	      for (i = 1; i < num_sec; i++)
1777		{
1778		  dynsymhdr = elf_elfsections (abfd)[i];
1779		  if (dynsymhdr->sh_type == SHT_DYNSYM)
1780		    {
1781		      hdr->sh_link = dynsymhdr->sh_link;
1782		      break;
1783		    }
1784		}
1785	    }
1786	}
1787      break;
1788
1789    case SHT_SYMTAB:		/* A symbol table */
1790      if (elf_onesymtab (abfd) == shindex)
1791	return true;
1792
1793      BFD_ASSERT (hdr->sh_entsize == bed->s->sizeof_sym);
1794      BFD_ASSERT (elf_onesymtab (abfd) == 0);
1795      elf_onesymtab (abfd) = shindex;
1796      elf_tdata (abfd)->symtab_hdr = *hdr;
1797      elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->symtab_hdr;
1798      abfd->flags |= HAS_SYMS;
1799
1800      /* Sometimes a shared object will map in the symbol table.  If
1801         SHF_ALLOC is set, and this is a shared object, then we also
1802         treat this section as a BFD section.  We can not base the
1803         decision purely on SHF_ALLOC, because that flag is sometimes
1804         set in a relocateable object file, which would confuse the
1805         linker.  */
1806      if ((hdr->sh_flags & SHF_ALLOC) != 0
1807	  && (abfd->flags & DYNAMIC) != 0
1808	  && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name))
1809	return false;
1810
1811      return true;
1812
1813    case SHT_DYNSYM:		/* A dynamic symbol table */
1814      if (elf_dynsymtab (abfd) == shindex)
1815	return true;
1816
1817      BFD_ASSERT (hdr->sh_entsize == bed->s->sizeof_sym);
1818      BFD_ASSERT (elf_dynsymtab (abfd) == 0);
1819      elf_dynsymtab (abfd) = shindex;
1820      elf_tdata (abfd)->dynsymtab_hdr = *hdr;
1821      elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->dynsymtab_hdr;
1822      abfd->flags |= HAS_SYMS;
1823
1824      /* Besides being a symbol table, we also treat this as a regular
1825	 section, so that objcopy can handle it.  */
1826      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1827
1828    case SHT_SYMTAB_SHNDX:	/* Symbol section indices when >64k sections */
1829      if (elf_symtab_shndx (abfd) == shindex)
1830	return true;
1831
1832      /* Get the associated symbol table.  */
1833      if (! bfd_section_from_shdr (abfd, hdr->sh_link)
1834	  || hdr->sh_link != elf_onesymtab (abfd))
1835	return false;
1836
1837      elf_symtab_shndx (abfd) = shindex;
1838      elf_tdata (abfd)->symtab_shndx_hdr = *hdr;
1839      elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->symtab_shndx_hdr;
1840      return true;
1841
1842    case SHT_STRTAB:		/* A string table */
1843      if (hdr->bfd_section != NULL)
1844	return true;
1845      if (ehdr->e_shstrndx == shindex)
1846	{
1847	  elf_tdata (abfd)->shstrtab_hdr = *hdr;
1848	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
1849	  return true;
1850	}
1851      {
1852	unsigned int i, num_sec;
1853
1854	num_sec = elf_numsections (abfd);
1855	for (i = 1; i < num_sec; i++)
1856	  {
1857	    Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
1858	    if (hdr2->sh_link == shindex)
1859	      {
1860		if (! bfd_section_from_shdr (abfd, i))
1861		  return false;
1862		if (elf_onesymtab (abfd) == i)
1863		  {
1864		    elf_tdata (abfd)->strtab_hdr = *hdr;
1865		    elf_elfsections (abfd)[shindex] =
1866		      &elf_tdata (abfd)->strtab_hdr;
1867		    return true;
1868		  }
1869		if (elf_dynsymtab (abfd) == i)
1870		  {
1871		    elf_tdata (abfd)->dynstrtab_hdr = *hdr;
1872		    elf_elfsections (abfd)[shindex] = hdr =
1873		      &elf_tdata (abfd)->dynstrtab_hdr;
1874		    /* We also treat this as a regular section, so
1875		       that objcopy can handle it.  */
1876		    break;
1877		  }
1878#if 0 /* Not handling other string tables specially right now.  */
1879		hdr2 = elf_elfsections (abfd)[i];	/* in case it moved */
1880		/* We have a strtab for some random other section.  */
1881		newsect = (asection *) hdr2->bfd_section;
1882		if (!newsect)
1883		  break;
1884		hdr->bfd_section = newsect;
1885		hdr2 = &elf_section_data (newsect)->str_hdr;
1886		*hdr2 = *hdr;
1887		elf_elfsections (abfd)[shindex] = hdr2;
1888#endif
1889	      }
1890	  }
1891      }
1892
1893      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1894
1895    case SHT_REL:
1896    case SHT_RELA:
1897      /* *These* do a lot of work -- but build no sections!  */
1898      {
1899	asection *target_sect;
1900	Elf_Internal_Shdr *hdr2;
1901	unsigned int num_sec = elf_numsections (abfd);
1902
1903	/* Check for a bogus link to avoid crashing.  */
1904	if ((hdr->sh_link >= SHN_LORESERVE && hdr->sh_link <= SHN_HIRESERVE)
1905	    || hdr->sh_link >= num_sec)
1906	  {
1907	    ((*_bfd_error_handler)
1908	     (_("%s: invalid link %lu for reloc section %s (index %u)"),
1909	      bfd_archive_filename (abfd), hdr->sh_link, name, shindex));
1910	    return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1911	  }
1912
1913	/* For some incomprehensible reason Oracle distributes
1914	   libraries for Solaris in which some of the objects have
1915	   bogus sh_link fields.  It would be nice if we could just
1916	   reject them, but, unfortunately, some people need to use
1917	   them.  We scan through the section headers; if we find only
1918	   one suitable symbol table, we clobber the sh_link to point
1919	   to it.  I hope this doesn't break anything.  */
1920	if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_SYMTAB
1921	    && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_DYNSYM)
1922	  {
1923	    unsigned int scan;
1924	    int found;
1925
1926	    found = 0;
1927	    for (scan = 1; scan < num_sec; scan++)
1928	      {
1929		if (elf_elfsections (abfd)[scan]->sh_type == SHT_SYMTAB
1930		    || elf_elfsections (abfd)[scan]->sh_type == SHT_DYNSYM)
1931		  {
1932		    if (found != 0)
1933		      {
1934			found = 0;
1935			break;
1936		      }
1937		    found = scan;
1938		  }
1939	      }
1940	    if (found != 0)
1941	      hdr->sh_link = found;
1942	  }
1943
1944	/* Get the symbol table.  */
1945	if (elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_SYMTAB
1946	    && ! bfd_section_from_shdr (abfd, hdr->sh_link))
1947	  return false;
1948
1949	/* If this reloc section does not use the main symbol table we
1950	   don't treat it as a reloc section.  BFD can't adequately
1951	   represent such a section, so at least for now, we don't
1952	   try.  We just present it as a normal section.  We also
1953	   can't use it as a reloc section if it points to the null
1954	   section.  */
1955	if (hdr->sh_link != elf_onesymtab (abfd) || hdr->sh_info == SHN_UNDEF)
1956	  return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1957
1958	if (! bfd_section_from_shdr (abfd, hdr->sh_info))
1959	  return false;
1960	target_sect = bfd_section_from_elf_index (abfd, hdr->sh_info);
1961	if (target_sect == NULL)
1962	  return false;
1963
1964	if ((target_sect->flags & SEC_RELOC) == 0
1965	    || target_sect->reloc_count == 0)
1966	  hdr2 = &elf_section_data (target_sect)->rel_hdr;
1967	else
1968	  {
1969	    bfd_size_type amt;
1970	    BFD_ASSERT (elf_section_data (target_sect)->rel_hdr2 == NULL);
1971	    amt = sizeof (*hdr2);
1972	    hdr2 = (Elf_Internal_Shdr *) bfd_alloc (abfd, amt);
1973	    elf_section_data (target_sect)->rel_hdr2 = hdr2;
1974	  }
1975	*hdr2 = *hdr;
1976	elf_elfsections (abfd)[shindex] = hdr2;
1977	target_sect->reloc_count += NUM_SHDR_ENTRIES (hdr);
1978	target_sect->flags |= SEC_RELOC;
1979	target_sect->relocation = NULL;
1980	target_sect->rel_filepos = hdr->sh_offset;
1981	/* In the section to which the relocations apply, mark whether
1982	   its relocations are of the REL or RELA variety.  */
1983	if (hdr->sh_size != 0)
1984	  elf_section_data (target_sect)->use_rela_p
1985	    = (hdr->sh_type == SHT_RELA);
1986	abfd->flags |= HAS_RELOC;
1987	return true;
1988      }
1989      break;
1990
1991    case SHT_GNU_verdef:
1992      elf_dynverdef (abfd) = shindex;
1993      elf_tdata (abfd)->dynverdef_hdr = *hdr;
1994      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1995      break;
1996
1997    case SHT_GNU_versym:
1998      elf_dynversym (abfd) = shindex;
1999      elf_tdata (abfd)->dynversym_hdr = *hdr;
2000      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
2001      break;
2002
2003    case SHT_GNU_verneed:
2004      elf_dynverref (abfd) = shindex;
2005      elf_tdata (abfd)->dynverref_hdr = *hdr;
2006      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
2007      break;
2008
2009    case SHT_SHLIB:
2010      return true;
2011
2012    case SHT_GROUP:
2013      /* We need a BFD section for objcopy and relocatable linking,
2014	 and it's handy to have the signature available as the section
2015	 name.  */
2016      name = group_signature (abfd, hdr);
2017      if (name == NULL)
2018	return false;
2019      if (!_bfd_elf_make_section_from_shdr (abfd, hdr, name))
2020	return false;
2021      if (hdr->contents != NULL)
2022	{
2023	  Elf_Internal_Group *idx = (Elf_Internal_Group *) hdr->contents;
2024	  unsigned int n_elt = hdr->sh_size / 4;
2025	  asection *s;
2026
2027	  if (idx->flags & GRP_COMDAT)
2028	    hdr->bfd_section->flags
2029	      |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
2030
2031	  while (--n_elt != 0)
2032	    if ((s = (++idx)->shdr->bfd_section) != NULL
2033		&& elf_next_in_group (s) != NULL)
2034	      {
2035		elf_next_in_group (hdr->bfd_section) = s;
2036		break;
2037	      }
2038	}
2039      break;
2040
2041    default:
2042      /* Check for any processor-specific section types.  */
2043      {
2044	if (bed->elf_backend_section_from_shdr)
2045	  (*bed->elf_backend_section_from_shdr) (abfd, hdr, name);
2046      }
2047      break;
2048    }
2049
2050  return true;
2051}
2052
2053/* Return the section for the local symbol specified by ABFD, R_SYMNDX.
2054   Return SEC for sections that have no elf section, and NULL on error.  */
2055
2056asection *
2057bfd_section_from_r_symndx (abfd, cache, sec, r_symndx)
2058     bfd *abfd;
2059     struct sym_sec_cache *cache;
2060     asection *sec;
2061     unsigned long r_symndx;
2062{
2063  Elf_Internal_Shdr *symtab_hdr;
2064  unsigned char esym[sizeof (Elf64_External_Sym)];
2065  Elf_External_Sym_Shndx eshndx;
2066  Elf_Internal_Sym isym;
2067  unsigned int ent = r_symndx % LOCAL_SYM_CACHE_SIZE;
2068
2069  if (cache->abfd == abfd && cache->indx[ent] == r_symndx)
2070    return cache->sec[ent];
2071
2072  symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2073  if (bfd_elf_get_elf_syms (abfd, symtab_hdr, 1, r_symndx,
2074			    &isym, esym, &eshndx) == NULL)
2075    return NULL;
2076
2077  if (cache->abfd != abfd)
2078    {
2079      memset (cache->indx, -1, sizeof (cache->indx));
2080      cache->abfd = abfd;
2081    }
2082  cache->indx[ent] = r_symndx;
2083  cache->sec[ent] = sec;
2084  if (isym.st_shndx < SHN_LORESERVE || isym.st_shndx > SHN_HIRESERVE)
2085    {
2086      asection *s;
2087      s = bfd_section_from_elf_index (abfd, isym.st_shndx);
2088      if (s != NULL)
2089	cache->sec[ent] = s;
2090    }
2091  return cache->sec[ent];
2092}
2093
2094/* Given an ELF section number, retrieve the corresponding BFD
2095   section.  */
2096
2097asection *
2098bfd_section_from_elf_index (abfd, index)
2099     bfd *abfd;
2100     unsigned int index;
2101{
2102  if (index >= elf_numsections (abfd))
2103    return NULL;
2104  return elf_elfsections (abfd)[index]->bfd_section;
2105}
2106
2107boolean
2108_bfd_elf_new_section_hook (abfd, sec)
2109     bfd *abfd;
2110     asection *sec;
2111{
2112  struct bfd_elf_section_data *sdata;
2113  bfd_size_type amt = sizeof (*sdata);
2114
2115  sdata = (struct bfd_elf_section_data *) bfd_zalloc (abfd, amt);
2116  if (!sdata)
2117    return false;
2118  sec->used_by_bfd = (PTR) sdata;
2119
2120  /* Indicate whether or not this section should use RELA relocations.  */
2121  sdata->use_rela_p
2122    = get_elf_backend_data (abfd)->default_use_rela_p;
2123
2124  return true;
2125}
2126
2127/* Create a new bfd section from an ELF program header.
2128
2129   Since program segments have no names, we generate a synthetic name
2130   of the form segment<NUM>, where NUM is generally the index in the
2131   program header table.  For segments that are split (see below) we
2132   generate the names segment<NUM>a and segment<NUM>b.
2133
2134   Note that some program segments may have a file size that is different than
2135   (less than) the memory size.  All this means is that at execution the
2136   system must allocate the amount of memory specified by the memory size,
2137   but only initialize it with the first "file size" bytes read from the
2138   file.  This would occur for example, with program segments consisting
2139   of combined data+bss.
2140
2141   To handle the above situation, this routine generates TWO bfd sections
2142   for the single program segment.  The first has the length specified by
2143   the file size of the segment, and the second has the length specified
2144   by the difference between the two sizes.  In effect, the segment is split
2145   into it's initialized and uninitialized parts.
2146
2147 */
2148
2149boolean
2150_bfd_elf_make_section_from_phdr (abfd, hdr, index, typename)
2151     bfd *abfd;
2152     Elf_Internal_Phdr *hdr;
2153     int index;
2154     const char *typename;
2155{
2156  asection *newsect;
2157  char *name;
2158  char namebuf[64];
2159  size_t len;
2160  int split;
2161
2162  split = ((hdr->p_memsz > 0)
2163	    && (hdr->p_filesz > 0)
2164	    && (hdr->p_memsz > hdr->p_filesz));
2165  sprintf (namebuf, "%s%d%s", typename, index, split ? "a" : "");
2166  len = strlen (namebuf) + 1;
2167  name = bfd_alloc (abfd, (bfd_size_type) len);
2168  if (!name)
2169    return false;
2170  memcpy (name, namebuf, len);
2171  newsect = bfd_make_section (abfd, name);
2172  if (newsect == NULL)
2173    return false;
2174  newsect->vma = hdr->p_vaddr;
2175  newsect->lma = hdr->p_paddr;
2176  newsect->_raw_size = hdr->p_filesz;
2177  newsect->filepos = hdr->p_offset;
2178  newsect->flags |= SEC_HAS_CONTENTS;
2179  if (hdr->p_type == PT_LOAD)
2180    {
2181      newsect->flags |= SEC_ALLOC;
2182      newsect->flags |= SEC_LOAD;
2183      if (hdr->p_flags & PF_X)
2184	{
2185	  /* FIXME: all we known is that it has execute PERMISSION,
2186	     may be data.  */
2187	  newsect->flags |= SEC_CODE;
2188	}
2189    }
2190  if (!(hdr->p_flags & PF_W))
2191    {
2192      newsect->flags |= SEC_READONLY;
2193    }
2194
2195  if (split)
2196    {
2197      sprintf (namebuf, "%s%db", typename, index);
2198      len = strlen (namebuf) + 1;
2199      name = bfd_alloc (abfd, (bfd_size_type) len);
2200      if (!name)
2201	return false;
2202      memcpy (name, namebuf, len);
2203      newsect = bfd_make_section (abfd, name);
2204      if (newsect == NULL)
2205	return false;
2206      newsect->vma = hdr->p_vaddr + hdr->p_filesz;
2207      newsect->lma = hdr->p_paddr + hdr->p_filesz;
2208      newsect->_raw_size = hdr->p_memsz - hdr->p_filesz;
2209      if (hdr->p_type == PT_LOAD)
2210	{
2211	  newsect->flags |= SEC_ALLOC;
2212	  if (hdr->p_flags & PF_X)
2213	    newsect->flags |= SEC_CODE;
2214	}
2215      if (!(hdr->p_flags & PF_W))
2216	newsect->flags |= SEC_READONLY;
2217    }
2218
2219  return true;
2220}
2221
2222boolean
2223bfd_section_from_phdr (abfd, hdr, index)
2224     bfd *abfd;
2225     Elf_Internal_Phdr *hdr;
2226     int index;
2227{
2228  struct elf_backend_data *bed;
2229
2230  switch (hdr->p_type)
2231    {
2232    case PT_NULL:
2233      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "null");
2234
2235    case PT_LOAD:
2236      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "load");
2237
2238    case PT_DYNAMIC:
2239      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "dynamic");
2240
2241    case PT_INTERP:
2242      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "interp");
2243
2244    case PT_NOTE:
2245      if (! _bfd_elf_make_section_from_phdr (abfd, hdr, index, "note"))
2246	return false;
2247      if (! elfcore_read_notes (abfd, (file_ptr) hdr->p_offset, hdr->p_filesz))
2248	return false;
2249      return true;
2250
2251    case PT_SHLIB:
2252      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "shlib");
2253
2254    case PT_PHDR:
2255      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "phdr");
2256
2257    default:
2258      /* Check for any processor-specific program segment types.
2259         If no handler for them, default to making "segment" sections.  */
2260      bed = get_elf_backend_data (abfd);
2261      if (bed->elf_backend_section_from_phdr)
2262	return (*bed->elf_backend_section_from_phdr) (abfd, hdr, index);
2263      else
2264	return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "segment");
2265    }
2266}
2267
2268/* Initialize REL_HDR, the section-header for new section, containing
2269   relocations against ASECT.  If USE_RELA_P is true, we use RELA
2270   relocations; otherwise, we use REL relocations.  */
2271
2272boolean
2273_bfd_elf_init_reloc_shdr (abfd, rel_hdr, asect, use_rela_p)
2274     bfd *abfd;
2275     Elf_Internal_Shdr *rel_hdr;
2276     asection *asect;
2277     boolean use_rela_p;
2278{
2279  char *name;
2280  struct elf_backend_data *bed = get_elf_backend_data (abfd);
2281  bfd_size_type amt = sizeof ".rela" + strlen (asect->name);
2282
2283  name = bfd_alloc (abfd, amt);
2284  if (name == NULL)
2285    return false;
2286  sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", asect->name);
2287  rel_hdr->sh_name =
2288    (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd), name,
2289					false);
2290  if (rel_hdr->sh_name == (unsigned int) -1)
2291    return false;
2292  rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
2293  rel_hdr->sh_entsize = (use_rela_p
2294			 ? bed->s->sizeof_rela
2295			 : bed->s->sizeof_rel);
2296  rel_hdr->sh_addralign = bed->s->file_align;
2297  rel_hdr->sh_flags = 0;
2298  rel_hdr->sh_addr = 0;
2299  rel_hdr->sh_size = 0;
2300  rel_hdr->sh_offset = 0;
2301
2302  return true;
2303}
2304
2305/* Set up an ELF internal section header for a section.  */
2306
2307static void
2308elf_fake_sections (abfd, asect, failedptrarg)
2309     bfd *abfd;
2310     asection *asect;
2311     PTR failedptrarg;
2312{
2313  struct elf_backend_data *bed = get_elf_backend_data (abfd);
2314  boolean *failedptr = (boolean *) failedptrarg;
2315  Elf_Internal_Shdr *this_hdr;
2316
2317  if (*failedptr)
2318    {
2319      /* We already failed; just get out of the bfd_map_over_sections
2320         loop.  */
2321      return;
2322    }
2323
2324  this_hdr = &elf_section_data (asect)->this_hdr;
2325
2326  this_hdr->sh_name = (unsigned long) _bfd_elf_strtab_add (elf_shstrtab (abfd),
2327							   asect->name, false);
2328  if (this_hdr->sh_name == (unsigned long) -1)
2329    {
2330      *failedptr = true;
2331      return;
2332    }
2333
2334  this_hdr->sh_flags = 0;
2335
2336  if ((asect->flags & SEC_ALLOC) != 0
2337      || asect->user_set_vma)
2338    this_hdr->sh_addr = asect->vma;
2339  else
2340    this_hdr->sh_addr = 0;
2341
2342  this_hdr->sh_offset = 0;
2343  this_hdr->sh_size = asect->_raw_size;
2344  this_hdr->sh_link = 0;
2345  this_hdr->sh_addralign = 1 << asect->alignment_power;
2346  /* The sh_entsize and sh_info fields may have been set already by
2347     copy_private_section_data.  */
2348
2349  this_hdr->bfd_section = asect;
2350  this_hdr->contents = NULL;
2351
2352  /* FIXME: This should not be based on section names.  */
2353  if (strcmp (asect->name, ".dynstr") == 0)
2354    this_hdr->sh_type = SHT_STRTAB;
2355  else if (strcmp (asect->name, ".hash") == 0)
2356    {
2357      this_hdr->sh_type = SHT_HASH;
2358      this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
2359    }
2360  else if (strcmp (asect->name, ".dynsym") == 0)
2361    {
2362      this_hdr->sh_type = SHT_DYNSYM;
2363      this_hdr->sh_entsize = bed->s->sizeof_sym;
2364    }
2365  else if (strcmp (asect->name, ".dynamic") == 0)
2366    {
2367      this_hdr->sh_type = SHT_DYNAMIC;
2368      this_hdr->sh_entsize = bed->s->sizeof_dyn;
2369    }
2370  else if (strncmp (asect->name, ".rela", 5) == 0
2371	   && get_elf_backend_data (abfd)->may_use_rela_p)
2372    {
2373      this_hdr->sh_type = SHT_RELA;
2374      this_hdr->sh_entsize = bed->s->sizeof_rela;
2375    }
2376  else if (strncmp (asect->name, ".rel", 4) == 0
2377	   && get_elf_backend_data (abfd)->may_use_rel_p)
2378    {
2379      this_hdr->sh_type = SHT_REL;
2380      this_hdr->sh_entsize = bed->s->sizeof_rel;
2381    }
2382  else if (strcmp (asect->name, ".init_array") == 0)
2383    this_hdr->sh_type = SHT_INIT_ARRAY;
2384  else if (strcmp (asect->name, ".fini_array") == 0)
2385    this_hdr->sh_type = SHT_FINI_ARRAY;
2386  else if (strcmp (asect->name, ".preinit_array") == 0)
2387    this_hdr->sh_type = SHT_PREINIT_ARRAY;
2388  else if (strncmp (asect->name, ".note", 5) == 0)
2389    this_hdr->sh_type = SHT_NOTE;
2390  else if (strncmp (asect->name, ".stab", 5) == 0
2391	   && strcmp (asect->name + strlen (asect->name) - 3, "str") == 0)
2392    this_hdr->sh_type = SHT_STRTAB;
2393  else if (strcmp (asect->name, ".gnu.version") == 0)
2394    {
2395      this_hdr->sh_type = SHT_GNU_versym;
2396      this_hdr->sh_entsize = sizeof (Elf_External_Versym);
2397    }
2398  else if (strcmp (asect->name, ".gnu.version_d") == 0)
2399    {
2400      this_hdr->sh_type = SHT_GNU_verdef;
2401      this_hdr->sh_entsize = 0;
2402      /* objcopy or strip will copy over sh_info, but may not set
2403         cverdefs.  The linker will set cverdefs, but sh_info will be
2404         zero.  */
2405      if (this_hdr->sh_info == 0)
2406	this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
2407      else
2408	BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
2409		    || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
2410    }
2411  else if (strcmp (asect->name, ".gnu.version_r") == 0)
2412    {
2413      this_hdr->sh_type = SHT_GNU_verneed;
2414      this_hdr->sh_entsize = 0;
2415      /* objcopy or strip will copy over sh_info, but may not set
2416         cverrefs.  The linker will set cverrefs, but sh_info will be
2417         zero.  */
2418      if (this_hdr->sh_info == 0)
2419	this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
2420      else
2421	BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
2422		    || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
2423    }
2424  else if ((asect->flags & SEC_GROUP) != 0)
2425    {
2426      this_hdr->sh_type = SHT_GROUP;
2427      this_hdr->sh_entsize = 4;
2428    }
2429  else if ((asect->flags & SEC_ALLOC) != 0
2430	   && (((asect->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2431	       || (asect->flags & SEC_NEVER_LOAD) != 0))
2432    this_hdr->sh_type = SHT_NOBITS;
2433  else
2434    this_hdr->sh_type = SHT_PROGBITS;
2435
2436  if ((asect->flags & SEC_ALLOC) != 0)
2437    this_hdr->sh_flags |= SHF_ALLOC;
2438  if ((asect->flags & SEC_READONLY) == 0)
2439    this_hdr->sh_flags |= SHF_WRITE;
2440  if ((asect->flags & SEC_CODE) != 0)
2441    this_hdr->sh_flags |= SHF_EXECINSTR;
2442  if ((asect->flags & SEC_MERGE) != 0)
2443    {
2444      this_hdr->sh_flags |= SHF_MERGE;
2445      this_hdr->sh_entsize = asect->entsize;
2446      if ((asect->flags & SEC_STRINGS) != 0)
2447	this_hdr->sh_flags |= SHF_STRINGS;
2448    }
2449  if ((asect->flags & SEC_GROUP) == 0 && elf_group_name (asect) != NULL)
2450    this_hdr->sh_flags |= SHF_GROUP;
2451  if ((asect->flags & SEC_THREAD_LOCAL) != 0)
2452    {
2453      this_hdr->sh_flags |= SHF_TLS;
2454      if (asect->_raw_size == 0 && (asect->flags & SEC_HAS_CONTENTS) == 0)
2455	{
2456	  struct bfd_link_order *o;
2457
2458	  this_hdr->sh_size = 0;
2459	  for (o = asect->link_order_head; o != NULL; o = o->next)
2460	    if (this_hdr->sh_size < o->offset + o->size)
2461	      this_hdr->sh_size = o->offset + o->size;
2462	  if (this_hdr->sh_size)
2463	    this_hdr->sh_type = SHT_NOBITS;
2464	}
2465    }
2466
2467  /* Check for processor-specific section types.  */
2468  if (bed->elf_backend_fake_sections
2469      && !(*bed->elf_backend_fake_sections) (abfd, this_hdr, asect))
2470    *failedptr = true;
2471
2472  /* If the section has relocs, set up a section header for the
2473     SHT_REL[A] section.  If two relocation sections are required for
2474     this section, it is up to the processor-specific back-end to
2475     create the other.  */
2476  if ((asect->flags & SEC_RELOC) != 0
2477      && !_bfd_elf_init_reloc_shdr (abfd,
2478				    &elf_section_data (asect)->rel_hdr,
2479				    asect,
2480				    elf_section_data (asect)->use_rela_p))
2481    *failedptr = true;
2482}
2483
2484/* Fill in the contents of a SHT_GROUP section.  */
2485
2486void
2487bfd_elf_set_group_contents (abfd, sec, failedptrarg)
2488     bfd *abfd;
2489     asection *sec;
2490     PTR failedptrarg;
2491{
2492  boolean *failedptr = (boolean *) failedptrarg;
2493  unsigned long symindx;
2494  asection *elt, *first;
2495  unsigned char *loc;
2496  struct bfd_link_order *l;
2497  boolean gas;
2498
2499  if (elf_section_data (sec)->this_hdr.sh_type != SHT_GROUP
2500      || *failedptr)
2501    return;
2502
2503  symindx = 0;
2504  if (elf_group_id (sec) != NULL)
2505    symindx = elf_group_id (sec)->udata.i;
2506
2507  if (symindx == 0)
2508    {
2509      /* If called from the assembler, swap_out_syms will have set up
2510	 elf_section_syms;  If called for "ld -r", use target_index.  */
2511      if (elf_section_syms (abfd) != NULL)
2512	symindx = elf_section_syms (abfd)[sec->index]->udata.i;
2513      else
2514	symindx = sec->target_index;
2515    }
2516  elf_section_data (sec)->this_hdr.sh_info = symindx;
2517
2518  /* The contents won't be allocated for "ld -r" or objcopy.  */
2519  gas = true;
2520  if (sec->contents == NULL)
2521    {
2522      gas = false;
2523      sec->contents = bfd_alloc (abfd, sec->_raw_size);
2524
2525      /* Arrange for the section to be written out.  */
2526      elf_section_data (sec)->this_hdr.contents = sec->contents;
2527      if (sec->contents == NULL)
2528	{
2529	  *failedptr = true;
2530	  return;
2531	}
2532    }
2533
2534  loc = sec->contents + sec->_raw_size;
2535
2536  /* Get the pointer to the first section in the group that gas
2537     squirreled away here.  objcopy arranges for this to be set to the
2538     start of the input section group.  */
2539  first = elt = elf_next_in_group (sec);
2540
2541  /* First element is a flag word.  Rest of section is elf section
2542     indices for all the sections of the group.  Write them backwards
2543     just to keep the group in the same order as given in .section
2544     directives, not that it matters.  */
2545  while (elt != NULL)
2546    {
2547      asection *s;
2548      unsigned int idx;
2549
2550      loc -= 4;
2551      s = elt;
2552      if (!gas)
2553	s = s->output_section;
2554      idx = 0;
2555      if (s != NULL)
2556	idx = elf_section_data (s)->this_idx;
2557      H_PUT_32 (abfd, idx, loc);
2558      elt = elf_next_in_group (elt);
2559      if (elt == first)
2560	break;
2561    }
2562
2563  /* If this is a relocatable link, then the above did nothing because
2564     SEC is the output section.  Look through the input sections
2565     instead.  */
2566  for (l = sec->link_order_head; l != NULL; l = l->next)
2567    if (l->type == bfd_indirect_link_order
2568	&& (elt = elf_next_in_group (l->u.indirect.section)) != NULL)
2569      do
2570	{
2571	  loc -= 4;
2572	  H_PUT_32 (abfd,
2573		    elf_section_data (elt->output_section)->this_idx, loc);
2574	  elt = elf_next_in_group (elt);
2575	  /* During a relocatable link, the lists are circular.  */
2576	}
2577      while (elt != elf_next_in_group (l->u.indirect.section));
2578
2579  /* With ld -r, merging SHT_GROUP sections results in wasted space
2580     due to allowing for the flag word on each input.  We may well
2581     duplicate entries too.  */
2582  while ((loc -= 4) > sec->contents)
2583    H_PUT_32 (abfd, 0, loc);
2584
2585  if (loc != sec->contents)
2586    abort ();
2587
2588  H_PUT_32 (abfd, sec->flags & SEC_LINK_ONCE ? GRP_COMDAT : 0, loc);
2589}
2590
2591/* Assign all ELF section numbers.  The dummy first section is handled here
2592   too.  The link/info pointers for the standard section types are filled
2593   in here too, while we're at it.  */
2594
2595static boolean
2596assign_section_numbers (abfd)
2597     bfd *abfd;
2598{
2599  struct elf_obj_tdata *t = elf_tdata (abfd);
2600  asection *sec;
2601  unsigned int section_number, secn;
2602  Elf_Internal_Shdr **i_shdrp;
2603  bfd_size_type amt;
2604
2605  section_number = 1;
2606
2607  _bfd_elf_strtab_clear_all_refs (elf_shstrtab (abfd));
2608
2609  for (sec = abfd->sections; sec; sec = sec->next)
2610    {
2611      struct bfd_elf_section_data *d = elf_section_data (sec);
2612
2613      if (section_number == SHN_LORESERVE)
2614	section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2615      d->this_idx = section_number++;
2616      _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->this_hdr.sh_name);
2617      if ((sec->flags & SEC_RELOC) == 0)
2618	d->rel_idx = 0;
2619      else
2620	{
2621	  if (section_number == SHN_LORESERVE)
2622	    section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2623	  d->rel_idx = section_number++;
2624	  _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel_hdr.sh_name);
2625	}
2626
2627      if (d->rel_hdr2)
2628	{
2629	  if (section_number == SHN_LORESERVE)
2630	    section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2631	  d->rel_idx2 = section_number++;
2632	  _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel_hdr2->sh_name);
2633	}
2634      else
2635	d->rel_idx2 = 0;
2636    }
2637
2638  if (section_number == SHN_LORESERVE)
2639    section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2640  t->shstrtab_section = section_number++;
2641  _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->shstrtab_hdr.sh_name);
2642  elf_elfheader (abfd)->e_shstrndx = t->shstrtab_section;
2643
2644  if (bfd_get_symcount (abfd) > 0)
2645    {
2646      if (section_number == SHN_LORESERVE)
2647	section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2648      t->symtab_section = section_number++;
2649      _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->symtab_hdr.sh_name);
2650      if (section_number > SHN_LORESERVE - 2)
2651	{
2652	  if (section_number == SHN_LORESERVE)
2653	    section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2654	  t->symtab_shndx_section = section_number++;
2655	  t->symtab_shndx_hdr.sh_name
2656	    = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
2657						  ".symtab_shndx", false);
2658	  if (t->symtab_shndx_hdr.sh_name == (unsigned int) -1)
2659	    return false;
2660	}
2661      if (section_number == SHN_LORESERVE)
2662	section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2663      t->strtab_section = section_number++;
2664      _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->strtab_hdr.sh_name);
2665    }
2666
2667  _bfd_elf_strtab_finalize (elf_shstrtab (abfd));
2668  t->shstrtab_hdr.sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
2669
2670  elf_numsections (abfd) = section_number;
2671  elf_elfheader (abfd)->e_shnum = section_number;
2672  if (section_number > SHN_LORESERVE)
2673    elf_elfheader (abfd)->e_shnum -= SHN_HIRESERVE + 1 - SHN_LORESERVE;
2674
2675  /* Set up the list of section header pointers, in agreement with the
2676     indices.  */
2677  amt = section_number * sizeof (Elf_Internal_Shdr *);
2678  i_shdrp = (Elf_Internal_Shdr **) bfd_alloc (abfd, amt);
2679  if (i_shdrp == NULL)
2680    return false;
2681
2682  amt = sizeof (Elf_Internal_Shdr);
2683  i_shdrp[0] = (Elf_Internal_Shdr *) bfd_alloc (abfd, amt);
2684  if (i_shdrp[0] == NULL)
2685    {
2686      bfd_release (abfd, i_shdrp);
2687      return false;
2688    }
2689  memset (i_shdrp[0], 0, sizeof (Elf_Internal_Shdr));
2690
2691  elf_elfsections (abfd) = i_shdrp;
2692
2693  i_shdrp[t->shstrtab_section] = &t->shstrtab_hdr;
2694  if (bfd_get_symcount (abfd) > 0)
2695    {
2696      i_shdrp[t->symtab_section] = &t->symtab_hdr;
2697      if (elf_numsections (abfd) > SHN_LORESERVE)
2698	{
2699	  i_shdrp[t->symtab_shndx_section] = &t->symtab_shndx_hdr;
2700	  t->symtab_shndx_hdr.sh_link = t->symtab_section;
2701	}
2702      i_shdrp[t->strtab_section] = &t->strtab_hdr;
2703      t->symtab_hdr.sh_link = t->strtab_section;
2704    }
2705  for (sec = abfd->sections; sec; sec = sec->next)
2706    {
2707      struct bfd_elf_section_data *d = elf_section_data (sec);
2708      asection *s;
2709      const char *name;
2710
2711      i_shdrp[d->this_idx] = &d->this_hdr;
2712      if (d->rel_idx != 0)
2713	i_shdrp[d->rel_idx] = &d->rel_hdr;
2714      if (d->rel_idx2 != 0)
2715	i_shdrp[d->rel_idx2] = d->rel_hdr2;
2716
2717      /* Fill in the sh_link and sh_info fields while we're at it.  */
2718
2719      /* sh_link of a reloc section is the section index of the symbol
2720	 table.  sh_info is the section index of the section to which
2721	 the relocation entries apply.  */
2722      if (d->rel_idx != 0)
2723	{
2724	  d->rel_hdr.sh_link = t->symtab_section;
2725	  d->rel_hdr.sh_info = d->this_idx;
2726	}
2727      if (d->rel_idx2 != 0)
2728	{
2729	  d->rel_hdr2->sh_link = t->symtab_section;
2730	  d->rel_hdr2->sh_info = d->this_idx;
2731	}
2732
2733      switch (d->this_hdr.sh_type)
2734	{
2735	case SHT_REL:
2736	case SHT_RELA:
2737	  /* A reloc section which we are treating as a normal BFD
2738	     section.  sh_link is the section index of the symbol
2739	     table.  sh_info is the section index of the section to
2740	     which the relocation entries apply.  We assume that an
2741	     allocated reloc section uses the dynamic symbol table.
2742	     FIXME: How can we be sure?  */
2743	  s = bfd_get_section_by_name (abfd, ".dynsym");
2744	  if (s != NULL)
2745	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
2746
2747	  /* We look up the section the relocs apply to by name.  */
2748	  name = sec->name;
2749	  if (d->this_hdr.sh_type == SHT_REL)
2750	    name += 4;
2751	  else
2752	    name += 5;
2753	  s = bfd_get_section_by_name (abfd, name);
2754	  if (s != NULL)
2755	    d->this_hdr.sh_info = elf_section_data (s)->this_idx;
2756	  break;
2757
2758	case SHT_STRTAB:
2759	  /* We assume that a section named .stab*str is a stabs
2760	     string section.  We look for a section with the same name
2761	     but without the trailing ``str'', and set its sh_link
2762	     field to point to this section.  */
2763	  if (strncmp (sec->name, ".stab", sizeof ".stab" - 1) == 0
2764	      && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
2765	    {
2766	      size_t len;
2767	      char *alc;
2768
2769	      len = strlen (sec->name);
2770	      alc = (char *) bfd_malloc ((bfd_size_type) (len - 2));
2771	      if (alc == NULL)
2772		return false;
2773	      memcpy (alc, sec->name, len - 3);
2774	      alc[len - 3] = '\0';
2775	      s = bfd_get_section_by_name (abfd, alc);
2776	      free (alc);
2777	      if (s != NULL)
2778		{
2779		  elf_section_data (s)->this_hdr.sh_link = d->this_idx;
2780
2781		  /* This is a .stab section.  */
2782		  if (elf_section_data (s)->this_hdr.sh_entsize == 0)
2783		    elf_section_data (s)->this_hdr.sh_entsize
2784		      = 4 + 2 * bfd_get_arch_size (abfd) / 8;
2785		}
2786	    }
2787	  break;
2788
2789	case SHT_DYNAMIC:
2790	case SHT_DYNSYM:
2791	case SHT_GNU_verneed:
2792	case SHT_GNU_verdef:
2793	  /* sh_link is the section header index of the string table
2794	     used for the dynamic entries, or the symbol table, or the
2795	     version strings.  */
2796	  s = bfd_get_section_by_name (abfd, ".dynstr");
2797	  if (s != NULL)
2798	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
2799	  break;
2800
2801	case SHT_HASH:
2802	case SHT_GNU_versym:
2803	  /* sh_link is the section header index of the symbol table
2804	     this hash table or version table is for.  */
2805	  s = bfd_get_section_by_name (abfd, ".dynsym");
2806	  if (s != NULL)
2807	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
2808	  break;
2809
2810	case SHT_GROUP:
2811	  d->this_hdr.sh_link = t->symtab_section;
2812	}
2813    }
2814
2815  for (secn = 1; secn < section_number; ++secn)
2816    if (i_shdrp[secn] == NULL)
2817      i_shdrp[secn] = i_shdrp[0];
2818    else
2819      i_shdrp[secn]->sh_name = _bfd_elf_strtab_offset (elf_shstrtab (abfd),
2820						       i_shdrp[secn]->sh_name);
2821  return true;
2822}
2823
2824/* Map symbol from it's internal number to the external number, moving
2825   all local symbols to be at the head of the list.  */
2826
2827static INLINE int
2828sym_is_global (abfd, sym)
2829     bfd *abfd;
2830     asymbol *sym;
2831{
2832  /* If the backend has a special mapping, use it.  */
2833  if (get_elf_backend_data (abfd)->elf_backend_sym_is_global)
2834    return ((*get_elf_backend_data (abfd)->elf_backend_sym_is_global)
2835	    (abfd, sym));
2836
2837  return ((sym->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2838	  || bfd_is_und_section (bfd_get_section (sym))
2839	  || bfd_is_com_section (bfd_get_section (sym)));
2840}
2841
2842static boolean
2843elf_map_symbols (abfd)
2844     bfd *abfd;
2845{
2846  unsigned int symcount = bfd_get_symcount (abfd);
2847  asymbol **syms = bfd_get_outsymbols (abfd);
2848  asymbol **sect_syms;
2849  unsigned int num_locals = 0;
2850  unsigned int num_globals = 0;
2851  unsigned int num_locals2 = 0;
2852  unsigned int num_globals2 = 0;
2853  int max_index = 0;
2854  unsigned int idx;
2855  asection *asect;
2856  asymbol **new_syms;
2857  bfd_size_type amt;
2858
2859#ifdef DEBUG
2860  fprintf (stderr, "elf_map_symbols\n");
2861  fflush (stderr);
2862#endif
2863
2864  for (asect = abfd->sections; asect; asect = asect->next)
2865    {
2866      if (max_index < asect->index)
2867	max_index = asect->index;
2868    }
2869
2870  max_index++;
2871  amt = max_index * sizeof (asymbol *);
2872  sect_syms = (asymbol **) bfd_zalloc (abfd, amt);
2873  if (sect_syms == NULL)
2874    return false;
2875  elf_section_syms (abfd) = sect_syms;
2876  elf_num_section_syms (abfd) = max_index;
2877
2878  /* Init sect_syms entries for any section symbols we have already
2879     decided to output.  */
2880  for (idx = 0; idx < symcount; idx++)
2881    {
2882      asymbol *sym = syms[idx];
2883
2884      if ((sym->flags & BSF_SECTION_SYM) != 0
2885	  && sym->value == 0)
2886	{
2887	  asection *sec;
2888
2889	  sec = sym->section;
2890
2891	  if (sec->owner != NULL)
2892	    {
2893	      if (sec->owner != abfd)
2894		{
2895		  if (sec->output_offset != 0)
2896		    continue;
2897
2898		  sec = sec->output_section;
2899
2900		  /* Empty sections in the input files may have had a
2901		     section symbol created for them.  (See the comment
2902		     near the end of _bfd_generic_link_output_symbols in
2903		     linker.c).  If the linker script discards such
2904		     sections then we will reach this point.  Since we know
2905		     that we cannot avoid this case, we detect it and skip
2906		     the abort and the assignment to the sect_syms array.
2907		     To reproduce this particular case try running the
2908		     linker testsuite test ld-scripts/weak.exp for an ELF
2909		     port that uses the generic linker.  */
2910		  if (sec->owner == NULL)
2911		    continue;
2912
2913		  BFD_ASSERT (sec->owner == abfd);
2914		}
2915	      sect_syms[sec->index] = syms[idx];
2916	    }
2917	}
2918    }
2919
2920  /* Classify all of the symbols.  */
2921  for (idx = 0; idx < symcount; idx++)
2922    {
2923      if (!sym_is_global (abfd, syms[idx]))
2924	num_locals++;
2925      else
2926	num_globals++;
2927    }
2928
2929  /* We will be adding a section symbol for each BFD section.  Most normal
2930     sections will already have a section symbol in outsymbols, but
2931     eg. SHT_GROUP sections will not, and we need the section symbol mapped
2932     at least in that case.  */
2933  for (asect = abfd->sections; asect; asect = asect->next)
2934    {
2935      if (sect_syms[asect->index] == NULL)
2936	{
2937	  if (!sym_is_global (abfd, asect->symbol))
2938	    num_locals++;
2939	  else
2940	    num_globals++;
2941	}
2942    }
2943
2944  /* Now sort the symbols so the local symbols are first.  */
2945  amt = (num_locals + num_globals) * sizeof (asymbol *);
2946  new_syms = (asymbol **) bfd_alloc (abfd, amt);
2947
2948  if (new_syms == NULL)
2949    return false;
2950
2951  for (idx = 0; idx < symcount; idx++)
2952    {
2953      asymbol *sym = syms[idx];
2954      unsigned int i;
2955
2956      if (!sym_is_global (abfd, sym))
2957	i = num_locals2++;
2958      else
2959	i = num_locals + num_globals2++;
2960      new_syms[i] = sym;
2961      sym->udata.i = i + 1;
2962    }
2963  for (asect = abfd->sections; asect; asect = asect->next)
2964    {
2965      if (sect_syms[asect->index] == NULL)
2966	{
2967	  asymbol *sym = asect->symbol;
2968	  unsigned int i;
2969
2970	  sect_syms[asect->index] = sym;
2971	  if (!sym_is_global (abfd, sym))
2972	    i = num_locals2++;
2973	  else
2974	    i = num_locals + num_globals2++;
2975	  new_syms[i] = sym;
2976	  sym->udata.i = i + 1;
2977	}
2978    }
2979
2980  bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
2981
2982  elf_num_locals (abfd) = num_locals;
2983  elf_num_globals (abfd) = num_globals;
2984  return true;
2985}
2986
2987/* Align to the maximum file alignment that could be required for any
2988   ELF data structure.  */
2989
2990static INLINE file_ptr align_file_position PARAMS ((file_ptr, int));
2991static INLINE file_ptr
2992align_file_position (off, align)
2993     file_ptr off;
2994     int align;
2995{
2996  return (off + align - 1) & ~(align - 1);
2997}
2998
2999/* Assign a file position to a section, optionally aligning to the
3000   required section alignment.  */
3001
3002INLINE file_ptr
3003_bfd_elf_assign_file_position_for_section (i_shdrp, offset, align)
3004     Elf_Internal_Shdr *i_shdrp;
3005     file_ptr offset;
3006     boolean align;
3007{
3008  if (align)
3009    {
3010      unsigned int al;
3011
3012      al = i_shdrp->sh_addralign;
3013      if (al > 1)
3014	offset = BFD_ALIGN (offset, al);
3015    }
3016  i_shdrp->sh_offset = offset;
3017  if (i_shdrp->bfd_section != NULL)
3018    i_shdrp->bfd_section->filepos = offset;
3019  if (i_shdrp->sh_type != SHT_NOBITS)
3020    offset += i_shdrp->sh_size;
3021  return offset;
3022}
3023
3024/* Compute the file positions we are going to put the sections at, and
3025   otherwise prepare to begin writing out the ELF file.  If LINK_INFO
3026   is not NULL, this is being called by the ELF backend linker.  */
3027
3028boolean
3029_bfd_elf_compute_section_file_positions (abfd, link_info)
3030     bfd *abfd;
3031     struct bfd_link_info *link_info;
3032{
3033  struct elf_backend_data *bed = get_elf_backend_data (abfd);
3034  boolean failed;
3035  struct bfd_strtab_hash *strtab;
3036  Elf_Internal_Shdr *shstrtab_hdr;
3037
3038  if (abfd->output_has_begun)
3039    return true;
3040
3041  /* Do any elf backend specific processing first.  */
3042  if (bed->elf_backend_begin_write_processing)
3043    (*bed->elf_backend_begin_write_processing) (abfd, link_info);
3044
3045  if (! prep_headers (abfd))
3046    return false;
3047
3048  /* Post process the headers if necessary.  */
3049  if (bed->elf_backend_post_process_headers)
3050    (*bed->elf_backend_post_process_headers) (abfd, link_info);
3051
3052  failed = false;
3053  bfd_map_over_sections (abfd, elf_fake_sections, &failed);
3054  if (failed)
3055    return false;
3056
3057  if (!assign_section_numbers (abfd))
3058    return false;
3059
3060  /* The backend linker builds symbol table information itself.  */
3061  if (link_info == NULL && bfd_get_symcount (abfd) > 0)
3062    {
3063      /* Non-zero if doing a relocatable link.  */
3064      int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
3065
3066      if (! swap_out_syms (abfd, &strtab, relocatable_p))
3067	return false;
3068    }
3069
3070  if (link_info == NULL)
3071    {
3072      bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
3073      if (failed)
3074	return false;
3075    }
3076
3077  shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
3078  /* sh_name was set in prep_headers.  */
3079  shstrtab_hdr->sh_type = SHT_STRTAB;
3080  shstrtab_hdr->sh_flags = 0;
3081  shstrtab_hdr->sh_addr = 0;
3082  shstrtab_hdr->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
3083  shstrtab_hdr->sh_entsize = 0;
3084  shstrtab_hdr->sh_link = 0;
3085  shstrtab_hdr->sh_info = 0;
3086  /* sh_offset is set in assign_file_positions_except_relocs.  */
3087  shstrtab_hdr->sh_addralign = 1;
3088
3089  if (!assign_file_positions_except_relocs (abfd))
3090    return false;
3091
3092  if (link_info == NULL && bfd_get_symcount (abfd) > 0)
3093    {
3094      file_ptr off;
3095      Elf_Internal_Shdr *hdr;
3096
3097      off = elf_tdata (abfd)->next_file_pos;
3098
3099      hdr = &elf_tdata (abfd)->symtab_hdr;
3100      off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3101
3102      hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
3103      if (hdr->sh_size != 0)
3104	off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3105
3106      hdr = &elf_tdata (abfd)->strtab_hdr;
3107      off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3108
3109      elf_tdata (abfd)->next_file_pos = off;
3110
3111      /* Now that we know where the .strtab section goes, write it
3112         out.  */
3113      if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
3114	  || ! _bfd_stringtab_emit (abfd, strtab))
3115	return false;
3116      _bfd_stringtab_free (strtab);
3117    }
3118
3119  abfd->output_has_begun = true;
3120
3121  return true;
3122}
3123
3124/* Create a mapping from a set of sections to a program segment.  */
3125
3126static INLINE struct elf_segment_map *
3127make_mapping (abfd, sections, from, to, phdr)
3128     bfd *abfd;
3129     asection **sections;
3130     unsigned int from;
3131     unsigned int to;
3132     boolean phdr;
3133{
3134  struct elf_segment_map *m;
3135  unsigned int i;
3136  asection **hdrpp;
3137  bfd_size_type amt;
3138
3139  amt = sizeof (struct elf_segment_map);
3140  amt += (to - from - 1) * sizeof (asection *);
3141  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3142  if (m == NULL)
3143    return NULL;
3144  m->next = NULL;
3145  m->p_type = PT_LOAD;
3146  for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
3147    m->sections[i - from] = *hdrpp;
3148  m->count = to - from;
3149
3150  if (from == 0 && phdr)
3151    {
3152      /* Include the headers in the first PT_LOAD segment.  */
3153      m->includes_filehdr = 1;
3154      m->includes_phdrs = 1;
3155    }
3156
3157  return m;
3158}
3159
3160/* Set up a mapping from BFD sections to program segments.  */
3161
3162static boolean
3163map_sections_to_segments (abfd)
3164     bfd *abfd;
3165{
3166  asection **sections = NULL;
3167  asection *s;
3168  unsigned int i;
3169  unsigned int count;
3170  struct elf_segment_map *mfirst;
3171  struct elf_segment_map **pm;
3172  struct elf_segment_map *m;
3173  asection *last_hdr;
3174  unsigned int phdr_index;
3175  bfd_vma maxpagesize;
3176  asection **hdrpp;
3177  boolean phdr_in_segment = true;
3178  boolean writable;
3179  int tls_count = 0;
3180  asection *first_tls = NULL;
3181  asection *dynsec, *eh_frame_hdr;
3182  bfd_size_type amt;
3183
3184  if (elf_tdata (abfd)->segment_map != NULL)
3185    return true;
3186
3187  if (bfd_count_sections (abfd) == 0)
3188    return true;
3189
3190  /* Select the allocated sections, and sort them.  */
3191
3192  amt = bfd_count_sections (abfd) * sizeof (asection *);
3193  sections = (asection **) bfd_malloc (amt);
3194  if (sections == NULL)
3195    goto error_return;
3196
3197  i = 0;
3198  for (s = abfd->sections; s != NULL; s = s->next)
3199    {
3200      if ((s->flags & SEC_ALLOC) != 0)
3201	{
3202	  sections[i] = s;
3203	  ++i;
3204	}
3205    }
3206  BFD_ASSERT (i <= bfd_count_sections (abfd));
3207  count = i;
3208
3209  qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
3210
3211  /* Build the mapping.  */
3212
3213  mfirst = NULL;
3214  pm = &mfirst;
3215
3216  /* If we have a .interp section, then create a PT_PHDR segment for
3217     the program headers and a PT_INTERP segment for the .interp
3218     section.  */
3219  s = bfd_get_section_by_name (abfd, ".interp");
3220  if (s != NULL && (s->flags & SEC_LOAD) != 0)
3221    {
3222      amt = sizeof (struct elf_segment_map);
3223      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3224      if (m == NULL)
3225	goto error_return;
3226      m->next = NULL;
3227      m->p_type = PT_PHDR;
3228      /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
3229      m->p_flags = PF_R | PF_X;
3230      m->p_flags_valid = 1;
3231      m->includes_phdrs = 1;
3232
3233      *pm = m;
3234      pm = &m->next;
3235
3236      amt = sizeof (struct elf_segment_map);
3237      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3238      if (m == NULL)
3239	goto error_return;
3240      m->next = NULL;
3241      m->p_type = PT_INTERP;
3242      m->count = 1;
3243      m->sections[0] = s;
3244
3245      *pm = m;
3246      pm = &m->next;
3247    }
3248
3249  /* Look through the sections.  We put sections in the same program
3250     segment when the start of the second section can be placed within
3251     a few bytes of the end of the first section.  */
3252  last_hdr = NULL;
3253  phdr_index = 0;
3254  maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
3255  writable = false;
3256  dynsec = bfd_get_section_by_name (abfd, ".dynamic");
3257  if (dynsec != NULL
3258      && (dynsec->flags & SEC_LOAD) == 0)
3259    dynsec = NULL;
3260
3261  /* Deal with -Ttext or something similar such that the first section
3262     is not adjacent to the program headers.  This is an
3263     approximation, since at this point we don't know exactly how many
3264     program headers we will need.  */
3265  if (count > 0)
3266    {
3267      bfd_size_type phdr_size;
3268
3269      phdr_size = elf_tdata (abfd)->program_header_size;
3270      if (phdr_size == 0)
3271	phdr_size = get_elf_backend_data (abfd)->s->sizeof_phdr;
3272      if ((abfd->flags & D_PAGED) == 0
3273	  || sections[0]->lma < phdr_size
3274	  || sections[0]->lma % maxpagesize < phdr_size % maxpagesize)
3275	phdr_in_segment = false;
3276    }
3277
3278  for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
3279    {
3280      asection *hdr;
3281      boolean new_segment;
3282
3283      hdr = *hdrpp;
3284
3285      /* See if this section and the last one will fit in the same
3286         segment.  */
3287
3288      if (last_hdr == NULL)
3289	{
3290	  /* If we don't have a segment yet, then we don't need a new
3291	     one (we build the last one after this loop).  */
3292	  new_segment = false;
3293	}
3294      else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
3295	{
3296	  /* If this section has a different relation between the
3297             virtual address and the load address, then we need a new
3298             segment.  */
3299	  new_segment = true;
3300	}
3301      else if (BFD_ALIGN (last_hdr->lma + last_hdr->_raw_size, maxpagesize)
3302	       < BFD_ALIGN (hdr->lma, maxpagesize))
3303	{
3304	  /* If putting this section in this segment would force us to
3305             skip a page in the segment, then we need a new segment.  */
3306	  new_segment = true;
3307	}
3308      else if ((last_hdr->flags & SEC_LOAD) == 0
3309	       && (hdr->flags & SEC_LOAD) != 0)
3310	{
3311	  /* We don't want to put a loadable section after a
3312             nonloadable section in the same segment.  */
3313	  new_segment = true;
3314	}
3315      else if ((abfd->flags & D_PAGED) == 0)
3316	{
3317	  /* If the file is not demand paged, which means that we
3318             don't require the sections to be correctly aligned in the
3319             file, then there is no other reason for a new segment.  */
3320	  new_segment = false;
3321	}
3322      else if (! writable
3323	       && (hdr->flags & SEC_READONLY) == 0
3324	       && (((last_hdr->lma + last_hdr->_raw_size - 1)
3325		    & ~(maxpagesize - 1))
3326		   != (hdr->lma & ~(maxpagesize - 1))))
3327	{
3328	  /* We don't want to put a writable section in a read only
3329             segment, unless they are on the same page in memory
3330             anyhow.  We already know that the last section does not
3331             bring us past the current section on the page, so the
3332             only case in which the new section is not on the same
3333             page as the previous section is when the previous section
3334             ends precisely on a page boundary.  */
3335	  new_segment = true;
3336	}
3337      else
3338	{
3339	  /* Otherwise, we can use the same segment.  */
3340	  new_segment = false;
3341	}
3342
3343      if (! new_segment)
3344	{
3345	  if ((hdr->flags & SEC_READONLY) == 0)
3346	    writable = true;
3347	  last_hdr = hdr;
3348	  continue;
3349	}
3350
3351      /* We need a new program segment.  We must create a new program
3352         header holding all the sections from phdr_index until hdr.  */
3353
3354      m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
3355      if (m == NULL)
3356	goto error_return;
3357
3358      *pm = m;
3359      pm = &m->next;
3360
3361      if ((hdr->flags & SEC_READONLY) == 0)
3362	writable = true;
3363      else
3364	writable = false;
3365
3366      last_hdr = hdr;
3367      phdr_index = i;
3368      phdr_in_segment = false;
3369    }
3370
3371  /* Create a final PT_LOAD program segment.  */
3372  if (last_hdr != NULL)
3373    {
3374      m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
3375      if (m == NULL)
3376	goto error_return;
3377
3378      *pm = m;
3379      pm = &m->next;
3380    }
3381
3382  /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
3383  if (dynsec != NULL)
3384    {
3385      amt = sizeof (struct elf_segment_map);
3386      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3387      if (m == NULL)
3388	goto error_return;
3389      m->next = NULL;
3390      m->p_type = PT_DYNAMIC;
3391      m->count = 1;
3392      m->sections[0] = dynsec;
3393
3394      *pm = m;
3395      pm = &m->next;
3396    }
3397
3398  /* For each loadable .note section, add a PT_NOTE segment.  We don't
3399     use bfd_get_section_by_name, because if we link together
3400     nonloadable .note sections and loadable .note sections, we will
3401     generate two .note sections in the output file.  FIXME: Using
3402     names for section types is bogus anyhow.  */
3403  for (s = abfd->sections; s != NULL; s = s->next)
3404    {
3405      if ((s->flags & SEC_LOAD) != 0
3406	  && strncmp (s->name, ".note", 5) == 0)
3407	{
3408	  amt = sizeof (struct elf_segment_map);
3409	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3410	  if (m == NULL)
3411	    goto error_return;
3412	  m->next = NULL;
3413	  m->p_type = PT_NOTE;
3414	  m->count = 1;
3415	  m->sections[0] = s;
3416
3417	  *pm = m;
3418	  pm = &m->next;
3419	}
3420      if (s->flags & SEC_THREAD_LOCAL)
3421	{
3422	  if (! tls_count)
3423	    first_tls = s;
3424	  tls_count++;
3425	}
3426    }
3427
3428  /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
3429  if (tls_count > 0)
3430    {
3431      int i;
3432
3433      amt = sizeof (struct elf_segment_map);
3434      amt += (tls_count - 1) * sizeof (asection *);
3435      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3436      if (m == NULL)
3437	goto error_return;
3438      m->next = NULL;
3439      m->p_type = PT_TLS;
3440      m->count = tls_count;
3441      /* Mandated PF_R.  */
3442      m->p_flags = PF_R;
3443      m->p_flags_valid = 1;
3444      for (i = 0; i < tls_count; ++i)
3445	{
3446	  BFD_ASSERT (first_tls->flags & SEC_THREAD_LOCAL);
3447	  m->sections[i] = first_tls;
3448	  first_tls = first_tls->next;
3449	}
3450
3451      *pm = m;
3452      pm = &m->next;
3453    }
3454
3455  /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
3456     segment.  */
3457  eh_frame_hdr = NULL;
3458  if (elf_tdata (abfd)->eh_frame_hdr)
3459    eh_frame_hdr = bfd_get_section_by_name (abfd, ".eh_frame_hdr");
3460  if (eh_frame_hdr != NULL && (eh_frame_hdr->flags & SEC_LOAD))
3461    {
3462      amt = sizeof (struct elf_segment_map);
3463      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3464      if (m == NULL)
3465	goto error_return;
3466      m->next = NULL;
3467      m->p_type = PT_GNU_EH_FRAME;
3468      m->count = 1;
3469      m->sections[0] = eh_frame_hdr;
3470
3471      *pm = m;
3472      pm = &m->next;
3473    }
3474
3475  free (sections);
3476  sections = NULL;
3477
3478  elf_tdata (abfd)->segment_map = mfirst;
3479  return true;
3480
3481 error_return:
3482  if (sections != NULL)
3483    free (sections);
3484  return false;
3485}
3486
3487/* Sort sections by address.  */
3488
3489static int
3490elf_sort_sections (arg1, arg2)
3491     const PTR arg1;
3492     const PTR arg2;
3493{
3494  const asection *sec1 = *(const asection **) arg1;
3495  const asection *sec2 = *(const asection **) arg2;
3496
3497  /* Sort by LMA first, since this is the address used to
3498     place the section into a segment.  */
3499  if (sec1->lma < sec2->lma)
3500    return -1;
3501  else if (sec1->lma > sec2->lma)
3502    return 1;
3503
3504  /* Then sort by VMA.  Normally the LMA and the VMA will be
3505     the same, and this will do nothing.  */
3506  if (sec1->vma < sec2->vma)
3507    return -1;
3508  else if (sec1->vma > sec2->vma)
3509    return 1;
3510
3511  /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
3512
3513#define TOEND(x) (((x)->flags & SEC_LOAD) == 0)
3514
3515  if (TOEND (sec1))
3516    {
3517      if (TOEND (sec2))
3518	{
3519	  /* If the indicies are the same, do not return 0
3520	     here, but continue to try the next comparison.  */
3521	  if (sec1->target_index - sec2->target_index != 0)
3522	    return sec1->target_index - sec2->target_index;
3523	}
3524      else
3525	return 1;
3526    }
3527  else if (TOEND (sec2))
3528    return -1;
3529
3530#undef TOEND
3531
3532  /* Sort by size, to put zero sized sections
3533     before others at the same address.  */
3534
3535  if (sec1->_raw_size < sec2->_raw_size)
3536    return -1;
3537  if (sec1->_raw_size > sec2->_raw_size)
3538    return 1;
3539
3540  return sec1->target_index - sec2->target_index;
3541}
3542
3543/* Assign file positions to the sections based on the mapping from
3544   sections to segments.  This function also sets up some fields in
3545   the file header, and writes out the program headers.  */
3546
3547static boolean
3548assign_file_positions_for_segments (abfd)
3549     bfd *abfd;
3550{
3551  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3552  unsigned int count;
3553  struct elf_segment_map *m;
3554  unsigned int alloc;
3555  Elf_Internal_Phdr *phdrs;
3556  file_ptr off, voff;
3557  bfd_vma filehdr_vaddr, filehdr_paddr;
3558  bfd_vma phdrs_vaddr, phdrs_paddr;
3559  Elf_Internal_Phdr *p;
3560  bfd_size_type amt;
3561
3562  if (elf_tdata (abfd)->segment_map == NULL)
3563    {
3564      if (! map_sections_to_segments (abfd))
3565	return false;
3566    }
3567  else
3568    {
3569      /* The placement algorithm assumes that non allocated sections are
3570	 not in PT_LOAD segments.  We ensure this here by removing such
3571	 sections from the segment map.  */
3572      for (m = elf_tdata (abfd)->segment_map;
3573	   m != NULL;
3574	   m = m->next)
3575	{
3576	  unsigned int new_count;
3577	  unsigned int i;
3578
3579	  if (m->p_type != PT_LOAD)
3580	    continue;
3581
3582	  new_count = 0;
3583	  for (i = 0; i < m->count; i ++)
3584	    {
3585	      if ((m->sections[i]->flags & SEC_ALLOC) != 0)
3586		{
3587		  if (i != new_count)
3588		    m->sections[new_count] = m->sections[i];
3589
3590		  new_count ++;
3591		}
3592	    }
3593
3594	  if (new_count != m->count)
3595	    m->count = new_count;
3596	}
3597    }
3598
3599  if (bed->elf_backend_modify_segment_map)
3600    {
3601      if (! (*bed->elf_backend_modify_segment_map) (abfd))
3602	return false;
3603    }
3604
3605  count = 0;
3606  for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
3607    ++count;
3608
3609  elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
3610  elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
3611  elf_elfheader (abfd)->e_phnum = count;
3612
3613  if (count == 0)
3614    return true;
3615
3616  /* If we already counted the number of program segments, make sure
3617     that we allocated enough space.  This happens when SIZEOF_HEADERS
3618     is used in a linker script.  */
3619  alloc = elf_tdata (abfd)->program_header_size / bed->s->sizeof_phdr;
3620  if (alloc != 0 && count > alloc)
3621    {
3622      ((*_bfd_error_handler)
3623       (_("%s: Not enough room for program headers (allocated %u, need %u)"),
3624	bfd_get_filename (abfd), alloc, count));
3625      bfd_set_error (bfd_error_bad_value);
3626      return false;
3627    }
3628
3629  if (alloc == 0)
3630    alloc = count;
3631
3632  amt = alloc * sizeof (Elf_Internal_Phdr);
3633  phdrs = (Elf_Internal_Phdr *) bfd_alloc (abfd, amt);
3634  if (phdrs == NULL)
3635    return false;
3636
3637  off = bed->s->sizeof_ehdr;
3638  off += alloc * bed->s->sizeof_phdr;
3639
3640  filehdr_vaddr = 0;
3641  filehdr_paddr = 0;
3642  phdrs_vaddr = 0;
3643  phdrs_paddr = 0;
3644
3645  for (m = elf_tdata (abfd)->segment_map, p = phdrs;
3646       m != NULL;
3647       m = m->next, p++)
3648    {
3649      unsigned int i;
3650      asection **secpp;
3651
3652      /* If elf_segment_map is not from map_sections_to_segments, the
3653         sections may not be correctly ordered.  NOTE: sorting should
3654	 not be done to the PT_NOTE section of a corefile, which may
3655	 contain several pseudo-sections artificially created by bfd.
3656	 Sorting these pseudo-sections breaks things badly.  */
3657      if (m->count > 1
3658	  && !(elf_elfheader (abfd)->e_type == ET_CORE
3659	       && m->p_type == PT_NOTE))
3660	qsort (m->sections, (size_t) m->count, sizeof (asection *),
3661	       elf_sort_sections);
3662
3663      p->p_type = m->p_type;
3664      p->p_flags = m->p_flags;
3665
3666      if (p->p_type == PT_LOAD
3667	  && m->count > 0
3668	  && (m->sections[0]->flags & SEC_ALLOC) != 0)
3669	{
3670	  if ((abfd->flags & D_PAGED) != 0)
3671	    off += (m->sections[0]->vma - off) % bed->maxpagesize;
3672	  else
3673	    {
3674	      bfd_size_type align;
3675
3676	      align = 0;
3677	      for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
3678		{
3679		  bfd_size_type secalign;
3680
3681		  secalign = bfd_get_section_alignment (abfd, *secpp);
3682		  if (secalign > align)
3683		    align = secalign;
3684		}
3685
3686	      off += (m->sections[0]->vma - off) % (1 << align);
3687	    }
3688	}
3689
3690      if (m->count == 0)
3691	p->p_vaddr = 0;
3692      else
3693	p->p_vaddr = m->sections[0]->vma;
3694
3695      if (m->p_paddr_valid)
3696	p->p_paddr = m->p_paddr;
3697      else if (m->count == 0)
3698	p->p_paddr = 0;
3699      else
3700	p->p_paddr = m->sections[0]->lma;
3701
3702      if (p->p_type == PT_LOAD
3703	  && (abfd->flags & D_PAGED) != 0)
3704	p->p_align = bed->maxpagesize;
3705      else if (m->count == 0)
3706	p->p_align = bed->s->file_align;
3707      else
3708	p->p_align = 0;
3709
3710      p->p_offset = 0;
3711      p->p_filesz = 0;
3712      p->p_memsz = 0;
3713
3714      if (m->includes_filehdr)
3715	{
3716	  if (! m->p_flags_valid)
3717	    p->p_flags |= PF_R;
3718	  p->p_offset = 0;
3719	  p->p_filesz = bed->s->sizeof_ehdr;
3720	  p->p_memsz = bed->s->sizeof_ehdr;
3721	  if (m->count > 0)
3722	    {
3723	      BFD_ASSERT (p->p_type == PT_LOAD);
3724
3725	      if (p->p_vaddr < (bfd_vma) off)
3726		{
3727		  (*_bfd_error_handler)
3728		    (_("%s: Not enough room for program headers, try linking with -N"),
3729		     bfd_get_filename (abfd));
3730		  bfd_set_error (bfd_error_bad_value);
3731		  return false;
3732		}
3733
3734	      p->p_vaddr -= off;
3735	      if (! m->p_paddr_valid)
3736		p->p_paddr -= off;
3737	    }
3738	  if (p->p_type == PT_LOAD)
3739	    {
3740	      filehdr_vaddr = p->p_vaddr;
3741	      filehdr_paddr = p->p_paddr;
3742	    }
3743	}
3744
3745      if (m->includes_phdrs)
3746	{
3747	  if (! m->p_flags_valid)
3748	    p->p_flags |= PF_R;
3749
3750	  if (m->includes_filehdr)
3751	    {
3752	      if (p->p_type == PT_LOAD)
3753		{
3754		  phdrs_vaddr = p->p_vaddr + bed->s->sizeof_ehdr;
3755		  phdrs_paddr = p->p_paddr + bed->s->sizeof_ehdr;
3756		}
3757	    }
3758	  else
3759	    {
3760	      p->p_offset = bed->s->sizeof_ehdr;
3761
3762	      if (m->count > 0)
3763		{
3764		  BFD_ASSERT (p->p_type == PT_LOAD);
3765		  p->p_vaddr -= off - p->p_offset;
3766		  if (! m->p_paddr_valid)
3767		    p->p_paddr -= off - p->p_offset;
3768		}
3769
3770	      if (p->p_type == PT_LOAD)
3771		{
3772		  phdrs_vaddr = p->p_vaddr;
3773		  phdrs_paddr = p->p_paddr;
3774		}
3775	      else
3776		phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
3777	    }
3778
3779	  p->p_filesz += alloc * bed->s->sizeof_phdr;
3780	  p->p_memsz += alloc * bed->s->sizeof_phdr;
3781	}
3782
3783      if (p->p_type == PT_LOAD
3784	  || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
3785	{
3786	  if (! m->includes_filehdr && ! m->includes_phdrs)
3787	    p->p_offset = off;
3788	  else
3789	    {
3790	      file_ptr adjust;
3791
3792	      adjust = off - (p->p_offset + p->p_filesz);
3793	      p->p_filesz += adjust;
3794	      p->p_memsz += adjust;
3795	    }
3796	}
3797
3798      voff = off;
3799
3800      for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
3801	{
3802	  asection *sec;
3803	  flagword flags;
3804	  bfd_size_type align;
3805
3806	  sec = *secpp;
3807	  flags = sec->flags;
3808	  align = 1 << bfd_get_section_alignment (abfd, sec);
3809
3810	  /* The section may have artificial alignment forced by a
3811	     link script.  Notice this case by the gap between the
3812	     cumulative phdr lma and the section's lma.  */
3813	  if (p->p_paddr + p->p_memsz < sec->lma)
3814	    {
3815	      bfd_vma adjust = sec->lma - (p->p_paddr + p->p_memsz);
3816
3817	      p->p_memsz += adjust;
3818	      off += adjust;
3819	      voff += adjust;
3820	      if ((flags & SEC_LOAD) != 0)
3821		p->p_filesz += adjust;
3822	    }
3823
3824	  if (p->p_type == PT_LOAD)
3825	    {
3826	      bfd_signed_vma adjust;
3827
3828	      if ((flags & SEC_LOAD) != 0)
3829		{
3830		  adjust = sec->lma - (p->p_paddr + p->p_memsz);
3831		  if (adjust < 0)
3832		    adjust = 0;
3833		}
3834	      else if ((flags & SEC_ALLOC) != 0)
3835		{
3836		  /* The section VMA must equal the file position
3837		     modulo the page size.  FIXME: I'm not sure if
3838		     this adjustment is really necessary.  We used to
3839		     not have the SEC_LOAD case just above, and then
3840		     this was necessary, but now I'm not sure.  */
3841		  if ((abfd->flags & D_PAGED) != 0)
3842		    adjust = (sec->vma - voff) % bed->maxpagesize;
3843		  else
3844		    adjust = (sec->vma - voff) % align;
3845		}
3846	      else
3847		adjust = 0;
3848
3849	      if (adjust != 0)
3850		{
3851		  if (i == 0)
3852		    {
3853		      (* _bfd_error_handler) (_("\
3854Error: First section in segment (%s) starts at 0x%x whereas the segment starts at 0x%x"),
3855					      bfd_section_name (abfd, sec),
3856					      sec->lma,
3857					      p->p_paddr);
3858		      return false;
3859		    }
3860		  p->p_memsz += adjust;
3861		  off += adjust;
3862		  voff += adjust;
3863		  if ((flags & SEC_LOAD) != 0)
3864		    p->p_filesz += adjust;
3865		}
3866
3867	      sec->filepos = off;
3868
3869	      /* We check SEC_HAS_CONTENTS here because if NOLOAD is
3870                 used in a linker script we may have a section with
3871                 SEC_LOAD clear but which is supposed to have
3872                 contents.  */
3873	      if ((flags & SEC_LOAD) != 0
3874		  || (flags & SEC_HAS_CONTENTS) != 0)
3875		off += sec->_raw_size;
3876
3877	      if ((flags & SEC_ALLOC) != 0)
3878		voff += sec->_raw_size;
3879	    }
3880
3881	  if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
3882	    {
3883	      /* The actual "note" segment has i == 0.
3884		 This is the one that actually contains everything.  */
3885	      if (i == 0)
3886		{
3887		  sec->filepos = off;
3888		  p->p_filesz = sec->_raw_size;
3889		  off += sec->_raw_size;
3890		  voff = off;
3891		}
3892	      else
3893		{
3894		  /* Fake sections -- don't need to be written.  */
3895		  sec->filepos = 0;
3896		  sec->_raw_size = 0;
3897		  flags = sec->flags = 0;
3898		}
3899	      p->p_memsz = 0;
3900	      p->p_align = 1;
3901	    }
3902	  else
3903	    {
3904	      p->p_memsz += sec->_raw_size;
3905
3906	      if ((flags & SEC_LOAD) != 0)
3907		p->p_filesz += sec->_raw_size;
3908
3909	      if (p->p_type == PT_TLS
3910		  && sec->_raw_size == 0
3911		  && (sec->flags & SEC_HAS_CONTENTS) == 0)
3912		{
3913		  struct bfd_link_order *o;
3914		  bfd_vma tbss_size = 0;
3915
3916		  for (o = sec->link_order_head; o != NULL; o = o->next)
3917		    if (tbss_size < o->offset + o->size)
3918		      tbss_size = o->offset + o->size;
3919
3920		  p->p_memsz += tbss_size;
3921		}
3922
3923	      if (align > p->p_align
3924		  && (p->p_type != PT_LOAD || (abfd->flags & D_PAGED) == 0))
3925		p->p_align = align;
3926	    }
3927
3928	  if (! m->p_flags_valid)
3929	    {
3930	      p->p_flags |= PF_R;
3931	      if ((flags & SEC_CODE) != 0)
3932		p->p_flags |= PF_X;
3933	      if ((flags & SEC_READONLY) == 0)
3934		p->p_flags |= PF_W;
3935	    }
3936	}
3937    }
3938
3939  /* Now that we have set the section file positions, we can set up
3940     the file positions for the non PT_LOAD segments.  */
3941  for (m = elf_tdata (abfd)->segment_map, p = phdrs;
3942       m != NULL;
3943       m = m->next, p++)
3944    {
3945      if (p->p_type != PT_LOAD && m->count > 0)
3946	{
3947	  BFD_ASSERT (! m->includes_filehdr && ! m->includes_phdrs);
3948	  p->p_offset = m->sections[0]->filepos;
3949	}
3950      if (m->count == 0)
3951	{
3952	  if (m->includes_filehdr)
3953	    {
3954	      p->p_vaddr = filehdr_vaddr;
3955	      if (! m->p_paddr_valid)
3956		p->p_paddr = filehdr_paddr;
3957	    }
3958	  else if (m->includes_phdrs)
3959	    {
3960	      p->p_vaddr = phdrs_vaddr;
3961	      if (! m->p_paddr_valid)
3962		p->p_paddr = phdrs_paddr;
3963	    }
3964	}
3965    }
3966
3967  /* Clear out any program headers we allocated but did not use.  */
3968  for (; count < alloc; count++, p++)
3969    {
3970      memset (p, 0, sizeof *p);
3971      p->p_type = PT_NULL;
3972    }
3973
3974  elf_tdata (abfd)->phdr = phdrs;
3975
3976  elf_tdata (abfd)->next_file_pos = off;
3977
3978  /* Write out the program headers.  */
3979  if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
3980      || bed->s->write_out_phdrs (abfd, phdrs, alloc) != 0)
3981    return false;
3982
3983  return true;
3984}
3985
3986/* Get the size of the program header.
3987
3988   If this is called by the linker before any of the section VMA's are set, it
3989   can't calculate the correct value for a strange memory layout.  This only
3990   happens when SIZEOF_HEADERS is used in a linker script.  In this case,
3991   SORTED_HDRS is NULL and we assume the normal scenario of one text and one
3992   data segment (exclusive of .interp and .dynamic).
3993
3994   ??? User written scripts must either not use SIZEOF_HEADERS, or assume there
3995   will be two segments.  */
3996
3997static bfd_size_type
3998get_program_header_size (abfd)
3999     bfd *abfd;
4000{
4001  size_t segs;
4002  asection *s;
4003  struct elf_backend_data *bed = get_elf_backend_data (abfd);
4004
4005  /* We can't return a different result each time we're called.  */
4006  if (elf_tdata (abfd)->program_header_size != 0)
4007    return elf_tdata (abfd)->program_header_size;
4008
4009  if (elf_tdata (abfd)->segment_map != NULL)
4010    {
4011      struct elf_segment_map *m;
4012
4013      segs = 0;
4014      for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
4015	++segs;
4016      elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
4017      return elf_tdata (abfd)->program_header_size;
4018    }
4019
4020  /* Assume we will need exactly two PT_LOAD segments: one for text
4021     and one for data.  */
4022  segs = 2;
4023
4024  s = bfd_get_section_by_name (abfd, ".interp");
4025  if (s != NULL && (s->flags & SEC_LOAD) != 0)
4026    {
4027      /* If we have a loadable interpreter section, we need a
4028	 PT_INTERP segment.  In this case, assume we also need a
4029	 PT_PHDR segment, although that may not be true for all
4030	 targets.  */
4031      segs += 2;
4032    }
4033
4034  if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
4035    {
4036      /* We need a PT_DYNAMIC segment.  */
4037      ++segs;
4038    }
4039
4040  if (elf_tdata (abfd)->eh_frame_hdr
4041      && bfd_get_section_by_name (abfd, ".eh_frame_hdr") != NULL)
4042    {
4043      /* We need a PT_GNU_EH_FRAME segment.  */
4044      ++segs;
4045    }
4046
4047  for (s = abfd->sections; s != NULL; s = s->next)
4048    {
4049      if ((s->flags & SEC_LOAD) != 0
4050	  && strncmp (s->name, ".note", 5) == 0)
4051	{
4052	  /* We need a PT_NOTE segment.  */
4053	  ++segs;
4054	}
4055    }
4056
4057  for (s = abfd->sections; s != NULL; s = s->next)
4058    {
4059      if (s->flags & SEC_THREAD_LOCAL)
4060	{
4061	  /* We need a PT_TLS segment.  */
4062	  ++segs;
4063	  break;
4064	}
4065    }
4066
4067  /* Let the backend count up any program headers it might need.  */
4068  if (bed->elf_backend_additional_program_headers)
4069    {
4070      int a;
4071
4072      a = (*bed->elf_backend_additional_program_headers) (abfd);
4073      if (a == -1)
4074	abort ();
4075      segs += a;
4076    }
4077
4078  elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
4079  return elf_tdata (abfd)->program_header_size;
4080}
4081
4082/* Work out the file positions of all the sections.  This is called by
4083   _bfd_elf_compute_section_file_positions.  All the section sizes and
4084   VMAs must be known before this is called.
4085
4086   We do not consider reloc sections at this point, unless they form
4087   part of the loadable image.  Reloc sections are assigned file
4088   positions in assign_file_positions_for_relocs, which is called by
4089   write_object_contents and final_link.
4090
4091   We also don't set the positions of the .symtab and .strtab here.  */
4092
4093static boolean
4094assign_file_positions_except_relocs (abfd)
4095     bfd *abfd;
4096{
4097  struct elf_obj_tdata * const tdata = elf_tdata (abfd);
4098  Elf_Internal_Ehdr * const i_ehdrp = elf_elfheader (abfd);
4099  Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
4100  unsigned int num_sec = elf_numsections (abfd);
4101  file_ptr off;
4102  struct elf_backend_data *bed = get_elf_backend_data (abfd);
4103
4104  if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
4105      && bfd_get_format (abfd) != bfd_core)
4106    {
4107      Elf_Internal_Shdr **hdrpp;
4108      unsigned int i;
4109
4110      /* Start after the ELF header.  */
4111      off = i_ehdrp->e_ehsize;
4112
4113      /* We are not creating an executable, which means that we are
4114	 not creating a program header, and that the actual order of
4115	 the sections in the file is unimportant.  */
4116      for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
4117	{
4118	  Elf_Internal_Shdr *hdr;
4119
4120	  hdr = *hdrpp;
4121	  if (hdr->sh_type == SHT_REL
4122	      || hdr->sh_type == SHT_RELA
4123	      || i == tdata->symtab_section
4124	      || i == tdata->symtab_shndx_section
4125	      || i == tdata->strtab_section)
4126	    {
4127	      hdr->sh_offset = -1;
4128	    }
4129	  else
4130	    off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
4131
4132	  if (i == SHN_LORESERVE - 1)
4133	    {
4134	      i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4135	      hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4136	    }
4137	}
4138    }
4139  else
4140    {
4141      unsigned int i;
4142      Elf_Internal_Shdr **hdrpp;
4143
4144      /* Assign file positions for the loaded sections based on the
4145         assignment of sections to segments.  */
4146      if (! assign_file_positions_for_segments (abfd))
4147	return false;
4148
4149      /* Assign file positions for the other sections.  */
4150
4151      off = elf_tdata (abfd)->next_file_pos;
4152      for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
4153	{
4154	  Elf_Internal_Shdr *hdr;
4155
4156	  hdr = *hdrpp;
4157	  if (hdr->bfd_section != NULL
4158	      && hdr->bfd_section->filepos != 0)
4159	    hdr->sh_offset = hdr->bfd_section->filepos;
4160	  else if ((hdr->sh_flags & SHF_ALLOC) != 0)
4161	    {
4162	      ((*_bfd_error_handler)
4163	       (_("%s: warning: allocated section `%s' not in segment"),
4164		bfd_get_filename (abfd),
4165		(hdr->bfd_section == NULL
4166		 ? "*unknown*"
4167		 : hdr->bfd_section->name)));
4168	      if ((abfd->flags & D_PAGED) != 0)
4169		off += (hdr->sh_addr - off) % bed->maxpagesize;
4170	      else
4171		off += (hdr->sh_addr - off) % hdr->sh_addralign;
4172	      off = _bfd_elf_assign_file_position_for_section (hdr, off,
4173							       false);
4174	    }
4175	  else if (hdr->sh_type == SHT_REL
4176		   || hdr->sh_type == SHT_RELA
4177		   || hdr == i_shdrpp[tdata->symtab_section]
4178		   || hdr == i_shdrpp[tdata->symtab_shndx_section]
4179		   || hdr == i_shdrpp[tdata->strtab_section])
4180	    hdr->sh_offset = -1;
4181	  else
4182	    off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
4183
4184	  if (i == SHN_LORESERVE - 1)
4185	    {
4186	      i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4187	      hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4188	    }
4189	}
4190    }
4191
4192  /* Place the section headers.  */
4193  off = align_file_position (off, bed->s->file_align);
4194  i_ehdrp->e_shoff = off;
4195  off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
4196
4197  elf_tdata (abfd)->next_file_pos = off;
4198
4199  return true;
4200}
4201
4202static boolean
4203prep_headers (abfd)
4204     bfd *abfd;
4205{
4206  Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form */
4207  Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
4208  Elf_Internal_Shdr **i_shdrp;	/* Section header table, internal form */
4209  struct elf_strtab_hash *shstrtab;
4210  struct elf_backend_data *bed = get_elf_backend_data (abfd);
4211
4212  i_ehdrp = elf_elfheader (abfd);
4213  i_shdrp = elf_elfsections (abfd);
4214
4215  shstrtab = _bfd_elf_strtab_init ();
4216  if (shstrtab == NULL)
4217    return false;
4218
4219  elf_shstrtab (abfd) = shstrtab;
4220
4221  i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
4222  i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
4223  i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
4224  i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
4225
4226  i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
4227  i_ehdrp->e_ident[EI_DATA] =
4228    bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
4229  i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
4230
4231  i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
4232
4233  if ((abfd->flags & DYNAMIC) != 0)
4234    i_ehdrp->e_type = ET_DYN;
4235  else if ((abfd->flags & EXEC_P) != 0)
4236    i_ehdrp->e_type = ET_EXEC;
4237  else if (bfd_get_format (abfd) == bfd_core)
4238    i_ehdrp->e_type = ET_CORE;
4239  else
4240    i_ehdrp->e_type = ET_REL;
4241
4242  switch (bfd_get_arch (abfd))
4243    {
4244    case bfd_arch_unknown:
4245      i_ehdrp->e_machine = EM_NONE;
4246      break;
4247
4248      /* There used to be a long list of cases here, each one setting
4249	 e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
4250	 in the corresponding bfd definition.  To avoid duplication,
4251	 the switch was removed.  Machines that need special handling
4252	 can generally do it in elf_backend_final_write_processing(),
4253	 unless they need the information earlier than the final write.
4254	 Such need can generally be supplied by replacing the tests for
4255	 e_machine with the conditions used to determine it.  */
4256    default:
4257      if (get_elf_backend_data (abfd) != NULL)
4258	i_ehdrp->e_machine = get_elf_backend_data (abfd)->elf_machine_code;
4259      else
4260	i_ehdrp->e_machine = EM_NONE;
4261      }
4262
4263  i_ehdrp->e_version = bed->s->ev_current;
4264  i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
4265
4266  /* No program header, for now.  */
4267  i_ehdrp->e_phoff = 0;
4268  i_ehdrp->e_phentsize = 0;
4269  i_ehdrp->e_phnum = 0;
4270
4271  /* Each bfd section is section header entry.  */
4272  i_ehdrp->e_entry = bfd_get_start_address (abfd);
4273  i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
4274
4275  /* If we're building an executable, we'll need a program header table.  */
4276  if (abfd->flags & EXEC_P)
4277    {
4278      /* It all happens later.  */
4279#if 0
4280      i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
4281
4282      /* elf_build_phdrs() returns a (NULL-terminated) array of
4283	 Elf_Internal_Phdrs.  */
4284      i_phdrp = elf_build_phdrs (abfd, i_ehdrp, i_shdrp, &i_ehdrp->e_phnum);
4285      i_ehdrp->e_phoff = outbase;
4286      outbase += i_ehdrp->e_phentsize * i_ehdrp->e_phnum;
4287#endif
4288    }
4289  else
4290    {
4291      i_ehdrp->e_phentsize = 0;
4292      i_phdrp = 0;
4293      i_ehdrp->e_phoff = 0;
4294    }
4295
4296  elf_tdata (abfd)->symtab_hdr.sh_name =
4297    (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", false);
4298  elf_tdata (abfd)->strtab_hdr.sh_name =
4299    (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", false);
4300  elf_tdata (abfd)->shstrtab_hdr.sh_name =
4301    (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", false);
4302  if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4303      || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4304      || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
4305    return false;
4306
4307  return true;
4308}
4309
4310/* Assign file positions for all the reloc sections which are not part
4311   of the loadable file image.  */
4312
4313void
4314_bfd_elf_assign_file_positions_for_relocs (abfd)
4315     bfd *abfd;
4316{
4317  file_ptr off;
4318  unsigned int i, num_sec;
4319  Elf_Internal_Shdr **shdrpp;
4320
4321  off = elf_tdata (abfd)->next_file_pos;
4322
4323  num_sec = elf_numsections (abfd);
4324  for (i = 1, shdrpp = elf_elfsections (abfd) + 1; i < num_sec; i++, shdrpp++)
4325    {
4326      Elf_Internal_Shdr *shdrp;
4327
4328      shdrp = *shdrpp;
4329      if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
4330	  && shdrp->sh_offset == -1)
4331	off = _bfd_elf_assign_file_position_for_section (shdrp, off, true);
4332    }
4333
4334  elf_tdata (abfd)->next_file_pos = off;
4335}
4336
4337boolean
4338_bfd_elf_write_object_contents (abfd)
4339     bfd *abfd;
4340{
4341  struct elf_backend_data *bed = get_elf_backend_data (abfd);
4342  Elf_Internal_Ehdr *i_ehdrp;
4343  Elf_Internal_Shdr **i_shdrp;
4344  boolean failed;
4345  unsigned int count, num_sec;
4346
4347  if (! abfd->output_has_begun
4348      && ! _bfd_elf_compute_section_file_positions
4349             (abfd, (struct bfd_link_info *) NULL))
4350    return false;
4351
4352  i_shdrp = elf_elfsections (abfd);
4353  i_ehdrp = elf_elfheader (abfd);
4354
4355  failed = false;
4356  bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
4357  if (failed)
4358    return false;
4359
4360  _bfd_elf_assign_file_positions_for_relocs (abfd);
4361
4362  /* After writing the headers, we need to write the sections too...  */
4363  num_sec = elf_numsections (abfd);
4364  for (count = 1; count < num_sec; count++)
4365    {
4366      if (bed->elf_backend_section_processing)
4367	(*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
4368      if (i_shdrp[count]->contents)
4369	{
4370	  bfd_size_type amt = i_shdrp[count]->sh_size;
4371
4372	  if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
4373	      || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
4374	    return false;
4375	}
4376      if (count == SHN_LORESERVE - 1)
4377	count += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4378    }
4379
4380  /* Write out the section header names.  */
4381  if (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
4382      || ! _bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd)))
4383    return false;
4384
4385  if (bed->elf_backend_final_write_processing)
4386    (*bed->elf_backend_final_write_processing) (abfd,
4387						elf_tdata (abfd)->linker);
4388
4389  return bed->s->write_shdrs_and_ehdr (abfd);
4390}
4391
4392boolean
4393_bfd_elf_write_corefile_contents (abfd)
4394     bfd *abfd;
4395{
4396  /* Hopefully this can be done just like an object file.  */
4397  return _bfd_elf_write_object_contents (abfd);
4398}
4399
4400/* Given a section, search the header to find them.  */
4401
4402int
4403_bfd_elf_section_from_bfd_section (abfd, asect)
4404     bfd *abfd;
4405     struct sec *asect;
4406{
4407  struct elf_backend_data *bed;
4408  int index;
4409
4410  if (elf_section_data (asect) != NULL
4411      && elf_section_data (asect)->this_idx != 0)
4412    return elf_section_data (asect)->this_idx;
4413
4414  if (bfd_is_abs_section (asect))
4415    index = SHN_ABS;
4416  else if (bfd_is_com_section (asect))
4417    index = SHN_COMMON;
4418  else if (bfd_is_und_section (asect))
4419    index = SHN_UNDEF;
4420  else
4421    {
4422      Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
4423      int maxindex = elf_numsections (abfd);
4424
4425      for (index = 1; index < maxindex; index++)
4426	{
4427	  Elf_Internal_Shdr *hdr = i_shdrp[index];
4428
4429	  if (hdr != NULL && hdr->bfd_section == asect)
4430	    return index;
4431	}
4432      index = -1;
4433    }
4434
4435  bed = get_elf_backend_data (abfd);
4436  if (bed->elf_backend_section_from_bfd_section)
4437    {
4438      int retval = index;
4439
4440      if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
4441	return retval;
4442    }
4443
4444  if (index == -1)
4445    bfd_set_error (bfd_error_nonrepresentable_section);
4446
4447  return index;
4448}
4449
4450/* Given a BFD symbol, return the index in the ELF symbol table, or -1
4451   on error.  */
4452
4453int
4454_bfd_elf_symbol_from_bfd_symbol (abfd, asym_ptr_ptr)
4455     bfd *abfd;
4456     asymbol **asym_ptr_ptr;
4457{
4458  asymbol *asym_ptr = *asym_ptr_ptr;
4459  int idx;
4460  flagword flags = asym_ptr->flags;
4461
4462  /* When gas creates relocations against local labels, it creates its
4463     own symbol for the section, but does put the symbol into the
4464     symbol chain, so udata is 0.  When the linker is generating
4465     relocatable output, this section symbol may be for one of the
4466     input sections rather than the output section.  */
4467  if (asym_ptr->udata.i == 0
4468      && (flags & BSF_SECTION_SYM)
4469      && asym_ptr->section)
4470    {
4471      int indx;
4472
4473      if (asym_ptr->section->output_section != NULL)
4474	indx = asym_ptr->section->output_section->index;
4475      else
4476	indx = asym_ptr->section->index;
4477      if (indx < elf_num_section_syms (abfd)
4478	  && elf_section_syms (abfd)[indx] != NULL)
4479	asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
4480    }
4481
4482  idx = asym_ptr->udata.i;
4483
4484  if (idx == 0)
4485    {
4486      /* This case can occur when using --strip-symbol on a symbol
4487         which is used in a relocation entry.  */
4488      (*_bfd_error_handler)
4489	(_("%s: symbol `%s' required but not present"),
4490	 bfd_archive_filename (abfd), bfd_asymbol_name (asym_ptr));
4491      bfd_set_error (bfd_error_no_symbols);
4492      return -1;
4493    }
4494
4495#if DEBUG & 4
4496  {
4497    fprintf (stderr,
4498	     "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx%s\n",
4499	     (long) asym_ptr, asym_ptr->name, idx, flags,
4500	     elf_symbol_flags (flags));
4501    fflush (stderr);
4502  }
4503#endif
4504
4505  return idx;
4506}
4507
4508/* Copy private BFD data.  This copies any program header information.  */
4509
4510static boolean
4511copy_private_bfd_data (ibfd, obfd)
4512     bfd *ibfd;
4513     bfd *obfd;
4514{
4515  Elf_Internal_Ehdr *       iehdr;
4516  struct elf_segment_map *  map;
4517  struct elf_segment_map *  map_first;
4518  struct elf_segment_map ** pointer_to_map;
4519  Elf_Internal_Phdr *       segment;
4520  asection *                section;
4521  unsigned int              i;
4522  unsigned int              num_segments;
4523  boolean                   phdr_included = false;
4524  bfd_vma                   maxpagesize;
4525  struct elf_segment_map *  phdr_adjust_seg = NULL;
4526  unsigned int              phdr_adjust_num = 0;
4527  struct elf_backend_data * bed;
4528
4529  if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
4530      || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
4531    return true;
4532
4533  if (elf_tdata (ibfd)->phdr == NULL)
4534    return true;
4535
4536  bed = get_elf_backend_data (ibfd);
4537  iehdr = elf_elfheader (ibfd);
4538
4539  map_first = NULL;
4540  pointer_to_map = &map_first;
4541
4542  num_segments = elf_elfheader (ibfd)->e_phnum;
4543  maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
4544
4545  /* Returns the end address of the segment + 1.  */
4546#define SEGMENT_END(segment, start)					\
4547  (start + (segment->p_memsz > segment->p_filesz			\
4548	    ? segment->p_memsz : segment->p_filesz))
4549
4550  /* Returns true if the given section is contained within
4551     the given segment.  VMA addresses are compared.  */
4552#define IS_CONTAINED_BY_VMA(section, segment)				\
4553  (section->vma >= segment->p_vaddr					\
4554   && (section->vma + section->_raw_size				\
4555       <= (SEGMENT_END (segment, segment->p_vaddr))))
4556
4557  /* Returns true if the given section is contained within
4558     the given segment.  LMA addresses are compared.  */
4559#define IS_CONTAINED_BY_LMA(section, segment, base)			\
4560  (section->lma >= base							\
4561   && (section->lma + section->_raw_size				\
4562       <= SEGMENT_END (segment, base)))
4563
4564  /* Special case: corefile "NOTE" section containing regs, prpsinfo etc.  */
4565#define IS_COREFILE_NOTE(p, s)						\
4566  (p->p_type == PT_NOTE							\
4567   && bfd_get_format (ibfd) == bfd_core					\
4568   && s->vma == 0 && s->lma == 0					\
4569   && (bfd_vma) s->filepos >= p->p_offset				\
4570   && ((bfd_vma) s->filepos + s->_raw_size				\
4571       <= p->p_offset + p->p_filesz))
4572
4573  /* The complicated case when p_vaddr is 0 is to handle the Solaris
4574     linker, which generates a PT_INTERP section with p_vaddr and
4575     p_memsz set to 0.  */
4576#define IS_SOLARIS_PT_INTERP(p, s)					\
4577  (p->p_vaddr == 0							\
4578   && p->p_paddr == 0							\
4579   && p->p_memsz == 0							\
4580   && p->p_filesz > 0							\
4581   && (s->flags & SEC_HAS_CONTENTS) != 0				\
4582   && s->_raw_size > 0							\
4583   && (bfd_vma) s->filepos >= p->p_offset				\
4584   && ((bfd_vma) s->filepos + s->_raw_size				\
4585       <= p->p_offset + p->p_filesz))
4586
4587  /* Decide if the given section should be included in the given segment.
4588     A section will be included if:
4589       1. It is within the address space of the segment -- we use the LMA
4590          if that is set for the segment and the VMA otherwise,
4591       2. It is an allocated segment,
4592       3. There is an output section associated with it,
4593       4. The section has not already been allocated to a previous segment.  */
4594#define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)		\
4595  ((((segment->p_paddr							\
4596      ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)	\
4597      : IS_CONTAINED_BY_VMA (section, segment))				\
4598     && (section->flags & SEC_ALLOC) != 0)				\
4599    || IS_COREFILE_NOTE (segment, section))				\
4600   && section->output_section != NULL					\
4601   && ! section->segment_mark)
4602
4603  /* Returns true iff seg1 starts after the end of seg2.  */
4604#define SEGMENT_AFTER_SEGMENT(seg1, seg2)				\
4605  (seg1->p_vaddr >= SEGMENT_END (seg2, seg2->p_vaddr))
4606
4607  /* Returns true iff seg1 and seg2 overlap.  */
4608#define SEGMENT_OVERLAPS(seg1, seg2)					\
4609  (!(SEGMENT_AFTER_SEGMENT (seg1, seg2)					\
4610     || SEGMENT_AFTER_SEGMENT (seg2, seg1)))
4611
4612  /* Initialise the segment mark field.  */
4613  for (section = ibfd->sections; section != NULL; section = section->next)
4614    section->segment_mark = false;
4615
4616  /* Scan through the segments specified in the program header
4617     of the input BFD.  For this first scan we look for overlaps
4618     in the loadable segments.  These can be created by weird
4619     parameters to objcopy.  Also, fix some solaris weirdness.  */
4620  for (i = 0, segment = elf_tdata (ibfd)->phdr;
4621       i < num_segments;
4622       i++, segment++)
4623    {
4624      unsigned int j;
4625      Elf_Internal_Phdr *segment2;
4626
4627      if (segment->p_type == PT_INTERP)
4628	for (section = ibfd->sections; section; section = section->next)
4629	  if (IS_SOLARIS_PT_INTERP (segment, section))
4630	    {
4631	      /* Mininal change so that the normal section to segment
4632		 assigment code will work.  */
4633	      segment->p_vaddr = section->vma;
4634	      break;
4635	    }
4636
4637      if (segment->p_type != PT_LOAD)
4638	continue;
4639
4640      /* Determine if this segment overlaps any previous segments.  */
4641      for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2 ++)
4642	{
4643	  bfd_signed_vma extra_length;
4644
4645	  if (segment2->p_type != PT_LOAD
4646	      || ! SEGMENT_OVERLAPS (segment, segment2))
4647	    continue;
4648
4649	  /* Merge the two segments together.  */
4650	  if (segment2->p_vaddr < segment->p_vaddr)
4651	    {
4652	      /* Extend SEGMENT2 to include SEGMENT and then delete
4653                 SEGMENT.  */
4654	      extra_length =
4655		SEGMENT_END (segment, segment->p_vaddr)
4656		- SEGMENT_END (segment2, segment2->p_vaddr);
4657
4658	      if (extra_length > 0)
4659		{
4660		  segment2->p_memsz  += extra_length;
4661		  segment2->p_filesz += extra_length;
4662		}
4663
4664	      segment->p_type = PT_NULL;
4665
4666	      /* Since we have deleted P we must restart the outer loop.  */
4667	      i = 0;
4668	      segment = elf_tdata (ibfd)->phdr;
4669	      break;
4670	    }
4671	  else
4672	    {
4673	      /* Extend SEGMENT to include SEGMENT2 and then delete
4674                 SEGMENT2.  */
4675	      extra_length =
4676		SEGMENT_END (segment2, segment2->p_vaddr)
4677		- SEGMENT_END (segment, segment->p_vaddr);
4678
4679	      if (extra_length > 0)
4680		{
4681		  segment->p_memsz  += extra_length;
4682		  segment->p_filesz += extra_length;
4683		}
4684
4685	      segment2->p_type = PT_NULL;
4686	    }
4687	}
4688    }
4689
4690  /* The second scan attempts to assign sections to segments.  */
4691  for (i = 0, segment = elf_tdata (ibfd)->phdr;
4692       i < num_segments;
4693       i ++, segment ++)
4694    {
4695      unsigned int  section_count;
4696      asection **   sections;
4697      asection *    output_section;
4698      unsigned int  isec;
4699      bfd_vma       matching_lma;
4700      bfd_vma       suggested_lma;
4701      unsigned int  j;
4702      bfd_size_type amt;
4703
4704      if (segment->p_type == PT_NULL)
4705	continue;
4706
4707      /* Compute how many sections might be placed into this segment.  */
4708      section_count = 0;
4709      for (section = ibfd->sections; section != NULL; section = section->next)
4710	if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
4711	  ++section_count;
4712
4713      /* Allocate a segment map big enough to contain all of the
4714	 sections we have selected.  */
4715      amt = sizeof (struct elf_segment_map);
4716      amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
4717      map = (struct elf_segment_map *) bfd_alloc (obfd, amt);
4718      if (map == NULL)
4719	return false;
4720
4721      /* Initialise the fields of the segment map.  Default to
4722	 using the physical address of the segment in the input BFD.  */
4723      map->next          = NULL;
4724      map->p_type        = segment->p_type;
4725      map->p_flags       = segment->p_flags;
4726      map->p_flags_valid = 1;
4727      map->p_paddr       = segment->p_paddr;
4728      map->p_paddr_valid = 1;
4729
4730      /* Determine if this segment contains the ELF file header
4731	 and if it contains the program headers themselves.  */
4732      map->includes_filehdr = (segment->p_offset == 0
4733			       && segment->p_filesz >= iehdr->e_ehsize);
4734
4735      map->includes_phdrs = 0;
4736
4737      if (! phdr_included || segment->p_type != PT_LOAD)
4738	{
4739	  map->includes_phdrs =
4740	    (segment->p_offset <= (bfd_vma) iehdr->e_phoff
4741	     && (segment->p_offset + segment->p_filesz
4742		 >= ((bfd_vma) iehdr->e_phoff
4743		     + iehdr->e_phnum * iehdr->e_phentsize)));
4744
4745	  if (segment->p_type == PT_LOAD && map->includes_phdrs)
4746	    phdr_included = true;
4747	}
4748
4749      if (section_count == 0)
4750	{
4751	  /* Special segments, such as the PT_PHDR segment, may contain
4752	     no sections, but ordinary, loadable segments should contain
4753	     something.  They are allowed by the ELF spec however, so only
4754	     a warning is produced.  */
4755	  if (segment->p_type == PT_LOAD)
4756	    (*_bfd_error_handler)
4757	      (_("%s: warning: Empty loadable segment detected, is this intentional ?\n"),
4758	       bfd_archive_filename (ibfd));
4759
4760	  map->count = 0;
4761	  *pointer_to_map = map;
4762	  pointer_to_map = &map->next;
4763
4764	  continue;
4765	}
4766
4767      /* Now scan the sections in the input BFD again and attempt
4768	 to add their corresponding output sections to the segment map.
4769	 The problem here is how to handle an output section which has
4770	 been moved (ie had its LMA changed).  There are four possibilities:
4771
4772	 1. None of the sections have been moved.
4773	    In this case we can continue to use the segment LMA from the
4774	    input BFD.
4775
4776	 2. All of the sections have been moved by the same amount.
4777	    In this case we can change the segment's LMA to match the LMA
4778	    of the first section.
4779
4780	 3. Some of the sections have been moved, others have not.
4781	    In this case those sections which have not been moved can be
4782	    placed in the current segment which will have to have its size,
4783	    and possibly its LMA changed, and a new segment or segments will
4784	    have to be created to contain the other sections.
4785
4786	 4. The sections have been moved, but not be the same amount.
4787	    In this case we can change the segment's LMA to match the LMA
4788	    of the first section and we will have to create a new segment
4789	    or segments to contain the other sections.
4790
4791	 In order to save time, we allocate an array to hold the section
4792	 pointers that we are interested in.  As these sections get assigned
4793	 to a segment, they are removed from this array.  */
4794
4795      /* Gcc 2.96 miscompiles this code on mips. Don't do casting here
4796	 to work around this long long bug.  */
4797      amt = section_count * sizeof (asection *);
4798      sections = (asection **) bfd_malloc (amt);
4799      if (sections == NULL)
4800	return false;
4801
4802      /* Step One: Scan for segment vs section LMA conflicts.
4803	 Also add the sections to the section array allocated above.
4804	 Also add the sections to the current segment.  In the common
4805	 case, where the sections have not been moved, this means that
4806	 we have completely filled the segment, and there is nothing
4807	 more to do.  */
4808      isec = 0;
4809      matching_lma = 0;
4810      suggested_lma = 0;
4811
4812      for (j = 0, section = ibfd->sections;
4813	   section != NULL;
4814	   section = section->next)
4815	{
4816	  if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
4817	    {
4818	      output_section = section->output_section;
4819
4820	      sections[j ++] = section;
4821
4822	      /* The Solaris native linker always sets p_paddr to 0.
4823		 We try to catch that case here, and set it to the
4824		 correct value.  Note - some backends require that
4825		 p_paddr be left as zero.  */
4826	      if (segment->p_paddr == 0
4827		  && segment->p_vaddr != 0
4828		  && (! bed->want_p_paddr_set_to_zero)
4829		  && isec == 0
4830		  && output_section->lma != 0
4831		  && (output_section->vma == (segment->p_vaddr
4832					      + (map->includes_filehdr
4833						 ? iehdr->e_ehsize
4834						 : 0)
4835					      + (map->includes_phdrs
4836						 ? (iehdr->e_phnum
4837						    * iehdr->e_phentsize)
4838						 : 0))))
4839		map->p_paddr = segment->p_vaddr;
4840
4841	      /* Match up the physical address of the segment with the
4842		 LMA address of the output section.  */
4843	      if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
4844		  || IS_COREFILE_NOTE (segment, section)
4845		  || (bed->want_p_paddr_set_to_zero &&
4846		      IS_CONTAINED_BY_VMA (output_section, segment))
4847                )
4848		{
4849		  if (matching_lma == 0)
4850		    matching_lma = output_section->lma;
4851
4852		  /* We assume that if the section fits within the segment
4853		     then it does not overlap any other section within that
4854		     segment.  */
4855		  map->sections[isec ++] = output_section;
4856		}
4857	      else if (suggested_lma == 0)
4858		suggested_lma = output_section->lma;
4859	    }
4860	}
4861
4862      BFD_ASSERT (j == section_count);
4863
4864      /* Step Two: Adjust the physical address of the current segment,
4865	 if necessary.  */
4866      if (isec == section_count)
4867	{
4868	  /* All of the sections fitted within the segment as currently
4869	     specified.  This is the default case.  Add the segment to
4870	     the list of built segments and carry on to process the next
4871	     program header in the input BFD.  */
4872	  map->count = section_count;
4873	  *pointer_to_map = map;
4874	  pointer_to_map = &map->next;
4875
4876	  free (sections);
4877	  continue;
4878	}
4879      else
4880	{
4881	  if (matching_lma != 0)
4882	    {
4883	      /* At least one section fits inside the current segment.
4884		 Keep it, but modify its physical address to match the
4885		 LMA of the first section that fitted.  */
4886	      map->p_paddr = matching_lma;
4887	    }
4888	  else
4889	    {
4890	      /* None of the sections fitted inside the current segment.
4891		 Change the current segment's physical address to match
4892		 the LMA of the first section.  */
4893	      map->p_paddr = suggested_lma;
4894	    }
4895
4896	  /* Offset the segment physical address from the lma
4897	     to allow for space taken up by elf headers.  */
4898	  if (map->includes_filehdr)
4899	    map->p_paddr -= iehdr->e_ehsize;
4900
4901	  if (map->includes_phdrs)
4902	    {
4903	      map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
4904
4905	      /* iehdr->e_phnum is just an estimate of the number
4906		 of program headers that we will need.  Make a note
4907		 here of the number we used and the segment we chose
4908		 to hold these headers, so that we can adjust the
4909		 offset when we know the correct value.  */
4910	      phdr_adjust_num = iehdr->e_phnum;
4911	      phdr_adjust_seg = map;
4912	    }
4913	}
4914
4915      /* Step Three: Loop over the sections again, this time assigning
4916	 those that fit to the current segment and removing them from the
4917	 sections array; but making sure not to leave large gaps.  Once all
4918	 possible sections have been assigned to the current segment it is
4919	 added to the list of built segments and if sections still remain
4920	 to be assigned, a new segment is constructed before repeating
4921	 the loop.  */
4922      isec = 0;
4923      do
4924	{
4925	  map->count = 0;
4926	  suggested_lma = 0;
4927
4928	  /* Fill the current segment with sections that fit.  */
4929	  for (j = 0; j < section_count; j++)
4930	    {
4931	      section = sections[j];
4932
4933	      if (section == NULL)
4934		continue;
4935
4936	      output_section = section->output_section;
4937
4938	      BFD_ASSERT (output_section != NULL);
4939
4940	      if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
4941		  || IS_COREFILE_NOTE (segment, section))
4942		{
4943		  if (map->count == 0)
4944		    {
4945		      /* If the first section in a segment does not start at
4946			 the beginning of the segment, then something is
4947			 wrong.  */
4948		      if (output_section->lma !=
4949			  (map->p_paddr
4950			   + (map->includes_filehdr ? iehdr->e_ehsize : 0)
4951			   + (map->includes_phdrs
4952			      ? iehdr->e_phnum * iehdr->e_phentsize
4953			      : 0)))
4954			abort ();
4955		    }
4956		  else
4957		    {
4958		      asection * prev_sec;
4959
4960		      prev_sec = map->sections[map->count - 1];
4961
4962		      /* If the gap between the end of the previous section
4963			 and the start of this section is more than
4964			 maxpagesize then we need to start a new segment.  */
4965		      if ((BFD_ALIGN (prev_sec->lma + prev_sec->_raw_size,
4966				      maxpagesize)
4967			   < BFD_ALIGN (output_section->lma, maxpagesize))
4968			  || ((prev_sec->lma + prev_sec->_raw_size)
4969			      > output_section->lma))
4970			{
4971			  if (suggested_lma == 0)
4972			    suggested_lma = output_section->lma;
4973
4974			  continue;
4975			}
4976		    }
4977
4978		  map->sections[map->count++] = output_section;
4979		  ++isec;
4980		  sections[j] = NULL;
4981		  section->segment_mark = true;
4982		}
4983	      else if (suggested_lma == 0)
4984		suggested_lma = output_section->lma;
4985	    }
4986
4987	  BFD_ASSERT (map->count > 0);
4988
4989	  /* Add the current segment to the list of built segments.  */
4990	  *pointer_to_map = map;
4991	  pointer_to_map = &map->next;
4992
4993	  if (isec < section_count)
4994	    {
4995	      /* We still have not allocated all of the sections to
4996		 segments.  Create a new segment here, initialise it
4997		 and carry on looping.  */
4998	      amt = sizeof (struct elf_segment_map);
4999	      amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
5000	      map = (struct elf_segment_map *) bfd_alloc (obfd, amt);
5001	      if (map == NULL)
5002		return false;
5003
5004	      /* Initialise the fields of the segment map.  Set the physical
5005		 physical address to the LMA of the first section that has
5006		 not yet been assigned.  */
5007	      map->next             = NULL;
5008	      map->p_type           = segment->p_type;
5009	      map->p_flags          = segment->p_flags;
5010	      map->p_flags_valid    = 1;
5011	      map->p_paddr          = suggested_lma;
5012	      map->p_paddr_valid    = 1;
5013	      map->includes_filehdr = 0;
5014	      map->includes_phdrs   = 0;
5015	    }
5016	}
5017      while (isec < section_count);
5018
5019      free (sections);
5020    }
5021
5022  /* The Solaris linker creates program headers in which all the
5023     p_paddr fields are zero.  When we try to objcopy or strip such a
5024     file, we get confused.  Check for this case, and if we find it
5025     reset the p_paddr_valid fields.  */
5026  for (map = map_first; map != NULL; map = map->next)
5027    if (map->p_paddr != 0)
5028      break;
5029  if (map == NULL)
5030    {
5031      for (map = map_first; map != NULL; map = map->next)
5032	map->p_paddr_valid = 0;
5033    }
5034
5035  elf_tdata (obfd)->segment_map = map_first;
5036
5037  /* If we had to estimate the number of program headers that were
5038     going to be needed, then check our estimate now and adjust
5039     the offset if necessary.  */
5040  if (phdr_adjust_seg != NULL)
5041    {
5042      unsigned int count;
5043
5044      for (count = 0, map = map_first; map != NULL; map = map->next)
5045	count++;
5046
5047      if (count > phdr_adjust_num)
5048	phdr_adjust_seg->p_paddr
5049	  -= (count - phdr_adjust_num) * iehdr->e_phentsize;
5050    }
5051
5052#if 0
5053  /* Final Step: Sort the segments into ascending order of physical
5054     address.  */
5055  if (map_first != NULL)
5056    {
5057      struct elf_segment_map *prev;
5058
5059      prev = map_first;
5060      for (map = map_first->next; map != NULL; prev = map, map = map->next)
5061	{
5062	  /* Yes I know - its a bubble sort....  */
5063	  if (map->next != NULL && (map->next->p_paddr < map->p_paddr))
5064	    {
5065	      /* Swap map and map->next.  */
5066	      prev->next = map->next;
5067	      map->next = map->next->next;
5068	      prev->next->next = map;
5069
5070	      /* Restart loop.  */
5071	      map = map_first;
5072	    }
5073	}
5074    }
5075#endif
5076
5077#undef SEGMENT_END
5078#undef IS_CONTAINED_BY_VMA
5079#undef IS_CONTAINED_BY_LMA
5080#undef IS_COREFILE_NOTE
5081#undef IS_SOLARIS_PT_INTERP
5082#undef INCLUDE_SECTION_IN_SEGMENT
5083#undef SEGMENT_AFTER_SEGMENT
5084#undef SEGMENT_OVERLAPS
5085  return true;
5086}
5087
5088/* Copy private section information.  This copies over the entsize
5089   field, and sometimes the info field.  */
5090
5091boolean
5092_bfd_elf_copy_private_section_data (ibfd, isec, obfd, osec)
5093     bfd *ibfd;
5094     asection *isec;
5095     bfd *obfd;
5096     asection *osec;
5097{
5098  Elf_Internal_Shdr *ihdr, *ohdr;
5099
5100  if (ibfd->xvec->flavour != bfd_target_elf_flavour
5101      || obfd->xvec->flavour != bfd_target_elf_flavour)
5102    return true;
5103
5104  if (elf_tdata (obfd)->segment_map == NULL && elf_tdata (ibfd)->phdr != NULL)
5105    {
5106	asection *s;
5107
5108	/* Only set up the segments if there are no more SEC_ALLOC
5109	   sections.  FIXME: This won't do the right thing if objcopy is
5110	   used to remove the last SEC_ALLOC section, since objcopy
5111	   won't call this routine in that case.  */
5112	for (s = isec->next; s != NULL; s = s->next)
5113	  if ((s->flags & SEC_ALLOC) != 0)
5114	    break;
5115	if (s == NULL)
5116	  {
5117	    if (! copy_private_bfd_data (ibfd, obfd))
5118	      return false;
5119	  }
5120    }
5121
5122  ihdr = &elf_section_data (isec)->this_hdr;
5123  ohdr = &elf_section_data (osec)->this_hdr;
5124
5125  ohdr->sh_entsize = ihdr->sh_entsize;
5126
5127  if (ihdr->sh_type == SHT_SYMTAB
5128      || ihdr->sh_type == SHT_DYNSYM
5129      || ihdr->sh_type == SHT_GNU_verneed
5130      || ihdr->sh_type == SHT_GNU_verdef)
5131    ohdr->sh_info = ihdr->sh_info;
5132
5133  /* Set things up for objcopy.  The output SHT_GROUP section will
5134     have its elf_next_in_group pointing back to the input group
5135     members.  */
5136  elf_next_in_group (osec) = elf_next_in_group (isec);
5137  elf_group_name (osec) = elf_group_name (isec);
5138
5139  elf_section_data (osec)->use_rela_p
5140    = elf_section_data (isec)->use_rela_p;
5141
5142  return true;
5143}
5144
5145/* Copy private symbol information.  If this symbol is in a section
5146   which we did not map into a BFD section, try to map the section
5147   index correctly.  We use special macro definitions for the mapped
5148   section indices; these definitions are interpreted by the
5149   swap_out_syms function.  */
5150
5151#define MAP_ONESYMTAB (SHN_HIOS + 1)
5152#define MAP_DYNSYMTAB (SHN_HIOS + 2)
5153#define MAP_STRTAB    (SHN_HIOS + 3)
5154#define MAP_SHSTRTAB  (SHN_HIOS + 4)
5155#define MAP_SYM_SHNDX (SHN_HIOS + 5)
5156
5157boolean
5158_bfd_elf_copy_private_symbol_data (ibfd, isymarg, obfd, osymarg)
5159     bfd *ibfd;
5160     asymbol *isymarg;
5161     bfd *obfd;
5162     asymbol *osymarg;
5163{
5164  elf_symbol_type *isym, *osym;
5165
5166  if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
5167      || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
5168    return true;
5169
5170  isym = elf_symbol_from (ibfd, isymarg);
5171  osym = elf_symbol_from (obfd, osymarg);
5172
5173  if (isym != NULL
5174      && osym != NULL
5175      && bfd_is_abs_section (isym->symbol.section))
5176    {
5177      unsigned int shndx;
5178
5179      shndx = isym->internal_elf_sym.st_shndx;
5180      if (shndx == elf_onesymtab (ibfd))
5181	shndx = MAP_ONESYMTAB;
5182      else if (shndx == elf_dynsymtab (ibfd))
5183	shndx = MAP_DYNSYMTAB;
5184      else if (shndx == elf_tdata (ibfd)->strtab_section)
5185	shndx = MAP_STRTAB;
5186      else if (shndx == elf_tdata (ibfd)->shstrtab_section)
5187	shndx = MAP_SHSTRTAB;
5188      else if (shndx == elf_tdata (ibfd)->symtab_shndx_section)
5189	shndx = MAP_SYM_SHNDX;
5190      osym->internal_elf_sym.st_shndx = shndx;
5191    }
5192
5193  return true;
5194}
5195
5196/* Swap out the symbols.  */
5197
5198static boolean
5199swap_out_syms (abfd, sttp, relocatable_p)
5200     bfd *abfd;
5201     struct bfd_strtab_hash **sttp;
5202     int relocatable_p;
5203{
5204  struct elf_backend_data *bed;
5205  int symcount;
5206  asymbol **syms;
5207  struct bfd_strtab_hash *stt;
5208  Elf_Internal_Shdr *symtab_hdr;
5209  Elf_Internal_Shdr *symtab_shndx_hdr;
5210  Elf_Internal_Shdr *symstrtab_hdr;
5211  char *outbound_syms;
5212  char *outbound_shndx;
5213  int idx;
5214  bfd_size_type amt;
5215
5216  if (!elf_map_symbols (abfd))
5217    return false;
5218
5219  /* Dump out the symtabs.  */
5220  stt = _bfd_elf_stringtab_init ();
5221  if (stt == NULL)
5222    return false;
5223
5224  bed = get_elf_backend_data (abfd);
5225  symcount = bfd_get_symcount (abfd);
5226  symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
5227  symtab_hdr->sh_type = SHT_SYMTAB;
5228  symtab_hdr->sh_entsize = bed->s->sizeof_sym;
5229  symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
5230  symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
5231  symtab_hdr->sh_addralign = bed->s->file_align;
5232
5233  symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
5234  symstrtab_hdr->sh_type = SHT_STRTAB;
5235
5236  amt = (bfd_size_type) (1 + symcount) * bed->s->sizeof_sym;
5237  outbound_syms = bfd_alloc (abfd, amt);
5238  if (outbound_syms == NULL)
5239    return false;
5240  symtab_hdr->contents = (PTR) outbound_syms;
5241
5242  outbound_shndx = NULL;
5243  symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
5244  if (symtab_shndx_hdr->sh_name != 0)
5245    {
5246      amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
5247      outbound_shndx = bfd_zalloc (abfd, amt);
5248      if (outbound_shndx == NULL)
5249	return false;
5250      symtab_shndx_hdr->contents = outbound_shndx;
5251      symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
5252      symtab_shndx_hdr->sh_size = amt;
5253      symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
5254      symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
5255    }
5256
5257  /* now generate the data (for "contents") */
5258  {
5259    /* Fill in zeroth symbol and swap it out.  */
5260    Elf_Internal_Sym sym;
5261    sym.st_name = 0;
5262    sym.st_value = 0;
5263    sym.st_size = 0;
5264    sym.st_info = 0;
5265    sym.st_other = 0;
5266    sym.st_shndx = SHN_UNDEF;
5267    bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
5268    outbound_syms += bed->s->sizeof_sym;
5269    if (outbound_shndx != NULL)
5270      outbound_shndx += sizeof (Elf_External_Sym_Shndx);
5271  }
5272
5273  syms = bfd_get_outsymbols (abfd);
5274  for (idx = 0; idx < symcount; idx++)
5275    {
5276      Elf_Internal_Sym sym;
5277      bfd_vma value = syms[idx]->value;
5278      elf_symbol_type *type_ptr;
5279      flagword flags = syms[idx]->flags;
5280      int type;
5281
5282      if ((flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
5283	{
5284	  /* Local section symbols have no name.  */
5285	  sym.st_name = 0;
5286	}
5287      else
5288	{
5289	  sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
5290							    syms[idx]->name,
5291							    true, false);
5292	  if (sym.st_name == (unsigned long) -1)
5293	    return false;
5294	}
5295
5296      type_ptr = elf_symbol_from (abfd, syms[idx]);
5297
5298      if ((flags & BSF_SECTION_SYM) == 0
5299	  && bfd_is_com_section (syms[idx]->section))
5300	{
5301	  /* ELF common symbols put the alignment into the `value' field,
5302	     and the size into the `size' field.  This is backwards from
5303	     how BFD handles it, so reverse it here.  */
5304	  sym.st_size = value;
5305	  if (type_ptr == NULL
5306	      || type_ptr->internal_elf_sym.st_value == 0)
5307	    sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
5308	  else
5309	    sym.st_value = type_ptr->internal_elf_sym.st_value;
5310	  sym.st_shndx = _bfd_elf_section_from_bfd_section
5311	    (abfd, syms[idx]->section);
5312	}
5313      else
5314	{
5315	  asection *sec = syms[idx]->section;
5316	  int shndx;
5317
5318	  if (sec->output_section)
5319	    {
5320	      value += sec->output_offset;
5321	      sec = sec->output_section;
5322	    }
5323	  /* Don't add in the section vma for relocatable output.  */
5324	  if (! relocatable_p)
5325	    value += sec->vma;
5326	  sym.st_value = value;
5327	  sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
5328
5329	  if (bfd_is_abs_section (sec)
5330	      && type_ptr != NULL
5331	      && type_ptr->internal_elf_sym.st_shndx != 0)
5332	    {
5333	      /* This symbol is in a real ELF section which we did
5334		 not create as a BFD section.  Undo the mapping done
5335		 by copy_private_symbol_data.  */
5336	      shndx = type_ptr->internal_elf_sym.st_shndx;
5337	      switch (shndx)
5338		{
5339		case MAP_ONESYMTAB:
5340		  shndx = elf_onesymtab (abfd);
5341		  break;
5342		case MAP_DYNSYMTAB:
5343		  shndx = elf_dynsymtab (abfd);
5344		  break;
5345		case MAP_STRTAB:
5346		  shndx = elf_tdata (abfd)->strtab_section;
5347		  break;
5348		case MAP_SHSTRTAB:
5349		  shndx = elf_tdata (abfd)->shstrtab_section;
5350		  break;
5351		case MAP_SYM_SHNDX:
5352		  shndx = elf_tdata (abfd)->symtab_shndx_section;
5353		  break;
5354		default:
5355		  break;
5356		}
5357	    }
5358	  else
5359	    {
5360	      shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
5361
5362	      if (shndx == -1)
5363		{
5364		  asection *sec2;
5365
5366		  /* Writing this would be a hell of a lot easier if
5367		     we had some decent documentation on bfd, and
5368		     knew what to expect of the library, and what to
5369		     demand of applications.  For example, it
5370		     appears that `objcopy' might not set the
5371		     section of a symbol to be a section that is
5372		     actually in the output file.  */
5373		  sec2 = bfd_get_section_by_name (abfd, sec->name);
5374		  BFD_ASSERT (sec2 != 0);
5375		  shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
5376		  BFD_ASSERT (shndx != -1);
5377		}
5378	    }
5379
5380	  sym.st_shndx = shndx;
5381	}
5382
5383      if ((flags & BSF_THREAD_LOCAL) != 0)
5384	type = STT_TLS;
5385      else if ((flags & BSF_FUNCTION) != 0)
5386	type = STT_FUNC;
5387      else if ((flags & BSF_OBJECT) != 0)
5388	type = STT_OBJECT;
5389      else
5390	type = STT_NOTYPE;
5391
5392      if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
5393	type = STT_TLS;
5394
5395      /* Processor-specific types */
5396      if (type_ptr != NULL
5397	  && bed->elf_backend_get_symbol_type)
5398	type = ((*bed->elf_backend_get_symbol_type)
5399		(&type_ptr->internal_elf_sym, type));
5400
5401      if (flags & BSF_SECTION_SYM)
5402	{
5403	  if (flags & BSF_GLOBAL)
5404	    sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
5405	  else
5406	    sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
5407	}
5408      else if (bfd_is_com_section (syms[idx]->section))
5409	sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
5410      else if (bfd_is_und_section (syms[idx]->section))
5411	sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
5412				    ? STB_WEAK
5413				    : STB_GLOBAL),
5414				   type);
5415      else if (flags & BSF_FILE)
5416	sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
5417      else
5418	{
5419	  int bind = STB_LOCAL;
5420
5421	  if (flags & BSF_LOCAL)
5422	    bind = STB_LOCAL;
5423	  else if (flags & BSF_WEAK)
5424	    bind = STB_WEAK;
5425	  else if (flags & BSF_GLOBAL)
5426	    bind = STB_GLOBAL;
5427
5428	  sym.st_info = ELF_ST_INFO (bind, type);
5429	}
5430
5431      if (type_ptr != NULL)
5432	sym.st_other = type_ptr->internal_elf_sym.st_other;
5433      else
5434	sym.st_other = 0;
5435
5436      bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
5437      outbound_syms += bed->s->sizeof_sym;
5438      if (outbound_shndx != NULL)
5439	outbound_shndx += sizeof (Elf_External_Sym_Shndx);
5440    }
5441
5442  *sttp = stt;
5443  symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
5444  symstrtab_hdr->sh_type = SHT_STRTAB;
5445
5446  symstrtab_hdr->sh_flags = 0;
5447  symstrtab_hdr->sh_addr = 0;
5448  symstrtab_hdr->sh_entsize = 0;
5449  symstrtab_hdr->sh_link = 0;
5450  symstrtab_hdr->sh_info = 0;
5451  symstrtab_hdr->sh_addralign = 1;
5452
5453  return true;
5454}
5455
5456/* Return the number of bytes required to hold the symtab vector.
5457
5458   Note that we base it on the count plus 1, since we will null terminate
5459   the vector allocated based on this size.  However, the ELF symbol table
5460   always has a dummy entry as symbol #0, so it ends up even.  */
5461
5462long
5463_bfd_elf_get_symtab_upper_bound (abfd)
5464     bfd *abfd;
5465{
5466  long symcount;
5467  long symtab_size;
5468  Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
5469
5470  symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
5471  symtab_size = (symcount + 1) * (sizeof (asymbol *));
5472  if (symcount > 0)
5473    symtab_size -= sizeof (asymbol *);
5474
5475  return symtab_size;
5476}
5477
5478long
5479_bfd_elf_get_dynamic_symtab_upper_bound (abfd)
5480     bfd *abfd;
5481{
5482  long symcount;
5483  long symtab_size;
5484  Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
5485
5486  if (elf_dynsymtab (abfd) == 0)
5487    {
5488      bfd_set_error (bfd_error_invalid_operation);
5489      return -1;
5490    }
5491
5492  symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
5493  symtab_size = (symcount + 1) * (sizeof (asymbol *));
5494  if (symcount > 0)
5495    symtab_size -= sizeof (asymbol *);
5496
5497  return symtab_size;
5498}
5499
5500long
5501_bfd_elf_get_reloc_upper_bound (abfd, asect)
5502     bfd *abfd ATTRIBUTE_UNUSED;
5503     sec_ptr asect;
5504{
5505  return (asect->reloc_count + 1) * sizeof (arelent *);
5506}
5507
5508/* Canonicalize the relocs.  */
5509
5510long
5511_bfd_elf_canonicalize_reloc (abfd, section, relptr, symbols)
5512     bfd *abfd;
5513     sec_ptr section;
5514     arelent **relptr;
5515     asymbol **symbols;
5516{
5517  arelent *tblptr;
5518  unsigned int i;
5519  struct elf_backend_data *bed = get_elf_backend_data (abfd);
5520
5521  if (! bed->s->slurp_reloc_table (abfd, section, symbols, false))
5522    return -1;
5523
5524  tblptr = section->relocation;
5525  for (i = 0; i < section->reloc_count; i++)
5526    *relptr++ = tblptr++;
5527
5528  *relptr = NULL;
5529
5530  return section->reloc_count;
5531}
5532
5533long
5534_bfd_elf_get_symtab (abfd, alocation)
5535     bfd *abfd;
5536     asymbol **alocation;
5537{
5538  struct elf_backend_data *bed = get_elf_backend_data (abfd);
5539  long symcount = bed->s->slurp_symbol_table (abfd, alocation, false);
5540
5541  if (symcount >= 0)
5542    bfd_get_symcount (abfd) = symcount;
5543  return symcount;
5544}
5545
5546long
5547_bfd_elf_canonicalize_dynamic_symtab (abfd, alocation)
5548     bfd *abfd;
5549     asymbol **alocation;
5550{
5551  struct elf_backend_data *bed = get_elf_backend_data (abfd);
5552  long symcount = bed->s->slurp_symbol_table (abfd, alocation, true);
5553
5554  if (symcount >= 0)
5555    bfd_get_dynamic_symcount (abfd) = symcount;
5556  return symcount;
5557}
5558
5559/* Return the size required for the dynamic reloc entries.  Any
5560   section that was actually installed in the BFD, and has type
5561   SHT_REL or SHT_RELA, and uses the dynamic symbol table, is
5562   considered to be a dynamic reloc section.  */
5563
5564long
5565_bfd_elf_get_dynamic_reloc_upper_bound (abfd)
5566     bfd *abfd;
5567{
5568  long ret;
5569  asection *s;
5570
5571  if (elf_dynsymtab (abfd) == 0)
5572    {
5573      bfd_set_error (bfd_error_invalid_operation);
5574      return -1;
5575    }
5576
5577  ret = sizeof (arelent *);
5578  for (s = abfd->sections; s != NULL; s = s->next)
5579    if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
5580	&& (elf_section_data (s)->this_hdr.sh_type == SHT_REL
5581	    || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
5582      ret += ((s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize)
5583	      * sizeof (arelent *));
5584
5585  return ret;
5586}
5587
5588/* Canonicalize the dynamic relocation entries.  Note that we return
5589   the dynamic relocations as a single block, although they are
5590   actually associated with particular sections; the interface, which
5591   was designed for SunOS style shared libraries, expects that there
5592   is only one set of dynamic relocs.  Any section that was actually
5593   installed in the BFD, and has type SHT_REL or SHT_RELA, and uses
5594   the dynamic symbol table, is considered to be a dynamic reloc
5595   section.  */
5596
5597long
5598_bfd_elf_canonicalize_dynamic_reloc (abfd, storage, syms)
5599     bfd *abfd;
5600     arelent **storage;
5601     asymbol **syms;
5602{
5603  boolean (*slurp_relocs) PARAMS ((bfd *, asection *, asymbol **, boolean));
5604  asection *s;
5605  long ret;
5606
5607  if (elf_dynsymtab (abfd) == 0)
5608    {
5609      bfd_set_error (bfd_error_invalid_operation);
5610      return -1;
5611    }
5612
5613  slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
5614  ret = 0;
5615  for (s = abfd->sections; s != NULL; s = s->next)
5616    {
5617      if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
5618	  && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
5619	      || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
5620	{
5621	  arelent *p;
5622	  long count, i;
5623
5624	  if (! (*slurp_relocs) (abfd, s, syms, true))
5625	    return -1;
5626	  count = s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize;
5627	  p = s->relocation;
5628	  for (i = 0; i < count; i++)
5629	    *storage++ = p++;
5630	  ret += count;
5631	}
5632    }
5633
5634  *storage = NULL;
5635
5636  return ret;
5637}
5638
5639/* Read in the version information.  */
5640
5641boolean
5642_bfd_elf_slurp_version_tables (abfd)
5643     bfd *abfd;
5644{
5645  bfd_byte *contents = NULL;
5646  bfd_size_type amt;
5647
5648  if (elf_dynverdef (abfd) != 0)
5649    {
5650      Elf_Internal_Shdr *hdr;
5651      Elf_External_Verdef *everdef;
5652      Elf_Internal_Verdef *iverdef;
5653      Elf_Internal_Verdef *iverdefarr;
5654      Elf_Internal_Verdef iverdefmem;
5655      unsigned int i;
5656      unsigned int maxidx;
5657
5658      hdr = &elf_tdata (abfd)->dynverdef_hdr;
5659
5660      contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
5661      if (contents == NULL)
5662	goto error_return;
5663      if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
5664	  || bfd_bread ((PTR) contents, hdr->sh_size, abfd) != hdr->sh_size)
5665	goto error_return;
5666
5667      /* We know the number of entries in the section but not the maximum
5668	 index.  Therefore we have to run through all entries and find
5669	 the maximum.  */
5670      everdef = (Elf_External_Verdef *) contents;
5671      maxidx = 0;
5672      for (i = 0; i < hdr->sh_info; ++i)
5673	{
5674	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
5675
5676	  if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
5677	    maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
5678
5679	  everdef = ((Elf_External_Verdef *)
5680		     ((bfd_byte *) everdef + iverdefmem.vd_next));
5681	}
5682
5683      amt = (bfd_size_type) maxidx * sizeof (Elf_Internal_Verdef);
5684      elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *) bfd_zalloc (abfd, amt);
5685      if (elf_tdata (abfd)->verdef == NULL)
5686	goto error_return;
5687
5688      elf_tdata (abfd)->cverdefs = maxidx;
5689
5690      everdef = (Elf_External_Verdef *) contents;
5691      iverdefarr = elf_tdata (abfd)->verdef;
5692      for (i = 0; i < hdr->sh_info; i++)
5693	{
5694	  Elf_External_Verdaux *everdaux;
5695	  Elf_Internal_Verdaux *iverdaux;
5696	  unsigned int j;
5697
5698	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
5699
5700	  iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
5701	  memcpy (iverdef, &iverdefmem, sizeof (Elf_Internal_Verdef));
5702
5703	  iverdef->vd_bfd = abfd;
5704
5705	  amt = (bfd_size_type) iverdef->vd_cnt * sizeof (Elf_Internal_Verdaux);
5706	  iverdef->vd_auxptr = (Elf_Internal_Verdaux *) bfd_alloc (abfd, amt);
5707	  if (iverdef->vd_auxptr == NULL)
5708	    goto error_return;
5709
5710	  everdaux = ((Elf_External_Verdaux *)
5711		      ((bfd_byte *) everdef + iverdef->vd_aux));
5712	  iverdaux = iverdef->vd_auxptr;
5713	  for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
5714	    {
5715	      _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
5716
5717	      iverdaux->vda_nodename =
5718		bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5719						 iverdaux->vda_name);
5720	      if (iverdaux->vda_nodename == NULL)
5721		goto error_return;
5722
5723	      if (j + 1 < iverdef->vd_cnt)
5724		iverdaux->vda_nextptr = iverdaux + 1;
5725	      else
5726		iverdaux->vda_nextptr = NULL;
5727
5728	      everdaux = ((Elf_External_Verdaux *)
5729			  ((bfd_byte *) everdaux + iverdaux->vda_next));
5730	    }
5731
5732	  iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
5733
5734	  if (i + 1 < hdr->sh_info)
5735	    iverdef->vd_nextdef = iverdef + 1;
5736	  else
5737	    iverdef->vd_nextdef = NULL;
5738
5739	  everdef = ((Elf_External_Verdef *)
5740		     ((bfd_byte *) everdef + iverdef->vd_next));
5741	}
5742
5743      free (contents);
5744      contents = NULL;
5745    }
5746
5747  if (elf_dynverref (abfd) != 0)
5748    {
5749      Elf_Internal_Shdr *hdr;
5750      Elf_External_Verneed *everneed;
5751      Elf_Internal_Verneed *iverneed;
5752      unsigned int i;
5753
5754      hdr = &elf_tdata (abfd)->dynverref_hdr;
5755
5756      amt = (bfd_size_type) hdr->sh_info * sizeof (Elf_Internal_Verneed);
5757      elf_tdata (abfd)->verref =
5758	(Elf_Internal_Verneed *) bfd_zalloc (abfd, amt);
5759      if (elf_tdata (abfd)->verref == NULL)
5760	goto error_return;
5761
5762      elf_tdata (abfd)->cverrefs = hdr->sh_info;
5763
5764      contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
5765      if (contents == NULL)
5766	goto error_return;
5767      if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
5768	  || bfd_bread ((PTR) contents, hdr->sh_size, abfd) != hdr->sh_size)
5769	goto error_return;
5770
5771      everneed = (Elf_External_Verneed *) contents;
5772      iverneed = elf_tdata (abfd)->verref;
5773      for (i = 0; i < hdr->sh_info; i++, iverneed++)
5774	{
5775	  Elf_External_Vernaux *evernaux;
5776	  Elf_Internal_Vernaux *ivernaux;
5777	  unsigned int j;
5778
5779	  _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
5780
5781	  iverneed->vn_bfd = abfd;
5782
5783	  iverneed->vn_filename =
5784	    bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5785					     iverneed->vn_file);
5786	  if (iverneed->vn_filename == NULL)
5787	    goto error_return;
5788
5789	  amt = iverneed->vn_cnt;
5790	  amt *= sizeof (Elf_Internal_Vernaux);
5791	  iverneed->vn_auxptr = (Elf_Internal_Vernaux *) bfd_alloc (abfd, amt);
5792
5793	  evernaux = ((Elf_External_Vernaux *)
5794		      ((bfd_byte *) everneed + iverneed->vn_aux));
5795	  ivernaux = iverneed->vn_auxptr;
5796	  for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
5797	    {
5798	      _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
5799
5800	      ivernaux->vna_nodename =
5801		bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5802						 ivernaux->vna_name);
5803	      if (ivernaux->vna_nodename == NULL)
5804		goto error_return;
5805
5806	      if (j + 1 < iverneed->vn_cnt)
5807		ivernaux->vna_nextptr = ivernaux + 1;
5808	      else
5809		ivernaux->vna_nextptr = NULL;
5810
5811	      evernaux = ((Elf_External_Vernaux *)
5812			  ((bfd_byte *) evernaux + ivernaux->vna_next));
5813	    }
5814
5815	  if (i + 1 < hdr->sh_info)
5816	    iverneed->vn_nextref = iverneed + 1;
5817	  else
5818	    iverneed->vn_nextref = NULL;
5819
5820	  everneed = ((Elf_External_Verneed *)
5821		      ((bfd_byte *) everneed + iverneed->vn_next));
5822	}
5823
5824      free (contents);
5825      contents = NULL;
5826    }
5827
5828  return true;
5829
5830 error_return:
5831  if (contents == NULL)
5832    free (contents);
5833  return false;
5834}
5835
5836asymbol *
5837_bfd_elf_make_empty_symbol (abfd)
5838     bfd *abfd;
5839{
5840  elf_symbol_type *newsym;
5841  bfd_size_type amt = sizeof (elf_symbol_type);
5842
5843  newsym = (elf_symbol_type *) bfd_zalloc (abfd, amt);
5844  if (!newsym)
5845    return NULL;
5846  else
5847    {
5848      newsym->symbol.the_bfd = abfd;
5849      return &newsym->symbol;
5850    }
5851}
5852
5853void
5854_bfd_elf_get_symbol_info (ignore_abfd, symbol, ret)
5855     bfd *ignore_abfd ATTRIBUTE_UNUSED;
5856     asymbol *symbol;
5857     symbol_info *ret;
5858{
5859  bfd_symbol_info (symbol, ret);
5860}
5861
5862/* Return whether a symbol name implies a local symbol.  Most targets
5863   use this function for the is_local_label_name entry point, but some
5864   override it.  */
5865
5866boolean
5867_bfd_elf_is_local_label_name (abfd, name)
5868     bfd *abfd ATTRIBUTE_UNUSED;
5869     const char *name;
5870{
5871  /* Normal local symbols start with ``.L''.  */
5872  if (name[0] == '.' && name[1] == 'L')
5873    return true;
5874
5875  /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
5876     DWARF debugging symbols starting with ``..''.  */
5877  if (name[0] == '.' && name[1] == '.')
5878    return true;
5879
5880  /* gcc will sometimes generate symbols beginning with ``_.L_'' when
5881     emitting DWARF debugging output.  I suspect this is actually a
5882     small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
5883     ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
5884     underscore to be emitted on some ELF targets).  For ease of use,
5885     we treat such symbols as local.  */
5886  if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
5887    return true;
5888
5889  return false;
5890}
5891
5892alent *
5893_bfd_elf_get_lineno (ignore_abfd, symbol)
5894     bfd *ignore_abfd ATTRIBUTE_UNUSED;
5895     asymbol *symbol ATTRIBUTE_UNUSED;
5896{
5897  abort ();
5898  return NULL;
5899}
5900
5901boolean
5902_bfd_elf_set_arch_mach (abfd, arch, machine)
5903     bfd *abfd;
5904     enum bfd_architecture arch;
5905     unsigned long machine;
5906{
5907  /* If this isn't the right architecture for this backend, and this
5908     isn't the generic backend, fail.  */
5909  if (arch != get_elf_backend_data (abfd)->arch
5910      && arch != bfd_arch_unknown
5911      && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
5912    return false;
5913
5914  return bfd_default_set_arch_mach (abfd, arch, machine);
5915}
5916
5917/* Find the function to a particular section and offset,
5918   for error reporting.  */
5919
5920static boolean
5921elf_find_function (abfd, section, symbols, offset,
5922		   filename_ptr, functionname_ptr)
5923     bfd *abfd ATTRIBUTE_UNUSED;
5924     asection *section;
5925     asymbol **symbols;
5926     bfd_vma offset;
5927     const char **filename_ptr;
5928     const char **functionname_ptr;
5929{
5930  const char *filename;
5931  asymbol *func;
5932  bfd_vma low_func;
5933  asymbol **p;
5934
5935  filename = NULL;
5936  func = NULL;
5937  low_func = 0;
5938
5939  for (p = symbols; *p != NULL; p++)
5940    {
5941      elf_symbol_type *q;
5942
5943      q = (elf_symbol_type *) *p;
5944
5945      if (bfd_get_section (&q->symbol) != section)
5946	continue;
5947
5948      switch (ELF_ST_TYPE (q->internal_elf_sym.st_info))
5949	{
5950	default:
5951	  break;
5952	case STT_FILE:
5953	  filename = bfd_asymbol_name (&q->symbol);
5954	  break;
5955	case STT_NOTYPE:
5956	case STT_FUNC:
5957	  if (q->symbol.section == section
5958	      && q->symbol.value >= low_func
5959	      && q->symbol.value <= offset)
5960	    {
5961	      func = (asymbol *) q;
5962	      low_func = q->symbol.value;
5963	    }
5964	  break;
5965	}
5966    }
5967
5968  if (func == NULL)
5969    return false;
5970
5971  if (filename_ptr)
5972    *filename_ptr = filename;
5973  if (functionname_ptr)
5974    *functionname_ptr = bfd_asymbol_name (func);
5975
5976  return true;
5977}
5978
5979/* Find the nearest line to a particular section and offset,
5980   for error reporting.  */
5981
5982boolean
5983_bfd_elf_find_nearest_line (abfd, section, symbols, offset,
5984			    filename_ptr, functionname_ptr, line_ptr)
5985     bfd *abfd;
5986     asection *section;
5987     asymbol **symbols;
5988     bfd_vma offset;
5989     const char **filename_ptr;
5990     const char **functionname_ptr;
5991     unsigned int *line_ptr;
5992{
5993  boolean found;
5994
5995  if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
5996				     filename_ptr, functionname_ptr,
5997				     line_ptr))
5998    {
5999      if (!*functionname_ptr)
6000	elf_find_function (abfd, section, symbols, offset,
6001			   *filename_ptr ? NULL : filename_ptr,
6002			   functionname_ptr);
6003
6004      return true;
6005    }
6006
6007  if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
6008				     filename_ptr, functionname_ptr,
6009				     line_ptr, 0,
6010				     &elf_tdata (abfd)->dwarf2_find_line_info))
6011    {
6012      if (!*functionname_ptr)
6013	elf_find_function (abfd, section, symbols, offset,
6014			   *filename_ptr ? NULL : filename_ptr,
6015			   functionname_ptr);
6016
6017      return true;
6018    }
6019
6020  if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
6021					     &found, filename_ptr,
6022					     functionname_ptr, line_ptr,
6023					     &elf_tdata (abfd)->line_info))
6024    return false;
6025  if (found && (*functionname_ptr || *line_ptr))
6026    return true;
6027
6028  if (symbols == NULL)
6029    return false;
6030
6031  if (! elf_find_function (abfd, section, symbols, offset,
6032			   filename_ptr, functionname_ptr))
6033    return false;
6034
6035  *line_ptr = 0;
6036  return true;
6037}
6038
6039int
6040_bfd_elf_sizeof_headers (abfd, reloc)
6041     bfd *abfd;
6042     boolean reloc;
6043{
6044  int ret;
6045
6046  ret = get_elf_backend_data (abfd)->s->sizeof_ehdr;
6047  if (! reloc)
6048    ret += get_program_header_size (abfd);
6049  return ret;
6050}
6051
6052boolean
6053_bfd_elf_set_section_contents (abfd, section, location, offset, count)
6054     bfd *abfd;
6055     sec_ptr section;
6056     PTR location;
6057     file_ptr offset;
6058     bfd_size_type count;
6059{
6060  Elf_Internal_Shdr *hdr;
6061  bfd_signed_vma pos;
6062
6063  if (! abfd->output_has_begun
6064      && ! (_bfd_elf_compute_section_file_positions
6065	    (abfd, (struct bfd_link_info *) NULL)))
6066    return false;
6067
6068  hdr = &elf_section_data (section)->this_hdr;
6069  pos = hdr->sh_offset + offset;
6070  if (bfd_seek (abfd, pos, SEEK_SET) != 0
6071      || bfd_bwrite (location, count, abfd) != count)
6072    return false;
6073
6074  return true;
6075}
6076
6077void
6078_bfd_elf_no_info_to_howto (abfd, cache_ptr, dst)
6079     bfd *abfd ATTRIBUTE_UNUSED;
6080     arelent *cache_ptr ATTRIBUTE_UNUSED;
6081     Elf_Internal_Rela *dst ATTRIBUTE_UNUSED;
6082{
6083  abort ();
6084}
6085
6086#if 0
6087void
6088_bfd_elf_no_info_to_howto_rel (abfd, cache_ptr, dst)
6089     bfd *abfd;
6090     arelent *cache_ptr;
6091     Elf_Internal_Rel *dst;
6092{
6093  abort ();
6094}
6095#endif
6096
6097/* Try to convert a non-ELF reloc into an ELF one.  */
6098
6099boolean
6100_bfd_elf_validate_reloc (abfd, areloc)
6101     bfd *abfd;
6102     arelent *areloc;
6103{
6104  /* Check whether we really have an ELF howto.  */
6105
6106  if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
6107    {
6108      bfd_reloc_code_real_type code;
6109      reloc_howto_type *howto;
6110
6111      /* Alien reloc: Try to determine its type to replace it with an
6112	 equivalent ELF reloc.  */
6113
6114      if (areloc->howto->pc_relative)
6115	{
6116	  switch (areloc->howto->bitsize)
6117	    {
6118	    case 8:
6119	      code = BFD_RELOC_8_PCREL;
6120	      break;
6121	    case 12:
6122	      code = BFD_RELOC_12_PCREL;
6123	      break;
6124	    case 16:
6125	      code = BFD_RELOC_16_PCREL;
6126	      break;
6127	    case 24:
6128	      code = BFD_RELOC_24_PCREL;
6129	      break;
6130	    case 32:
6131	      code = BFD_RELOC_32_PCREL;
6132	      break;
6133	    case 64:
6134	      code = BFD_RELOC_64_PCREL;
6135	      break;
6136	    default:
6137	      goto fail;
6138	    }
6139
6140	  howto = bfd_reloc_type_lookup (abfd, code);
6141
6142	  if (areloc->howto->pcrel_offset != howto->pcrel_offset)
6143	    {
6144	      if (howto->pcrel_offset)
6145		areloc->addend += areloc->address;
6146	      else
6147		areloc->addend -= areloc->address; /* addend is unsigned!! */
6148	    }
6149	}
6150      else
6151	{
6152	  switch (areloc->howto->bitsize)
6153	    {
6154	    case 8:
6155	      code = BFD_RELOC_8;
6156	      break;
6157	    case 14:
6158	      code = BFD_RELOC_14;
6159	      break;
6160	    case 16:
6161	      code = BFD_RELOC_16;
6162	      break;
6163	    case 26:
6164	      code = BFD_RELOC_26;
6165	      break;
6166	    case 32:
6167	      code = BFD_RELOC_32;
6168	      break;
6169	    case 64:
6170	      code = BFD_RELOC_64;
6171	      break;
6172	    default:
6173	      goto fail;
6174	    }
6175
6176	  howto = bfd_reloc_type_lookup (abfd, code);
6177	}
6178
6179      if (howto)
6180	areloc->howto = howto;
6181      else
6182	goto fail;
6183    }
6184
6185  return true;
6186
6187 fail:
6188  (*_bfd_error_handler)
6189    (_("%s: unsupported relocation type %s"),
6190     bfd_archive_filename (abfd), areloc->howto->name);
6191  bfd_set_error (bfd_error_bad_value);
6192  return false;
6193}
6194
6195boolean
6196_bfd_elf_close_and_cleanup (abfd)
6197     bfd *abfd;
6198{
6199  if (bfd_get_format (abfd) == bfd_object)
6200    {
6201      if (elf_shstrtab (abfd) != NULL)
6202	_bfd_elf_strtab_free (elf_shstrtab (abfd));
6203    }
6204
6205  return _bfd_generic_close_and_cleanup (abfd);
6206}
6207
6208/* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
6209   in the relocation's offset.  Thus we cannot allow any sort of sanity
6210   range-checking to interfere.  There is nothing else to do in processing
6211   this reloc.  */
6212
6213bfd_reloc_status_type
6214_bfd_elf_rel_vtable_reloc_fn (abfd, re, symbol, data, is, obfd, errmsg)
6215     bfd *abfd ATTRIBUTE_UNUSED;
6216     arelent *re ATTRIBUTE_UNUSED;
6217     struct symbol_cache_entry *symbol ATTRIBUTE_UNUSED;
6218     PTR data ATTRIBUTE_UNUSED;
6219     asection *is ATTRIBUTE_UNUSED;
6220     bfd *obfd ATTRIBUTE_UNUSED;
6221     char **errmsg ATTRIBUTE_UNUSED;
6222{
6223  return bfd_reloc_ok;
6224}
6225
6226/* Elf core file support.  Much of this only works on native
6227   toolchains, since we rely on knowing the
6228   machine-dependent procfs structure in order to pick
6229   out details about the corefile.  */
6230
6231#ifdef HAVE_SYS_PROCFS_H
6232# include <sys/procfs.h>
6233#endif
6234
6235/* FIXME: this is kinda wrong, but it's what gdb wants.  */
6236
6237static int
6238elfcore_make_pid (abfd)
6239     bfd *abfd;
6240{
6241  return ((elf_tdata (abfd)->core_lwpid << 16)
6242	  + (elf_tdata (abfd)->core_pid));
6243}
6244
6245/* If there isn't a section called NAME, make one, using
6246   data from SECT.  Note, this function will generate a
6247   reference to NAME, so you shouldn't deallocate or
6248   overwrite it.  */
6249
6250static boolean
6251elfcore_maybe_make_sect (abfd, name, sect)
6252     bfd *abfd;
6253     char *name;
6254     asection *sect;
6255{
6256  asection *sect2;
6257
6258  if (bfd_get_section_by_name (abfd, name) != NULL)
6259    return true;
6260
6261  sect2 = bfd_make_section (abfd, name);
6262  if (sect2 == NULL)
6263    return false;
6264
6265  sect2->_raw_size = sect->_raw_size;
6266  sect2->filepos = sect->filepos;
6267  sect2->flags = sect->flags;
6268  sect2->alignment_power = sect->alignment_power;
6269  return true;
6270}
6271
6272/* Create a pseudosection containing SIZE bytes at FILEPOS.  This
6273   actually creates up to two pseudosections:
6274   - For the single-threaded case, a section named NAME, unless
6275     such a section already exists.
6276   - For the multi-threaded case, a section named "NAME/PID", where
6277     PID is elfcore_make_pid (abfd).
6278   Both pseudosections have identical contents. */
6279boolean
6280_bfd_elfcore_make_pseudosection (abfd, name, size, filepos)
6281     bfd *abfd;
6282     char *name;
6283     size_t size;
6284     ufile_ptr filepos;
6285{
6286  char buf[100];
6287  char *threaded_name;
6288  size_t len;
6289  asection *sect;
6290
6291  /* Build the section name.  */
6292
6293  sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
6294  len = strlen (buf) + 1;
6295  threaded_name = bfd_alloc (abfd, (bfd_size_type) len);
6296  if (threaded_name == NULL)
6297    return false;
6298  memcpy (threaded_name, buf, len);
6299
6300  sect = bfd_make_section (abfd, threaded_name);
6301  if (sect == NULL)
6302    return false;
6303  sect->_raw_size = size;
6304  sect->filepos = filepos;
6305  sect->flags = SEC_HAS_CONTENTS;
6306  sect->alignment_power = 2;
6307
6308  return elfcore_maybe_make_sect (abfd, name, sect);
6309}
6310
6311/* prstatus_t exists on:
6312     solaris 2.5+
6313     linux 2.[01] + glibc
6314     unixware 4.2
6315*/
6316
6317#if defined (HAVE_PRSTATUS_T)
6318static boolean elfcore_grok_prstatus PARAMS ((bfd *, Elf_Internal_Note *));
6319
6320static boolean
6321elfcore_grok_prstatus (abfd, note)
6322     bfd *abfd;
6323     Elf_Internal_Note *note;
6324{
6325  size_t raw_size;
6326  int offset;
6327
6328  if (note->descsz == sizeof (prstatus_t))
6329    {
6330      prstatus_t prstat;
6331
6332      raw_size = sizeof (prstat.pr_reg);
6333      offset   = offsetof (prstatus_t, pr_reg);
6334      memcpy (&prstat, note->descdata, sizeof (prstat));
6335
6336      /* Do not overwrite the core signal if it
6337	 has already been set by another thread.  */
6338      if (elf_tdata (abfd)->core_signal == 0)
6339	elf_tdata (abfd)->core_signal = prstat.pr_cursig;
6340      elf_tdata (abfd)->core_pid = prstat.pr_pid;
6341
6342      /* pr_who exists on:
6343	 solaris 2.5+
6344	 unixware 4.2
6345	 pr_who doesn't exist on:
6346	 linux 2.[01]
6347	 */
6348#if defined (HAVE_PRSTATUS_T_PR_WHO)
6349      elf_tdata (abfd)->core_lwpid = prstat.pr_who;
6350#endif
6351    }
6352#if defined (HAVE_PRSTATUS32_T)
6353  else if (note->descsz == sizeof (prstatus32_t))
6354    {
6355      /* 64-bit host, 32-bit corefile */
6356      prstatus32_t prstat;
6357
6358      raw_size = sizeof (prstat.pr_reg);
6359      offset   = offsetof (prstatus32_t, pr_reg);
6360      memcpy (&prstat, note->descdata, sizeof (prstat));
6361
6362      /* Do not overwrite the core signal if it
6363	 has already been set by another thread.  */
6364      if (elf_tdata (abfd)->core_signal == 0)
6365	elf_tdata (abfd)->core_signal = prstat.pr_cursig;
6366      elf_tdata (abfd)->core_pid = prstat.pr_pid;
6367
6368      /* pr_who exists on:
6369	 solaris 2.5+
6370	 unixware 4.2
6371	 pr_who doesn't exist on:
6372	 linux 2.[01]
6373	 */
6374#if defined (HAVE_PRSTATUS32_T_PR_WHO)
6375      elf_tdata (abfd)->core_lwpid = prstat.pr_who;
6376#endif
6377    }
6378#endif /* HAVE_PRSTATUS32_T */
6379  else
6380    {
6381      /* Fail - we don't know how to handle any other
6382	 note size (ie. data object type).  */
6383      return true;
6384    }
6385
6386  /* Make a ".reg/999" section and a ".reg" section.  */
6387  return _bfd_elfcore_make_pseudosection (abfd, ".reg",
6388					  raw_size, note->descpos + offset);
6389}
6390#endif /* defined (HAVE_PRSTATUS_T) */
6391
6392/* Create a pseudosection containing the exact contents of NOTE.  */
6393static boolean
6394elfcore_make_note_pseudosection (abfd, name, note)
6395     bfd *abfd;
6396     char *name;
6397     Elf_Internal_Note *note;
6398{
6399  return _bfd_elfcore_make_pseudosection (abfd, name,
6400					  note->descsz, note->descpos);
6401}
6402
6403/* There isn't a consistent prfpregset_t across platforms,
6404   but it doesn't matter, because we don't have to pick this
6405   data structure apart.  */
6406
6407static boolean
6408elfcore_grok_prfpreg (abfd, note)
6409     bfd *abfd;
6410     Elf_Internal_Note *note;
6411{
6412  return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6413}
6414
6415/* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
6416   type of 5 (NT_PRXFPREG).  Just include the whole note's contents
6417   literally.  */
6418
6419static boolean
6420elfcore_grok_prxfpreg (abfd, note)
6421     bfd *abfd;
6422     Elf_Internal_Note *note;
6423{
6424  return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
6425}
6426
6427#if defined (HAVE_PRPSINFO_T)
6428typedef prpsinfo_t   elfcore_psinfo_t;
6429#if defined (HAVE_PRPSINFO32_T)		/* Sparc64 cross Sparc32 */
6430typedef prpsinfo32_t elfcore_psinfo32_t;
6431#endif
6432#endif
6433
6434#if defined (HAVE_PSINFO_T)
6435typedef psinfo_t   elfcore_psinfo_t;
6436#if defined (HAVE_PSINFO32_T)		/* Sparc64 cross Sparc32 */
6437typedef psinfo32_t elfcore_psinfo32_t;
6438#endif
6439#endif
6440
6441/* return a malloc'ed copy of a string at START which is at
6442   most MAX bytes long, possibly without a terminating '\0'.
6443   the copy will always have a terminating '\0'.  */
6444
6445char *
6446_bfd_elfcore_strndup (abfd, start, max)
6447     bfd *abfd;
6448     char *start;
6449     size_t max;
6450{
6451  char *dups;
6452  char *end = memchr (start, '\0', max);
6453  size_t len;
6454
6455  if (end == NULL)
6456    len = max;
6457  else
6458    len = end - start;
6459
6460  dups = bfd_alloc (abfd, (bfd_size_type) len + 1);
6461  if (dups == NULL)
6462    return NULL;
6463
6464  memcpy (dups, start, len);
6465  dups[len] = '\0';
6466
6467  return dups;
6468}
6469
6470#if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6471static boolean elfcore_grok_psinfo PARAMS ((bfd *, Elf_Internal_Note *));
6472
6473static boolean
6474elfcore_grok_psinfo (abfd, note)
6475     bfd *abfd;
6476     Elf_Internal_Note *note;
6477{
6478  if (note->descsz == sizeof (elfcore_psinfo_t))
6479    {
6480      elfcore_psinfo_t psinfo;
6481
6482      memcpy (&psinfo, note->descdata, sizeof (psinfo));
6483
6484      elf_tdata (abfd)->core_program
6485	= _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
6486				sizeof (psinfo.pr_fname));
6487
6488      elf_tdata (abfd)->core_command
6489	= _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
6490				sizeof (psinfo.pr_psargs));
6491    }
6492#if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
6493  else if (note->descsz == sizeof (elfcore_psinfo32_t))
6494    {
6495      /* 64-bit host, 32-bit corefile */
6496      elfcore_psinfo32_t psinfo;
6497
6498      memcpy (&psinfo, note->descdata, sizeof (psinfo));
6499
6500      elf_tdata (abfd)->core_program
6501	= _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
6502				sizeof (psinfo.pr_fname));
6503
6504      elf_tdata (abfd)->core_command
6505	= _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
6506				sizeof (psinfo.pr_psargs));
6507    }
6508#endif
6509
6510  else
6511    {
6512      /* Fail - we don't know how to handle any other
6513	 note size (ie. data object type).  */
6514      return true;
6515    }
6516
6517  /* Note that for some reason, a spurious space is tacked
6518     onto the end of the args in some (at least one anyway)
6519     implementations, so strip it off if it exists.  */
6520
6521  {
6522    char *command = elf_tdata (abfd)->core_command;
6523    int n = strlen (command);
6524
6525    if (0 < n && command[n - 1] == ' ')
6526      command[n - 1] = '\0';
6527  }
6528
6529  return true;
6530}
6531#endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
6532
6533#if defined (HAVE_PSTATUS_T)
6534static boolean elfcore_grok_pstatus PARAMS ((bfd *, Elf_Internal_Note *));
6535
6536static boolean
6537elfcore_grok_pstatus (abfd, note)
6538     bfd *abfd;
6539     Elf_Internal_Note *note;
6540{
6541  if (note->descsz == sizeof (pstatus_t)
6542#if defined (HAVE_PXSTATUS_T)
6543      || note->descsz == sizeof (pxstatus_t)
6544#endif
6545      )
6546    {
6547      pstatus_t pstat;
6548
6549      memcpy (&pstat, note->descdata, sizeof (pstat));
6550
6551      elf_tdata (abfd)->core_pid = pstat.pr_pid;
6552    }
6553#if defined (HAVE_PSTATUS32_T)
6554  else if (note->descsz == sizeof (pstatus32_t))
6555    {
6556      /* 64-bit host, 32-bit corefile */
6557      pstatus32_t pstat;
6558
6559      memcpy (&pstat, note->descdata, sizeof (pstat));
6560
6561      elf_tdata (abfd)->core_pid = pstat.pr_pid;
6562    }
6563#endif
6564  /* Could grab some more details from the "representative"
6565     lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
6566     NT_LWPSTATUS note, presumably.  */
6567
6568  return true;
6569}
6570#endif /* defined (HAVE_PSTATUS_T) */
6571
6572#if defined (HAVE_LWPSTATUS_T)
6573static boolean elfcore_grok_lwpstatus PARAMS ((bfd *, Elf_Internal_Note *));
6574
6575static boolean
6576elfcore_grok_lwpstatus (abfd, note)
6577     bfd *abfd;
6578     Elf_Internal_Note *note;
6579{
6580  lwpstatus_t lwpstat;
6581  char buf[100];
6582  char *name;
6583  size_t len;
6584  asection *sect;
6585
6586  if (note->descsz != sizeof (lwpstat)
6587#if defined (HAVE_LWPXSTATUS_T)
6588      && note->descsz != sizeof (lwpxstatus_t)
6589#endif
6590      )
6591    return true;
6592
6593  memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
6594
6595  elf_tdata (abfd)->core_lwpid = lwpstat.pr_lwpid;
6596  elf_tdata (abfd)->core_signal = lwpstat.pr_cursig;
6597
6598  /* Make a ".reg/999" section.  */
6599
6600  sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
6601  len = strlen (buf) + 1;
6602  name = bfd_alloc (abfd, (bfd_size_type) len);
6603  if (name == NULL)
6604    return false;
6605  memcpy (name, buf, len);
6606
6607  sect = bfd_make_section (abfd, name);
6608  if (sect == NULL)
6609    return false;
6610
6611#if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
6612  sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
6613  sect->filepos = note->descpos
6614    + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
6615#endif
6616
6617#if defined (HAVE_LWPSTATUS_T_PR_REG)
6618  sect->_raw_size = sizeof (lwpstat.pr_reg);
6619  sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
6620#endif
6621
6622  sect->flags = SEC_HAS_CONTENTS;
6623  sect->alignment_power = 2;
6624
6625  if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
6626    return false;
6627
6628  /* Make a ".reg2/999" section */
6629
6630  sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
6631  len = strlen (buf) + 1;
6632  name = bfd_alloc (abfd, (bfd_size_type) len);
6633  if (name == NULL)
6634    return false;
6635  memcpy (name, buf, len);
6636
6637  sect = bfd_make_section (abfd, name);
6638  if (sect == NULL)
6639    return false;
6640
6641#if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
6642  sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
6643  sect->filepos = note->descpos
6644    + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
6645#endif
6646
6647#if defined (HAVE_LWPSTATUS_T_PR_FPREG)
6648  sect->_raw_size = sizeof (lwpstat.pr_fpreg);
6649  sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
6650#endif
6651
6652  sect->flags = SEC_HAS_CONTENTS;
6653  sect->alignment_power = 2;
6654
6655  return elfcore_maybe_make_sect (abfd, ".reg2", sect);
6656}
6657#endif /* defined (HAVE_LWPSTATUS_T) */
6658
6659#if defined (HAVE_WIN32_PSTATUS_T)
6660static boolean
6661elfcore_grok_win32pstatus (abfd, note)
6662     bfd *abfd;
6663     Elf_Internal_Note *note;
6664{
6665  char buf[30];
6666  char *name;
6667  size_t len;
6668  asection *sect;
6669  win32_pstatus_t pstatus;
6670
6671  if (note->descsz < sizeof (pstatus))
6672    return true;
6673
6674  memcpy (&pstatus, note->descdata, sizeof (pstatus));
6675
6676  switch (pstatus.data_type)
6677    {
6678    case NOTE_INFO_PROCESS:
6679      /* FIXME: need to add ->core_command.  */
6680      elf_tdata (abfd)->core_signal = pstatus.data.process_info.signal;
6681      elf_tdata (abfd)->core_pid = pstatus.data.process_info.pid;
6682      break;
6683
6684    case NOTE_INFO_THREAD:
6685      /* Make a ".reg/999" section.  */
6686      sprintf (buf, ".reg/%d", pstatus.data.thread_info.tid);
6687
6688      len = strlen (buf) + 1;
6689      name = bfd_alloc (abfd, (bfd_size_type) len);
6690      if (name == NULL)
6691	return false;
6692
6693      memcpy (name, buf, len);
6694
6695      sect = bfd_make_section (abfd, name);
6696      if (sect == NULL)
6697	return false;
6698
6699      sect->_raw_size = sizeof (pstatus.data.thread_info.thread_context);
6700      sect->filepos = (note->descpos
6701		       + offsetof (struct win32_pstatus,
6702				   data.thread_info.thread_context));
6703      sect->flags = SEC_HAS_CONTENTS;
6704      sect->alignment_power = 2;
6705
6706      if (pstatus.data.thread_info.is_active_thread)
6707	if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
6708	  return false;
6709      break;
6710
6711    case NOTE_INFO_MODULE:
6712      /* Make a ".module/xxxxxxxx" section.  */
6713      sprintf (buf, ".module/%08x", pstatus.data.module_info.base_address);
6714
6715      len = strlen (buf) + 1;
6716      name = bfd_alloc (abfd, (bfd_size_type) len);
6717      if (name == NULL)
6718	return false;
6719
6720      memcpy (name, buf, len);
6721
6722      sect = bfd_make_section (abfd, name);
6723
6724      if (sect == NULL)
6725	return false;
6726
6727      sect->_raw_size = note->descsz;
6728      sect->filepos = note->descpos;
6729      sect->flags = SEC_HAS_CONTENTS;
6730      sect->alignment_power = 2;
6731      break;
6732
6733    default:
6734      return true;
6735    }
6736
6737  return true;
6738}
6739#endif /* HAVE_WIN32_PSTATUS_T */
6740
6741static boolean
6742elfcore_grok_note (abfd, note)
6743     bfd *abfd;
6744     Elf_Internal_Note *note;
6745{
6746  struct elf_backend_data *bed = get_elf_backend_data (abfd);
6747
6748  switch (note->type)
6749    {
6750    default:
6751      return true;
6752
6753    case NT_PRSTATUS:
6754      if (bed->elf_backend_grok_prstatus)
6755	if ((*bed->elf_backend_grok_prstatus) (abfd, note))
6756	  return true;
6757#if defined (HAVE_PRSTATUS_T)
6758      return elfcore_grok_prstatus (abfd, note);
6759#else
6760      return true;
6761#endif
6762
6763#if defined (HAVE_PSTATUS_T)
6764    case NT_PSTATUS:
6765      return elfcore_grok_pstatus (abfd, note);
6766#endif
6767
6768#if defined (HAVE_LWPSTATUS_T)
6769    case NT_LWPSTATUS:
6770      return elfcore_grok_lwpstatus (abfd, note);
6771#endif
6772
6773    case NT_FPREGSET:		/* FIXME: rename to NT_PRFPREG */
6774      return elfcore_grok_prfpreg (abfd, note);
6775
6776#if defined (HAVE_WIN32_PSTATUS_T)
6777    case NT_WIN32PSTATUS:
6778      return elfcore_grok_win32pstatus (abfd, note);
6779#endif
6780
6781    case NT_PRXFPREG:		/* Linux SSE extension */
6782      if (note->namesz == 5
6783	  && ! strcmp (note->namedata, "LINUX"))
6784	return elfcore_grok_prxfpreg (abfd, note);
6785      else
6786	return true;
6787
6788    case NT_PRPSINFO:
6789    case NT_PSINFO:
6790      if (bed->elf_backend_grok_psinfo)
6791	if ((*bed->elf_backend_grok_psinfo) (abfd, note))
6792	  return true;
6793#if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6794      return elfcore_grok_psinfo (abfd, note);
6795#else
6796      return true;
6797#endif
6798    }
6799}
6800
6801static boolean
6802elfcore_netbsd_get_lwpid (note, lwpidp)
6803     Elf_Internal_Note *note;
6804     int *lwpidp;
6805{
6806  char *cp;
6807
6808  cp = strchr (note->namedata, '@');
6809  if (cp != NULL)
6810    {
6811      *lwpidp = atoi(cp + 1);
6812      return true;
6813    }
6814  return false;
6815}
6816
6817static boolean
6818elfcore_grok_netbsd_procinfo (abfd, note)
6819     bfd *abfd;
6820     Elf_Internal_Note *note;
6821{
6822
6823  /* Signal number at offset 0x08. */
6824  elf_tdata (abfd)->core_signal
6825    = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
6826
6827  /* Process ID at offset 0x50. */
6828  elf_tdata (abfd)->core_pid
6829    = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
6830
6831  /* Command name at 0x7c (max 32 bytes, including nul). */
6832  elf_tdata (abfd)->core_command
6833    = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
6834
6835  return true;
6836}
6837
6838static boolean
6839elfcore_grok_netbsd_note (abfd, note)
6840     bfd *abfd;
6841     Elf_Internal_Note *note;
6842{
6843  int lwp;
6844
6845  if (elfcore_netbsd_get_lwpid (note, &lwp))
6846    elf_tdata (abfd)->core_lwpid = lwp;
6847
6848  if (note->type == NT_NETBSDCORE_PROCINFO)
6849    {
6850      /* NetBSD-specific core "procinfo".  Note that we expect to
6851         find this note before any of the others, which is fine,
6852         since the kernel writes this note out first when it
6853         creates a core file.  */
6854
6855      return elfcore_grok_netbsd_procinfo (abfd, note);
6856    }
6857
6858  /* As of Jan 2002 there are no other machine-independent notes
6859     defined for NetBSD core files.  If the note type is less
6860     than the start of the machine-dependent note types, we don't
6861     understand it.  */
6862
6863  if (note->type < NT_NETBSDCORE_FIRSTMACH)
6864    return true;
6865
6866
6867  switch (bfd_get_arch (abfd))
6868    {
6869    /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
6870       PT_GETFPREGS == mach+2.  */
6871
6872    case bfd_arch_alpha:
6873    case bfd_arch_sparc:
6874      switch (note->type)
6875        {
6876        case NT_NETBSDCORE_FIRSTMACH+0:
6877          return elfcore_make_note_pseudosection (abfd, ".reg", note);
6878
6879        case NT_NETBSDCORE_FIRSTMACH+2:
6880          return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6881
6882        default:
6883          return true;
6884        }
6885
6886    /* On all other arch's, PT_GETREGS == mach+1 and
6887       PT_GETFPREGS == mach+3.  */
6888
6889    default:
6890      switch (note->type)
6891        {
6892        case NT_NETBSDCORE_FIRSTMACH+1:
6893          return elfcore_make_note_pseudosection (abfd, ".reg", note);
6894
6895        case NT_NETBSDCORE_FIRSTMACH+3:
6896          return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6897
6898        default:
6899          return true;
6900        }
6901    }
6902    /* NOTREACHED */
6903}
6904
6905/* Function: elfcore_write_note
6906
6907   Inputs:
6908     buffer to hold note
6909     name of note
6910     type of note
6911     data for note
6912     size of data for note
6913
6914   Return:
6915   End of buffer containing note.  */
6916
6917char *
6918elfcore_write_note (abfd, buf, bufsiz, name, type, input, size)
6919     bfd  *abfd;
6920     char *buf;
6921     int  *bufsiz;
6922     const char *name;
6923     int  type;
6924     const PTR input;
6925     int  size;
6926{
6927  Elf_External_Note *xnp;
6928  size_t namesz;
6929  size_t pad;
6930  size_t newspace;
6931  char *p, *dest;
6932
6933  namesz = 0;
6934  pad = 0;
6935  if (name != NULL)
6936    {
6937      struct elf_backend_data *bed;
6938
6939      namesz = strlen (name) + 1;
6940      bed = get_elf_backend_data (abfd);
6941      pad = -namesz & (bed->s->file_align - 1);
6942    }
6943
6944  newspace = sizeof (Elf_External_Note) - 1 + namesz + pad + size;
6945
6946  p = realloc (buf, *bufsiz + newspace);
6947  dest = p + *bufsiz;
6948  *bufsiz += newspace;
6949  xnp = (Elf_External_Note *) dest;
6950  H_PUT_32 (abfd, namesz, xnp->namesz);
6951  H_PUT_32 (abfd, size, xnp->descsz);
6952  H_PUT_32 (abfd, type, xnp->type);
6953  dest = xnp->name;
6954  if (name != NULL)
6955    {
6956      memcpy (dest, name, namesz);
6957      dest += namesz;
6958      while (pad != 0)
6959	{
6960	  *dest++ = '\0';
6961	  --pad;
6962	}
6963    }
6964  memcpy (dest, input, size);
6965  return p;
6966}
6967
6968#if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6969char *
6970elfcore_write_prpsinfo (abfd, buf, bufsiz, fname, psargs)
6971     bfd  *abfd;
6972     char *buf;
6973     int  *bufsiz;
6974     const char *fname;
6975     const char *psargs;
6976{
6977  int note_type;
6978  char *note_name = "CORE";
6979
6980#if defined (HAVE_PSINFO_T)
6981  psinfo_t  data;
6982  note_type = NT_PSINFO;
6983#else
6984  prpsinfo_t data;
6985  note_type = NT_PRPSINFO;
6986#endif
6987
6988  memset (&data, 0, sizeof (data));
6989  strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
6990  strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
6991  return elfcore_write_note (abfd, buf, bufsiz,
6992			     note_name, note_type, &data, sizeof (data));
6993}
6994#endif	/* PSINFO_T or PRPSINFO_T */
6995
6996#if defined (HAVE_PRSTATUS_T)
6997char *
6998elfcore_write_prstatus (abfd, buf, bufsiz, pid, cursig, gregs)
6999     bfd *abfd;
7000     char *buf;
7001     int *bufsiz;
7002     long pid;
7003     int cursig;
7004     const PTR gregs;
7005{
7006  prstatus_t prstat;
7007  char *note_name = "CORE";
7008
7009  memset (&prstat, 0, sizeof (prstat));
7010  prstat.pr_pid = pid;
7011  prstat.pr_cursig = cursig;
7012  memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
7013  return elfcore_write_note (abfd, buf, bufsiz,
7014			     note_name, NT_PRSTATUS, &prstat, sizeof (prstat));
7015}
7016#endif /* HAVE_PRSTATUS_T */
7017
7018#if defined (HAVE_LWPSTATUS_T)
7019char *
7020elfcore_write_lwpstatus (abfd, buf, bufsiz, pid, cursig, gregs)
7021     bfd *abfd;
7022     char *buf;
7023     int *bufsiz;
7024     long pid;
7025     int cursig;
7026     const PTR gregs;
7027{
7028  lwpstatus_t lwpstat;
7029  char *note_name = "CORE";
7030
7031  memset (&lwpstat, 0, sizeof (lwpstat));
7032  lwpstat.pr_lwpid  = pid >> 16;
7033  lwpstat.pr_cursig = cursig;
7034#if defined (HAVE_LWPSTATUS_T_PR_REG)
7035  memcpy (lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
7036#elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
7037#if !defined(gregs)
7038  memcpy (lwpstat.pr_context.uc_mcontext.gregs,
7039	  gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
7040#else
7041  memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
7042	  gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
7043#endif
7044#endif
7045  return elfcore_write_note (abfd, buf, bufsiz, note_name,
7046			     NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
7047}
7048#endif /* HAVE_LWPSTATUS_T */
7049
7050#if defined (HAVE_PSTATUS_T)
7051char *
7052elfcore_write_pstatus (abfd, buf, bufsiz, pid, cursig, gregs)
7053     bfd *abfd;
7054     char *buf;
7055     int *bufsiz;
7056     long pid;
7057     int cursig;
7058     const PTR gregs;
7059{
7060  pstatus_t pstat;
7061  char *note_name = "CORE";
7062
7063  memset (&pstat, 0, sizeof (pstat));
7064  pstat.pr_pid = pid & 0xffff;
7065  buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
7066			    NT_PSTATUS, &pstat, sizeof (pstat));
7067  return buf;
7068}
7069#endif /* HAVE_PSTATUS_T */
7070
7071char *
7072elfcore_write_prfpreg (abfd, buf, bufsiz, fpregs, size)
7073     bfd  *abfd;
7074     char *buf;
7075     int  *bufsiz;
7076     const PTR fpregs;
7077     int size;
7078{
7079  char *note_name = "CORE";
7080  return elfcore_write_note (abfd, buf, bufsiz,
7081			     note_name, NT_FPREGSET, fpregs, size);
7082}
7083
7084char *
7085elfcore_write_prxfpreg (abfd, buf, bufsiz, xfpregs, size)
7086     bfd  *abfd;
7087     char *buf;
7088     int  *bufsiz;
7089     const PTR xfpregs;
7090     int size;
7091{
7092  char *note_name = "LINUX";
7093  return elfcore_write_note (abfd, buf, bufsiz,
7094			     note_name, NT_PRXFPREG, xfpregs, size);
7095}
7096
7097static boolean
7098elfcore_read_notes (abfd, offset, size)
7099     bfd *abfd;
7100     file_ptr offset;
7101     bfd_size_type size;
7102{
7103  char *buf;
7104  char *p;
7105
7106  if (size <= 0)
7107    return true;
7108
7109  if (bfd_seek (abfd, offset, SEEK_SET) != 0)
7110    return false;
7111
7112  buf = bfd_malloc (size);
7113  if (buf == NULL)
7114    return false;
7115
7116  if (bfd_bread (buf, size, abfd) != size)
7117    {
7118    error:
7119      free (buf);
7120      return false;
7121    }
7122
7123  p = buf;
7124  while (p < buf + size)
7125    {
7126      /* FIXME: bad alignment assumption.  */
7127      Elf_External_Note *xnp = (Elf_External_Note *) p;
7128      Elf_Internal_Note in;
7129
7130      in.type = H_GET_32 (abfd, xnp->type);
7131
7132      in.namesz = H_GET_32 (abfd, xnp->namesz);
7133      in.namedata = xnp->name;
7134
7135      in.descsz = H_GET_32 (abfd, xnp->descsz);
7136      in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
7137      in.descpos = offset + (in.descdata - buf);
7138
7139      if (strncmp (in.namedata, "NetBSD-CORE", 11) == 0)
7140        {
7141          if (! elfcore_grok_netbsd_note (abfd, &in))
7142            goto error;
7143        }
7144      else
7145        {
7146          if (! elfcore_grok_note (abfd, &in))
7147            goto error;
7148        }
7149
7150      p = in.descdata + BFD_ALIGN (in.descsz, 4);
7151    }
7152
7153  free (buf);
7154  return true;
7155}
7156
7157/* Providing external access to the ELF program header table.  */
7158
7159/* Return an upper bound on the number of bytes required to store a
7160   copy of ABFD's program header table entries.  Return -1 if an error
7161   occurs; bfd_get_error will return an appropriate code.  */
7162
7163long
7164bfd_get_elf_phdr_upper_bound (abfd)
7165     bfd *abfd;
7166{
7167  if (abfd->xvec->flavour != bfd_target_elf_flavour)
7168    {
7169      bfd_set_error (bfd_error_wrong_format);
7170      return -1;
7171    }
7172
7173  return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
7174}
7175
7176/* Copy ABFD's program header table entries to *PHDRS.  The entries
7177   will be stored as an array of Elf_Internal_Phdr structures, as
7178   defined in include/elf/internal.h.  To find out how large the
7179   buffer needs to be, call bfd_get_elf_phdr_upper_bound.
7180
7181   Return the number of program header table entries read, or -1 if an
7182   error occurs; bfd_get_error will return an appropriate code.  */
7183
7184int
7185bfd_get_elf_phdrs (abfd, phdrs)
7186     bfd *abfd;
7187     void *phdrs;
7188{
7189  int num_phdrs;
7190
7191  if (abfd->xvec->flavour != bfd_target_elf_flavour)
7192    {
7193      bfd_set_error (bfd_error_wrong_format);
7194      return -1;
7195    }
7196
7197  num_phdrs = elf_elfheader (abfd)->e_phnum;
7198  memcpy (phdrs, elf_tdata (abfd)->phdr,
7199	  num_phdrs * sizeof (Elf_Internal_Phdr));
7200
7201  return num_phdrs;
7202}
7203
7204void
7205_bfd_elf_sprintf_vma (abfd, buf, value)
7206     bfd *abfd ATTRIBUTE_UNUSED;
7207     char *buf;
7208     bfd_vma value;
7209{
7210#ifdef BFD64
7211  Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form */
7212
7213  i_ehdrp = elf_elfheader (abfd);
7214  if (i_ehdrp == NULL)
7215    sprintf_vma (buf, value);
7216  else
7217    {
7218      if (i_ehdrp->e_ident[EI_CLASS] == ELFCLASS64)
7219	{
7220#if BFD_HOST_64BIT_LONG
7221	  sprintf (buf, "%016lx", value);
7222#else
7223	  sprintf (buf, "%08lx%08lx", _bfd_int64_high (value),
7224		   _bfd_int64_low (value));
7225#endif
7226	}
7227      else
7228	sprintf (buf, "%08lx", (unsigned long) (value & 0xffffffff));
7229    }
7230#else
7231  sprintf_vma (buf, value);
7232#endif
7233}
7234
7235void
7236_bfd_elf_fprintf_vma (abfd, stream, value)
7237     bfd *abfd ATTRIBUTE_UNUSED;
7238     PTR stream;
7239     bfd_vma value;
7240{
7241#ifdef BFD64
7242  Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form */
7243
7244  i_ehdrp = elf_elfheader (abfd);
7245  if (i_ehdrp == NULL)
7246    fprintf_vma ((FILE *) stream, value);
7247  else
7248    {
7249      if (i_ehdrp->e_ident[EI_CLASS] == ELFCLASS64)
7250	{
7251#if BFD_HOST_64BIT_LONG
7252	  fprintf ((FILE *) stream, "%016lx", value);
7253#else
7254	  fprintf ((FILE *) stream, "%08lx%08lx",
7255		   _bfd_int64_high (value), _bfd_int64_low (value));
7256#endif
7257	}
7258      else
7259	fprintf ((FILE *) stream, "%08lx",
7260		 (unsigned long) (value & 0xffffffff));
7261    }
7262#else
7263  fprintf_vma ((FILE *) stream, value);
7264#endif
7265}
7266
7267enum elf_reloc_type_class
7268_bfd_elf_reloc_type_class (rela)
7269     const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED;
7270{
7271  return reloc_class_normal;
7272}
7273
7274/* For RELA architectures, return the relocation value for a
7275   relocation against a local symbol.  */
7276
7277bfd_vma
7278_bfd_elf_rela_local_sym (abfd, sym, sec, rel)
7279     bfd *abfd;
7280     Elf_Internal_Sym *sym;
7281     asection *sec;
7282     Elf_Internal_Rela *rel;
7283{
7284  bfd_vma relocation;
7285
7286  relocation = (sec->output_section->vma
7287		+ sec->output_offset
7288		+ sym->st_value);
7289  if ((sec->flags & SEC_MERGE)
7290      && ELF_ST_TYPE (sym->st_info) == STT_SECTION
7291      && elf_section_data (sec)->sec_info_type == ELF_INFO_TYPE_MERGE)
7292    {
7293      asection *msec;
7294
7295      msec = sec;
7296      rel->r_addend =
7297	_bfd_merged_section_offset (abfd, &msec,
7298				    elf_section_data (sec)->sec_info,
7299				    sym->st_value + rel->r_addend,
7300				    (bfd_vma) 0)
7301	- relocation;
7302      rel->r_addend += msec->output_section->vma + msec->output_offset;
7303    }
7304  return relocation;
7305}
7306
7307bfd_vma
7308_bfd_elf_rel_local_sym (abfd, sym, psec, addend)
7309     bfd *abfd;
7310     Elf_Internal_Sym *sym;
7311     asection **psec;
7312     bfd_vma addend;
7313{
7314  asection *sec = *psec;
7315
7316  if (elf_section_data (sec)->sec_info_type != ELF_INFO_TYPE_MERGE)
7317    return sym->st_value + addend;
7318
7319  return _bfd_merged_section_offset (abfd, psec,
7320				     elf_section_data (sec)->sec_info,
7321				     sym->st_value + addend, (bfd_vma) 0);
7322}
7323
7324bfd_vma
7325_bfd_elf_section_offset (abfd, info, sec, offset)
7326     bfd *abfd;
7327     struct bfd_link_info *info;
7328     asection *sec;
7329     bfd_vma offset;
7330{
7331  struct bfd_elf_section_data *sec_data;
7332
7333  sec_data = elf_section_data (sec);
7334  switch (sec_data->sec_info_type)
7335    {
7336    case ELF_INFO_TYPE_STABS:
7337      return _bfd_stab_section_offset
7338	(abfd, &elf_hash_table (info)->merge_info, sec, &sec_data->sec_info,
7339	 offset);
7340    case ELF_INFO_TYPE_EH_FRAME:
7341      return _bfd_elf_eh_frame_section_offset (abfd, sec, offset);
7342    default:
7343      return offset;
7344    }
7345}
7346