OSDN Git Service

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