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