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