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