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