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