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