OSDN Git Service

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