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