OSDN Git Service

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