elf.c revision 68767
1/* ELF executable support for BFD.
2   Copyright 1993, 94, 95, 96, 97, 98, 99, 2000 Free Software Foundation, Inc.
3
4This file is part of BFD, the Binary File Descriptor library.
5
6This program is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 2 of the License, or
9(at your option) any later version.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program; if not, write to the Free Software
18Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20/* $FreeBSD: head/contrib/binutils/bfd/elf.c 68767 2000-11-15 21:04:41Z obrien $ */
21
22/*
23
24SECTION
25	ELF backends
26
27	BFD support for ELF formats is being worked on.
28	Currently, the best supported back ends are for sparc and i386
29	(running svr4 or Solaris 2).
30
31	Documentation of the internals of the support code still needs
32	to be written.  The code is changing quickly enough that we
33	haven't bothered yet.
34 */
35
36#include "bfd.h"
37#include "sysdep.h"
38#include "bfdlink.h"
39#include "libbfd.h"
40#define ARCH_SIZE 0
41#include "elf-bfd.h"
42
43static INLINE struct elf_segment_map *make_mapping
44  PARAMS ((bfd *, asection **, unsigned int, unsigned int, boolean));
45static boolean map_sections_to_segments PARAMS ((bfd *));
46static int elf_sort_sections PARAMS ((const PTR, const PTR));
47static boolean assign_file_positions_for_segments PARAMS ((bfd *));
48static boolean assign_file_positions_except_relocs PARAMS ((bfd *));
49static boolean prep_headers PARAMS ((bfd *));
50static boolean swap_out_syms PARAMS ((bfd *, struct bfd_strtab_hash **, int));
51static boolean copy_private_bfd_data PARAMS ((bfd *, bfd *));
52static char *elf_read PARAMS ((bfd *, long, unsigned int));
53static void elf_fake_sections PARAMS ((bfd *, asection *, PTR));
54static boolean assign_section_numbers PARAMS ((bfd *));
55static INLINE int sym_is_global PARAMS ((bfd *, asymbol *));
56static boolean elf_map_symbols PARAMS ((bfd *));
57static bfd_size_type get_program_header_size PARAMS ((bfd *));
58static boolean elfcore_read_notes PARAMS ((bfd *, bfd_vma, bfd_vma));
59
60/* Swap version information in and out.  The version information is
61   currently size independent.  If that ever changes, this code will
62   need to move into elfcode.h.  */
63
64/* Swap in a Verdef structure.  */
65
66void
67_bfd_elf_swap_verdef_in (abfd, src, dst)
68     bfd *abfd;
69     const Elf_External_Verdef *src;
70     Elf_Internal_Verdef *dst;
71{
72  dst->vd_version = bfd_h_get_16 (abfd, src->vd_version);
73  dst->vd_flags   = bfd_h_get_16 (abfd, src->vd_flags);
74  dst->vd_ndx     = bfd_h_get_16 (abfd, src->vd_ndx);
75  dst->vd_cnt     = bfd_h_get_16 (abfd, src->vd_cnt);
76  dst->vd_hash    = bfd_h_get_32 (abfd, src->vd_hash);
77  dst->vd_aux     = bfd_h_get_32 (abfd, src->vd_aux);
78  dst->vd_next    = bfd_h_get_32 (abfd, src->vd_next);
79}
80
81/* Swap out a Verdef structure.  */
82
83void
84_bfd_elf_swap_verdef_out (abfd, src, dst)
85     bfd *abfd;
86     const Elf_Internal_Verdef *src;
87     Elf_External_Verdef *dst;
88{
89  bfd_h_put_16 (abfd, src->vd_version, dst->vd_version);
90  bfd_h_put_16 (abfd, src->vd_flags, dst->vd_flags);
91  bfd_h_put_16 (abfd, src->vd_ndx, dst->vd_ndx);
92  bfd_h_put_16 (abfd, src->vd_cnt, dst->vd_cnt);
93  bfd_h_put_32 (abfd, src->vd_hash, dst->vd_hash);
94  bfd_h_put_32 (abfd, src->vd_aux, dst->vd_aux);
95  bfd_h_put_32 (abfd, src->vd_next, dst->vd_next);
96}
97
98/* Swap in a Verdaux structure.  */
99
100void
101_bfd_elf_swap_verdaux_in (abfd, src, dst)
102     bfd *abfd;
103     const Elf_External_Verdaux *src;
104     Elf_Internal_Verdaux *dst;
105{
106  dst->vda_name = bfd_h_get_32 (abfd, src->vda_name);
107  dst->vda_next = bfd_h_get_32 (abfd, src->vda_next);
108}
109
110/* Swap out a Verdaux structure.  */
111
112void
113_bfd_elf_swap_verdaux_out (abfd, src, dst)
114     bfd *abfd;
115     const Elf_Internal_Verdaux *src;
116     Elf_External_Verdaux *dst;
117{
118  bfd_h_put_32 (abfd, src->vda_name, dst->vda_name);
119  bfd_h_put_32 (abfd, src->vda_next, dst->vda_next);
120}
121
122/* Swap in a Verneed structure.  */
123
124void
125_bfd_elf_swap_verneed_in (abfd, src, dst)
126     bfd *abfd;
127     const Elf_External_Verneed *src;
128     Elf_Internal_Verneed *dst;
129{
130  dst->vn_version = bfd_h_get_16 (abfd, src->vn_version);
131  dst->vn_cnt     = bfd_h_get_16 (abfd, src->vn_cnt);
132  dst->vn_file    = bfd_h_get_32 (abfd, src->vn_file);
133  dst->vn_aux     = bfd_h_get_32 (abfd, src->vn_aux);
134  dst->vn_next    = bfd_h_get_32 (abfd, src->vn_next);
135}
136
137/* Swap out a Verneed structure.  */
138
139void
140_bfd_elf_swap_verneed_out (abfd, src, dst)
141     bfd *abfd;
142     const Elf_Internal_Verneed *src;
143     Elf_External_Verneed *dst;
144{
145  bfd_h_put_16 (abfd, src->vn_version, dst->vn_version);
146  bfd_h_put_16 (abfd, src->vn_cnt, dst->vn_cnt);
147  bfd_h_put_32 (abfd, src->vn_file, dst->vn_file);
148  bfd_h_put_32 (abfd, src->vn_aux, dst->vn_aux);
149  bfd_h_put_32 (abfd, src->vn_next, dst->vn_next);
150}
151
152/* Swap in a Vernaux structure.  */
153
154void
155_bfd_elf_swap_vernaux_in (abfd, src, dst)
156     bfd *abfd;
157     const Elf_External_Vernaux *src;
158     Elf_Internal_Vernaux *dst;
159{
160  dst->vna_hash  = bfd_h_get_32 (abfd, src->vna_hash);
161  dst->vna_flags = bfd_h_get_16 (abfd, src->vna_flags);
162  dst->vna_other = bfd_h_get_16 (abfd, src->vna_other);
163  dst->vna_name  = bfd_h_get_32 (abfd, src->vna_name);
164  dst->vna_next  = bfd_h_get_32 (abfd, src->vna_next);
165}
166
167/* Swap out a Vernaux structure.  */
168
169void
170_bfd_elf_swap_vernaux_out (abfd, src, dst)
171     bfd *abfd;
172     const Elf_Internal_Vernaux *src;
173     Elf_External_Vernaux *dst;
174{
175  bfd_h_put_32 (abfd, src->vna_hash, dst->vna_hash);
176  bfd_h_put_16 (abfd, src->vna_flags, dst->vna_flags);
177  bfd_h_put_16 (abfd, src->vna_other, dst->vna_other);
178  bfd_h_put_32 (abfd, src->vna_name, dst->vna_name);
179  bfd_h_put_32 (abfd, src->vna_next, dst->vna_next);
180}
181
182/* Swap in a Versym structure.  */
183
184void
185_bfd_elf_swap_versym_in (abfd, src, dst)
186     bfd *abfd;
187     const Elf_External_Versym *src;
188     Elf_Internal_Versym *dst;
189{
190  dst->vs_vers = bfd_h_get_16 (abfd, src->vs_vers);
191}
192
193/* Swap out a Versym structure.  */
194
195void
196_bfd_elf_swap_versym_out (abfd, src, dst)
197     bfd *abfd;
198     const Elf_Internal_Versym *src;
199     Elf_External_Versym *dst;
200{
201  bfd_h_put_16 (abfd, src->vs_vers, dst->vs_vers);
202}
203
204/* Standard ELF hash function.  Do not change this function; you will
205   cause invalid hash tables to be generated.  */
206
207unsigned long
208bfd_elf_hash (namearg)
209     const char *namearg;
210{
211  const unsigned char *name = (const unsigned char *) namearg;
212  unsigned long h = 0;
213  unsigned long g;
214  int ch;
215
216  while ((ch = *name++) != '\0')
217    {
218      h = (h << 4) + ch;
219      if ((g = (h & 0xf0000000)) != 0)
220	{
221	  h ^= g >> 24;
222	  /* The ELF ABI says `h &= ~g', but this is equivalent in
223	     this case and on some machines one insn instead of two.  */
224	  h ^= g;
225	}
226    }
227  return h;
228}
229
230/* Read a specified number of bytes at a specified offset in an ELF
231   file, into a newly allocated buffer, and return a pointer to the
232   buffer. */
233
234static char *
235elf_read (abfd, offset, size)
236     bfd * abfd;
237     long offset;
238     unsigned int size;
239{
240  char *buf;
241
242  if ((buf = bfd_alloc (abfd, size)) == NULL)
243    return NULL;
244  if (bfd_seek (abfd, offset, SEEK_SET) == -1)
245    return NULL;
246  if (bfd_read ((PTR) buf, size, 1, abfd) != size)
247    {
248      if (bfd_get_error () != bfd_error_system_call)
249	bfd_set_error (bfd_error_file_truncated);
250      return NULL;
251    }
252  return buf;
253}
254
255boolean
256bfd_elf_mkobject (abfd)
257     bfd * abfd;
258{
259  /* this just does initialization */
260  /* coff_mkobject zalloc's space for tdata.coff_obj_data ... */
261  elf_tdata (abfd) = (struct elf_obj_tdata *)
262    bfd_zalloc (abfd, sizeof (struct elf_obj_tdata));
263  if (elf_tdata (abfd) == 0)
264    return false;
265  /* since everything is done at close time, do we need any
266     initialization? */
267
268  return true;
269}
270
271boolean
272bfd_elf_mkcorefile (abfd)
273     bfd * abfd;
274{
275  /* I think this can be done just like an object file. */
276  return bfd_elf_mkobject (abfd);
277}
278
279char *
280bfd_elf_get_str_section (abfd, shindex)
281     bfd * abfd;
282     unsigned int shindex;
283{
284  Elf_Internal_Shdr **i_shdrp;
285  char *shstrtab = NULL;
286  unsigned int offset;
287  unsigned int shstrtabsize;
288
289  i_shdrp = elf_elfsections (abfd);
290  if (i_shdrp == 0 || i_shdrp[shindex] == 0)
291    return 0;
292
293  shstrtab = (char *) i_shdrp[shindex]->contents;
294  if (shstrtab == NULL)
295    {
296      /* No cached one, attempt to read, and cache what we read. */
297      offset = i_shdrp[shindex]->sh_offset;
298      shstrtabsize = i_shdrp[shindex]->sh_size;
299      shstrtab = elf_read (abfd, offset, shstrtabsize);
300      i_shdrp[shindex]->contents = (PTR) shstrtab;
301    }
302  return shstrtab;
303}
304
305char *
306bfd_elf_string_from_elf_section (abfd, shindex, strindex)
307     bfd * abfd;
308     unsigned int shindex;
309     unsigned int strindex;
310{
311  Elf_Internal_Shdr *hdr;
312
313  if (strindex == 0)
314    return "";
315
316  hdr = elf_elfsections (abfd)[shindex];
317
318  if (hdr->contents == NULL
319      && bfd_elf_get_str_section (abfd, shindex) == NULL)
320    return NULL;
321
322  if (strindex >= hdr->sh_size)
323    {
324      (*_bfd_error_handler)
325	(_("%s: invalid string offset %u >= %lu for section `%s'"),
326	 bfd_get_filename (abfd), strindex, (unsigned long) hdr->sh_size,
327	 ((shindex == elf_elfheader(abfd)->e_shstrndx
328	   && strindex == hdr->sh_name)
329	  ? ".shstrtab"
330	  : elf_string_from_elf_strtab (abfd, hdr->sh_name)));
331      return "";
332    }
333
334  return ((char *) hdr->contents) + strindex;
335}
336
337/* Make a BFD section from an ELF section.  We store a pointer to the
338   BFD section in the bfd_section field of the header.  */
339
340boolean
341_bfd_elf_make_section_from_shdr (abfd, hdr, name)
342     bfd *abfd;
343     Elf_Internal_Shdr *hdr;
344     const char *name;
345{
346  asection *newsect;
347  flagword flags;
348
349  if (hdr->bfd_section != NULL)
350    {
351      BFD_ASSERT (strcmp (name,
352			  bfd_get_section_name (abfd, hdr->bfd_section)) == 0);
353      return true;
354    }
355
356  newsect = bfd_make_section_anyway (abfd, name);
357  if (newsect == NULL)
358    return false;
359
360  newsect->filepos = hdr->sh_offset;
361
362  if (! bfd_set_section_vma (abfd, newsect, hdr->sh_addr)
363      || ! bfd_set_section_size (abfd, newsect, hdr->sh_size)
364      || ! bfd_set_section_alignment (abfd, newsect,
365				      bfd_log2 (hdr->sh_addralign)))
366    return false;
367
368  flags = SEC_NO_FLAGS;
369  if (hdr->sh_type != SHT_NOBITS)
370    flags |= SEC_HAS_CONTENTS;
371  if ((hdr->sh_flags & SHF_ALLOC) != 0)
372    {
373      flags |= SEC_ALLOC;
374      if (hdr->sh_type != SHT_NOBITS)
375	flags |= SEC_LOAD;
376    }
377  if ((hdr->sh_flags & SHF_WRITE) == 0)
378    flags |= SEC_READONLY;
379  if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
380    flags |= SEC_CODE;
381  else if ((flags & SEC_LOAD) != 0)
382    flags |= SEC_DATA;
383
384  /* The debugging sections appear to be recognized only by name, not
385     any sort of flag.  */
386  if (strncmp (name, ".debug", sizeof ".debug" - 1) == 0
387      || strncmp (name, ".line", sizeof ".line" - 1) == 0
388      || strncmp (name, ".stab", sizeof ".stab" - 1) == 0)
389    flags |= SEC_DEBUGGING;
390
391  /* As a GNU extension, if the name begins with .gnu.linkonce, we
392     only link a single copy of the section.  This is used to support
393     g++.  g++ will emit each template expansion in its own section.
394     The symbols will be defined as weak, so that multiple definitions
395     are permitted.  The GNU linker extension is to actually discard
396     all but one of the sections.  */
397  if (strncmp (name, ".gnu.linkonce", sizeof ".gnu.linkonce" - 1) == 0)
398    flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
399
400  if (! bfd_set_section_flags (abfd, newsect, flags))
401    return false;
402
403  if ((flags & SEC_ALLOC) != 0)
404    {
405      Elf_Internal_Phdr *phdr;
406      unsigned int i;
407
408      /* Look through the phdrs to see if we need to adjust the lma.
409         If all the p_paddr fields are zero, we ignore them, since
410         some ELF linkers produce such output.  */
411      phdr = elf_tdata (abfd)->phdr;
412      for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
413	{
414	  if (phdr->p_paddr != 0)
415	    break;
416	}
417      if (i < elf_elfheader (abfd)->e_phnum)
418	{
419	  phdr = elf_tdata (abfd)->phdr;
420	  for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
421	    {
422	      if (phdr->p_type == PT_LOAD
423		  && phdr->p_vaddr != phdr->p_paddr
424		  && phdr->p_vaddr <= hdr->sh_addr
425		  && (phdr->p_vaddr + phdr->p_memsz
426		      >= hdr->sh_addr + hdr->sh_size)
427		  && ((flags & SEC_LOAD) == 0
428		      || (phdr->p_offset <= (bfd_vma) hdr->sh_offset
429			  && (phdr->p_offset + phdr->p_filesz
430			      >= hdr->sh_offset + hdr->sh_size))))
431		{
432		  newsect->lma += phdr->p_paddr - phdr->p_vaddr;
433		  break;
434		}
435	    }
436	}
437    }
438
439  hdr->bfd_section = newsect;
440  elf_section_data (newsect)->this_hdr = *hdr;
441
442  return true;
443}
444
445/*
446INTERNAL_FUNCTION
447	bfd_elf_find_section
448
449SYNOPSIS
450	struct elf_internal_shdr *bfd_elf_find_section (bfd *abfd, char *name);
451
452DESCRIPTION
453	Helper functions for GDB to locate the string tables.
454	Since BFD hides string tables from callers, GDB needs to use an
455	internal hook to find them.  Sun's .stabstr, in particular,
456	isn't even pointed to by the .stab section, so ordinary
457	mechanisms wouldn't work to find it, even if we had some.
458*/
459
460struct elf_internal_shdr *
461bfd_elf_find_section (abfd, name)
462     bfd * abfd;
463     char *name;
464{
465  Elf_Internal_Shdr **i_shdrp;
466  char *shstrtab;
467  unsigned int max;
468  unsigned int i;
469
470  i_shdrp = elf_elfsections (abfd);
471  if (i_shdrp != NULL)
472    {
473      shstrtab = bfd_elf_get_str_section
474	(abfd, elf_elfheader (abfd)->e_shstrndx);
475      if (shstrtab != NULL)
476	{
477	  max = elf_elfheader (abfd)->e_shnum;
478	  for (i = 1; i < max; i++)
479	    if (!strcmp (&shstrtab[i_shdrp[i]->sh_name], name))
480	      return i_shdrp[i];
481	}
482    }
483  return 0;
484}
485
486const char *const bfd_elf_section_type_names[] = {
487  "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB",
488  "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE",
489  "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM",
490};
491
492/* ELF relocs are against symbols.  If we are producing relocateable
493   output, and the reloc is against an external symbol, and nothing
494   has given us any additional addend, the resulting reloc will also
495   be against the same symbol.  In such a case, we don't want to
496   change anything about the way the reloc is handled, since it will
497   all be done at final link time.  Rather than put special case code
498   into bfd_perform_relocation, all the reloc types use this howto
499   function.  It just short circuits the reloc if producing
500   relocateable output against an external symbol.  */
501
502/*ARGSUSED*/
503bfd_reloc_status_type
504bfd_elf_generic_reloc (abfd,
505		       reloc_entry,
506		       symbol,
507		       data,
508		       input_section,
509		       output_bfd,
510		       error_message)
511     bfd *abfd ATTRIBUTE_UNUSED;
512     arelent *reloc_entry;
513     asymbol *symbol;
514     PTR data ATTRIBUTE_UNUSED;
515     asection *input_section;
516     bfd *output_bfd;
517     char **error_message ATTRIBUTE_UNUSED;
518{
519  if (output_bfd != (bfd *) NULL
520      && (symbol->flags & BSF_SECTION_SYM) == 0
521      && (! reloc_entry->howto->partial_inplace
522	  || reloc_entry->addend == 0))
523    {
524      reloc_entry->address += input_section->output_offset;
525      return bfd_reloc_ok;
526    }
527
528  return bfd_reloc_continue;
529}
530
531/* Print out the program headers.  */
532
533boolean
534_bfd_elf_print_private_bfd_data (abfd, farg)
535     bfd *abfd;
536     PTR farg;
537{
538  FILE *f = (FILE *) farg;
539  Elf_Internal_Phdr *p;
540  asection *s;
541  bfd_byte *dynbuf = NULL;
542
543  p = elf_tdata (abfd)->phdr;
544  if (p != NULL)
545    {
546      unsigned int i, c;
547
548      fprintf (f, _("\nProgram Header:\n"));
549      c = elf_elfheader (abfd)->e_phnum;
550      for (i = 0; i < c; i++, p++)
551	{
552	  const char *s;
553	  char buf[20];
554
555	  switch (p->p_type)
556	    {
557	    case PT_NULL: s = "NULL"; break;
558	    case PT_LOAD: s = "LOAD"; break;
559	    case PT_DYNAMIC: s = "DYNAMIC"; break;
560	    case PT_INTERP: s = "INTERP"; break;
561	    case PT_NOTE: s = "NOTE"; break;
562	    case PT_SHLIB: s = "SHLIB"; break;
563	    case PT_PHDR: s = "PHDR"; break;
564	    default: sprintf (buf, "0x%lx", p->p_type); s = buf; break;
565	    }
566	  fprintf (f, "%8s off    0x", s);
567	  fprintf_vma (f, p->p_offset);
568	  fprintf (f, " vaddr 0x");
569	  fprintf_vma (f, p->p_vaddr);
570	  fprintf (f, " paddr 0x");
571	  fprintf_vma (f, p->p_paddr);
572	  fprintf (f, " align 2**%u\n", bfd_log2 (p->p_align));
573	  fprintf (f, "         filesz 0x");
574	  fprintf_vma (f, p->p_filesz);
575	  fprintf (f, " memsz 0x");
576	  fprintf_vma (f, p->p_memsz);
577	  fprintf (f, " flags %c%c%c",
578		   (p->p_flags & PF_R) != 0 ? 'r' : '-',
579		   (p->p_flags & PF_W) != 0 ? 'w' : '-',
580		   (p->p_flags & PF_X) != 0 ? 'x' : '-');
581	  if ((p->p_flags &~ (PF_R | PF_W | PF_X)) != 0)
582	    fprintf (f, " %lx", p->p_flags &~ (PF_R | PF_W | PF_X));
583	  fprintf (f, "\n");
584	}
585    }
586
587  s = bfd_get_section_by_name (abfd, ".dynamic");
588  if (s != NULL)
589    {
590      int elfsec;
591      unsigned long link;
592      bfd_byte *extdyn, *extdynend;
593      size_t extdynsize;
594      void (*swap_dyn_in) PARAMS ((bfd *, const PTR, Elf_Internal_Dyn *));
595
596      fprintf (f, _("\nDynamic Section:\n"));
597
598      dynbuf = (bfd_byte *) bfd_malloc (s->_raw_size);
599      if (dynbuf == NULL)
600	goto error_return;
601      if (! bfd_get_section_contents (abfd, s, (PTR) dynbuf, (file_ptr) 0,
602				      s->_raw_size))
603	goto error_return;
604
605      elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
606      if (elfsec == -1)
607	goto error_return;
608      link = elf_elfsections (abfd)[elfsec]->sh_link;
609
610      extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
611      swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
612
613      extdyn = dynbuf;
614      extdynend = extdyn + s->_raw_size;
615      for (; extdyn < extdynend; extdyn += extdynsize)
616	{
617	  Elf_Internal_Dyn dyn;
618	  const char *name;
619	  char ab[20];
620	  boolean stringp;
621
622	  (*swap_dyn_in) (abfd, (PTR) extdyn, &dyn);
623
624	  if (dyn.d_tag == DT_NULL)
625	    break;
626
627	  stringp = false;
628	  switch (dyn.d_tag)
629	    {
630	    default:
631	      sprintf (ab, "0x%lx", (unsigned long) dyn.d_tag);
632	      name = ab;
633	      break;
634
635	    case DT_NEEDED: name = "NEEDED"; stringp = true; break;
636	    case DT_PLTRELSZ: name = "PLTRELSZ"; break;
637	    case DT_PLTGOT: name = "PLTGOT"; break;
638	    case DT_HASH: name = "HASH"; break;
639	    case DT_STRTAB: name = "STRTAB"; break;
640	    case DT_SYMTAB: name = "SYMTAB"; break;
641	    case DT_RELA: name = "RELA"; break;
642	    case DT_RELASZ: name = "RELASZ"; break;
643	    case DT_RELAENT: name = "RELAENT"; break;
644	    case DT_STRSZ: name = "STRSZ"; break;
645	    case DT_SYMENT: name = "SYMENT"; break;
646	    case DT_INIT: name = "INIT"; break;
647	    case DT_FINI: name = "FINI"; break;
648	    case DT_SONAME: name = "SONAME"; stringp = true; break;
649	    case DT_RPATH: name = "RPATH"; stringp = true; break;
650	    case DT_SYMBOLIC: name = "SYMBOLIC"; break;
651	    case DT_REL: name = "REL"; break;
652	    case DT_RELSZ: name = "RELSZ"; break;
653	    case DT_RELENT: name = "RELENT"; break;
654	    case DT_PLTREL: name = "PLTREL"; break;
655	    case DT_DEBUG: name = "DEBUG"; break;
656	    case DT_TEXTREL: name = "TEXTREL"; break;
657	    case DT_JMPREL: name = "JMPREL"; break;
658	    case DT_AUXILIARY: name = "AUXILIARY"; stringp = true; break;
659	    case DT_FILTER: name = "FILTER"; stringp = true; break;
660	    case DT_VERSYM: name = "VERSYM"; break;
661	    case DT_VERDEF: name = "VERDEF"; break;
662	    case DT_VERDEFNUM: name = "VERDEFNUM"; break;
663	    case DT_VERNEED: name = "VERNEED"; break;
664	    case DT_VERNEEDNUM: name = "VERNEEDNUM"; break;
665	    }
666
667	  fprintf (f, "  %-11s ", name);
668	  if (! stringp)
669	    fprintf (f, "0x%lx", (unsigned long) dyn.d_un.d_val);
670	  else
671	    {
672	      const char *string;
673
674	      string = bfd_elf_string_from_elf_section (abfd, link,
675							dyn.d_un.d_val);
676	      if (string == NULL)
677		goto error_return;
678	      fprintf (f, "%s", string);
679	    }
680	  fprintf (f, "\n");
681	}
682
683      free (dynbuf);
684      dynbuf = NULL;
685    }
686
687  if ((elf_dynverdef (abfd) != 0 && elf_tdata (abfd)->verdef == NULL)
688      || (elf_dynverref (abfd) != 0 && elf_tdata (abfd)->verref == NULL))
689    {
690      if (! _bfd_elf_slurp_version_tables (abfd))
691	return false;
692    }
693
694  if (elf_dynverdef (abfd) != 0)
695    {
696      Elf_Internal_Verdef *t;
697
698      fprintf (f, _("\nVersion definitions:\n"));
699      for (t = elf_tdata (abfd)->verdef; t != NULL; t = t->vd_nextdef)
700	{
701	  fprintf (f, "%d 0x%2.2x 0x%8.8lx %s\n", t->vd_ndx,
702		   t->vd_flags, t->vd_hash, t->vd_nodename);
703	  if (t->vd_auxptr->vda_nextptr != NULL)
704	    {
705	      Elf_Internal_Verdaux *a;
706
707	      fprintf (f, "\t");
708	      for (a = t->vd_auxptr->vda_nextptr;
709		   a != NULL;
710		   a = a->vda_nextptr)
711		fprintf (f, "%s ", a->vda_nodename);
712	      fprintf (f, "\n");
713	    }
714	}
715    }
716
717  if (elf_dynverref (abfd) != 0)
718    {
719      Elf_Internal_Verneed *t;
720
721      fprintf (f, _("\nVersion References:\n"));
722      for (t = elf_tdata (abfd)->verref; t != NULL; t = t->vn_nextref)
723	{
724	  Elf_Internal_Vernaux *a;
725
726	  fprintf (f, _("  required from %s:\n"), t->vn_filename);
727	  for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
728	    fprintf (f, "    0x%8.8lx 0x%2.2x %2.2d %s\n", a->vna_hash,
729		     a->vna_flags, a->vna_other, a->vna_nodename);
730	}
731    }
732
733  return true;
734
735 error_return:
736  if (dynbuf != NULL)
737    free (dynbuf);
738  return false;
739}
740
741/* Display ELF-specific fields of a symbol.  */
742
743void
744bfd_elf_print_symbol (abfd, filep, symbol, how)
745     bfd *abfd;
746     PTR filep;
747     asymbol *symbol;
748     bfd_print_symbol_type how;
749{
750  FILE *file = (FILE *) filep;
751  switch (how)
752    {
753    case bfd_print_symbol_name:
754      fprintf (file, "%s", symbol->name);
755      break;
756    case bfd_print_symbol_more:
757      fprintf (file, "elf ");
758      fprintf_vma (file, symbol->value);
759      fprintf (file, " %lx", (long) symbol->flags);
760      break;
761    case bfd_print_symbol_all:
762      {
763	CONST char *section_name;
764	CONST char *name = NULL;
765	struct elf_backend_data *bed;
766	unsigned char st_other;
767
768	section_name = symbol->section ? symbol->section->name : "(*none*)";
769
770	bed = get_elf_backend_data (abfd);
771	if (bed->elf_backend_print_symbol_all)
772	    name = (*bed->elf_backend_print_symbol_all) (abfd, filep, symbol);
773
774	if (name == NULL)
775	  {
776	    name = symbol->name;
777	    bfd_print_symbol_vandf ((PTR) file, symbol);
778	  }
779
780	fprintf (file, " %s\t", section_name);
781	/* Print the "other" value for a symbol.  For common symbols,
782	   we've already printed the size; now print the alignment.
783	   For other symbols, we have no specified alignment, and
784	   we've printed the address; now print the size.  */
785	fprintf_vma (file,
786		     (bfd_is_com_section (symbol->section)
787		      ? ((elf_symbol_type *) symbol)->internal_elf_sym.st_value
788		      : ((elf_symbol_type *) symbol)->internal_elf_sym.st_size));
789
790	/* If we have version information, print it.  */
791	if (elf_tdata (abfd)->dynversym_section != 0
792	    && (elf_tdata (abfd)->dynverdef_section != 0
793		|| elf_tdata (abfd)->dynverref_section != 0))
794	  {
795	    unsigned int vernum;
796	    const char *version_string;
797
798	    vernum = ((elf_symbol_type *) symbol)->version & VERSYM_VERSION;
799
800	    if (vernum == 0)
801	      version_string = "";
802	    else if (vernum == 1)
803	      version_string = "Base";
804	    else if (vernum <= elf_tdata (abfd)->cverdefs)
805	      version_string =
806		elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
807	    else
808	      {
809		Elf_Internal_Verneed *t;
810
811		version_string = "";
812		for (t = elf_tdata (abfd)->verref;
813		     t != NULL;
814		     t = t->vn_nextref)
815		  {
816		    Elf_Internal_Vernaux *a;
817
818		    for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
819		      {
820			if (a->vna_other == vernum)
821			  {
822			    version_string = a->vna_nodename;
823			    break;
824			  }
825		      }
826		  }
827	      }
828
829	    if ((((elf_symbol_type *) symbol)->version & VERSYM_HIDDEN) == 0)
830	      fprintf (file, "  %-11s", version_string);
831	    else
832	      {
833		int i;
834
835		fprintf (file, " (%s)", version_string);
836		for (i = 10 - strlen (version_string); i > 0; --i)
837		  putc (' ', file);
838	      }
839	  }
840
841	/* If the st_other field is not zero, print it.  */
842	st_other = ((elf_symbol_type *) symbol)->internal_elf_sym.st_other;
843
844	switch (st_other)
845	  {
846	  case 0: break;
847	  case STV_INTERNAL:  fprintf (file, " .internal");  break;
848	  case STV_HIDDEN:    fprintf (file, " .hidden");    break;
849	  case STV_PROTECTED: fprintf (file, " .protected"); break;
850	  default:
851	    /* Some other non-defined flags are also present, so print
852	       everything hex.  */
853	    fprintf (file, " 0x%02x", (unsigned int) st_other);
854	  }
855
856	fprintf (file, " %s", name);
857      }
858      break;
859    }
860}
861
862/* Create an entry in an ELF linker hash table.  */
863
864struct bfd_hash_entry *
865_bfd_elf_link_hash_newfunc (entry, table, string)
866     struct bfd_hash_entry *entry;
867     struct bfd_hash_table *table;
868     const char *string;
869{
870  struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
871
872  /* Allocate the structure if it has not already been allocated by a
873     subclass.  */
874  if (ret == (struct elf_link_hash_entry *) NULL)
875    ret = ((struct elf_link_hash_entry *)
876	   bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry)));
877  if (ret == (struct elf_link_hash_entry *) NULL)
878    return (struct bfd_hash_entry *) ret;
879
880  /* Call the allocation method of the superclass.  */
881  ret = ((struct elf_link_hash_entry *)
882	 _bfd_link_hash_newfunc ((struct bfd_hash_entry *) ret,
883				 table, string));
884  if (ret != (struct elf_link_hash_entry *) NULL)
885    {
886      /* Set local fields.  */
887      ret->indx = -1;
888      ret->size = 0;
889      ret->dynindx = -1;
890      ret->dynstr_index = 0;
891      ret->weakdef = NULL;
892      ret->got.offset = (bfd_vma) -1;
893      ret->plt.offset = (bfd_vma) -1;
894      ret->linker_section_pointer = (elf_linker_section_pointers_t *)0;
895      ret->verinfo.verdef = NULL;
896      ret->vtable_entries_used = NULL;
897      ret->vtable_entries_size = 0;
898      ret->vtable_parent = NULL;
899      ret->type = STT_NOTYPE;
900      ret->other = 0;
901      /* Assume that we have been called by a non-ELF symbol reader.
902         This flag is then reset by the code which reads an ELF input
903         file.  This ensures that a symbol created by a non-ELF symbol
904         reader will have the flag set correctly.  */
905      ret->elf_link_hash_flags = ELF_LINK_NON_ELF;
906    }
907
908  return (struct bfd_hash_entry *) ret;
909}
910
911/* Copy data from an indirect symbol to its direct symbol, hiding the
912   old indirect symbol.  */
913
914void
915_bfd_elf_link_hash_copy_indirect (dir, ind)
916     struct elf_link_hash_entry *dir, *ind;
917{
918  /* Copy down any references that we may have already seen to the
919     symbol which just became indirect.  */
920
921  dir->elf_link_hash_flags |=
922    (ind->elf_link_hash_flags
923     & (ELF_LINK_HASH_REF_DYNAMIC
924	| ELF_LINK_HASH_REF_REGULAR
925	| ELF_LINK_HASH_REF_REGULAR_NONWEAK
926	| ELF_LINK_NON_GOT_REF));
927
928  /* Copy over the global and procedure linkage table offset entries.
929     These may have been already set up by a check_relocs routine.  */
930  if (dir->got.offset == (bfd_vma) -1)
931    {
932      dir->got.offset = ind->got.offset;
933      ind->got.offset = (bfd_vma) -1;
934    }
935  BFD_ASSERT (ind->got.offset == (bfd_vma) -1);
936
937  if (dir->plt.offset == (bfd_vma) -1)
938    {
939      dir->plt.offset = ind->plt.offset;
940      ind->plt.offset = (bfd_vma) -1;
941    }
942  BFD_ASSERT (ind->plt.offset == (bfd_vma) -1);
943
944  if (dir->dynindx == -1)
945    {
946      dir->dynindx = ind->dynindx;
947      dir->dynstr_index = ind->dynstr_index;
948      ind->dynindx = -1;
949      ind->dynstr_index = 0;
950    }
951  BFD_ASSERT (ind->dynindx == -1);
952}
953
954void
955_bfd_elf_link_hash_hide_symbol(h)
956     struct elf_link_hash_entry *h;
957{
958  h->elf_link_hash_flags &= ~ELF_LINK_HASH_NEEDS_PLT;
959  h->dynindx = -1;
960  h->plt.offset = (bfd_vma) -1;
961}
962
963/* Initialize an ELF linker hash table.  */
964
965boolean
966_bfd_elf_link_hash_table_init (table, abfd, newfunc)
967     struct elf_link_hash_table *table;
968     bfd *abfd;
969     struct bfd_hash_entry *(*newfunc) PARAMS ((struct bfd_hash_entry *,
970						struct bfd_hash_table *,
971						const char *));
972{
973  table->dynamic_sections_created = false;
974  table->dynobj = NULL;
975  /* The first dynamic symbol is a dummy.  */
976  table->dynsymcount = 1;
977  table->dynstr = NULL;
978  table->bucketcount = 0;
979  table->needed = NULL;
980  table->hgot = NULL;
981  table->stab_info = NULL;
982  table->dynlocal = NULL;
983  return _bfd_link_hash_table_init (&table->root, abfd, newfunc);
984}
985
986/* Create an ELF linker hash table.  */
987
988struct bfd_link_hash_table *
989_bfd_elf_link_hash_table_create (abfd)
990     bfd *abfd;
991{
992  struct elf_link_hash_table *ret;
993
994  ret = ((struct elf_link_hash_table *)
995	 bfd_alloc (abfd, sizeof (struct elf_link_hash_table)));
996  if (ret == (struct elf_link_hash_table *) NULL)
997    return NULL;
998
999  if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc))
1000    {
1001      bfd_release (abfd, ret);
1002      return NULL;
1003    }
1004
1005  return &ret->root;
1006}
1007
1008/* This is a hook for the ELF emulation code in the generic linker to
1009   tell the backend linker what file name to use for the DT_NEEDED
1010   entry for a dynamic object.  The generic linker passes name as an
1011   empty string to indicate that no DT_NEEDED entry should be made.  */
1012
1013void
1014bfd_elf_set_dt_needed_name (abfd, name)
1015     bfd *abfd;
1016     const char *name;
1017{
1018  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1019      && bfd_get_format (abfd) == bfd_object)
1020    elf_dt_name (abfd) = name;
1021}
1022
1023/* Get the list of DT_NEEDED entries for a link.  This is a hook for
1024   the linker ELF emulation code.  */
1025
1026struct bfd_link_needed_list *
1027bfd_elf_get_needed_list (abfd, info)
1028     bfd *abfd ATTRIBUTE_UNUSED;
1029     struct bfd_link_info *info;
1030{
1031  if (info->hash->creator->flavour != bfd_target_elf_flavour)
1032    return NULL;
1033  return elf_hash_table (info)->needed;
1034}
1035
1036/* Get the name actually used for a dynamic object for a link.  This
1037   is the SONAME entry if there is one.  Otherwise, it is the string
1038   passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
1039
1040const char *
1041bfd_elf_get_dt_soname (abfd)
1042     bfd *abfd;
1043{
1044  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1045      && bfd_get_format (abfd) == bfd_object)
1046    return elf_dt_name (abfd);
1047  return NULL;
1048}
1049
1050/* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
1051   the ELF linker emulation code.  */
1052
1053boolean
1054bfd_elf_get_bfd_needed_list (abfd, pneeded)
1055     bfd *abfd;
1056     struct bfd_link_needed_list **pneeded;
1057{
1058  asection *s;
1059  bfd_byte *dynbuf = NULL;
1060  int elfsec;
1061  unsigned long link;
1062  bfd_byte *extdyn, *extdynend;
1063  size_t extdynsize;
1064  void (*swap_dyn_in) PARAMS ((bfd *, const PTR, Elf_Internal_Dyn *));
1065
1066  *pneeded = NULL;
1067
1068  if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
1069      || bfd_get_format (abfd) != bfd_object)
1070    return true;
1071
1072  s = bfd_get_section_by_name (abfd, ".dynamic");
1073  if (s == NULL || s->_raw_size == 0)
1074    return true;
1075
1076  dynbuf = (bfd_byte *) bfd_malloc (s->_raw_size);
1077  if (dynbuf == NULL)
1078    goto error_return;
1079
1080  if (! bfd_get_section_contents (abfd, s, (PTR) dynbuf, (file_ptr) 0,
1081				  s->_raw_size))
1082    goto error_return;
1083
1084  elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
1085  if (elfsec == -1)
1086    goto error_return;
1087
1088  link = elf_elfsections (abfd)[elfsec]->sh_link;
1089
1090  extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
1091  swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
1092
1093  extdyn = dynbuf;
1094  extdynend = extdyn + s->_raw_size;
1095  for (; extdyn < extdynend; extdyn += extdynsize)
1096    {
1097      Elf_Internal_Dyn dyn;
1098
1099      (*swap_dyn_in) (abfd, (PTR) extdyn, &dyn);
1100
1101      if (dyn.d_tag == DT_NULL)
1102	break;
1103
1104      if (dyn.d_tag == DT_NEEDED)
1105	{
1106	  const char *string;
1107	  struct bfd_link_needed_list *l;
1108
1109	  string = bfd_elf_string_from_elf_section (abfd, link,
1110						    dyn.d_un.d_val);
1111	  if (string == NULL)
1112	    goto error_return;
1113
1114	  l = (struct bfd_link_needed_list *) bfd_alloc (abfd, sizeof *l);
1115	  if (l == NULL)
1116	    goto error_return;
1117
1118	  l->by = abfd;
1119	  l->name = string;
1120	  l->next = *pneeded;
1121	  *pneeded = l;
1122	}
1123    }
1124
1125  free (dynbuf);
1126
1127  return true;
1128
1129 error_return:
1130  if (dynbuf != NULL)
1131    free (dynbuf);
1132  return false;
1133}
1134
1135/* Allocate an ELF string table--force the first byte to be zero.  */
1136
1137struct bfd_strtab_hash *
1138_bfd_elf_stringtab_init ()
1139{
1140  struct bfd_strtab_hash *ret;
1141
1142  ret = _bfd_stringtab_init ();
1143  if (ret != NULL)
1144    {
1145      bfd_size_type loc;
1146
1147      loc = _bfd_stringtab_add (ret, "", true, false);
1148      BFD_ASSERT (loc == 0 || loc == (bfd_size_type) -1);
1149      if (loc == (bfd_size_type) -1)
1150	{
1151	  _bfd_stringtab_free (ret);
1152	  ret = NULL;
1153	}
1154    }
1155  return ret;
1156}
1157
1158/* ELF .o/exec file reading */
1159
1160/* Create a new bfd section from an ELF section header. */
1161
1162boolean
1163bfd_section_from_shdr (abfd, shindex)
1164     bfd *abfd;
1165     unsigned int shindex;
1166{
1167  Elf_Internal_Shdr *hdr = elf_elfsections (abfd)[shindex];
1168  Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
1169  struct elf_backend_data *bed = get_elf_backend_data (abfd);
1170  char *name;
1171
1172  name = elf_string_from_elf_strtab (abfd, hdr->sh_name);
1173
1174  switch (hdr->sh_type)
1175    {
1176    case SHT_NULL:
1177      /* Inactive section. Throw it away.  */
1178      return true;
1179
1180    case SHT_PROGBITS:	/* Normal section with contents.  */
1181    case SHT_DYNAMIC:	/* Dynamic linking information.  */
1182    case SHT_NOBITS:	/* .bss section.  */
1183    case SHT_HASH:	/* .hash section.  */
1184    case SHT_NOTE:	/* .note section.  */
1185      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1186
1187    case SHT_SYMTAB:		/* A symbol table */
1188      if (elf_onesymtab (abfd) == shindex)
1189	return true;
1190
1191      BFD_ASSERT (hdr->sh_entsize == bed->s->sizeof_sym);
1192      BFD_ASSERT (elf_onesymtab (abfd) == 0);
1193      elf_onesymtab (abfd) = shindex;
1194      elf_tdata (abfd)->symtab_hdr = *hdr;
1195      elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->symtab_hdr;
1196      abfd->flags |= HAS_SYMS;
1197
1198      /* Sometimes a shared object will map in the symbol table.  If
1199         SHF_ALLOC is set, and this is a shared object, then we also
1200         treat this section as a BFD section.  We can not base the
1201         decision purely on SHF_ALLOC, because that flag is sometimes
1202         set in a relocateable object file, which would confuse the
1203         linker.  */
1204      if ((hdr->sh_flags & SHF_ALLOC) != 0
1205	  && (abfd->flags & DYNAMIC) != 0
1206	  && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name))
1207	return false;
1208
1209      return true;
1210
1211    case SHT_DYNSYM:		/* A dynamic symbol table */
1212      if (elf_dynsymtab (abfd) == shindex)
1213	return true;
1214
1215      BFD_ASSERT (hdr->sh_entsize == bed->s->sizeof_sym);
1216      BFD_ASSERT (elf_dynsymtab (abfd) == 0);
1217      elf_dynsymtab (abfd) = shindex;
1218      elf_tdata (abfd)->dynsymtab_hdr = *hdr;
1219      elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->dynsymtab_hdr;
1220      abfd->flags |= HAS_SYMS;
1221
1222      /* Besides being a symbol table, we also treat this as a regular
1223	 section, so that objcopy can handle it.  */
1224      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1225
1226    case SHT_STRTAB:		/* A string table */
1227      if (hdr->bfd_section != NULL)
1228	return true;
1229      if (ehdr->e_shstrndx == shindex)
1230	{
1231	  elf_tdata (abfd)->shstrtab_hdr = *hdr;
1232	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
1233	  return true;
1234	}
1235      {
1236	unsigned int i;
1237
1238	for (i = 1; i < ehdr->e_shnum; i++)
1239	  {
1240	    Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
1241	    if (hdr2->sh_link == shindex)
1242	      {
1243		if (! bfd_section_from_shdr (abfd, i))
1244		  return false;
1245		if (elf_onesymtab (abfd) == i)
1246		  {
1247		    elf_tdata (abfd)->strtab_hdr = *hdr;
1248		    elf_elfsections (abfd)[shindex] =
1249		      &elf_tdata (abfd)->strtab_hdr;
1250		    return true;
1251		  }
1252		if (elf_dynsymtab (abfd) == i)
1253		  {
1254		    elf_tdata (abfd)->dynstrtab_hdr = *hdr;
1255		    elf_elfsections (abfd)[shindex] = hdr =
1256		      &elf_tdata (abfd)->dynstrtab_hdr;
1257		    /* We also treat this as a regular section, so
1258		       that objcopy can handle it.  */
1259		    break;
1260		  }
1261#if 0 /* Not handling other string tables specially right now.  */
1262		hdr2 = elf_elfsections (abfd)[i];	/* in case it moved */
1263		/* We have a strtab for some random other section.  */
1264		newsect = (asection *) hdr2->bfd_section;
1265		if (!newsect)
1266		  break;
1267		hdr->bfd_section = newsect;
1268		hdr2 = &elf_section_data (newsect)->str_hdr;
1269		*hdr2 = *hdr;
1270		elf_elfsections (abfd)[shindex] = hdr2;
1271#endif
1272	      }
1273	  }
1274      }
1275
1276      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1277
1278    case SHT_REL:
1279    case SHT_RELA:
1280      /* *These* do a lot of work -- but build no sections!  */
1281      {
1282	asection *target_sect;
1283	Elf_Internal_Shdr *hdr2;
1284
1285	/* Check for a bogus link to avoid crashing.  */
1286	if (hdr->sh_link >= ehdr->e_shnum)
1287	  {
1288	    ((*_bfd_error_handler)
1289	     (_("%s: invalid link %lu for reloc section %s (index %u)"),
1290	      bfd_get_filename (abfd), hdr->sh_link, name, shindex));
1291	    return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1292	  }
1293
1294	/* For some incomprehensible reason Oracle distributes
1295	   libraries for Solaris in which some of the objects have
1296	   bogus sh_link fields.  It would be nice if we could just
1297	   reject them, but, unfortunately, some people need to use
1298	   them.  We scan through the section headers; if we find only
1299	   one suitable symbol table, we clobber the sh_link to point
1300	   to it.  I hope this doesn't break anything.  */
1301	if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_SYMTAB
1302	    && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_DYNSYM)
1303	  {
1304	    int scan;
1305	    int found;
1306
1307	    found = 0;
1308	    for (scan = 1; scan < ehdr->e_shnum; scan++)
1309	      {
1310		if (elf_elfsections (abfd)[scan]->sh_type == SHT_SYMTAB
1311		    || elf_elfsections (abfd)[scan]->sh_type == SHT_DYNSYM)
1312		  {
1313		    if (found != 0)
1314		      {
1315			found = 0;
1316			break;
1317		      }
1318		    found = scan;
1319		  }
1320	      }
1321	    if (found != 0)
1322	      hdr->sh_link = found;
1323	  }
1324
1325	/* Get the symbol table.  */
1326	if (elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_SYMTAB
1327	    && ! bfd_section_from_shdr (abfd, hdr->sh_link))
1328	  return false;
1329
1330	/* If this reloc section does not use the main symbol table we
1331	   don't treat it as a reloc section.  BFD can't adequately
1332	   represent such a section, so at least for now, we don't
1333	   try.  We just present it as a normal section.  */
1334	if (hdr->sh_link != elf_onesymtab (abfd))
1335	  return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1336
1337	if (! bfd_section_from_shdr (abfd, hdr->sh_info))
1338	  return false;
1339	target_sect = bfd_section_from_elf_index (abfd, hdr->sh_info);
1340	if (target_sect == NULL)
1341	  return false;
1342
1343	if ((target_sect->flags & SEC_RELOC) == 0
1344	    || target_sect->reloc_count == 0)
1345	  hdr2 = &elf_section_data (target_sect)->rel_hdr;
1346	else
1347	  {
1348	    BFD_ASSERT (elf_section_data (target_sect)->rel_hdr2 == NULL);
1349	    hdr2 = (Elf_Internal_Shdr *) bfd_alloc (abfd, sizeof (*hdr2));
1350	    elf_section_data (target_sect)->rel_hdr2 = hdr2;
1351	  }
1352	*hdr2 = *hdr;
1353	elf_elfsections (abfd)[shindex] = hdr2;
1354	target_sect->reloc_count += hdr->sh_size / hdr->sh_entsize;
1355	target_sect->flags |= SEC_RELOC;
1356	target_sect->relocation = NULL;
1357	target_sect->rel_filepos = hdr->sh_offset;
1358	/* In the section to which the relocations apply, mark whether
1359	   its relocations are of the REL or RELA variety.  */
1360	if (hdr->sh_size != 0)
1361	  elf_section_data (target_sect)->use_rela_p
1362	    = (hdr->sh_type == SHT_RELA);
1363	abfd->flags |= HAS_RELOC;
1364	return true;
1365      }
1366      break;
1367
1368    case SHT_GNU_verdef:
1369      elf_dynverdef (abfd) = shindex;
1370      elf_tdata (abfd)->dynverdef_hdr = *hdr;
1371      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1372      break;
1373
1374    case SHT_GNU_versym:
1375      elf_dynversym (abfd) = shindex;
1376      elf_tdata (abfd)->dynversym_hdr = *hdr;
1377      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1378      break;
1379
1380    case SHT_GNU_verneed:
1381      elf_dynverref (abfd) = shindex;
1382      elf_tdata (abfd)->dynverref_hdr = *hdr;
1383      return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1384      break;
1385
1386    case SHT_SHLIB:
1387      return true;
1388
1389    default:
1390      /* Check for any processor-specific section types.  */
1391      {
1392	if (bed->elf_backend_section_from_shdr)
1393	  (*bed->elf_backend_section_from_shdr) (abfd, hdr, name);
1394      }
1395      break;
1396    }
1397
1398  return true;
1399}
1400
1401/* Given an ELF section number, retrieve the corresponding BFD
1402   section.  */
1403
1404asection *
1405bfd_section_from_elf_index (abfd, index)
1406     bfd *abfd;
1407     unsigned int index;
1408{
1409  BFD_ASSERT (index > 0 && index < SHN_LORESERVE);
1410  if (index >= elf_elfheader (abfd)->e_shnum)
1411    return NULL;
1412  return elf_elfsections (abfd)[index]->bfd_section;
1413}
1414
1415boolean
1416_bfd_elf_new_section_hook (abfd, sec)
1417     bfd *abfd;
1418     asection *sec;
1419{
1420  struct bfd_elf_section_data *sdata;
1421
1422  sdata = (struct bfd_elf_section_data *) bfd_zalloc (abfd, sizeof (*sdata));
1423  if (!sdata)
1424    return false;
1425  sec->used_by_bfd = (PTR) sdata;
1426
1427  /* Indicate whether or not this section should use RELA relocations.  */
1428  sdata->use_rela_p
1429    = get_elf_backend_data (abfd)->default_use_rela_p;
1430
1431  return true;
1432}
1433
1434/* Create a new bfd section from an ELF program header.
1435
1436   Since program segments have no names, we generate a synthetic name
1437   of the form segment<NUM>, where NUM is generally the index in the
1438   program header table.  For segments that are split (see below) we
1439   generate the names segment<NUM>a and segment<NUM>b.
1440
1441   Note that some program segments may have a file size that is different than
1442   (less than) the memory size.  All this means is that at execution the
1443   system must allocate the amount of memory specified by the memory size,
1444   but only initialize it with the first "file size" bytes read from the
1445   file.  This would occur for example, with program segments consisting
1446   of combined data+bss.
1447
1448   To handle the above situation, this routine generates TWO bfd sections
1449   for the single program segment.  The first has the length specified by
1450   the file size of the segment, and the second has the length specified
1451   by the difference between the two sizes.  In effect, the segment is split
1452   into it's initialized and uninitialized parts.
1453
1454 */
1455
1456boolean
1457_bfd_elf_make_section_from_phdr (abfd, hdr, index, typename)
1458     bfd *abfd;
1459     Elf_Internal_Phdr *hdr;
1460     int index;
1461     const char *typename;
1462{
1463  asection *newsect;
1464  char *name;
1465  char namebuf[64];
1466  int split;
1467
1468  split = ((hdr->p_memsz > 0)
1469	    && (hdr->p_filesz > 0)
1470	    && (hdr->p_memsz > hdr->p_filesz));
1471  sprintf (namebuf, "%s%d%s", typename, index, split ? "a" : "");
1472  name = bfd_alloc (abfd, strlen (namebuf) + 1);
1473  if (!name)
1474    return false;
1475  strcpy (name, namebuf);
1476  newsect = bfd_make_section (abfd, name);
1477  if (newsect == NULL)
1478    return false;
1479  newsect->vma = hdr->p_vaddr;
1480  newsect->lma = hdr->p_paddr;
1481  newsect->_raw_size = hdr->p_filesz;
1482  newsect->filepos = hdr->p_offset;
1483  newsect->flags |= SEC_HAS_CONTENTS;
1484  if (hdr->p_type == PT_LOAD)
1485    {
1486      newsect->flags |= SEC_ALLOC;
1487      newsect->flags |= SEC_LOAD;
1488      if (hdr->p_flags & PF_X)
1489	{
1490	  /* FIXME: all we known is that it has execute PERMISSION,
1491	     may be data. */
1492	  newsect->flags |= SEC_CODE;
1493	}
1494    }
1495  if (!(hdr->p_flags & PF_W))
1496    {
1497      newsect->flags |= SEC_READONLY;
1498    }
1499
1500  if (split)
1501    {
1502      sprintf (namebuf, "%s%db", typename, index);
1503      name = bfd_alloc (abfd, strlen (namebuf) + 1);
1504      if (!name)
1505	return false;
1506      strcpy (name, namebuf);
1507      newsect = bfd_make_section (abfd, name);
1508      if (newsect == NULL)
1509	return false;
1510      newsect->vma = hdr->p_vaddr + hdr->p_filesz;
1511      newsect->lma = hdr->p_paddr + hdr->p_filesz;
1512      newsect->_raw_size = hdr->p_memsz - hdr->p_filesz;
1513      if (hdr->p_type == PT_LOAD)
1514	{
1515	  newsect->flags |= SEC_ALLOC;
1516	  if (hdr->p_flags & PF_X)
1517	    newsect->flags |= SEC_CODE;
1518	}
1519      if (!(hdr->p_flags & PF_W))
1520	newsect->flags |= SEC_READONLY;
1521    }
1522
1523  return true;
1524}
1525
1526boolean
1527bfd_section_from_phdr (abfd, hdr, index)
1528     bfd *abfd;
1529     Elf_Internal_Phdr *hdr;
1530     int index;
1531{
1532  struct elf_backend_data *bed;
1533
1534  switch (hdr->p_type)
1535    {
1536    case PT_NULL:
1537      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "null");
1538
1539    case PT_LOAD:
1540      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "load");
1541
1542    case PT_DYNAMIC:
1543      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "dynamic");
1544
1545    case PT_INTERP:
1546      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "interp");
1547
1548    case PT_NOTE:
1549      if (! _bfd_elf_make_section_from_phdr (abfd, hdr, index, "note"))
1550	return false;
1551      if (! elfcore_read_notes (abfd, hdr->p_offset, hdr->p_filesz))
1552	return false;
1553      return true;
1554
1555    case PT_SHLIB:
1556      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "shlib");
1557
1558    case PT_PHDR:
1559      return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "phdr");
1560
1561    default:
1562      /* Check for any processor-specific program segment types.
1563         If no handler for them, default to making "segment" sections. */
1564      bed = get_elf_backend_data (abfd);
1565      if (bed->elf_backend_section_from_phdr)
1566	return (*bed->elf_backend_section_from_phdr) (abfd, hdr, index);
1567      else
1568	return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "segment");
1569    }
1570}
1571
1572/* Initialize REL_HDR, the section-header for new section, containing
1573   relocations against ASECT.  If USE_RELA_P is true, we use RELA
1574   relocations; otherwise, we use REL relocations.  */
1575
1576boolean
1577_bfd_elf_init_reloc_shdr (abfd, rel_hdr, asect, use_rela_p)
1578     bfd *abfd;
1579     Elf_Internal_Shdr *rel_hdr;
1580     asection *asect;
1581     boolean use_rela_p;
1582{
1583  char *name;
1584  struct elf_backend_data *bed;
1585
1586  bed = get_elf_backend_data (abfd);
1587  name = bfd_alloc (abfd, sizeof ".rela" + strlen (asect->name));
1588  if (name == NULL)
1589    return false;
1590  sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", asect->name);
1591  rel_hdr->sh_name =
1592    (unsigned int) _bfd_stringtab_add (elf_shstrtab (abfd), name,
1593				       true, false);
1594  if (rel_hdr->sh_name == (unsigned int) -1)
1595    return false;
1596  rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
1597  rel_hdr->sh_entsize = (use_rela_p
1598			 ? bed->s->sizeof_rela
1599			 : bed->s->sizeof_rel);
1600  rel_hdr->sh_addralign = bed->s->file_align;
1601  rel_hdr->sh_flags = 0;
1602  rel_hdr->sh_addr = 0;
1603  rel_hdr->sh_size = 0;
1604  rel_hdr->sh_offset = 0;
1605
1606  return true;
1607}
1608
1609/* Set up an ELF internal section header for a section.  */
1610
1611/*ARGSUSED*/
1612static void
1613elf_fake_sections (abfd, asect, failedptrarg)
1614     bfd *abfd;
1615     asection *asect;
1616     PTR failedptrarg;
1617{
1618  struct elf_backend_data *bed = get_elf_backend_data (abfd);
1619  boolean *failedptr = (boolean *) failedptrarg;
1620  Elf_Internal_Shdr *this_hdr;
1621
1622  if (*failedptr)
1623    {
1624      /* We already failed; just get out of the bfd_map_over_sections
1625         loop.  */
1626      return;
1627    }
1628
1629  this_hdr = &elf_section_data (asect)->this_hdr;
1630
1631  this_hdr->sh_name = (unsigned long) _bfd_stringtab_add (elf_shstrtab (abfd),
1632							  asect->name,
1633							  true, false);
1634  if (this_hdr->sh_name == (unsigned long) -1)
1635    {
1636      *failedptr = true;
1637      return;
1638    }
1639
1640  this_hdr->sh_flags = 0;
1641
1642  if ((asect->flags & SEC_ALLOC) != 0
1643      || asect->user_set_vma)
1644    this_hdr->sh_addr = asect->vma;
1645  else
1646    this_hdr->sh_addr = 0;
1647
1648  this_hdr->sh_offset = 0;
1649  this_hdr->sh_size = asect->_raw_size;
1650  this_hdr->sh_link = 0;
1651  this_hdr->sh_addralign = 1 << asect->alignment_power;
1652  /* The sh_entsize and sh_info fields may have been set already by
1653     copy_private_section_data.  */
1654
1655  this_hdr->bfd_section = asect;
1656  this_hdr->contents = NULL;
1657
1658  /* FIXME: This should not be based on section names.  */
1659  if (strcmp (asect->name, ".dynstr") == 0)
1660    this_hdr->sh_type = SHT_STRTAB;
1661  else if (strcmp (asect->name, ".hash") == 0)
1662    {
1663      this_hdr->sh_type = SHT_HASH;
1664      this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
1665    }
1666  else if (strcmp (asect->name, ".dynsym") == 0)
1667    {
1668      this_hdr->sh_type = SHT_DYNSYM;
1669      this_hdr->sh_entsize = bed->s->sizeof_sym;
1670    }
1671  else if (strcmp (asect->name, ".dynamic") == 0)
1672    {
1673      this_hdr->sh_type = SHT_DYNAMIC;
1674      this_hdr->sh_entsize = bed->s->sizeof_dyn;
1675    }
1676  else if (strncmp (asect->name, ".rela", 5) == 0
1677	   && get_elf_backend_data (abfd)->may_use_rela_p)
1678    {
1679      this_hdr->sh_type = SHT_RELA;
1680      this_hdr->sh_entsize = bed->s->sizeof_rela;
1681    }
1682  else if (strncmp (asect->name, ".rel", 4) == 0
1683	   && get_elf_backend_data (abfd)->may_use_rel_p)
1684    {
1685      this_hdr->sh_type = SHT_REL;
1686      this_hdr->sh_entsize = bed->s->sizeof_rel;
1687    }
1688  else if (strncmp (asect->name, ".note", 5) == 0)
1689    this_hdr->sh_type = SHT_NOTE;
1690  else if (strncmp (asect->name, ".stab", 5) == 0
1691	   && strcmp (asect->name + strlen (asect->name) - 3, "str") == 0)
1692    this_hdr->sh_type = SHT_STRTAB;
1693  else if (strcmp (asect->name, ".gnu.version") == 0)
1694    {
1695      this_hdr->sh_type = SHT_GNU_versym;
1696      this_hdr->sh_entsize = sizeof (Elf_External_Versym);
1697    }
1698  else if (strcmp (asect->name, ".gnu.version_d") == 0)
1699    {
1700      this_hdr->sh_type = SHT_GNU_verdef;
1701      this_hdr->sh_entsize = 0;
1702      /* objcopy or strip will copy over sh_info, but may not set
1703         cverdefs.  The linker will set cverdefs, but sh_info will be
1704         zero.  */
1705      if (this_hdr->sh_info == 0)
1706	this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
1707      else
1708	BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
1709		    || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
1710    }
1711  else if (strcmp (asect->name, ".gnu.version_r") == 0)
1712    {
1713      this_hdr->sh_type = SHT_GNU_verneed;
1714      this_hdr->sh_entsize = 0;
1715      /* objcopy or strip will copy over sh_info, but may not set
1716         cverrefs.  The linker will set cverrefs, but sh_info will be
1717         zero.  */
1718      if (this_hdr->sh_info == 0)
1719	this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
1720      else
1721	BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
1722		    || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
1723    }
1724  else if ((asect->flags & SEC_ALLOC) != 0
1725	   && (asect->flags & SEC_LOAD) != 0)
1726    this_hdr->sh_type = SHT_PROGBITS;
1727  else if ((asect->flags & SEC_ALLOC) != 0
1728	   && ((asect->flags & SEC_LOAD) == 0))
1729    this_hdr->sh_type = SHT_NOBITS;
1730  else
1731    {
1732      /* Who knows?  */
1733      this_hdr->sh_type = SHT_PROGBITS;
1734    }
1735
1736  if ((asect->flags & SEC_ALLOC) != 0)
1737    this_hdr->sh_flags |= SHF_ALLOC;
1738  if ((asect->flags & SEC_READONLY) == 0)
1739    this_hdr->sh_flags |= SHF_WRITE;
1740  if ((asect->flags & SEC_CODE) != 0)
1741    this_hdr->sh_flags |= SHF_EXECINSTR;
1742
1743  /* Check for processor-specific section types.  */
1744  if (bed->elf_backend_fake_sections)
1745    (*bed->elf_backend_fake_sections) (abfd, this_hdr, asect);
1746
1747  /* If the section has relocs, set up a section header for the
1748     SHT_REL[A] section.  If two relocation sections are required for
1749     this section, it is up to the processor-specific back-end to
1750     create the other.  */
1751  if ((asect->flags & SEC_RELOC) != 0
1752      && !_bfd_elf_init_reloc_shdr (abfd,
1753				    &elf_section_data (asect)->rel_hdr,
1754				    asect,
1755				    elf_section_data (asect)->use_rela_p))
1756    *failedptr = true;
1757}
1758
1759/* Assign all ELF section numbers.  The dummy first section is handled here
1760   too.  The link/info pointers for the standard section types are filled
1761   in here too, while we're at it.  */
1762
1763static boolean
1764assign_section_numbers (abfd)
1765     bfd *abfd;
1766{
1767  struct elf_obj_tdata *t = elf_tdata (abfd);
1768  asection *sec;
1769  unsigned int section_number;
1770  Elf_Internal_Shdr **i_shdrp;
1771  struct elf_backend_data *bed = get_elf_backend_data (abfd);
1772
1773  section_number = 1;
1774
1775  for (sec = abfd->sections; sec; sec = sec->next)
1776    {
1777      struct bfd_elf_section_data *d = elf_section_data (sec);
1778
1779      d->this_idx = section_number++;
1780      if ((sec->flags & SEC_RELOC) == 0)
1781	d->rel_idx = 0;
1782      else
1783	d->rel_idx = section_number++;
1784
1785      if (d->rel_hdr2)
1786	d->rel_idx2 = section_number++;
1787      else
1788	d->rel_idx2 = 0;
1789    }
1790
1791  t->shstrtab_section = section_number++;
1792  elf_elfheader (abfd)->e_shstrndx = t->shstrtab_section;
1793  t->shstrtab_hdr.sh_size = _bfd_stringtab_size (elf_shstrtab (abfd));
1794
1795  if (bfd_get_symcount (abfd) > 0)
1796    {
1797      t->symtab_section = section_number++;
1798      t->strtab_section = section_number++;
1799    }
1800
1801  elf_elfheader (abfd)->e_shnum = section_number;
1802
1803  /* Set up the list of section header pointers, in agreement with the
1804     indices.  */
1805  i_shdrp = ((Elf_Internal_Shdr **)
1806	     bfd_alloc (abfd, section_number * sizeof (Elf_Internal_Shdr *)));
1807  if (i_shdrp == NULL)
1808    return false;
1809
1810  i_shdrp[0] = ((Elf_Internal_Shdr *)
1811		bfd_alloc (abfd, sizeof (Elf_Internal_Shdr)));
1812  if (i_shdrp[0] == NULL)
1813    {
1814      bfd_release (abfd, i_shdrp);
1815      return false;
1816    }
1817  memset (i_shdrp[0], 0, sizeof (Elf_Internal_Shdr));
1818
1819  elf_elfsections (abfd) = i_shdrp;
1820
1821  i_shdrp[t->shstrtab_section] = &t->shstrtab_hdr;
1822  if (bfd_get_symcount (abfd) > 0)
1823    {
1824      i_shdrp[t->symtab_section] = &t->symtab_hdr;
1825      i_shdrp[t->strtab_section] = &t->strtab_hdr;
1826      t->symtab_hdr.sh_link = t->strtab_section;
1827    }
1828  for (sec = abfd->sections; sec; sec = sec->next)
1829    {
1830      struct bfd_elf_section_data *d = elf_section_data (sec);
1831      asection *s;
1832      const char *name;
1833
1834      i_shdrp[d->this_idx] = &d->this_hdr;
1835      if (d->rel_idx != 0)
1836	i_shdrp[d->rel_idx] = &d->rel_hdr;
1837      if (d->rel_idx2 != 0)
1838	i_shdrp[d->rel_idx2] = d->rel_hdr2;
1839
1840      /* Fill in the sh_link and sh_info fields while we're at it.  */
1841
1842      /* sh_link of a reloc section is the section index of the symbol
1843	 table.  sh_info is the section index of the section to which
1844	 the relocation entries apply.  */
1845      if (d->rel_idx != 0)
1846	{
1847	  d->rel_hdr.sh_link = t->symtab_section;
1848	  d->rel_hdr.sh_info = d->this_idx;
1849	}
1850      if (d->rel_idx2 != 0)
1851	{
1852	  d->rel_hdr2->sh_link = t->symtab_section;
1853	  d->rel_hdr2->sh_info = d->this_idx;
1854	}
1855
1856      switch (d->this_hdr.sh_type)
1857	{
1858	case SHT_REL:
1859	case SHT_RELA:
1860	  /* A reloc section which we are treating as a normal BFD
1861	     section.  sh_link is the section index of the symbol
1862	     table.  sh_info is the section index of the section to
1863	     which the relocation entries apply.  We assume that an
1864	     allocated reloc section uses the dynamic symbol table.
1865	     FIXME: How can we be sure?  */
1866	  s = bfd_get_section_by_name (abfd, ".dynsym");
1867	  if (s != NULL)
1868	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1869
1870	  /* We look up the section the relocs apply to by name.  */
1871	  name = sec->name;
1872	  if (d->this_hdr.sh_type == SHT_REL)
1873	    name += 4;
1874	  else
1875	    name += 5;
1876	  s = bfd_get_section_by_name (abfd, name);
1877	  if (s != NULL)
1878	    d->this_hdr.sh_info = elf_section_data (s)->this_idx;
1879	  break;
1880
1881	case SHT_STRTAB:
1882	  /* We assume that a section named .stab*str is a stabs
1883	     string section.  We look for a section with the same name
1884	     but without the trailing ``str'', and set its sh_link
1885	     field to point to this section.  */
1886	  if (strncmp (sec->name, ".stab", sizeof ".stab" - 1) == 0
1887	      && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
1888	    {
1889	      size_t len;
1890	      char *alc;
1891
1892	      len = strlen (sec->name);
1893	      alc = (char *) bfd_malloc (len - 2);
1894	      if (alc == NULL)
1895		return false;
1896	      strncpy (alc, sec->name, len - 3);
1897	      alc[len - 3] = '\0';
1898	      s = bfd_get_section_by_name (abfd, alc);
1899	      free (alc);
1900	      if (s != NULL)
1901		{
1902		  elf_section_data (s)->this_hdr.sh_link = d->this_idx;
1903
1904		  /* This is a .stab section.  */
1905		  elf_section_data (s)->this_hdr.sh_entsize =
1906		    4 + 2 * (bed->s->arch_size / 8);
1907		}
1908	    }
1909	  break;
1910
1911	case SHT_DYNAMIC:
1912	case SHT_DYNSYM:
1913	case SHT_GNU_verneed:
1914	case SHT_GNU_verdef:
1915	  /* sh_link is the section header index of the string table
1916	     used for the dynamic entries, or the symbol table, or the
1917	     version strings.  */
1918	  s = bfd_get_section_by_name (abfd, ".dynstr");
1919	  if (s != NULL)
1920	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1921	  break;
1922
1923	case SHT_HASH:
1924	case SHT_GNU_versym:
1925	  /* sh_link is the section header index of the symbol table
1926	     this hash table or version table is for.  */
1927	  s = bfd_get_section_by_name (abfd, ".dynsym");
1928	  if (s != NULL)
1929	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1930	  break;
1931	}
1932    }
1933
1934  return true;
1935}
1936
1937/* Map symbol from it's internal number to the external number, moving
1938   all local symbols to be at the head of the list.  */
1939
1940static INLINE int
1941sym_is_global (abfd, sym)
1942     bfd *abfd;
1943     asymbol *sym;
1944{
1945  /* If the backend has a special mapping, use it.  */
1946  if (get_elf_backend_data (abfd)->elf_backend_sym_is_global)
1947    return ((*get_elf_backend_data (abfd)->elf_backend_sym_is_global)
1948	    (abfd, sym));
1949
1950  return ((sym->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1951	  || bfd_is_und_section (bfd_get_section (sym))
1952	  || bfd_is_com_section (bfd_get_section (sym)));
1953}
1954
1955static boolean
1956elf_map_symbols (abfd)
1957     bfd *abfd;
1958{
1959  int symcount = bfd_get_symcount (abfd);
1960  asymbol **syms = bfd_get_outsymbols (abfd);
1961  asymbol **sect_syms;
1962  int num_locals = 0;
1963  int num_globals = 0;
1964  int num_locals2 = 0;
1965  int num_globals2 = 0;
1966  int max_index = 0;
1967  int num_sections = 0;
1968  int idx;
1969  asection *asect;
1970  asymbol **new_syms;
1971  asymbol *sym;
1972
1973#ifdef DEBUG
1974  fprintf (stderr, "elf_map_symbols\n");
1975  fflush (stderr);
1976#endif
1977
1978  /* Add a section symbol for each BFD section.  FIXME: Is this really
1979     necessary?  */
1980  for (asect = abfd->sections; asect; asect = asect->next)
1981    {
1982      if (max_index < asect->index)
1983	max_index = asect->index;
1984    }
1985
1986  max_index++;
1987  sect_syms = (asymbol **) bfd_zalloc (abfd, max_index * sizeof (asymbol *));
1988  if (sect_syms == NULL)
1989    return false;
1990  elf_section_syms (abfd) = sect_syms;
1991
1992  for (idx = 0; idx < symcount; idx++)
1993    {
1994      sym = syms[idx];
1995
1996      if ((sym->flags & BSF_SECTION_SYM) != 0
1997	  && sym->value == 0)
1998	{
1999	  asection *sec;
2000
2001	  sec = sym->section;
2002
2003	  if (sec->owner != NULL)
2004	    {
2005	      if (sec->owner != abfd)
2006		{
2007		  if (sec->output_offset != 0)
2008		    continue;
2009
2010		  sec = sec->output_section;
2011
2012		  /* Empty sections in the input files may have had a section
2013		     symbol created for them.  (See the comment near the end of
2014		     _bfd_generic_link_output_symbols in linker.c).  If the linker
2015		     script discards such sections then we will reach this point.
2016		     Since we know that we cannot avoid this case, we detect it
2017		     and skip the abort and the assignment to the sect_syms array.
2018		     To reproduce this particular case try running the linker
2019		     testsuite test ld-scripts/weak.exp for an ELF port that uses
2020		     the generic linker.  */
2021		  if (sec->owner == NULL)
2022		    continue;
2023
2024		  BFD_ASSERT (sec->owner == abfd);
2025		}
2026	      sect_syms[sec->index] = syms[idx];
2027	    }
2028	}
2029    }
2030
2031  for (asect = abfd->sections; asect; asect = asect->next)
2032    {
2033      if (sect_syms[asect->index] != NULL)
2034	continue;
2035
2036      sym = bfd_make_empty_symbol (abfd);
2037      if (sym == NULL)
2038	return false;
2039      sym->the_bfd = abfd;
2040      sym->name = asect->name;
2041      sym->value = 0;
2042      /* Set the flags to 0 to indicate that this one was newly added.  */
2043      sym->flags = 0;
2044      sym->section = asect;
2045      sect_syms[asect->index] = sym;
2046      num_sections++;
2047#ifdef DEBUG
2048      fprintf (stderr,
2049 _("creating section symbol, name = %s, value = 0x%.8lx, index = %d, section = 0x%.8lx\n"),
2050	       asect->name, (long) asect->vma, asect->index, (long) asect);
2051#endif
2052    }
2053
2054  /* Classify all of the symbols.  */
2055  for (idx = 0; idx < symcount; idx++)
2056    {
2057      if (!sym_is_global (abfd, syms[idx]))
2058	num_locals++;
2059      else
2060	num_globals++;
2061    }
2062  for (asect = abfd->sections; asect; asect = asect->next)
2063    {
2064      if (sect_syms[asect->index] != NULL
2065	  && sect_syms[asect->index]->flags == 0)
2066	{
2067	  sect_syms[asect->index]->flags = BSF_SECTION_SYM;
2068	  if (!sym_is_global (abfd, sect_syms[asect->index]))
2069	    num_locals++;
2070	  else
2071	    num_globals++;
2072	  sect_syms[asect->index]->flags = 0;
2073	}
2074    }
2075
2076  /* Now sort the symbols so the local symbols are first.  */
2077  new_syms = ((asymbol **)
2078	      bfd_alloc (abfd,
2079			 (num_locals + num_globals) * sizeof (asymbol *)));
2080  if (new_syms == NULL)
2081    return false;
2082
2083  for (idx = 0; idx < symcount; idx++)
2084    {
2085      asymbol *sym = syms[idx];
2086      int i;
2087
2088      if (!sym_is_global (abfd, sym))
2089	i = num_locals2++;
2090      else
2091	i = num_locals + num_globals2++;
2092      new_syms[i] = sym;
2093      sym->udata.i = i + 1;
2094    }
2095  for (asect = abfd->sections; asect; asect = asect->next)
2096    {
2097      if (sect_syms[asect->index] != NULL
2098	  && sect_syms[asect->index]->flags == 0)
2099	{
2100	  asymbol *sym = sect_syms[asect->index];
2101	  int i;
2102
2103	  sym->flags = BSF_SECTION_SYM;
2104	  if (!sym_is_global (abfd, sym))
2105	    i = num_locals2++;
2106	  else
2107	    i = num_locals + num_globals2++;
2108	  new_syms[i] = sym;
2109	  sym->udata.i = i + 1;
2110	}
2111    }
2112
2113  bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
2114
2115  elf_num_locals (abfd) = num_locals;
2116  elf_num_globals (abfd) = num_globals;
2117  return true;
2118}
2119
2120/* Align to the maximum file alignment that could be required for any
2121   ELF data structure.  */
2122
2123static INLINE file_ptr align_file_position PARAMS ((file_ptr, int));
2124static INLINE file_ptr
2125align_file_position (off, align)
2126     file_ptr off;
2127     int align;
2128{
2129  return (off + align - 1) & ~(align - 1);
2130}
2131
2132/* Assign a file position to a section, optionally aligning to the
2133   required section alignment.  */
2134
2135INLINE file_ptr
2136_bfd_elf_assign_file_position_for_section (i_shdrp, offset, align)
2137     Elf_Internal_Shdr *i_shdrp;
2138     file_ptr offset;
2139     boolean align;
2140{
2141  if (align)
2142    {
2143      unsigned int al;
2144
2145      al = i_shdrp->sh_addralign;
2146      if (al > 1)
2147	offset = BFD_ALIGN (offset, al);
2148    }
2149  i_shdrp->sh_offset = offset;
2150  if (i_shdrp->bfd_section != NULL)
2151    i_shdrp->bfd_section->filepos = offset;
2152  if (i_shdrp->sh_type != SHT_NOBITS)
2153    offset += i_shdrp->sh_size;
2154  return offset;
2155}
2156
2157/* Compute the file positions we are going to put the sections at, and
2158   otherwise prepare to begin writing out the ELF file.  If LINK_INFO
2159   is not NULL, this is being called by the ELF backend linker.  */
2160
2161boolean
2162_bfd_elf_compute_section_file_positions (abfd, link_info)
2163     bfd *abfd;
2164     struct bfd_link_info *link_info;
2165{
2166  struct elf_backend_data *bed = get_elf_backend_data (abfd);
2167  boolean failed;
2168  struct bfd_strtab_hash *strtab;
2169  Elf_Internal_Shdr *shstrtab_hdr;
2170
2171  if (abfd->output_has_begun)
2172    return true;
2173
2174  /* Do any elf backend specific processing first.  */
2175  if (bed->elf_backend_begin_write_processing)
2176    (*bed->elf_backend_begin_write_processing) (abfd, link_info);
2177
2178  if (! prep_headers (abfd))
2179    return false;
2180
2181  /* Post process the headers if necessary.  */
2182  if (bed->elf_backend_post_process_headers)
2183    (*bed->elf_backend_post_process_headers) (abfd, link_info);
2184
2185  failed = false;
2186  bfd_map_over_sections (abfd, elf_fake_sections, &failed);
2187  if (failed)
2188    return false;
2189
2190  if (!assign_section_numbers (abfd))
2191    return false;
2192
2193  /* The backend linker builds symbol table information itself.  */
2194  if (link_info == NULL && bfd_get_symcount (abfd) > 0)
2195    {
2196      /* Non-zero if doing a relocatable link.  */
2197      int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
2198
2199      if (! swap_out_syms (abfd, &strtab, relocatable_p))
2200	return false;
2201    }
2202
2203  shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
2204  /* sh_name was set in prep_headers.  */
2205  shstrtab_hdr->sh_type = SHT_STRTAB;
2206  shstrtab_hdr->sh_flags = 0;
2207  shstrtab_hdr->sh_addr = 0;
2208  shstrtab_hdr->sh_size = _bfd_stringtab_size (elf_shstrtab (abfd));
2209  shstrtab_hdr->sh_entsize = 0;
2210  shstrtab_hdr->sh_link = 0;
2211  shstrtab_hdr->sh_info = 0;
2212  /* sh_offset is set in assign_file_positions_except_relocs.  */
2213  shstrtab_hdr->sh_addralign = 1;
2214
2215  if (!assign_file_positions_except_relocs (abfd))
2216    return false;
2217
2218  if (link_info == NULL && bfd_get_symcount (abfd) > 0)
2219    {
2220      file_ptr off;
2221      Elf_Internal_Shdr *hdr;
2222
2223      off = elf_tdata (abfd)->next_file_pos;
2224
2225      hdr = &elf_tdata (abfd)->symtab_hdr;
2226      off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
2227
2228      hdr = &elf_tdata (abfd)->strtab_hdr;
2229      off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
2230
2231      elf_tdata (abfd)->next_file_pos = off;
2232
2233      /* Now that we know where the .strtab section goes, write it
2234         out.  */
2235      if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
2236	  || ! _bfd_stringtab_emit (abfd, strtab))
2237	return false;
2238      _bfd_stringtab_free (strtab);
2239    }
2240
2241  abfd->output_has_begun = true;
2242
2243  return true;
2244}
2245
2246/* Create a mapping from a set of sections to a program segment.  */
2247
2248static INLINE struct elf_segment_map *
2249make_mapping (abfd, sections, from, to, phdr)
2250     bfd *abfd;
2251     asection **sections;
2252     unsigned int from;
2253     unsigned int to;
2254     boolean phdr;
2255{
2256  struct elf_segment_map *m;
2257  unsigned int i;
2258  asection **hdrpp;
2259
2260  m = ((struct elf_segment_map *)
2261       bfd_zalloc (abfd,
2262		   (sizeof (struct elf_segment_map)
2263		    + (to - from - 1) * sizeof (asection *))));
2264  if (m == NULL)
2265    return NULL;
2266  m->next = NULL;
2267  m->p_type = PT_LOAD;
2268  for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
2269    m->sections[i - from] = *hdrpp;
2270  m->count = to - from;
2271
2272  if (from == 0 && phdr)
2273    {
2274      /* Include the headers in the first PT_LOAD segment.  */
2275      m->includes_filehdr = 1;
2276      m->includes_phdrs = 1;
2277    }
2278
2279  return m;
2280}
2281
2282/* Set up a mapping from BFD sections to program segments.  */
2283
2284static boolean
2285map_sections_to_segments (abfd)
2286     bfd *abfd;
2287{
2288  asection **sections = NULL;
2289  asection *s;
2290  unsigned int i;
2291  unsigned int count;
2292  struct elf_segment_map *mfirst;
2293  struct elf_segment_map **pm;
2294  struct elf_segment_map *m;
2295  asection *last_hdr;
2296  unsigned int phdr_index;
2297  bfd_vma maxpagesize;
2298  asection **hdrpp;
2299  boolean phdr_in_segment = true;
2300  boolean writable;
2301  asection *dynsec;
2302
2303  if (elf_tdata (abfd)->segment_map != NULL)
2304    return true;
2305
2306  if (bfd_count_sections (abfd) == 0)
2307    return true;
2308
2309  /* Select the allocated sections, and sort them.  */
2310
2311  sections = (asection **) bfd_malloc (bfd_count_sections (abfd)
2312				       * sizeof (asection *));
2313  if (sections == NULL)
2314    goto error_return;
2315
2316  i = 0;
2317  for (s = abfd->sections; s != NULL; s = s->next)
2318    {
2319      if ((s->flags & SEC_ALLOC) != 0)
2320	{
2321	  sections[i] = s;
2322	  ++i;
2323	}
2324    }
2325  BFD_ASSERT (i <= bfd_count_sections (abfd));
2326  count = i;
2327
2328  qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
2329
2330  /* Build the mapping.  */
2331
2332  mfirst = NULL;
2333  pm = &mfirst;
2334
2335  /* If we have a .interp section, then create a PT_PHDR segment for
2336     the program headers and a PT_INTERP segment for the .interp
2337     section.  */
2338  s = bfd_get_section_by_name (abfd, ".interp");
2339  if (s != NULL && (s->flags & SEC_LOAD) != 0)
2340    {
2341      m = ((struct elf_segment_map *)
2342	   bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2343      if (m == NULL)
2344	goto error_return;
2345      m->next = NULL;
2346      m->p_type = PT_PHDR;
2347      /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
2348      m->p_flags = PF_R | PF_X;
2349      m->p_flags_valid = 1;
2350      m->includes_phdrs = 1;
2351
2352      *pm = m;
2353      pm = &m->next;
2354
2355      m = ((struct elf_segment_map *)
2356	   bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2357      if (m == NULL)
2358	goto error_return;
2359      m->next = NULL;
2360      m->p_type = PT_INTERP;
2361      m->count = 1;
2362      m->sections[0] = s;
2363
2364      *pm = m;
2365      pm = &m->next;
2366    }
2367
2368  /* Look through the sections.  We put sections in the same program
2369     segment when the start of the second section can be placed within
2370     a few bytes of the end of the first section.  */
2371  last_hdr = NULL;
2372  phdr_index = 0;
2373  maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
2374  writable = false;
2375  dynsec = bfd_get_section_by_name (abfd, ".dynamic");
2376  if (dynsec != NULL
2377      && (dynsec->flags & SEC_LOAD) == 0)
2378    dynsec = NULL;
2379
2380  /* Deal with -Ttext or something similar such that the first section
2381     is not adjacent to the program headers.  This is an
2382     approximation, since at this point we don't know exactly how many
2383     program headers we will need.  */
2384  if (count > 0)
2385    {
2386      bfd_size_type phdr_size;
2387
2388      phdr_size = elf_tdata (abfd)->program_header_size;
2389      if (phdr_size == 0)
2390	phdr_size = get_elf_backend_data (abfd)->s->sizeof_phdr;
2391      if ((abfd->flags & D_PAGED) == 0
2392	  || sections[0]->lma < phdr_size
2393	  || sections[0]->lma % maxpagesize < phdr_size % maxpagesize)
2394	phdr_in_segment = false;
2395    }
2396
2397  for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
2398    {
2399      asection *hdr;
2400      boolean new_segment;
2401
2402      hdr = *hdrpp;
2403
2404      /* See if this section and the last one will fit in the same
2405         segment.  */
2406
2407      if (last_hdr == NULL)
2408	{
2409	  /* If we don't have a segment yet, then we don't need a new
2410	     one (we build the last one after this loop).  */
2411	  new_segment = false;
2412	}
2413      else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
2414	{
2415	  /* If this section has a different relation between the
2416             virtual address and the load address, then we need a new
2417             segment.  */
2418	  new_segment = true;
2419	}
2420      else if (BFD_ALIGN (last_hdr->lma + last_hdr->_raw_size, maxpagesize)
2421	       < BFD_ALIGN (hdr->lma, maxpagesize))
2422	{
2423	  /* If putting this section in this segment would force us to
2424             skip a page in the segment, then we need a new segment.  */
2425	  new_segment = true;
2426	}
2427      else if ((last_hdr->flags & SEC_LOAD) == 0
2428	       && (hdr->flags & SEC_LOAD) != 0)
2429	{
2430	  /* We don't want to put a loadable section after a
2431             nonloadable section in the same segment.  */
2432	  new_segment = true;
2433	}
2434      else if ((abfd->flags & D_PAGED) == 0)
2435	{
2436	  /* If the file is not demand paged, which means that we
2437             don't require the sections to be correctly aligned in the
2438             file, then there is no other reason for a new segment.  */
2439	  new_segment = false;
2440	}
2441      else if (! writable
2442	       && (hdr->flags & SEC_READONLY) == 0
2443	       && (BFD_ALIGN (last_hdr->lma + last_hdr->_raw_size, maxpagesize)
2444		   == hdr->lma))
2445	{
2446	  /* We don't want to put a writable section in a read only
2447             segment, unless they are on the same page in memory
2448             anyhow.  We already know that the last section does not
2449             bring us past the current section on the page, so the
2450             only case in which the new section is not on the same
2451             page as the previous section is when the previous section
2452             ends precisely on a page boundary.  */
2453	  new_segment = true;
2454	}
2455      else
2456	{
2457	  /* Otherwise, we can use the same segment.  */
2458	  new_segment = false;
2459	}
2460
2461      if (! new_segment)
2462	{
2463	  if ((hdr->flags & SEC_READONLY) == 0)
2464	    writable = true;
2465	  last_hdr = hdr;
2466	  continue;
2467	}
2468
2469      /* We need a new program segment.  We must create a new program
2470         header holding all the sections from phdr_index until hdr.  */
2471
2472      m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
2473      if (m == NULL)
2474	goto error_return;
2475
2476      *pm = m;
2477      pm = &m->next;
2478
2479      if ((hdr->flags & SEC_READONLY) == 0)
2480	writable = true;
2481      else
2482	writable = false;
2483
2484      last_hdr = hdr;
2485      phdr_index = i;
2486      phdr_in_segment = false;
2487    }
2488
2489  /* Create a final PT_LOAD program segment.  */
2490  if (last_hdr != NULL)
2491    {
2492      m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
2493      if (m == NULL)
2494	goto error_return;
2495
2496      *pm = m;
2497      pm = &m->next;
2498    }
2499
2500  /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
2501  if (dynsec != NULL)
2502    {
2503      m = ((struct elf_segment_map *)
2504	   bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2505      if (m == NULL)
2506	goto error_return;
2507      m->next = NULL;
2508      m->p_type = PT_DYNAMIC;
2509      m->count = 1;
2510      m->sections[0] = dynsec;
2511
2512      *pm = m;
2513      pm = &m->next;
2514    }
2515
2516  /* For each loadable .note section, add a PT_NOTE segment.  We don't
2517     use bfd_get_section_by_name, because if we link together
2518     nonloadable .note sections and loadable .note sections, we will
2519     generate two .note sections in the output file.  FIXME: Using
2520     names for section types is bogus anyhow.  */
2521  for (s = abfd->sections; s != NULL; s = s->next)
2522    {
2523      if ((s->flags & SEC_LOAD) != 0
2524	  && strncmp (s->name, ".note", 5) == 0)
2525	{
2526	  m = ((struct elf_segment_map *)
2527	       bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2528	  if (m == NULL)
2529	    goto error_return;
2530	  m->next = NULL;
2531	  m->p_type = PT_NOTE;
2532	  m->count = 1;
2533	  m->sections[0] = s;
2534
2535	  *pm = m;
2536	  pm = &m->next;
2537	}
2538    }
2539
2540  free (sections);
2541  sections = NULL;
2542
2543  elf_tdata (abfd)->segment_map = mfirst;
2544  return true;
2545
2546 error_return:
2547  if (sections != NULL)
2548    free (sections);
2549  return false;
2550}
2551
2552/* Sort sections by address.  */
2553
2554static int
2555elf_sort_sections (arg1, arg2)
2556     const PTR arg1;
2557     const PTR arg2;
2558{
2559  const asection *sec1 = *(const asection **) arg1;
2560  const asection *sec2 = *(const asection **) arg2;
2561
2562  /* Sort by LMA first, since this is the address used to
2563     place the section into a segment.  */
2564  if (sec1->lma < sec2->lma)
2565    return -1;
2566  else if (sec1->lma > sec2->lma)
2567    return 1;
2568
2569  /* Then sort by VMA.  Normally the LMA and the VMA will be
2570     the same, and this will do nothing.  */
2571  if (sec1->vma < sec2->vma)
2572    return -1;
2573  else if (sec1->vma > sec2->vma)
2574    return 1;
2575
2576  /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
2577
2578#define TOEND(x) (((x)->flags & SEC_LOAD) == 0)
2579
2580  if (TOEND (sec1))
2581    {
2582      if (TOEND (sec2))
2583	return sec1->target_index - sec2->target_index;
2584      else
2585	return 1;
2586    }
2587
2588  if (TOEND (sec2))
2589    return -1;
2590
2591#undef TOEND
2592
2593  /* Sort by size, to put zero sized sections before others at the
2594     same address.  */
2595
2596  if (sec1->_raw_size < sec2->_raw_size)
2597    return -1;
2598  if (sec1->_raw_size > sec2->_raw_size)
2599    return 1;
2600
2601  return sec1->target_index - sec2->target_index;
2602}
2603
2604/* Assign file positions to the sections based on the mapping from
2605   sections to segments.  This function also sets up some fields in
2606   the file header, and writes out the program headers.  */
2607
2608static boolean
2609assign_file_positions_for_segments (abfd)
2610     bfd *abfd;
2611{
2612  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2613  unsigned int count;
2614  struct elf_segment_map *m;
2615  unsigned int alloc;
2616  Elf_Internal_Phdr *phdrs;
2617  file_ptr off, voff;
2618  bfd_vma filehdr_vaddr, filehdr_paddr;
2619  bfd_vma phdrs_vaddr, phdrs_paddr;
2620  Elf_Internal_Phdr *p;
2621
2622  if (elf_tdata (abfd)->segment_map == NULL)
2623    {
2624      if (! map_sections_to_segments (abfd))
2625	return false;
2626    }
2627
2628  if (bed->elf_backend_modify_segment_map)
2629    {
2630      if (! (*bed->elf_backend_modify_segment_map) (abfd))
2631	return false;
2632    }
2633
2634  count = 0;
2635  for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
2636    ++count;
2637
2638  elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
2639  elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
2640  elf_elfheader (abfd)->e_phnum = count;
2641
2642  if (count == 0)
2643    return true;
2644
2645  /* If we already counted the number of program segments, make sure
2646     that we allocated enough space.  This happens when SIZEOF_HEADERS
2647     is used in a linker script.  */
2648  alloc = elf_tdata (abfd)->program_header_size / bed->s->sizeof_phdr;
2649  if (alloc != 0 && count > alloc)
2650    {
2651      ((*_bfd_error_handler)
2652       (_("%s: Not enough room for program headers (allocated %u, need %u)"),
2653	bfd_get_filename (abfd), alloc, count));
2654      bfd_set_error (bfd_error_bad_value);
2655      return false;
2656    }
2657
2658  if (alloc == 0)
2659    alloc = count;
2660
2661  phdrs = ((Elf_Internal_Phdr *)
2662	   bfd_alloc (abfd, alloc * sizeof (Elf_Internal_Phdr)));
2663  if (phdrs == NULL)
2664    return false;
2665
2666  off = bed->s->sizeof_ehdr;
2667  off += alloc * bed->s->sizeof_phdr;
2668
2669  filehdr_vaddr = 0;
2670  filehdr_paddr = 0;
2671  phdrs_vaddr = 0;
2672  phdrs_paddr = 0;
2673
2674  for (m = elf_tdata (abfd)->segment_map, p = phdrs;
2675       m != NULL;
2676       m = m->next, p++)
2677    {
2678      unsigned int i;
2679      asection **secpp;
2680
2681      /* If elf_segment_map is not from map_sections_to_segments, the
2682         sections may not be correctly ordered.  */
2683      if (m->count > 0)
2684	qsort (m->sections, (size_t) m->count, sizeof (asection *),
2685	       elf_sort_sections);
2686
2687      p->p_type = m->p_type;
2688      p->p_flags = m->p_flags;
2689
2690      if (p->p_type == PT_LOAD
2691	  && m->count > 0
2692	  && (m->sections[0]->flags & SEC_ALLOC) != 0)
2693	{
2694	  if ((abfd->flags & D_PAGED) != 0)
2695	    off += (m->sections[0]->vma - off) % bed->maxpagesize;
2696	  else
2697	    {
2698	      bfd_size_type align;
2699
2700	      align = 0;
2701	      for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
2702		{
2703		  bfd_size_type secalign;
2704
2705		  secalign = bfd_get_section_alignment (abfd, *secpp);
2706		  if (secalign > align)
2707		    align = secalign;
2708		}
2709
2710	      off += (m->sections[0]->vma - off) % (1 << align);
2711	    }
2712	}
2713
2714      if (m->count == 0)
2715	p->p_vaddr = 0;
2716      else
2717	p->p_vaddr = m->sections[0]->vma;
2718
2719      if (m->p_paddr_valid)
2720	p->p_paddr = m->p_paddr;
2721      else if (m->count == 0)
2722	p->p_paddr = 0;
2723      else
2724	p->p_paddr = m->sections[0]->lma;
2725
2726      if (p->p_type == PT_LOAD
2727	  && (abfd->flags & D_PAGED) != 0)
2728	p->p_align = bed->maxpagesize;
2729      else if (m->count == 0)
2730	p->p_align = bed->s->file_align;
2731      else
2732	p->p_align = 0;
2733
2734      p->p_offset = 0;
2735      p->p_filesz = 0;
2736      p->p_memsz = 0;
2737
2738      if (m->includes_filehdr)
2739	{
2740	  if (! m->p_flags_valid)
2741	    p->p_flags |= PF_R;
2742	  p->p_offset = 0;
2743	  p->p_filesz = bed->s->sizeof_ehdr;
2744	  p->p_memsz = bed->s->sizeof_ehdr;
2745	  if (m->count > 0)
2746	    {
2747	      BFD_ASSERT (p->p_type == PT_LOAD);
2748
2749	      if (p->p_vaddr < (bfd_vma) off)
2750		{
2751		  _bfd_error_handler (_("%s: Not enough room for program headers, try linking with -N"),
2752				      bfd_get_filename (abfd));
2753		  bfd_set_error (bfd_error_bad_value);
2754		  return false;
2755		}
2756
2757	      p->p_vaddr -= off;
2758	      if (! m->p_paddr_valid)
2759		p->p_paddr -= off;
2760	    }
2761	  if (p->p_type == PT_LOAD)
2762	    {
2763	      filehdr_vaddr = p->p_vaddr;
2764	      filehdr_paddr = p->p_paddr;
2765	    }
2766	}
2767
2768      if (m->includes_phdrs)
2769	{
2770	  if (! m->p_flags_valid)
2771	    p->p_flags |= PF_R;
2772
2773	  if (m->includes_filehdr)
2774	    {
2775	      if (p->p_type == PT_LOAD)
2776		{
2777		  phdrs_vaddr = p->p_vaddr + bed->s->sizeof_ehdr;
2778		  phdrs_paddr = p->p_paddr + bed->s->sizeof_ehdr;
2779		}
2780	    }
2781	  else
2782	    {
2783	      p->p_offset = bed->s->sizeof_ehdr;
2784
2785	      if (m->count > 0)
2786		{
2787		  BFD_ASSERT (p->p_type == PT_LOAD);
2788		  p->p_vaddr -= off - p->p_offset;
2789		  if (! m->p_paddr_valid)
2790		    p->p_paddr -= off - p->p_offset;
2791		}
2792
2793	      if (p->p_type == PT_LOAD)
2794		{
2795		  phdrs_vaddr = p->p_vaddr;
2796		  phdrs_paddr = p->p_paddr;
2797		}
2798	      else
2799		phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
2800	    }
2801
2802	  p->p_filesz += alloc * bed->s->sizeof_phdr;
2803	  p->p_memsz += alloc * bed->s->sizeof_phdr;
2804	}
2805
2806      if (p->p_type == PT_LOAD
2807	  || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
2808	{
2809	  if (! m->includes_filehdr && ! m->includes_phdrs)
2810	    p->p_offset = off;
2811	  else
2812	    {
2813	      file_ptr adjust;
2814
2815	      adjust = off - (p->p_offset + p->p_filesz);
2816	      p->p_filesz += adjust;
2817	      p->p_memsz += adjust;
2818	    }
2819	}
2820
2821      voff = off;
2822
2823      for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
2824	{
2825	  asection *sec;
2826	  flagword flags;
2827	  bfd_size_type align;
2828
2829	  sec = *secpp;
2830	  flags = sec->flags;
2831	  align = 1 << bfd_get_section_alignment (abfd, sec);
2832
2833	  /* The section may have artificial alignment forced by a
2834	     link script.  Notice this case by the gap between the
2835	     cumulative phdr vma and the section's vma.  */
2836	  if (p->p_vaddr + p->p_memsz < sec->vma)
2837	    {
2838	      bfd_vma adjust = sec->vma - (p->p_vaddr + p->p_memsz);
2839
2840	      p->p_memsz += adjust;
2841	      off += adjust;
2842	      voff += adjust;
2843	      if ((flags & SEC_LOAD) != 0)
2844		p->p_filesz += adjust;
2845	    }
2846
2847	  if (p->p_type == PT_LOAD)
2848	    {
2849	      bfd_signed_vma adjust;
2850
2851	      if ((flags & SEC_LOAD) != 0)
2852		{
2853		  adjust = sec->lma - (p->p_paddr + p->p_memsz);
2854		  if (adjust < 0)
2855		    adjust = 0;
2856		}
2857	      else if ((flags & SEC_ALLOC) != 0)
2858		{
2859		  /* The section VMA must equal the file position
2860		     modulo the page size.  FIXME: I'm not sure if
2861		     this adjustment is really necessary.  We used to
2862		     not have the SEC_LOAD case just above, and then
2863		     this was necessary, but now I'm not sure.  */
2864		  if ((abfd->flags & D_PAGED) != 0)
2865		    adjust = (sec->vma - voff) % bed->maxpagesize;
2866		  else
2867		    adjust = (sec->vma - voff) % align;
2868		}
2869	      else
2870		adjust = 0;
2871
2872	      if (adjust != 0)
2873		{
2874		  if (i == 0)
2875		    {
2876		      (* _bfd_error_handler)
2877			(_("Error: First section in segment (%s) starts at 0x%x"),
2878			 bfd_section_name (abfd, sec), sec->lma);
2879		      (* _bfd_error_handler)
2880			(_("       whereas segment starts at 0x%x"),
2881			 p->p_paddr);
2882
2883		      return false;
2884		    }
2885		  p->p_memsz += adjust;
2886		  off += adjust;
2887		  voff += adjust;
2888		  if ((flags & SEC_LOAD) != 0)
2889		    p->p_filesz += adjust;
2890		}
2891
2892	      sec->filepos = off;
2893
2894	      /* We check SEC_HAS_CONTENTS here because if NOLOAD is
2895                 used in a linker script we may have a section with
2896                 SEC_LOAD clear but which is supposed to have
2897                 contents.  */
2898	      if ((flags & SEC_LOAD) != 0
2899		  || (flags & SEC_HAS_CONTENTS) != 0)
2900		off += sec->_raw_size;
2901
2902	      if ((flags & SEC_ALLOC) != 0)
2903		voff += sec->_raw_size;
2904	    }
2905
2906	  if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
2907	    {
2908	      if (i == 0)	/* the actual "note" segment */
2909		{		/* this one actually contains everything. */
2910		  sec->filepos = off;
2911		  p->p_filesz = sec->_raw_size;
2912		  off += sec->_raw_size;
2913		  voff = off;
2914		}
2915	      else	/* fake sections -- don't need to be written */
2916		{
2917		  sec->filepos = 0;
2918		  sec->_raw_size = 0;
2919		  flags = sec->flags = 0;	/* no contents */
2920		}
2921	      p->p_memsz = 0;
2922	      p->p_align = 1;
2923	    }
2924	  else
2925	    {
2926	      p->p_memsz += sec->_raw_size;
2927
2928	      if ((flags & SEC_LOAD) != 0)
2929		p->p_filesz += sec->_raw_size;
2930
2931	      if (align > p->p_align
2932		  && (p->p_type != PT_LOAD || (abfd->flags & D_PAGED) == 0))
2933		p->p_align = align;
2934	    }
2935
2936	  if (! m->p_flags_valid)
2937	    {
2938	      p->p_flags |= PF_R;
2939	      if ((flags & SEC_CODE) != 0)
2940		p->p_flags |= PF_X;
2941	      if ((flags & SEC_READONLY) == 0)
2942		p->p_flags |= PF_W;
2943	    }
2944	}
2945    }
2946
2947  /* Now that we have set the section file positions, we can set up
2948     the file positions for the non PT_LOAD segments.  */
2949  for (m = elf_tdata (abfd)->segment_map, p = phdrs;
2950       m != NULL;
2951       m = m->next, p++)
2952    {
2953      if (p->p_type != PT_LOAD && m->count > 0)
2954	{
2955	  BFD_ASSERT (! m->includes_filehdr && ! m->includes_phdrs);
2956	  p->p_offset = m->sections[0]->filepos;
2957	}
2958      if (m->count == 0)
2959	{
2960	  if (m->includes_filehdr)
2961	    {
2962	      p->p_vaddr = filehdr_vaddr;
2963	      if (! m->p_paddr_valid)
2964		p->p_paddr = filehdr_paddr;
2965	    }
2966	  else if (m->includes_phdrs)
2967	    {
2968	      p->p_vaddr = phdrs_vaddr;
2969	      if (! m->p_paddr_valid)
2970		p->p_paddr = phdrs_paddr;
2971	    }
2972	}
2973    }
2974
2975  /* Clear out any program headers we allocated but did not use.  */
2976  for (; count < alloc; count++, p++)
2977    {
2978      memset (p, 0, sizeof *p);
2979      p->p_type = PT_NULL;
2980    }
2981
2982  elf_tdata (abfd)->phdr = phdrs;
2983
2984  elf_tdata (abfd)->next_file_pos = off;
2985
2986  /* Write out the program headers.  */
2987  if (bfd_seek (abfd, bed->s->sizeof_ehdr, SEEK_SET) != 0
2988      || bed->s->write_out_phdrs (abfd, phdrs, alloc) != 0)
2989    return false;
2990
2991  return true;
2992}
2993
2994/* Get the size of the program header.
2995
2996   If this is called by the linker before any of the section VMA's are set, it
2997   can't calculate the correct value for a strange memory layout.  This only
2998   happens when SIZEOF_HEADERS is used in a linker script.  In this case,
2999   SORTED_HDRS is NULL and we assume the normal scenario of one text and one
3000   data segment (exclusive of .interp and .dynamic).
3001
3002   ??? User written scripts must either not use SIZEOF_HEADERS, or assume there
3003   will be two segments.  */
3004
3005static bfd_size_type
3006get_program_header_size (abfd)
3007     bfd *abfd;
3008{
3009  size_t segs;
3010  asection *s;
3011  struct elf_backend_data *bed = get_elf_backend_data (abfd);
3012
3013  /* We can't return a different result each time we're called.  */
3014  if (elf_tdata (abfd)->program_header_size != 0)
3015    return elf_tdata (abfd)->program_header_size;
3016
3017  if (elf_tdata (abfd)->segment_map != NULL)
3018    {
3019      struct elf_segment_map *m;
3020
3021      segs = 0;
3022      for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
3023	++segs;
3024      elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
3025      return elf_tdata (abfd)->program_header_size;
3026    }
3027
3028  /* Assume we will need exactly two PT_LOAD segments: one for text
3029     and one for data.  */
3030  segs = 2;
3031
3032  s = bfd_get_section_by_name (abfd, ".interp");
3033  if (s != NULL && (s->flags & SEC_LOAD) != 0)
3034    {
3035      /* If we have a loadable interpreter section, we need a
3036	 PT_INTERP segment.  In this case, assume we also need a
3037	 PT_PHDR segment, although that may not be true for all
3038	 targets.  */
3039      segs += 2;
3040    }
3041
3042  if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
3043    {
3044      /* We need a PT_DYNAMIC segment.  */
3045      ++segs;
3046    }
3047
3048  for (s = abfd->sections; s != NULL; s = s->next)
3049    {
3050      if ((s->flags & SEC_LOAD) != 0
3051	  && strncmp (s->name, ".note", 5) == 0)
3052	{
3053	  /* We need a PT_NOTE segment.  */
3054	  ++segs;
3055	}
3056    }
3057
3058  /* Let the backend count up any program headers it might need.  */
3059  if (bed->elf_backend_additional_program_headers)
3060    {
3061      int a;
3062
3063      a = (*bed->elf_backend_additional_program_headers) (abfd);
3064      if (a == -1)
3065	abort ();
3066      segs += a;
3067    }
3068
3069  elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
3070  return elf_tdata (abfd)->program_header_size;
3071}
3072
3073/* Work out the file positions of all the sections.  This is called by
3074   _bfd_elf_compute_section_file_positions.  All the section sizes and
3075   VMAs must be known before this is called.
3076
3077   We do not consider reloc sections at this point, unless they form
3078   part of the loadable image.  Reloc sections are assigned file
3079   positions in assign_file_positions_for_relocs, which is called by
3080   write_object_contents and final_link.
3081
3082   We also don't set the positions of the .symtab and .strtab here.  */
3083
3084static boolean
3085assign_file_positions_except_relocs (abfd)
3086     bfd *abfd;
3087{
3088  struct elf_obj_tdata * const tdata = elf_tdata (abfd);
3089  Elf_Internal_Ehdr * const i_ehdrp = elf_elfheader (abfd);
3090  Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
3091  file_ptr off;
3092  struct elf_backend_data *bed = get_elf_backend_data (abfd);
3093
3094  if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
3095      && bfd_get_format (abfd) != bfd_core)
3096    {
3097      Elf_Internal_Shdr **hdrpp;
3098      unsigned int i;
3099
3100      /* Start after the ELF header.  */
3101      off = i_ehdrp->e_ehsize;
3102
3103      /* We are not creating an executable, which means that we are
3104	 not creating a program header, and that the actual order of
3105	 the sections in the file is unimportant.  */
3106      for (i = 1, hdrpp = i_shdrpp + 1; i < i_ehdrp->e_shnum; i++, hdrpp++)
3107	{
3108	  Elf_Internal_Shdr *hdr;
3109
3110	  hdr = *hdrpp;
3111	  if (hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
3112	    {
3113	      hdr->sh_offset = -1;
3114	      continue;
3115	    }
3116	  if (i == tdata->symtab_section
3117	      || i == tdata->strtab_section)
3118	    {
3119	      hdr->sh_offset = -1;
3120	      continue;
3121	    }
3122
3123	  off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3124	}
3125    }
3126  else
3127    {
3128      unsigned int i;
3129      Elf_Internal_Shdr **hdrpp;
3130
3131      /* Assign file positions for the loaded sections based on the
3132         assignment of sections to segments.  */
3133      if (! assign_file_positions_for_segments (abfd))
3134	return false;
3135
3136      /* Assign file positions for the other sections.  */
3137
3138      off = elf_tdata (abfd)->next_file_pos;
3139      for (i = 1, hdrpp = i_shdrpp + 1; i < i_ehdrp->e_shnum; i++, hdrpp++)
3140	{
3141	  Elf_Internal_Shdr *hdr;
3142
3143	  hdr = *hdrpp;
3144	  if (hdr->bfd_section != NULL
3145	      && hdr->bfd_section->filepos != 0)
3146	    hdr->sh_offset = hdr->bfd_section->filepos;
3147	  else if ((hdr->sh_flags & SHF_ALLOC) != 0)
3148	    {
3149	      ((*_bfd_error_handler)
3150	       (_("%s: warning: allocated section `%s' not in segment"),
3151		bfd_get_filename (abfd),
3152		(hdr->bfd_section == NULL
3153		 ? "*unknown*"
3154		 : hdr->bfd_section->name)));
3155	      if ((abfd->flags & D_PAGED) != 0)
3156		off += (hdr->sh_addr - off) % bed->maxpagesize;
3157	      else
3158		off += (hdr->sh_addr - off) % hdr->sh_addralign;
3159	      off = _bfd_elf_assign_file_position_for_section (hdr, off,
3160							       false);
3161	    }
3162	  else if (hdr->sh_type == SHT_REL
3163		   || hdr->sh_type == SHT_RELA
3164		   || hdr == i_shdrpp[tdata->symtab_section]
3165		   || hdr == i_shdrpp[tdata->strtab_section])
3166	    hdr->sh_offset = -1;
3167	  else
3168	    off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3169	}
3170    }
3171
3172  /* Place the section headers.  */
3173  off = align_file_position (off, bed->s->file_align);
3174  i_ehdrp->e_shoff = off;
3175  off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
3176
3177  elf_tdata (abfd)->next_file_pos = off;
3178
3179  return true;
3180}
3181
3182static boolean
3183prep_headers (abfd)
3184     bfd *abfd;
3185{
3186  Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form */
3187  Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
3188  Elf_Internal_Shdr **i_shdrp;	/* Section header table, internal form */
3189  int count;
3190  struct bfd_strtab_hash *shstrtab;
3191  struct elf_backend_data *bed = get_elf_backend_data (abfd);
3192
3193  i_ehdrp = elf_elfheader (abfd);
3194  i_shdrp = elf_elfsections (abfd);
3195
3196  shstrtab = _bfd_elf_stringtab_init ();
3197  if (shstrtab == NULL)
3198    return false;
3199
3200  elf_shstrtab (abfd) = shstrtab;
3201
3202  i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
3203  i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
3204  i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
3205  i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
3206
3207  i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
3208  i_ehdrp->e_ident[EI_DATA] =
3209    bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
3210  i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
3211
3212  i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
3213  i_ehdrp->e_ident[EI_ABIVERSION] = 0;
3214
3215  for (count = EI_PAD; count < EI_NIDENT; count++)
3216    i_ehdrp->e_ident[count] = 0;
3217
3218#ifdef __FreeBSD__
3219/* #ifdef BRANDELF_CHANGE_BOOTSTRAP */
3220#define _OLD_EI_BRAND_OFFSET 8
3221#define _OLD_BRANDING	"FreeBSD"
3222  strncpy((char *) &i_ehdrp->e_ident[_OLD_EI_BRAND_OFFSET], _OLD_BRANDING,
3223	  EI_NIDENT-_OLD_EI_BRAND_OFFSET);
3224/* #endif */
3225#endif
3226
3227  if ((abfd->flags & DYNAMIC) != 0)
3228    i_ehdrp->e_type = ET_DYN;
3229  else if ((abfd->flags & EXEC_P) != 0)
3230    i_ehdrp->e_type = ET_EXEC;
3231  else if (bfd_get_format (abfd) == bfd_core)
3232    i_ehdrp->e_type = ET_CORE;
3233  else
3234    i_ehdrp->e_type = ET_REL;
3235
3236  switch (bfd_get_arch (abfd))
3237    {
3238    case bfd_arch_unknown:
3239      i_ehdrp->e_machine = EM_NONE;
3240      break;
3241    case bfd_arch_sparc:
3242      if (bed->s->arch_size == 64)
3243	i_ehdrp->e_machine = EM_SPARCV9;
3244      else
3245	i_ehdrp->e_machine = EM_SPARC;
3246      break;
3247    case bfd_arch_i370:
3248      i_ehdrp->e_machine = EM_S370;
3249      break;
3250    case bfd_arch_i386:
3251      i_ehdrp->e_machine = EM_386;
3252      break;
3253    case bfd_arch_m68k:
3254      i_ehdrp->e_machine = EM_68K;
3255      break;
3256    case bfd_arch_m88k:
3257      i_ehdrp->e_machine = EM_88K;
3258      break;
3259    case bfd_arch_i860:
3260      i_ehdrp->e_machine = EM_860;
3261      break;
3262    case bfd_arch_i960:
3263      i_ehdrp->e_machine = EM_960;
3264      break;
3265    case bfd_arch_mips:	/* MIPS Rxxxx */
3266      i_ehdrp->e_machine = EM_MIPS;	/* only MIPS R3000 */
3267      break;
3268    case bfd_arch_hppa:
3269      i_ehdrp->e_machine = EM_PARISC;
3270      break;
3271    case bfd_arch_powerpc:
3272      i_ehdrp->e_machine = EM_PPC;
3273      break;
3274    case bfd_arch_alpha:
3275      i_ehdrp->e_machine = EM_ALPHA;
3276      break;
3277    case bfd_arch_sh:
3278      i_ehdrp->e_machine = EM_SH;
3279      break;
3280    case bfd_arch_d10v:
3281      i_ehdrp->e_machine = EM_CYGNUS_D10V;
3282      break;
3283    case bfd_arch_d30v:
3284      i_ehdrp->e_machine = EM_CYGNUS_D30V;
3285      break;
3286    case bfd_arch_fr30:
3287      i_ehdrp->e_machine = EM_CYGNUS_FR30;
3288      break;
3289    case bfd_arch_mcore:
3290      i_ehdrp->e_machine = EM_MCORE;
3291      break;
3292    case bfd_arch_avr:
3293      i_ehdrp->e_machine = EM_AVR;
3294      break;
3295    case bfd_arch_v850:
3296      switch (bfd_get_mach (abfd))
3297	{
3298	default:
3299	case 0:               i_ehdrp->e_machine = EM_CYGNUS_V850; break;
3300	}
3301      break;
3302   case bfd_arch_arc:
3303      i_ehdrp->e_machine = EM_CYGNUS_ARC;
3304      break;
3305   case bfd_arch_arm:
3306      i_ehdrp->e_machine = EM_ARM;
3307      break;
3308    case bfd_arch_m32r:
3309      i_ehdrp->e_machine = EM_CYGNUS_M32R;
3310      break;
3311    case bfd_arch_mn10200:
3312      i_ehdrp->e_machine = EM_CYGNUS_MN10200;
3313      break;
3314    case bfd_arch_mn10300:
3315      i_ehdrp->e_machine = EM_CYGNUS_MN10300;
3316      break;
3317    case bfd_arch_pj:
3318      i_ehdrp->e_machine = EM_PJ;
3319      break;
3320      /* also note that EM_M32, AT&T WE32100 is unknown to bfd */
3321    default:
3322      i_ehdrp->e_machine = EM_NONE;
3323    }
3324  i_ehdrp->e_version = bed->s->ev_current;
3325  i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
3326
3327  /* no program header, for now. */
3328  i_ehdrp->e_phoff = 0;
3329  i_ehdrp->e_phentsize = 0;
3330  i_ehdrp->e_phnum = 0;
3331
3332  /* each bfd section is section header entry */
3333  i_ehdrp->e_entry = bfd_get_start_address (abfd);
3334  i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
3335
3336  /* if we're building an executable, we'll need a program header table */
3337  if (abfd->flags & EXEC_P)
3338    {
3339      /* it all happens later */
3340#if 0
3341      i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
3342
3343      /* elf_build_phdrs() returns a (NULL-terminated) array of
3344	 Elf_Internal_Phdrs */
3345      i_phdrp = elf_build_phdrs (abfd, i_ehdrp, i_shdrp, &i_ehdrp->e_phnum);
3346      i_ehdrp->e_phoff = outbase;
3347      outbase += i_ehdrp->e_phentsize * i_ehdrp->e_phnum;
3348#endif
3349    }
3350  else
3351    {
3352      i_ehdrp->e_phentsize = 0;
3353      i_phdrp = 0;
3354      i_ehdrp->e_phoff = 0;
3355    }
3356
3357  elf_tdata (abfd)->symtab_hdr.sh_name =
3358    (unsigned int) _bfd_stringtab_add (shstrtab, ".symtab", true, false);
3359  elf_tdata (abfd)->strtab_hdr.sh_name =
3360    (unsigned int) _bfd_stringtab_add (shstrtab, ".strtab", true, false);
3361  elf_tdata (abfd)->shstrtab_hdr.sh_name =
3362    (unsigned int) _bfd_stringtab_add (shstrtab, ".shstrtab", true, false);
3363  if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
3364      || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
3365      || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
3366    return false;
3367
3368  return true;
3369}
3370
3371/* Assign file positions for all the reloc sections which are not part
3372   of the loadable file image.  */
3373
3374void
3375_bfd_elf_assign_file_positions_for_relocs (abfd)
3376     bfd *abfd;
3377{
3378  file_ptr off;
3379  unsigned int i;
3380  Elf_Internal_Shdr **shdrpp;
3381
3382  off = elf_tdata (abfd)->next_file_pos;
3383
3384  for (i = 1, shdrpp = elf_elfsections (abfd) + 1;
3385       i < elf_elfheader (abfd)->e_shnum;
3386       i++, shdrpp++)
3387    {
3388      Elf_Internal_Shdr *shdrp;
3389
3390      shdrp = *shdrpp;
3391      if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
3392	  && shdrp->sh_offset == -1)
3393	off = _bfd_elf_assign_file_position_for_section (shdrp, off, true);
3394    }
3395
3396  elf_tdata (abfd)->next_file_pos = off;
3397}
3398
3399boolean
3400_bfd_elf_write_object_contents (abfd)
3401     bfd *abfd;
3402{
3403  struct elf_backend_data *bed = get_elf_backend_data (abfd);
3404  Elf_Internal_Ehdr *i_ehdrp;
3405  Elf_Internal_Shdr **i_shdrp;
3406  boolean failed;
3407  unsigned int count;
3408
3409  if (! abfd->output_has_begun
3410      && ! _bfd_elf_compute_section_file_positions
3411             (abfd, (struct bfd_link_info *) NULL))
3412    return false;
3413
3414  i_shdrp = elf_elfsections (abfd);
3415  i_ehdrp = elf_elfheader (abfd);
3416
3417  failed = false;
3418  bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
3419  if (failed)
3420    return false;
3421
3422  _bfd_elf_assign_file_positions_for_relocs (abfd);
3423
3424  /* After writing the headers, we need to write the sections too... */
3425  for (count = 1; count < i_ehdrp->e_shnum; count++)
3426    {
3427      if (bed->elf_backend_section_processing)
3428	(*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
3429      if (i_shdrp[count]->contents)
3430	{
3431	  if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
3432	      || (bfd_write (i_shdrp[count]->contents, i_shdrp[count]->sh_size,
3433			     1, abfd)
3434		  != i_shdrp[count]->sh_size))
3435	    return false;
3436	}
3437    }
3438
3439  /* Write out the section header names.  */
3440  if (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
3441      || ! _bfd_stringtab_emit (abfd, elf_shstrtab (abfd)))
3442    return false;
3443
3444  if (bed->elf_backend_final_write_processing)
3445    (*bed->elf_backend_final_write_processing) (abfd,
3446						elf_tdata (abfd)->linker);
3447
3448  return bed->s->write_shdrs_and_ehdr (abfd);
3449}
3450
3451boolean
3452_bfd_elf_write_corefile_contents (abfd)
3453     bfd *abfd;
3454{
3455  /* Hopefully this can be done just like an object file. */
3456  return _bfd_elf_write_object_contents (abfd);
3457}
3458/* given a section, search the header to find them... */
3459int
3460_bfd_elf_section_from_bfd_section (abfd, asect)
3461     bfd *abfd;
3462     struct sec *asect;
3463{
3464  struct elf_backend_data *bed = get_elf_backend_data (abfd);
3465  Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
3466  int index;
3467  Elf_Internal_Shdr *hdr;
3468  int maxindex = elf_elfheader (abfd)->e_shnum;
3469
3470  for (index = 0; index < maxindex; index++)
3471    {
3472      hdr = i_shdrp[index];
3473      if (hdr->bfd_section == asect)
3474	return index;
3475    }
3476
3477  if (bed->elf_backend_section_from_bfd_section)
3478    {
3479      for (index = 0; index < maxindex; index++)
3480	{
3481	  int retval;
3482
3483	  hdr = i_shdrp[index];
3484	  retval = index;
3485	  if ((*bed->elf_backend_section_from_bfd_section)
3486	      (abfd, hdr, asect, &retval))
3487	    return retval;
3488	}
3489    }
3490
3491  if (bfd_is_abs_section (asect))
3492    return SHN_ABS;
3493  if (bfd_is_com_section (asect))
3494    return SHN_COMMON;
3495  if (bfd_is_und_section (asect))
3496    return SHN_UNDEF;
3497
3498  bfd_set_error (bfd_error_nonrepresentable_section);
3499
3500  return -1;
3501}
3502
3503/* Given a BFD symbol, return the index in the ELF symbol table, or -1
3504   on error.  */
3505
3506int
3507_bfd_elf_symbol_from_bfd_symbol (abfd, asym_ptr_ptr)
3508     bfd *abfd;
3509     asymbol **asym_ptr_ptr;
3510{
3511  asymbol *asym_ptr = *asym_ptr_ptr;
3512  int idx;
3513  flagword flags = asym_ptr->flags;
3514
3515  /* When gas creates relocations against local labels, it creates its
3516     own symbol for the section, but does put the symbol into the
3517     symbol chain, so udata is 0.  When the linker is generating
3518     relocatable output, this section symbol may be for one of the
3519     input sections rather than the output section.  */
3520  if (asym_ptr->udata.i == 0
3521      && (flags & BSF_SECTION_SYM)
3522      && asym_ptr->section)
3523    {
3524      int indx;
3525
3526      if (asym_ptr->section->output_section != NULL)
3527	indx = asym_ptr->section->output_section->index;
3528      else
3529	indx = asym_ptr->section->index;
3530      if (elf_section_syms (abfd)[indx])
3531	asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
3532    }
3533
3534  idx = asym_ptr->udata.i;
3535
3536  if (idx == 0)
3537    {
3538      /* This case can occur when using --strip-symbol on a symbol
3539         which is used in a relocation entry.  */
3540      (*_bfd_error_handler)
3541	(_("%s: symbol `%s' required but not present"),
3542	 bfd_get_filename (abfd), bfd_asymbol_name (asym_ptr));
3543      bfd_set_error (bfd_error_no_symbols);
3544      return -1;
3545    }
3546
3547#if DEBUG & 4
3548  {
3549    fprintf (stderr,
3550	     _("elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx%s\n"),
3551	     (long) asym_ptr, asym_ptr->name, idx, flags,
3552	     elf_symbol_flags (flags));
3553    fflush (stderr);
3554  }
3555#endif
3556
3557  return idx;
3558}
3559
3560/* Copy private BFD data.  This copies any program header information.  */
3561
3562static boolean
3563copy_private_bfd_data (ibfd, obfd)
3564     bfd *ibfd;
3565     bfd *obfd;
3566{
3567  Elf_Internal_Ehdr *iehdr;
3568  struct elf_segment_map *mfirst;
3569  struct elf_segment_map **pm;
3570  struct elf_segment_map *m;
3571  Elf_Internal_Phdr *p;
3572  unsigned int i;
3573  unsigned int num_segments;
3574  boolean phdr_included = false;
3575
3576  if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
3577      || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
3578    return true;
3579
3580  if (elf_tdata (ibfd)->phdr == NULL)
3581    return true;
3582
3583  iehdr = elf_elfheader (ibfd);
3584
3585  mfirst = NULL;
3586  pm = &mfirst;
3587
3588  num_segments = elf_elfheader (ibfd)->e_phnum;
3589
3590#define IS_CONTAINED_BY(addr, len, bottom, phdr)		 	\
3591	  ((addr) >= (bottom)				 	  	\
3592	   && (   ((addr) + (len)) <= ((bottom) + (phdr)->p_memsz)	\
3593	       || ((addr) + (len)) <= ((bottom) + (phdr)->p_filesz)))
3594
3595  /* Special case: corefile "NOTE" section containing regs, prpsinfo etc. */
3596
3597#define IS_COREFILE_NOTE(p, s)                                          \
3598	    (p->p_type == PT_NOTE                                       \
3599	     && bfd_get_format (ibfd) == bfd_core                       \
3600	     && s->vma == 0 && s->lma == 0                              \
3601	     && (bfd_vma) s->filepos >= p->p_offset                     \
3602	     && (bfd_vma) s->filepos + s->_raw_size                     \
3603	     <= p->p_offset + p->p_filesz)
3604
3605  /* The complicated case when p_vaddr is 0 is to handle the Solaris
3606     linker, which generates a PT_INTERP section with p_vaddr and
3607     p_memsz set to 0.  */
3608
3609#define IS_SOLARIS_PT_INTERP(p, s)					\
3610	    (p->p_vaddr == 0						\
3611	     && p->p_filesz > 0						\
3612	     && (s->flags & SEC_HAS_CONTENTS) != 0			\
3613	     && s->_raw_size > 0					\
3614	     && (bfd_vma) s->filepos >= p->p_offset			\
3615	     && ((bfd_vma) s->filepos + s->_raw_size			\
3616		     <= p->p_offset + p->p_filesz))
3617
3618  /* Scan through the segments specified in the program header
3619     of the input BFD.  */
3620  for (i = 0, p = elf_tdata (ibfd)->phdr; i < num_segments; i++, p++)
3621    {
3622      unsigned int csecs;
3623      asection *s;
3624      asection **sections;
3625      asection *os;
3626      unsigned int isec;
3627      bfd_vma matching_lma;
3628      bfd_vma suggested_lma;
3629      unsigned int j;
3630
3631      /* For each section in the input BFD, decide if it should be
3632	 included in the current segment.  A section will be included
3633	 if it is within the address space of the segment, and it is
3634	 an allocated segment, and there is an output section
3635	 associated with it.  */
3636      csecs = 0;
3637      for (s = ibfd->sections; s != NULL; s = s->next)
3638	if (s->output_section != NULL)
3639	  {
3640	    if ((IS_CONTAINED_BY (s->vma, s->_raw_size, p->p_vaddr, p)
3641		 || IS_SOLARIS_PT_INTERP (p, s))
3642		&& (s->flags & SEC_ALLOC) != 0)
3643	      ++csecs;
3644	    else if (IS_COREFILE_NOTE (p, s))
3645	      ++csecs;
3646	  }
3647
3648      /* Allocate a segment map big enough to contain all of the
3649	 sections we have selected.  */
3650      m = ((struct elf_segment_map *)
3651	   bfd_alloc (obfd,
3652		      (sizeof (struct elf_segment_map)
3653		       + ((size_t) csecs - 1) * sizeof (asection *))));
3654      if (m == NULL)
3655	return false;
3656
3657      /* Initialise the fields of the segment map.  Default to
3658	 using the physical address of the segment in the input BFD.  */
3659      m->next          = NULL;
3660      m->p_type        = p->p_type;
3661      m->p_flags       = p->p_flags;
3662      m->p_flags_valid = 1;
3663      m->p_paddr       = p->p_paddr;
3664      m->p_paddr_valid = 1;
3665
3666      /* Determine if this segment contains the ELF file header
3667	 and if it contains the program headers themselves.  */
3668      m->includes_filehdr = (p->p_offset == 0
3669			     && p->p_filesz >= iehdr->e_ehsize);
3670
3671      m->includes_phdrs = 0;
3672
3673      if (! phdr_included || p->p_type != PT_LOAD)
3674	{
3675	  m->includes_phdrs =
3676	    (p->p_offset <= (bfd_vma) iehdr->e_phoff
3677	     && (p->p_offset + p->p_filesz
3678		 >= ((bfd_vma) iehdr->e_phoff
3679		     + iehdr->e_phnum * iehdr->e_phentsize)));
3680	  if (p->p_type == PT_LOAD && m->includes_phdrs)
3681	    phdr_included = true;
3682	}
3683
3684      if (csecs == 0)
3685	{
3686	  /* Special segments, such as the PT_PHDR segment, may contain
3687	     no sections, but ordinary, loadable segments should contain
3688	     something.  */
3689
3690	  if (p->p_type == PT_LOAD)
3691	      _bfd_error_handler
3692		(_("%s: warning: Empty loadable segment detected\n"),
3693		 bfd_get_filename (ibfd));
3694
3695	  m->count = 0;
3696	  *pm = m;
3697	  pm = &m->next;
3698
3699	  continue;
3700	}
3701
3702      /* Now scan the sections in the input BFD again and attempt
3703	 to add their corresponding output sections to the segment map.
3704	 The problem here is how to handle an output section which has
3705	 been moved (ie had its LMA changed).  There are four possibilities:
3706
3707	 1. None of the sections have been moved.
3708	    In this case we can continue to use the segment LMA from the
3709	    input BFD.
3710
3711	 2. All of the sections have been moved by the same amount.
3712	    In this case we can change the segment's LMA to match the LMA
3713	    of the first section.
3714
3715	 3. Some of the sections have been moved, others have not.
3716	    In this case those sections which have not been moved can be
3717	    placed in the current segment which will have to have its size,
3718	    and possibly its LMA changed, and a new segment or segments will
3719	    have to be created to contain the other sections.
3720
3721	 4. The sections have been moved, but not be the same amount.
3722	    In this case we can change the segment's LMA to match the LMA
3723	    of the first section and we will have to create a new segment
3724	    or segments to contain the other sections.
3725
3726	 In order to save time, we allocate an array to hold the section
3727	 pointers that we are interested in.  As these sections get assigned
3728	 to a segment, they are removed from this array.  */
3729
3730      sections = (asection **) bfd_malloc (sizeof (asection *) * csecs);
3731      if (sections == NULL)
3732	return false;
3733
3734      /* Step One: Scan for segment vs section LMA conflicts.
3735	 Also add the sections to the section array allocated above.
3736	 Also add the sections to the current segment.  In the common
3737	 case, where the sections have not been moved, this means that
3738	 we have completely filled the segment, and there is nothing
3739	 more to do.  */
3740
3741      isec = 0;
3742      matching_lma = 0;
3743      suggested_lma = 0;
3744
3745      for (j = 0, s = ibfd->sections; s != NULL; s = s->next)
3746	{
3747	  os = s->output_section;
3748
3749	  if ((((IS_CONTAINED_BY (s->vma, s->_raw_size, p->p_vaddr, p)
3750		 || IS_SOLARIS_PT_INTERP (p, s))
3751		&& (s->flags & SEC_ALLOC) != 0)
3752	       || IS_COREFILE_NOTE (p, s))
3753	      && os != NULL)
3754	    {
3755	      sections[j++] = s;
3756
3757	      /* The Solaris native linker always sets p_paddr to 0.
3758		 We try to catch that case here, and set it to the
3759		 correct value.  */
3760	      if (p->p_paddr == 0
3761		  && p->p_vaddr != 0
3762		  && isec == 0
3763		  && os->lma != 0
3764		  && (os->vma == (p->p_vaddr
3765				  + (m->includes_filehdr
3766				     ? iehdr->e_ehsize
3767				     : 0)
3768				  + (m->includes_phdrs
3769				     ? iehdr->e_phnum * iehdr->e_phentsize
3770				     : 0))))
3771		m->p_paddr = p->p_vaddr;
3772
3773	      /* Match up the physical address of the segment with the
3774		 LMA address of the output section.  */
3775	      if (IS_CONTAINED_BY (os->lma, os->_raw_size, m->p_paddr, p)
3776		  || IS_COREFILE_NOTE (p, s))
3777		{
3778		  if (matching_lma == 0)
3779		    matching_lma = os->lma;
3780
3781		  /* We assume that if the section fits within the segment
3782		     that it does not overlap any other section within that
3783		     segment.  */
3784		  m->sections[isec++] = os;
3785		}
3786	      else if (suggested_lma == 0)
3787		suggested_lma = os->lma;
3788	    }
3789	}
3790
3791      BFD_ASSERT (j == csecs);
3792
3793      /* Step Two: Adjust the physical address of the current segment,
3794	 if necessary.  */
3795      if (isec == csecs)
3796	{
3797	  /* All of the sections fitted within the segment as currently
3798	     specified.  This is the default case.  Add the segment to
3799	     the list of built segments and carry on to process the next
3800	     program header in the input BFD.  */
3801	  m->count = csecs;
3802	  *pm = m;
3803	  pm = &m->next;
3804
3805	  free (sections);
3806	  continue;
3807	}
3808      else
3809	{
3810	  if (matching_lma != 0)
3811	    {
3812	      /* At least one section fits inside the current segment.
3813		 Keep it, but modify its physical address to match the
3814		 LMA of the first section that fitted.  */
3815
3816	      m->p_paddr = matching_lma;
3817	    }
3818	  else
3819	    {
3820	      /* None of the sections fitted inside the current segment.
3821		 Change the current segment's physical address to match
3822		 the LMA of the first section.  */
3823
3824	      m->p_paddr = suggested_lma;
3825	    }
3826
3827	  /* Offset the segment physical address from the lma to allow
3828	     for space taken up by elf headers.  */
3829	  if (m->includes_filehdr)
3830	    m->p_paddr -= iehdr->e_ehsize;
3831
3832	  if (m->includes_phdrs)
3833	    m->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
3834	}
3835
3836      /* Step Three: Loop over the sections again, this time assigning
3837	 those that fit to the current segment and remvoing them from the
3838	 sections array; but making sure not to leave large gaps.  Once all
3839	 possible sections have been assigned to the current segment it is
3840	 added to the list of built segments and if sections still remain
3841	 to be assigned, a new segment is constructed before repeating
3842	 the loop.  */
3843      isec = 0;
3844      do
3845	{
3846	  m->count = 0;
3847	  suggested_lma = 0;
3848
3849	  /* Fill the current segment with sections that fit.  */
3850	  for (j = 0; j < csecs; j++)
3851	    {
3852	      s = sections[j];
3853
3854	      if (s == NULL)
3855		continue;
3856
3857	      os = s->output_section;
3858
3859	      if (IS_CONTAINED_BY (os->lma, os->_raw_size, m->p_paddr, p)
3860		  || IS_COREFILE_NOTE (p, s))
3861		{
3862		  if (m->count == 0)
3863		    {
3864		      /* If the first section in a segment does not start at
3865			 the beginning of the segment, then something is wrong.  */
3866		      if (os->lma != (m->p_paddr
3867				      + (m->includes_filehdr
3868					 ? iehdr->e_ehsize : 0)
3869				      + (m->includes_phdrs
3870					 ? iehdr->e_phnum * iehdr->e_phentsize
3871					 : 0)))
3872			abort ();
3873		    }
3874		  else
3875		    {
3876		      asection * prev_sec;
3877		      bfd_vma maxpagesize;
3878
3879		      prev_sec = m->sections[m->count - 1];
3880		      maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
3881
3882		      /* If the gap between the end of the previous section
3883			 and the start of this section is more than maxpagesize
3884			 then we need to start a new segment.  */
3885		      if (BFD_ALIGN (prev_sec->lma + prev_sec->_raw_size, maxpagesize)
3886			  < BFD_ALIGN (os->lma, maxpagesize))
3887			{
3888			  if (suggested_lma == 0)
3889			    suggested_lma = os->lma;
3890
3891			  continue;
3892			}
3893		    }
3894
3895		  m->sections[m->count++] = os;
3896		  ++isec;
3897		  sections[j] = NULL;
3898		}
3899	      else if (suggested_lma == 0)
3900		suggested_lma = os->lma;
3901	    }
3902
3903	  BFD_ASSERT (m->count > 0);
3904
3905	  /* Add the current segment to the list of built segments.  */
3906	  *pm = m;
3907	  pm = &m->next;
3908
3909	  if (isec < csecs)
3910	    {
3911	      /* We still have not allocated all of the sections to
3912		 segments.  Create a new segment here, initialise it
3913		 and carry on looping.  */
3914
3915	      m = ((struct elf_segment_map *)
3916		   bfd_alloc (obfd,
3917			      (sizeof (struct elf_segment_map)
3918			       + ((size_t) csecs - 1) * sizeof (asection *))));
3919	      if (m == NULL)
3920		return false;
3921
3922	      /* Initialise the fields of the segment map.  Set the physical
3923		 physical address to the LMA of the first section that has
3924		 not yet been assigned.  */
3925
3926	      m->next             = NULL;
3927	      m->p_type           = p->p_type;
3928	      m->p_flags          = p->p_flags;
3929	      m->p_flags_valid    = 1;
3930	      m->p_paddr          = suggested_lma;
3931	      m->p_paddr_valid    = 1;
3932	      m->includes_filehdr = 0;
3933	      m->includes_phdrs   = 0;
3934	    }
3935	}
3936      while (isec < csecs);
3937
3938      free (sections);
3939    }
3940
3941  /* The Solaris linker creates program headers in which all the
3942     p_paddr fields are zero.  When we try to objcopy or strip such a
3943     file, we get confused.  Check for this case, and if we find it
3944     reset the p_paddr_valid fields.  */
3945  for (m = mfirst; m != NULL; m = m->next)
3946    if (m->p_paddr != 0)
3947      break;
3948  if (m == NULL)
3949    {
3950      for (m = mfirst; m != NULL; m = m->next)
3951	m->p_paddr_valid = 0;
3952    }
3953
3954  elf_tdata (obfd)->segment_map = mfirst;
3955
3956#if 0
3957  /* Final Step: Sort the segments into ascending order of physical address. */
3958  if (mfirst != NULL)
3959    {
3960      struct elf_segment_map* prev;
3961
3962      prev = mfirst;
3963      for (m = mfirst->next; m != NULL; prev = m, m = m->next)
3964	{
3965	  /* Yes I know - its a bubble sort....*/
3966	  if (m->next != NULL && (m->next->p_paddr < m->p_paddr))
3967	    {
3968	      /* swap m and m->next */
3969	      prev->next = m->next;
3970	      m->next = m->next->next;
3971	      prev->next->next = m;
3972
3973	      /* restart loop. */
3974	      m = mfirst;
3975	    }
3976	}
3977    }
3978#endif
3979
3980#undef IS_CONTAINED_BY
3981#undef IS_SOLARIS_PT_INTERP
3982#undef IS_COREFILE_NOTE
3983  return true;
3984}
3985
3986/* Copy private section information.  This copies over the entsize
3987   field, and sometimes the info field.  */
3988
3989boolean
3990_bfd_elf_copy_private_section_data (ibfd, isec, obfd, osec)
3991     bfd *ibfd;
3992     asection *isec;
3993     bfd *obfd;
3994     asection *osec;
3995{
3996  Elf_Internal_Shdr *ihdr, *ohdr;
3997
3998  if (ibfd->xvec->flavour != bfd_target_elf_flavour
3999      || obfd->xvec->flavour != bfd_target_elf_flavour)
4000    return true;
4001
4002  /* Copy over private BFD data if it has not already been copied.
4003     This must be done here, rather than in the copy_private_bfd_data
4004     entry point, because the latter is called after the section
4005     contents have been set, which means that the program headers have
4006     already been worked out.  */
4007  if (elf_tdata (obfd)->segment_map == NULL
4008      && elf_tdata (ibfd)->phdr != NULL)
4009    {
4010      asection *s;
4011
4012      /* Only set up the segments if there are no more SEC_ALLOC
4013         sections.  FIXME: This won't do the right thing if objcopy is
4014         used to remove the last SEC_ALLOC section, since objcopy
4015         won't call this routine in that case.  */
4016      for (s = isec->next; s != NULL; s = s->next)
4017	if ((s->flags & SEC_ALLOC) != 0)
4018	  break;
4019      if (s == NULL)
4020	{
4021	  if (! copy_private_bfd_data (ibfd, obfd))
4022	    return false;
4023	}
4024    }
4025
4026  ihdr = &elf_section_data (isec)->this_hdr;
4027  ohdr = &elf_section_data (osec)->this_hdr;
4028
4029  ohdr->sh_entsize = ihdr->sh_entsize;
4030
4031  if (ihdr->sh_type == SHT_SYMTAB
4032      || ihdr->sh_type == SHT_DYNSYM
4033      || ihdr->sh_type == SHT_GNU_verneed
4034      || ihdr->sh_type == SHT_GNU_verdef)
4035    ohdr->sh_info = ihdr->sh_info;
4036
4037  elf_section_data (osec)->use_rela_p
4038    = elf_section_data (isec)->use_rela_p;
4039
4040  return true;
4041}
4042
4043/* Copy private symbol information.  If this symbol is in a section
4044   which we did not map into a BFD section, try to map the section
4045   index correctly.  We use special macro definitions for the mapped
4046   section indices; these definitions are interpreted by the
4047   swap_out_syms function.  */
4048
4049#define MAP_ONESYMTAB (SHN_LORESERVE - 1)
4050#define MAP_DYNSYMTAB (SHN_LORESERVE - 2)
4051#define MAP_STRTAB (SHN_LORESERVE - 3)
4052#define MAP_SHSTRTAB (SHN_LORESERVE - 4)
4053
4054boolean
4055_bfd_elf_copy_private_symbol_data (ibfd, isymarg, obfd, osymarg)
4056     bfd *ibfd;
4057     asymbol *isymarg;
4058     bfd *obfd;
4059     asymbol *osymarg;
4060{
4061  elf_symbol_type *isym, *osym;
4062
4063  if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
4064      || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
4065    return true;
4066
4067  isym = elf_symbol_from (ibfd, isymarg);
4068  osym = elf_symbol_from (obfd, osymarg);
4069
4070  if (isym != NULL
4071      && osym != NULL
4072      && bfd_is_abs_section (isym->symbol.section))
4073    {
4074      unsigned int shndx;
4075
4076      shndx = isym->internal_elf_sym.st_shndx;
4077      if (shndx == elf_onesymtab (ibfd))
4078	shndx = MAP_ONESYMTAB;
4079      else if (shndx == elf_dynsymtab (ibfd))
4080	shndx = MAP_DYNSYMTAB;
4081      else if (shndx == elf_tdata (ibfd)->strtab_section)
4082	shndx = MAP_STRTAB;
4083      else if (shndx == elf_tdata (ibfd)->shstrtab_section)
4084	shndx = MAP_SHSTRTAB;
4085      osym->internal_elf_sym.st_shndx = shndx;
4086    }
4087
4088  return true;
4089}
4090
4091/* Swap out the symbols.  */
4092
4093static boolean
4094swap_out_syms (abfd, sttp, relocatable_p)
4095     bfd *abfd;
4096     struct bfd_strtab_hash **sttp;
4097     int relocatable_p;
4098{
4099  struct elf_backend_data *bed = get_elf_backend_data (abfd);
4100
4101  if (!elf_map_symbols (abfd))
4102    return false;
4103
4104  /* Dump out the symtabs. */
4105  {
4106    int symcount = bfd_get_symcount (abfd);
4107    asymbol **syms = bfd_get_outsymbols (abfd);
4108    struct bfd_strtab_hash *stt;
4109    Elf_Internal_Shdr *symtab_hdr;
4110    Elf_Internal_Shdr *symstrtab_hdr;
4111    char *outbound_syms;
4112    int idx;
4113
4114    stt = _bfd_elf_stringtab_init ();
4115    if (stt == NULL)
4116      return false;
4117
4118    symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
4119    symtab_hdr->sh_type = SHT_SYMTAB;
4120    symtab_hdr->sh_entsize = bed->s->sizeof_sym;
4121    symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
4122    symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
4123    symtab_hdr->sh_addralign = bed->s->file_align;
4124
4125    symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
4126    symstrtab_hdr->sh_type = SHT_STRTAB;
4127
4128    outbound_syms = bfd_alloc (abfd,
4129			       (1 + symcount) * bed->s->sizeof_sym);
4130    if (outbound_syms == NULL)
4131      return false;
4132    symtab_hdr->contents = (PTR) outbound_syms;
4133
4134    /* now generate the data (for "contents") */
4135    {
4136      /* Fill in zeroth symbol and swap it out.  */
4137      Elf_Internal_Sym sym;
4138      sym.st_name = 0;
4139      sym.st_value = 0;
4140      sym.st_size = 0;
4141      sym.st_info = 0;
4142      sym.st_other = 0;
4143      sym.st_shndx = SHN_UNDEF;
4144      bed->s->swap_symbol_out (abfd, &sym, (PTR) outbound_syms);
4145      outbound_syms += bed->s->sizeof_sym;
4146    }
4147    for (idx = 0; idx < symcount; idx++)
4148      {
4149	Elf_Internal_Sym sym;
4150	bfd_vma value = syms[idx]->value;
4151	elf_symbol_type *type_ptr;
4152	flagword flags = syms[idx]->flags;
4153	int type;
4154
4155	if (flags & BSF_SECTION_SYM)
4156	  /* Section symbols have no names.  */
4157	  sym.st_name = 0;
4158	else
4159	  {
4160	    sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
4161							      syms[idx]->name,
4162							      true, false);
4163	    if (sym.st_name == (unsigned long) -1)
4164	      return false;
4165	  }
4166
4167	type_ptr = elf_symbol_from (abfd, syms[idx]);
4168
4169	if ((flags & BSF_SECTION_SYM) == 0
4170	    && bfd_is_com_section (syms[idx]->section))
4171	  {
4172	    /* ELF common symbols put the alignment into the `value' field,
4173	       and the size into the `size' field.  This is backwards from
4174	       how BFD handles it, so reverse it here.  */
4175	    sym.st_size = value;
4176	    if (type_ptr == NULL
4177		|| type_ptr->internal_elf_sym.st_value == 0)
4178	      sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
4179	    else
4180	      sym.st_value = type_ptr->internal_elf_sym.st_value;
4181	    sym.st_shndx = _bfd_elf_section_from_bfd_section
4182	      (abfd, syms[idx]->section);
4183	  }
4184	else
4185	  {
4186	    asection *sec = syms[idx]->section;
4187	    int shndx;
4188
4189	    if (sec->output_section)
4190	      {
4191		value += sec->output_offset;
4192		sec = sec->output_section;
4193	      }
4194	    /* Don't add in the section vma for relocatable output.  */
4195	    if (! relocatable_p)
4196	      value += sec->vma;
4197	    sym.st_value = value;
4198	    sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
4199
4200	    if (bfd_is_abs_section (sec)
4201		&& type_ptr != NULL
4202		&& type_ptr->internal_elf_sym.st_shndx != 0)
4203	      {
4204		/* This symbol is in a real ELF section which we did
4205                   not create as a BFD section.  Undo the mapping done
4206                   by copy_private_symbol_data.  */
4207		shndx = type_ptr->internal_elf_sym.st_shndx;
4208		switch (shndx)
4209		  {
4210		  case MAP_ONESYMTAB:
4211		    shndx = elf_onesymtab (abfd);
4212		    break;
4213		  case MAP_DYNSYMTAB:
4214		    shndx = elf_dynsymtab (abfd);
4215		    break;
4216		  case MAP_STRTAB:
4217		    shndx = elf_tdata (abfd)->strtab_section;
4218		    break;
4219		  case MAP_SHSTRTAB:
4220		    shndx = elf_tdata (abfd)->shstrtab_section;
4221		    break;
4222		  default:
4223		    break;
4224		  }
4225	      }
4226	    else
4227	      {
4228		shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
4229
4230		if (shndx == -1)
4231		  {
4232		    asection *sec2;
4233
4234		    /* Writing this would be a hell of a lot easier if
4235		       we had some decent documentation on bfd, and
4236		       knew what to expect of the library, and what to
4237		       demand of applications.  For example, it
4238		       appears that `objcopy' might not set the
4239		       section of a symbol to be a section that is
4240		       actually in the output file.  */
4241		    sec2 = bfd_get_section_by_name (abfd, sec->name);
4242		    BFD_ASSERT (sec2 != 0);
4243		    shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
4244		    BFD_ASSERT (shndx != -1);
4245		  }
4246	      }
4247
4248	    sym.st_shndx = shndx;
4249	  }
4250
4251	if ((flags & BSF_FUNCTION) != 0)
4252	  type = STT_FUNC;
4253	else if ((flags & BSF_OBJECT) != 0)
4254	  type = STT_OBJECT;
4255	else
4256	  type = STT_NOTYPE;
4257
4258        /* Processor-specific types */
4259        if (type_ptr != NULL
4260	    && bed->elf_backend_get_symbol_type)
4261          type = (*bed->elf_backend_get_symbol_type) (&type_ptr->internal_elf_sym, type);
4262
4263	if (flags & BSF_SECTION_SYM)
4264	  sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
4265	else if (bfd_is_com_section (syms[idx]->section))
4266	  sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
4267	else if (bfd_is_und_section (syms[idx]->section))
4268	  sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
4269				      ? STB_WEAK
4270				      : STB_GLOBAL),
4271				     type);
4272	else if (flags & BSF_FILE)
4273	  sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
4274	else
4275	  {
4276	    int bind = STB_LOCAL;
4277
4278	    if (flags & BSF_LOCAL)
4279	      bind = STB_LOCAL;
4280	    else if (flags & BSF_WEAK)
4281	      bind = STB_WEAK;
4282	    else if (flags & BSF_GLOBAL)
4283	      bind = STB_GLOBAL;
4284
4285	    sym.st_info = ELF_ST_INFO (bind, type);
4286	  }
4287
4288	if (type_ptr != NULL)
4289	  sym.st_other = type_ptr->internal_elf_sym.st_other;
4290	else
4291	  sym.st_other = 0;
4292
4293	bed->s->swap_symbol_out (abfd, &sym, (PTR) outbound_syms);
4294	outbound_syms += bed->s->sizeof_sym;
4295      }
4296
4297    *sttp = stt;
4298    symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
4299    symstrtab_hdr->sh_type = SHT_STRTAB;
4300
4301    symstrtab_hdr->sh_flags = 0;
4302    symstrtab_hdr->sh_addr = 0;
4303    symstrtab_hdr->sh_entsize = 0;
4304    symstrtab_hdr->sh_link = 0;
4305    symstrtab_hdr->sh_info = 0;
4306    symstrtab_hdr->sh_addralign = 1;
4307  }
4308
4309  return true;
4310}
4311
4312/* Return the number of bytes required to hold the symtab vector.
4313
4314   Note that we base it on the count plus 1, since we will null terminate
4315   the vector allocated based on this size.  However, the ELF symbol table
4316   always has a dummy entry as symbol #0, so it ends up even.  */
4317
4318long
4319_bfd_elf_get_symtab_upper_bound (abfd)
4320     bfd *abfd;
4321{
4322  long symcount;
4323  long symtab_size;
4324  Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
4325
4326  symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
4327  symtab_size = (symcount - 1 + 1) * (sizeof (asymbol *));
4328
4329  return symtab_size;
4330}
4331
4332long
4333_bfd_elf_get_dynamic_symtab_upper_bound (abfd)
4334     bfd *abfd;
4335{
4336  long symcount;
4337  long symtab_size;
4338  Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4339
4340  if (elf_dynsymtab (abfd) == 0)
4341    {
4342      bfd_set_error (bfd_error_invalid_operation);
4343      return -1;
4344    }
4345
4346  symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
4347  symtab_size = (symcount - 1 + 1) * (sizeof (asymbol *));
4348
4349  return symtab_size;
4350}
4351
4352long
4353_bfd_elf_get_reloc_upper_bound (abfd, asect)
4354     bfd *abfd ATTRIBUTE_UNUSED;
4355     sec_ptr asect;
4356{
4357  return (asect->reloc_count + 1) * sizeof (arelent *);
4358}
4359
4360/* Canonicalize the relocs.  */
4361
4362long
4363_bfd_elf_canonicalize_reloc (abfd, section, relptr, symbols)
4364     bfd *abfd;
4365     sec_ptr section;
4366     arelent **relptr;
4367     asymbol **symbols;
4368{
4369  arelent *tblptr;
4370  unsigned int i;
4371
4372  if (! get_elf_backend_data (abfd)->s->slurp_reloc_table (abfd,
4373							   section,
4374							   symbols,
4375							   false))
4376    return -1;
4377
4378  tblptr = section->relocation;
4379  for (i = 0; i < section->reloc_count; i++)
4380    *relptr++ = tblptr++;
4381
4382  *relptr = NULL;
4383
4384  return section->reloc_count;
4385}
4386
4387long
4388_bfd_elf_get_symtab (abfd, alocation)
4389     bfd *abfd;
4390     asymbol **alocation;
4391{
4392  long symcount = get_elf_backend_data (abfd)->s->slurp_symbol_table
4393    (abfd, alocation, false);
4394
4395  if (symcount >= 0)
4396    bfd_get_symcount (abfd) = symcount;
4397  return symcount;
4398}
4399
4400long
4401_bfd_elf_canonicalize_dynamic_symtab (abfd, alocation)
4402     bfd *abfd;
4403     asymbol **alocation;
4404{
4405  return get_elf_backend_data (abfd)->s->slurp_symbol_table
4406    (abfd, alocation, true);
4407}
4408
4409/* Return the size required for the dynamic reloc entries.  Any
4410   section that was actually installed in the BFD, and has type
4411   SHT_REL or SHT_RELA, and uses the dynamic symbol table, is
4412   considered to be a dynamic reloc section.  */
4413
4414long
4415_bfd_elf_get_dynamic_reloc_upper_bound (abfd)
4416     bfd *abfd;
4417{
4418  long ret;
4419  asection *s;
4420
4421  if (elf_dynsymtab (abfd) == 0)
4422    {
4423      bfd_set_error (bfd_error_invalid_operation);
4424      return -1;
4425    }
4426
4427  ret = sizeof (arelent *);
4428  for (s = abfd->sections; s != NULL; s = s->next)
4429    if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
4430	&& (elf_section_data (s)->this_hdr.sh_type == SHT_REL
4431	    || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
4432      ret += ((s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize)
4433	      * sizeof (arelent *));
4434
4435  return ret;
4436}
4437
4438/* Canonicalize the dynamic relocation entries.  Note that we return
4439   the dynamic relocations as a single block, although they are
4440   actually associated with particular sections; the interface, which
4441   was designed for SunOS style shared libraries, expects that there
4442   is only one set of dynamic relocs.  Any section that was actually
4443   installed in the BFD, and has type SHT_REL or SHT_RELA, and uses
4444   the dynamic symbol table, is considered to be a dynamic reloc
4445   section.  */
4446
4447long
4448_bfd_elf_canonicalize_dynamic_reloc (abfd, storage, syms)
4449     bfd *abfd;
4450     arelent **storage;
4451     asymbol **syms;
4452{
4453  boolean (*slurp_relocs) PARAMS ((bfd *, asection *, asymbol **, boolean));
4454  asection *s;
4455  long ret;
4456
4457  if (elf_dynsymtab (abfd) == 0)
4458    {
4459      bfd_set_error (bfd_error_invalid_operation);
4460      return -1;
4461    }
4462
4463  slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
4464  ret = 0;
4465  for (s = abfd->sections; s != NULL; s = s->next)
4466    {
4467      if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
4468	  && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
4469	      || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
4470	{
4471	  arelent *p;
4472	  long count, i;
4473
4474	  if (! (*slurp_relocs) (abfd, s, syms, true))
4475	    return -1;
4476	  count = s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize;
4477	  p = s->relocation;
4478	  for (i = 0; i < count; i++)
4479	    *storage++ = p++;
4480	  ret += count;
4481	}
4482    }
4483
4484  *storage = NULL;
4485
4486  return ret;
4487}
4488
4489/* Read in the version information.  */
4490
4491boolean
4492_bfd_elf_slurp_version_tables (abfd)
4493     bfd *abfd;
4494{
4495  bfd_byte *contents = NULL;
4496
4497  if (elf_dynverdef (abfd) != 0)
4498    {
4499      Elf_Internal_Shdr *hdr;
4500      Elf_External_Verdef *everdef;
4501      Elf_Internal_Verdef *iverdef;
4502      Elf_Internal_Verdef *iverdefarr;
4503      Elf_Internal_Verdef iverdefmem;
4504      unsigned int i;
4505      unsigned int maxidx;
4506
4507      hdr = &elf_tdata (abfd)->dynverdef_hdr;
4508
4509      contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
4510      if (contents == NULL)
4511	goto error_return;
4512      if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
4513	  || bfd_read ((PTR) contents, 1, hdr->sh_size, abfd) != hdr->sh_size)
4514	goto error_return;
4515
4516      /* We know the number of entries in the section but not the maximum
4517	 index.  Therefore we have to run through all entries and find
4518	 the maximum.  */
4519      everdef = (Elf_External_Verdef *) contents;
4520      maxidx = 0;
4521      for (i = 0; i < hdr->sh_info; ++i)
4522	{
4523	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
4524
4525	  if ((iverdefmem.vd_ndx & VERSYM_VERSION) > maxidx)
4526	    maxidx = iverdefmem.vd_ndx & VERSYM_VERSION;
4527
4528	  everdef = ((Elf_External_Verdef *)
4529		     ((bfd_byte *) everdef + iverdefmem.vd_next));
4530	}
4531
4532      elf_tdata (abfd)->verdef =
4533	((Elf_Internal_Verdef *)
4534	 bfd_zalloc (abfd, maxidx * sizeof (Elf_Internal_Verdef)));
4535      if (elf_tdata (abfd)->verdef == NULL)
4536	goto error_return;
4537
4538      elf_tdata (abfd)->cverdefs = maxidx;
4539
4540      everdef = (Elf_External_Verdef *) contents;
4541      iverdefarr = elf_tdata (abfd)->verdef;
4542      for (i = 0; i < hdr->sh_info; i++)
4543	{
4544	  Elf_External_Verdaux *everdaux;
4545	  Elf_Internal_Verdaux *iverdaux;
4546	  unsigned int j;
4547
4548	  _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
4549
4550	  iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
4551	  memcpy (iverdef, &iverdefmem, sizeof (Elf_Internal_Verdef));
4552
4553	  iverdef->vd_bfd = abfd;
4554
4555	  iverdef->vd_auxptr = ((Elf_Internal_Verdaux *)
4556				bfd_alloc (abfd,
4557					   (iverdef->vd_cnt
4558					    * sizeof (Elf_Internal_Verdaux))));
4559	  if (iverdef->vd_auxptr == NULL)
4560	    goto error_return;
4561
4562	  everdaux = ((Elf_External_Verdaux *)
4563		      ((bfd_byte *) everdef + iverdef->vd_aux));
4564	  iverdaux = iverdef->vd_auxptr;
4565	  for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
4566	    {
4567	      _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
4568
4569	      iverdaux->vda_nodename =
4570		bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4571						 iverdaux->vda_name);
4572	      if (iverdaux->vda_nodename == NULL)
4573		goto error_return;
4574
4575	      if (j + 1 < iverdef->vd_cnt)
4576		iverdaux->vda_nextptr = iverdaux + 1;
4577	      else
4578		iverdaux->vda_nextptr = NULL;
4579
4580	      everdaux = ((Elf_External_Verdaux *)
4581			  ((bfd_byte *) everdaux + iverdaux->vda_next));
4582	    }
4583
4584	  iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
4585
4586	  if (i + 1 < hdr->sh_info)
4587	    iverdef->vd_nextdef = iverdef + 1;
4588	  else
4589	    iverdef->vd_nextdef = NULL;
4590
4591	  everdef = ((Elf_External_Verdef *)
4592		     ((bfd_byte *) everdef + iverdef->vd_next));
4593	}
4594
4595      free (contents);
4596      contents = NULL;
4597    }
4598
4599  if (elf_dynverref (abfd) != 0)
4600    {
4601      Elf_Internal_Shdr *hdr;
4602      Elf_External_Verneed *everneed;
4603      Elf_Internal_Verneed *iverneed;
4604      unsigned int i;
4605
4606      hdr = &elf_tdata (abfd)->dynverref_hdr;
4607
4608      elf_tdata (abfd)->verref =
4609	((Elf_Internal_Verneed *)
4610	 bfd_zalloc (abfd, hdr->sh_info * sizeof (Elf_Internal_Verneed)));
4611      if (elf_tdata (abfd)->verref == NULL)
4612	goto error_return;
4613
4614      elf_tdata (abfd)->cverrefs = hdr->sh_info;
4615
4616      contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
4617      if (contents == NULL)
4618	goto error_return;
4619      if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
4620	  || bfd_read ((PTR) contents, 1, hdr->sh_size, abfd) != hdr->sh_size)
4621	goto error_return;
4622
4623      everneed = (Elf_External_Verneed *) contents;
4624      iverneed = elf_tdata (abfd)->verref;
4625      for (i = 0; i < hdr->sh_info; i++, iverneed++)
4626	{
4627	  Elf_External_Vernaux *evernaux;
4628	  Elf_Internal_Vernaux *ivernaux;
4629	  unsigned int j;
4630
4631	  _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
4632
4633	  iverneed->vn_bfd = abfd;
4634
4635	  iverneed->vn_filename =
4636	    bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4637					     iverneed->vn_file);
4638	  if (iverneed->vn_filename == NULL)
4639	    goto error_return;
4640
4641	  iverneed->vn_auxptr =
4642	    ((Elf_Internal_Vernaux *)
4643	     bfd_alloc (abfd,
4644			iverneed->vn_cnt * sizeof (Elf_Internal_Vernaux)));
4645
4646	  evernaux = ((Elf_External_Vernaux *)
4647		      ((bfd_byte *) everneed + iverneed->vn_aux));
4648	  ivernaux = iverneed->vn_auxptr;
4649	  for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
4650	    {
4651	      _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
4652
4653	      ivernaux->vna_nodename =
4654		bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4655						 ivernaux->vna_name);
4656	      if (ivernaux->vna_nodename == NULL)
4657		goto error_return;
4658
4659	      if (j + 1 < iverneed->vn_cnt)
4660		ivernaux->vna_nextptr = ivernaux + 1;
4661	      else
4662		ivernaux->vna_nextptr = NULL;
4663
4664	      evernaux = ((Elf_External_Vernaux *)
4665			  ((bfd_byte *) evernaux + ivernaux->vna_next));
4666	    }
4667
4668	  if (i + 1 < hdr->sh_info)
4669	    iverneed->vn_nextref = iverneed + 1;
4670	  else
4671	    iverneed->vn_nextref = NULL;
4672
4673	  everneed = ((Elf_External_Verneed *)
4674		      ((bfd_byte *) everneed + iverneed->vn_next));
4675	}
4676
4677      free (contents);
4678      contents = NULL;
4679    }
4680
4681  return true;
4682
4683 error_return:
4684  if (contents == NULL)
4685    free (contents);
4686  return false;
4687}
4688
4689asymbol *
4690_bfd_elf_make_empty_symbol (abfd)
4691     bfd *abfd;
4692{
4693  elf_symbol_type *newsym;
4694
4695  newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof (elf_symbol_type));
4696  if (!newsym)
4697    return NULL;
4698  else
4699    {
4700      newsym->symbol.the_bfd = abfd;
4701      return &newsym->symbol;
4702    }
4703}
4704
4705void
4706_bfd_elf_get_symbol_info (ignore_abfd, symbol, ret)
4707     bfd *ignore_abfd ATTRIBUTE_UNUSED;
4708     asymbol *symbol;
4709     symbol_info *ret;
4710{
4711  bfd_symbol_info (symbol, ret);
4712}
4713
4714/* Return whether a symbol name implies a local symbol.  Most targets
4715   use this function for the is_local_label_name entry point, but some
4716   override it.  */
4717
4718boolean
4719_bfd_elf_is_local_label_name (abfd, name)
4720     bfd *abfd ATTRIBUTE_UNUSED;
4721     const char *name;
4722{
4723  /* Normal local symbols start with ``.L''.  */
4724  if (name[0] == '.' && name[1] == 'L')
4725    return true;
4726
4727  /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
4728     DWARF debugging symbols starting with ``..''.  */
4729  if (name[0] == '.' && name[1] == '.')
4730    return true;
4731
4732  /* gcc will sometimes generate symbols beginning with ``_.L_'' when
4733     emitting DWARF debugging output.  I suspect this is actually a
4734     small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
4735     ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
4736     underscore to be emitted on some ELF targets).  For ease of use,
4737     we treat such symbols as local.  */
4738  if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
4739    return true;
4740
4741  return false;
4742}
4743
4744alent *
4745_bfd_elf_get_lineno (ignore_abfd, symbol)
4746     bfd *ignore_abfd ATTRIBUTE_UNUSED;
4747     asymbol *symbol ATTRIBUTE_UNUSED;
4748{
4749  abort ();
4750  return NULL;
4751}
4752
4753boolean
4754_bfd_elf_set_arch_mach (abfd, arch, machine)
4755     bfd *abfd;
4756     enum bfd_architecture arch;
4757     unsigned long machine;
4758{
4759  /* If this isn't the right architecture for this backend, and this
4760     isn't the generic backend, fail.  */
4761  if (arch != get_elf_backend_data (abfd)->arch
4762      && arch != bfd_arch_unknown
4763      && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
4764    return false;
4765
4766  return bfd_default_set_arch_mach (abfd, arch, machine);
4767}
4768
4769/* Find the nearest line to a particular section and offset, for error
4770   reporting.  */
4771
4772boolean
4773_bfd_elf_find_nearest_line (abfd,
4774			    section,
4775			    symbols,
4776			    offset,
4777			    filename_ptr,
4778			    functionname_ptr,
4779			    line_ptr)
4780     bfd *abfd;
4781     asection *section;
4782     asymbol **symbols;
4783     bfd_vma offset;
4784     CONST char **filename_ptr;
4785     CONST char **functionname_ptr;
4786     unsigned int *line_ptr;
4787{
4788  boolean found;
4789  const char *filename;
4790  asymbol *func;
4791  bfd_vma low_func;
4792  asymbol **p;
4793
4794  if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
4795				     filename_ptr, functionname_ptr,
4796				     line_ptr))
4797    return true;
4798
4799  if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
4800				     filename_ptr, functionname_ptr,
4801				     line_ptr, 0))
4802    return true;
4803
4804  if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
4805					     &found, filename_ptr,
4806					     functionname_ptr, line_ptr,
4807					     &elf_tdata (abfd)->line_info))
4808    return false;
4809  if (found)
4810    return true;
4811
4812  if (symbols == NULL)
4813    return false;
4814
4815  filename = NULL;
4816  func = NULL;
4817  low_func = 0;
4818
4819  for (p = symbols; *p != NULL; p++)
4820    {
4821      elf_symbol_type *q;
4822
4823      q = (elf_symbol_type *) *p;
4824
4825      if (bfd_get_section (&q->symbol) != section)
4826	continue;
4827
4828      switch (ELF_ST_TYPE (q->internal_elf_sym.st_info))
4829	{
4830	default:
4831	  break;
4832	case STT_FILE:
4833	  filename = bfd_asymbol_name (&q->symbol);
4834	  break;
4835	case STT_NOTYPE:
4836	case STT_FUNC:
4837	  if (q->symbol.section == section
4838	      && q->symbol.value >= low_func
4839	      && q->symbol.value <= offset)
4840	    {
4841	      func = (asymbol *) q;
4842	      low_func = q->symbol.value;
4843	    }
4844	  break;
4845	}
4846    }
4847
4848  if (func == NULL)
4849    return false;
4850
4851  *filename_ptr = filename;
4852  *functionname_ptr = bfd_asymbol_name (func);
4853  *line_ptr = 0;
4854  return true;
4855}
4856
4857int
4858_bfd_elf_sizeof_headers (abfd, reloc)
4859     bfd *abfd;
4860     boolean reloc;
4861{
4862  int ret;
4863
4864  ret = get_elf_backend_data (abfd)->s->sizeof_ehdr;
4865  if (! reloc)
4866    ret += get_program_header_size (abfd);
4867  return ret;
4868}
4869
4870boolean
4871_bfd_elf_set_section_contents (abfd, section, location, offset, count)
4872     bfd *abfd;
4873     sec_ptr section;
4874     PTR location;
4875     file_ptr offset;
4876     bfd_size_type count;
4877{
4878  Elf_Internal_Shdr *hdr;
4879
4880  if (! abfd->output_has_begun
4881      && ! _bfd_elf_compute_section_file_positions
4882      (abfd, (struct bfd_link_info *) NULL))
4883    return false;
4884
4885  hdr = &elf_section_data (section)->this_hdr;
4886
4887  if (bfd_seek (abfd, hdr->sh_offset + offset, SEEK_SET) == -1)
4888    return false;
4889  if (bfd_write (location, 1, count, abfd) != count)
4890    return false;
4891
4892  return true;
4893}
4894
4895void
4896_bfd_elf_no_info_to_howto (abfd, cache_ptr, dst)
4897     bfd *abfd ATTRIBUTE_UNUSED;
4898     arelent *cache_ptr ATTRIBUTE_UNUSED;
4899     Elf_Internal_Rela *dst ATTRIBUTE_UNUSED;
4900{
4901  abort ();
4902}
4903
4904#if 0
4905void
4906_bfd_elf_no_info_to_howto_rel (abfd, cache_ptr, dst)
4907     bfd *abfd;
4908     arelent *cache_ptr;
4909     Elf_Internal_Rel *dst;
4910{
4911  abort ();
4912}
4913#endif
4914
4915/* Try to convert a non-ELF reloc into an ELF one.  */
4916
4917boolean
4918_bfd_elf_validate_reloc (abfd, areloc)
4919     bfd *abfd;
4920     arelent *areloc;
4921{
4922  /* Check whether we really have an ELF howto. */
4923
4924  if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
4925    {
4926      bfd_reloc_code_real_type code;
4927      reloc_howto_type *howto;
4928
4929      /* Alien reloc: Try to determine its type to replace it with an
4930	 equivalent ELF reloc. */
4931
4932      if (areloc->howto->pc_relative)
4933	{
4934	  switch (areloc->howto->bitsize)
4935	    {
4936	    case 8:
4937	      code = BFD_RELOC_8_PCREL;
4938	      break;
4939	    case 12:
4940	      code = BFD_RELOC_12_PCREL;
4941	      break;
4942	    case 16:
4943	      code = BFD_RELOC_16_PCREL;
4944	      break;
4945	    case 24:
4946	      code = BFD_RELOC_24_PCREL;
4947	      break;
4948	    case 32:
4949	      code = BFD_RELOC_32_PCREL;
4950	      break;
4951	    case 64:
4952	      code = BFD_RELOC_64_PCREL;
4953	      break;
4954	    default:
4955	      goto fail;
4956	    }
4957
4958	  howto = bfd_reloc_type_lookup (abfd, code);
4959
4960	  if (areloc->howto->pcrel_offset != howto->pcrel_offset)
4961	    {
4962	      if (howto->pcrel_offset)
4963		areloc->addend += areloc->address;
4964	      else
4965		areloc->addend -= areloc->address; /* addend is unsigned!! */
4966	    }
4967	}
4968      else
4969	{
4970	  switch (areloc->howto->bitsize)
4971	    {
4972	    case 8:
4973	      code = BFD_RELOC_8;
4974	      break;
4975	    case 14:
4976	      code = BFD_RELOC_14;
4977	      break;
4978	    case 16:
4979	      code = BFD_RELOC_16;
4980	      break;
4981	    case 26:
4982	      code = BFD_RELOC_26;
4983	      break;
4984	    case 32:
4985	      code = BFD_RELOC_32;
4986	      break;
4987	    case 64:
4988	      code = BFD_RELOC_64;
4989	      break;
4990	    default:
4991	      goto fail;
4992	    }
4993
4994	  howto = bfd_reloc_type_lookup (abfd, code);
4995	}
4996
4997      if (howto)
4998	areloc->howto = howto;
4999      else
5000	goto fail;
5001    }
5002
5003  return true;
5004
5005 fail:
5006  (*_bfd_error_handler)
5007    (_("%s: unsupported relocation type %s"),
5008     bfd_get_filename (abfd), areloc->howto->name);
5009  bfd_set_error (bfd_error_bad_value);
5010  return false;
5011}
5012
5013boolean
5014_bfd_elf_close_and_cleanup (abfd)
5015     bfd *abfd;
5016{
5017  if (bfd_get_format (abfd) == bfd_object)
5018    {
5019      if (elf_shstrtab (abfd) != NULL)
5020	_bfd_stringtab_free (elf_shstrtab (abfd));
5021    }
5022
5023  return _bfd_generic_close_and_cleanup (abfd);
5024}
5025
5026/* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
5027   in the relocation's offset.  Thus we cannot allow any sort of sanity
5028   range-checking to interfere.  There is nothing else to do in processing
5029   this reloc.  */
5030
5031bfd_reloc_status_type
5032_bfd_elf_rel_vtable_reloc_fn (abfd, re, symbol, data, is, obfd, errmsg)
5033     bfd *abfd ATTRIBUTE_UNUSED;
5034     arelent *re ATTRIBUTE_UNUSED;
5035     struct symbol_cache_entry *symbol ATTRIBUTE_UNUSED;
5036     PTR data ATTRIBUTE_UNUSED;
5037     asection *is ATTRIBUTE_UNUSED;
5038     bfd *obfd ATTRIBUTE_UNUSED;
5039     char **errmsg ATTRIBUTE_UNUSED;
5040{
5041  return bfd_reloc_ok;
5042}
5043
5044
5045/* Elf core file support.  Much of this only works on native
5046   toolchains, since we rely on knowing the
5047   machine-dependent procfs structure in order to pick
5048   out details about the corefile. */
5049
5050#ifdef HAVE_SYS_PROCFS_H
5051# include <sys/procfs.h>
5052#endif
5053
5054
5055/* Define offsetof for those systems which lack it. */
5056
5057#ifndef offsetof
5058# define offsetof(TYPE, MEMBER) ((unsigned long) &((TYPE *)0)->MEMBER)
5059#endif
5060
5061
5062/* FIXME: this is kinda wrong, but it's what gdb wants. */
5063
5064static int
5065elfcore_make_pid (abfd)
5066     bfd* abfd;
5067{
5068  return ((elf_tdata (abfd)->core_lwpid << 16)
5069	  + (elf_tdata (abfd)->core_pid));
5070}
5071
5072
5073/* If there isn't a section called NAME, make one, using
5074   data from SECT.  Note, this function will generate a
5075   reference to NAME, so you shouldn't deallocate or
5076   overwrite it. */
5077
5078static boolean
5079elfcore_maybe_make_sect (abfd, name, sect)
5080     bfd* abfd;
5081     char* name;
5082     asection* sect;
5083{
5084  asection* sect2;
5085
5086  if (bfd_get_section_by_name (abfd, name) != NULL)
5087    return true;
5088
5089  sect2 = bfd_make_section (abfd, name);
5090  if (sect2 == NULL)
5091    return false;
5092
5093  sect2->_raw_size = sect->_raw_size;
5094  sect2->filepos = sect->filepos;
5095  sect2->flags = sect->flags;
5096  sect2->alignment_power = sect->alignment_power;
5097  return true;
5098}
5099
5100
5101/* prstatus_t exists on:
5102     solaris 2.[567]
5103     linux 2.[01] + glibc
5104     unixware 4.2
5105*/
5106
5107#if defined (HAVE_PRSTATUS_T)
5108static boolean
5109elfcore_grok_prstatus (abfd, note)
5110     bfd* abfd;
5111     Elf_Internal_Note* note;
5112{
5113  prstatus_t prstat;
5114  char buf[100];
5115  char* name;
5116  asection* sect;
5117
5118  if (note->descsz != sizeof (prstat))
5119    return true;
5120
5121  memcpy (&prstat, note->descdata, sizeof (prstat));
5122
5123  elf_tdata (abfd)->core_signal = prstat.pr_cursig;
5124  elf_tdata (abfd)->core_pid = prstat.pr_pid;
5125
5126  /* pr_who exists on:
5127       solaris 2.[567]
5128       unixware 4.2
5129     pr_who doesn't exist on:
5130       linux 2.[01]
5131  */
5132#if defined (HAVE_PRSTATUS_T_PR_WHO)
5133  elf_tdata (abfd)->core_lwpid = prstat.pr_who;
5134#endif
5135
5136  /* Make a ".reg/999" section. */
5137
5138  sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
5139  name = bfd_alloc (abfd, strlen (buf) + 1);
5140  if (name == NULL)
5141    return false;
5142  strcpy (name, buf);
5143
5144  sect = bfd_make_section (abfd, name);
5145  if (sect == NULL)
5146    return false;
5147  sect->_raw_size = sizeof (prstat.pr_reg);
5148  sect->filepos = note->descpos + offsetof (prstatus_t, pr_reg);
5149  sect->flags = SEC_HAS_CONTENTS;
5150  sect->alignment_power = 2;
5151
5152  if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
5153    return false;
5154
5155  return true;
5156}
5157#endif /* defined (HAVE_PRSTATUS_T) */
5158
5159
5160/* Create a pseudosection containing the exact contents of NOTE.  This
5161   actually creates up to two pseudosections:
5162   - For the single-threaded case, a section named NAME, unless
5163     such a section already exists.
5164   - For the multi-threaded case, a section named "NAME/PID", where
5165     PID is elfcore_make_pid (abfd).
5166   Both pseudosections have identical contents: the contents of NOTE.  */
5167
5168static boolean
5169elfcore_make_note_pseudosection (abfd, name, note)
5170     bfd* abfd;
5171     char *name;
5172     Elf_Internal_Note* note;
5173{
5174  char buf[100];
5175  char *threaded_name;
5176  asection* sect;
5177
5178  /* Build the section name.  */
5179
5180  sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
5181  threaded_name = bfd_alloc (abfd, strlen (buf) + 1);
5182  if (threaded_name == NULL)
5183    return false;
5184  strcpy (threaded_name, buf);
5185
5186  sect = bfd_make_section (abfd, threaded_name);
5187  if (sect == NULL)
5188    return false;
5189  sect->_raw_size = note->descsz;
5190  sect->filepos = note->descpos;
5191  sect->flags = SEC_HAS_CONTENTS;
5192  sect->alignment_power = 2;
5193
5194  if (! elfcore_maybe_make_sect (abfd, name, sect))
5195    return false;
5196
5197  return true;
5198}
5199
5200
5201/* There isn't a consistent prfpregset_t across platforms,
5202   but it doesn't matter, because we don't have to pick this
5203   data structure apart. */
5204static boolean
5205elfcore_grok_prfpreg (abfd, note)
5206     bfd* abfd;
5207     Elf_Internal_Note* note;
5208{
5209  return elfcore_make_note_pseudosection (abfd, ".reg2", note);
5210}
5211
5212
5213/* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
5214   type of 5 (NT_PRXFPREG).  Just include the whole note's contents
5215   literally.  */
5216static boolean
5217elfcore_grok_prxfpreg (abfd, note)
5218     bfd* abfd;
5219     Elf_Internal_Note* note;
5220{
5221  return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
5222}
5223
5224
5225#if defined (HAVE_PRPSINFO_T)
5226# define elfcore_psinfo_t prpsinfo_t
5227#endif
5228
5229#if defined (HAVE_PSINFO_T)
5230# define elfcore_psinfo_t psinfo_t
5231#endif
5232
5233
5234#if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
5235
5236/* return a malloc'ed copy of a string at START which is at
5237   most MAX bytes long, possibly without a terminating '\0'.
5238   the copy will always have a terminating '\0'. */
5239
5240static char*
5241elfcore_strndup (abfd, start, max)
5242     bfd* abfd;
5243     char* start;
5244     int max;
5245{
5246  char* dup;
5247  char* end = memchr (start, '\0', max);
5248  int len;
5249
5250  if (end == NULL)
5251    len = max;
5252  else
5253    len = end - start;
5254
5255  dup = bfd_alloc (abfd, len + 1);
5256  if (dup == NULL)
5257    return NULL;
5258
5259  memcpy (dup, start, len);
5260  dup[len] = '\0';
5261
5262  return dup;
5263}
5264
5265static boolean
5266elfcore_grok_psinfo (abfd, note)
5267     bfd* abfd;
5268     Elf_Internal_Note* note;
5269{
5270  elfcore_psinfo_t psinfo;
5271
5272  if (note->descsz != sizeof (elfcore_psinfo_t))
5273    return true;
5274
5275  memcpy (&psinfo, note->descdata, note->descsz);
5276
5277  elf_tdata (abfd)->core_program
5278    = elfcore_strndup (abfd, psinfo.pr_fname, sizeof (psinfo.pr_fname));
5279
5280  elf_tdata (abfd)->core_command
5281    = elfcore_strndup (abfd, psinfo.pr_psargs, sizeof (psinfo.pr_psargs));
5282
5283  /* Note that for some reason, a spurious space is tacked
5284     onto the end of the args in some (at least one anyway)
5285     implementations, so strip it off if it exists. */
5286
5287  {
5288    char* command = elf_tdata (abfd)->core_command;
5289    int n = strlen (command);
5290
5291    if (0 < n && command[n - 1] == ' ')
5292      command[n - 1] = '\0';
5293  }
5294
5295  return true;
5296}
5297#endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
5298
5299
5300#if defined (HAVE_PSTATUS_T)
5301static boolean
5302elfcore_grok_pstatus (abfd, note)
5303     bfd* abfd;
5304     Elf_Internal_Note* note;
5305{
5306  pstatus_t pstat;
5307
5308  if (note->descsz != sizeof (pstat))
5309    return true;
5310
5311  memcpy (&pstat, note->descdata, sizeof (pstat));
5312
5313  elf_tdata (abfd)->core_pid = pstat.pr_pid;
5314
5315  /* Could grab some more details from the "representative"
5316     lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
5317     NT_LWPSTATUS note, presumably. */
5318
5319  return true;
5320}
5321#endif /* defined (HAVE_PSTATUS_T) */
5322
5323
5324#if defined (HAVE_LWPSTATUS_T)
5325static boolean
5326elfcore_grok_lwpstatus (abfd, note)
5327     bfd* abfd;
5328     Elf_Internal_Note* note;
5329{
5330  lwpstatus_t lwpstat;
5331  char buf[100];
5332  char* name;
5333  asection* sect;
5334
5335  if (note->descsz != sizeof (lwpstat))
5336    return true;
5337
5338  memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
5339
5340  elf_tdata (abfd)->core_lwpid = lwpstat.pr_lwpid;
5341  elf_tdata (abfd)->core_signal = lwpstat.pr_cursig;
5342
5343  /* Make a ".reg/999" section. */
5344
5345  sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
5346  name = bfd_alloc (abfd, strlen (buf) + 1);
5347  if (name == NULL)
5348    return false;
5349  strcpy (name, buf);
5350
5351  sect = bfd_make_section (abfd, name);
5352  if (sect == NULL)
5353    return false;
5354
5355#if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
5356  sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
5357  sect->filepos = note->descpos
5358    + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
5359#endif
5360
5361#if defined (HAVE_LWPSTATUS_T_PR_REG)
5362  sect->_raw_size = sizeof (lwpstat.pr_reg);
5363  sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
5364#endif
5365
5366  sect->flags = SEC_HAS_CONTENTS;
5367  sect->alignment_power = 2;
5368
5369  if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
5370    return false;
5371
5372  /* Make a ".reg2/999" section */
5373
5374  sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
5375  name = bfd_alloc (abfd, strlen (buf) + 1);
5376  if (name == NULL)
5377    return false;
5378  strcpy (name, buf);
5379
5380  sect = bfd_make_section (abfd, name);
5381  if (sect == NULL)
5382    return false;
5383
5384#if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
5385  sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
5386  sect->filepos = note->descpos
5387    + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
5388#endif
5389
5390#if defined (HAVE_LWPSTATUS_T_PR_FPREG)
5391  sect->_raw_size = sizeof (lwpstat.pr_fpreg);
5392  sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
5393#endif
5394
5395  sect->flags = SEC_HAS_CONTENTS;
5396  sect->alignment_power = 2;
5397
5398  if (!elfcore_maybe_make_sect (abfd, ".reg2", sect))
5399    return false;
5400
5401  return true;
5402}
5403#endif /* defined (HAVE_LWPSTATUS_T) */
5404
5405#if defined (HAVE_WIN32_PSTATUS_T)
5406static boolean
5407elfcore_grok_win32pstatus (abfd, note)
5408     bfd * abfd;
5409     Elf_Internal_Note * note;
5410{
5411  char buf[30];
5412  char * name;
5413  asection * sect;
5414  win32_pstatus_t pstatus;
5415
5416  if (note->descsz < sizeof (pstatus))
5417    return true;
5418
5419  memcpy (& pstatus, note->descdata, note->descsz);
5420
5421  switch (pstatus.data_type)
5422    {
5423    case NOTE_INFO_PROCESS:
5424      /* FIXME: need to add ->core_command.  */
5425      elf_tdata (abfd)->core_signal = pstatus.data.process_info.signal;
5426      elf_tdata (abfd)->core_pid = pstatus.data.process_info.pid;
5427      break ;
5428
5429    case NOTE_INFO_THREAD:
5430      /* Make a ".reg/999" section.  */
5431      sprintf (buf, ".reg/%d", pstatus.data.thread_info.tid);
5432
5433      name = bfd_alloc (abfd, strlen (buf) + 1);
5434      if (name == NULL)
5435        return false;
5436
5437      strcpy (name, buf);
5438
5439      sect = bfd_make_section (abfd, name);
5440      if (sect == NULL)
5441        return false;
5442
5443      sect->_raw_size = sizeof (pstatus.data.thread_info.thread_context);
5444      sect->filepos = note->descpos + offsetof (struct win32_pstatus,
5445						data.thread_info.thread_context);
5446      sect->flags = SEC_HAS_CONTENTS;
5447      sect->alignment_power = 2;
5448
5449      if (pstatus.data.thread_info.is_active_thread)
5450	if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
5451	  return false;
5452      break;
5453
5454    case NOTE_INFO_MODULE:
5455      /* Make a ".module/xxxxxxxx" section.  */
5456      sprintf (buf, ".module/%08x" , pstatus.data.module_info.base_address);
5457
5458      name = bfd_alloc (abfd, strlen (buf) + 1);
5459      if (name == NULL)
5460	return false;
5461
5462      strcpy (name, buf);
5463
5464      sect = bfd_make_section (abfd, name);
5465
5466      if (sect == NULL)
5467	return false;
5468
5469      sect->_raw_size = note->descsz;
5470      sect->filepos = note->descpos;
5471      sect->flags = SEC_HAS_CONTENTS;
5472      sect->alignment_power = 2;
5473      break;
5474
5475    default:
5476      return true;
5477    }
5478
5479  return true;
5480}
5481#endif /* HAVE_WIN32_PSTATUS_T */
5482
5483static boolean
5484elfcore_grok_note (abfd, note)
5485     bfd* abfd;
5486     Elf_Internal_Note* note;
5487{
5488  switch (note->type)
5489    {
5490    default:
5491      return true;
5492
5493#if defined (HAVE_PRSTATUS_T)
5494    case NT_PRSTATUS:
5495      return elfcore_grok_prstatus (abfd, note);
5496#endif
5497
5498#if defined (HAVE_PSTATUS_T)
5499    case NT_PSTATUS:
5500      return elfcore_grok_pstatus (abfd, note);
5501#endif
5502
5503#if defined (HAVE_LWPSTATUS_T)
5504    case NT_LWPSTATUS:
5505      return elfcore_grok_lwpstatus (abfd, note);
5506#endif
5507
5508    case NT_FPREGSET:		/* FIXME: rename to NT_PRFPREG */
5509      return elfcore_grok_prfpreg (abfd, note);
5510
5511#if defined (HAVE_WIN32_PSTATUS_T)
5512    case NT_WIN32PSTATUS:
5513      return elfcore_grok_win32pstatus (abfd, note);
5514#endif
5515
5516  case NT_PRXFPREG:		/* Linux SSE extension */
5517      if (note->namesz == 5
5518	  && ! strcmp (note->namedata, "LINUX"))
5519	return elfcore_grok_prxfpreg (abfd, note);
5520      else
5521	return true;
5522
5523#if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
5524    case NT_PRPSINFO:
5525    case NT_PSINFO:
5526      return elfcore_grok_psinfo (abfd, note);
5527#endif
5528    }
5529}
5530
5531
5532static boolean
5533elfcore_read_notes (abfd, offset, size)
5534     bfd* abfd;
5535     bfd_vma offset;
5536     bfd_vma size;
5537{
5538  char* buf;
5539  char* p;
5540
5541  if (size <= 0)
5542    return true;
5543
5544  if (bfd_seek (abfd, offset, SEEK_SET) == -1)
5545    return false;
5546
5547  buf = bfd_malloc ((size_t) size);
5548  if (buf == NULL)
5549    return false;
5550
5551  if (bfd_read (buf, size, 1, abfd) != size)
5552    {
5553    error:
5554      free (buf);
5555      return false;
5556    }
5557
5558  p = buf;
5559  while (p < buf + size)
5560    {
5561      /* FIXME: bad alignment assumption. */
5562      Elf_External_Note* xnp = (Elf_External_Note*) p;
5563      Elf_Internal_Note in;
5564
5565      in.type = bfd_h_get_32 (abfd, (bfd_byte *) xnp->type);
5566
5567      in.namesz = bfd_h_get_32 (abfd, (bfd_byte *) xnp->namesz);
5568      in.namedata = xnp->name;
5569
5570      in.descsz = bfd_h_get_32 (abfd, (bfd_byte *) xnp->descsz);
5571      in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
5572      in.descpos = offset + (in.descdata - buf);
5573
5574      if (! elfcore_grok_note (abfd, &in))
5575	goto error;
5576
5577      p = in.descdata + BFD_ALIGN (in.descsz, 4);
5578    }
5579
5580  free (buf);
5581  return true;
5582}
5583
5584
5585/* FIXME: This function is now unnecessary.  Callers can just call
5586   bfd_section_from_phdr directly.  */
5587
5588boolean
5589_bfd_elfcore_section_from_phdr (abfd, phdr, sec_num)
5590     bfd* abfd;
5591     Elf_Internal_Phdr* phdr;
5592     int sec_num;
5593{
5594  if (! bfd_section_from_phdr (abfd, phdr, sec_num))
5595    return false;
5596
5597  return true;
5598}
5599
5600
5601
5602/* Providing external access to the ELF program header table.  */
5603
5604/* Return an upper bound on the number of bytes required to store a
5605   copy of ABFD's program header table entries.  Return -1 if an error
5606   occurs; bfd_get_error will return an appropriate code.  */
5607long
5608bfd_get_elf_phdr_upper_bound (abfd)
5609     bfd *abfd;
5610{
5611  if (abfd->xvec->flavour != bfd_target_elf_flavour)
5612    {
5613      bfd_set_error (bfd_error_wrong_format);
5614      return -1;
5615    }
5616
5617  return (elf_elfheader (abfd)->e_phnum
5618	  * sizeof (Elf_Internal_Phdr));
5619}
5620
5621
5622/* Copy ABFD's program header table entries to *PHDRS.  The entries
5623   will be stored as an array of Elf_Internal_Phdr structures, as
5624   defined in include/elf/internal.h.  To find out how large the
5625   buffer needs to be, call bfd_get_elf_phdr_upper_bound.
5626
5627   Return the number of program header table entries read, or -1 if an
5628   error occurs; bfd_get_error will return an appropriate code.  */
5629int
5630bfd_get_elf_phdrs (abfd, phdrs)
5631     bfd *abfd;
5632     void *phdrs;
5633{
5634  int num_phdrs;
5635
5636  if (abfd->xvec->flavour != bfd_target_elf_flavour)
5637    {
5638      bfd_set_error (bfd_error_wrong_format);
5639      return -1;
5640    }
5641
5642  num_phdrs = elf_elfheader (abfd)->e_phnum;
5643  memcpy (phdrs, elf_tdata (abfd)->phdr,
5644	  num_phdrs * sizeof (Elf_Internal_Phdr));
5645
5646  return num_phdrs;
5647}
5648