]> Git Repo - binutils.git/blob - bfd/elf.c
* elf.c (bfd_section_from_shdr): Make "name" const.
[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   const 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)
3481                     (_("%s: Not enough room for program headers, try linking with -N"),
3482                      bfd_get_filename (abfd));
3483                   bfd_set_error (bfd_error_bad_value);
3484                   return false;
3485                 }
3486
3487               p->p_vaddr -= off;
3488               if (! m->p_paddr_valid)
3489                 p->p_paddr -= off;
3490             }
3491           if (p->p_type == PT_LOAD)
3492             {
3493               filehdr_vaddr = p->p_vaddr;
3494               filehdr_paddr = p->p_paddr;
3495             }
3496         }
3497
3498       if (m->includes_phdrs)
3499         {
3500           if (! m->p_flags_valid)
3501             p->p_flags |= PF_R;
3502
3503           if (m->includes_filehdr)
3504             {
3505               if (p->p_type == PT_LOAD)
3506                 {
3507                   phdrs_vaddr = p->p_vaddr + bed->s->sizeof_ehdr;
3508                   phdrs_paddr = p->p_paddr + bed->s->sizeof_ehdr;
3509                 }
3510             }
3511           else
3512             {
3513               p->p_offset = bed->s->sizeof_ehdr;
3514
3515               if (m->count > 0)
3516                 {
3517                   BFD_ASSERT (p->p_type == PT_LOAD);
3518                   p->p_vaddr -= off - p->p_offset;
3519                   if (! m->p_paddr_valid)
3520                     p->p_paddr -= off - p->p_offset;
3521                 }
3522
3523               if (p->p_type == PT_LOAD)
3524                 {
3525                   phdrs_vaddr = p->p_vaddr;
3526                   phdrs_paddr = p->p_paddr;
3527                 }
3528               else
3529                 phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
3530             }
3531
3532           p->p_filesz += alloc * bed->s->sizeof_phdr;
3533           p->p_memsz += alloc * bed->s->sizeof_phdr;
3534         }
3535
3536       if (p->p_type == PT_LOAD
3537           || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
3538         {
3539           if (! m->includes_filehdr && ! m->includes_phdrs)
3540             p->p_offset = off;
3541           else
3542             {
3543               file_ptr adjust;
3544
3545               adjust = off - (p->p_offset + p->p_filesz);
3546               p->p_filesz += adjust;
3547               p->p_memsz += adjust;
3548             }
3549         }
3550
3551       voff = off;
3552
3553       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
3554         {
3555           asection *sec;
3556           flagword flags;
3557           bfd_size_type align;
3558
3559           sec = *secpp;
3560           flags = sec->flags;
3561           align = 1 << bfd_get_section_alignment (abfd, sec);
3562
3563           /* The section may have artificial alignment forced by a
3564              link script.  Notice this case by the gap between the
3565              cumulative phdr lma and the section's lma.  */
3566           if (p->p_paddr + p->p_memsz < sec->lma)
3567             {
3568               bfd_vma adjust = sec->lma - (p->p_paddr + p->p_memsz);
3569
3570               p->p_memsz += adjust;
3571               off += adjust;
3572               voff += adjust;
3573               if ((flags & SEC_LOAD) != 0)
3574                 p->p_filesz += adjust;
3575             }
3576
3577           if (p->p_type == PT_LOAD)
3578             {
3579               bfd_signed_vma adjust;
3580
3581               if ((flags & SEC_LOAD) != 0)
3582                 {
3583                   adjust = sec->lma - (p->p_paddr + p->p_memsz);
3584                   if (adjust < 0)
3585                     adjust = 0;
3586                 }
3587               else if ((flags & SEC_ALLOC) != 0)
3588                 {
3589                   /* The section VMA must equal the file position
3590                      modulo the page size.  FIXME: I'm not sure if
3591                      this adjustment is really necessary.  We used to
3592                      not have the SEC_LOAD case just above, and then
3593                      this was necessary, but now I'm not sure.  */
3594                   if ((abfd->flags & D_PAGED) != 0)
3595                     adjust = (sec->vma - voff) % bed->maxpagesize;
3596                   else
3597                     adjust = (sec->vma - voff) % align;
3598                 }
3599               else
3600                 adjust = 0;
3601
3602               if (adjust != 0)
3603                 {
3604                   if (i == 0)
3605                     {
3606                       (* _bfd_error_handler) (_("\
3607 Error: First section in segment (%s) starts at 0x%x whereas the segment starts at 0x%x"),
3608                                               bfd_section_name (abfd, sec),
3609                                               sec->lma,
3610                                               p->p_paddr);
3611                       return false;
3612                     }
3613                   p->p_memsz += adjust;
3614                   off += adjust;
3615                   voff += adjust;
3616                   if ((flags & SEC_LOAD) != 0)
3617                     p->p_filesz += adjust;
3618                 }
3619
3620               sec->filepos = off;
3621
3622               /* We check SEC_HAS_CONTENTS here because if NOLOAD is
3623                  used in a linker script we may have a section with
3624                  SEC_LOAD clear but which is supposed to have
3625                  contents.  */
3626               if ((flags & SEC_LOAD) != 0
3627                   || (flags & SEC_HAS_CONTENTS) != 0)
3628                 off += sec->_raw_size;
3629
3630               if ((flags & SEC_ALLOC) != 0)
3631                 voff += sec->_raw_size;
3632             }
3633
3634           if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
3635             {
3636               /* The actual "note" segment has i == 0.
3637                  This is the one that actually contains everything.  */
3638               if (i == 0)
3639                 {
3640                   sec->filepos = off;
3641                   p->p_filesz = sec->_raw_size;
3642                   off += sec->_raw_size;
3643                   voff = off;
3644                 }
3645               else
3646                 {
3647                   /* Fake sections -- don't need to be written.  */
3648                   sec->filepos = 0;
3649                   sec->_raw_size = 0;
3650                   flags = sec->flags = 0;
3651                 }
3652               p->p_memsz = 0;
3653               p->p_align = 1;
3654             }
3655           else
3656             {
3657               p->p_memsz += sec->_raw_size;
3658
3659               if ((flags & SEC_LOAD) != 0)
3660                 p->p_filesz += sec->_raw_size;
3661
3662               if (p->p_type == PT_TLS
3663                   && sec->_raw_size == 0
3664                   && (sec->flags & SEC_HAS_CONTENTS) == 0)
3665                 {
3666                   struct bfd_link_order *o;
3667                   bfd_vma tbss_size = 0;
3668
3669                   for (o = sec->link_order_head; o != NULL; o = o->next)
3670                     if (tbss_size < o->offset + o->size)
3671                       tbss_size = o->offset + o->size;
3672
3673                   p->p_memsz += tbss_size;
3674                 }
3675
3676               if (align > p->p_align
3677                   && (p->p_type != PT_LOAD || (abfd->flags & D_PAGED) == 0))
3678                 p->p_align = align;
3679             }
3680
3681           if (! m->p_flags_valid)
3682             {
3683               p->p_flags |= PF_R;
3684               if ((flags & SEC_CODE) != 0)
3685                 p->p_flags |= PF_X;
3686               if ((flags & SEC_READONLY) == 0)
3687                 p->p_flags |= PF_W;
3688             }
3689         }
3690     }
3691
3692   /* Now that we have set the section file positions, we can set up
3693      the file positions for the non PT_LOAD segments.  */
3694   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
3695        m != NULL;
3696        m = m->next, p++)
3697     {
3698       if (p->p_type != PT_LOAD && m->count > 0)
3699         {
3700           BFD_ASSERT (! m->includes_filehdr && ! m->includes_phdrs);
3701           p->p_offset = m->sections[0]->filepos;
3702         }
3703       if (m->count == 0)
3704         {
3705           if (m->includes_filehdr)
3706             {
3707               p->p_vaddr = filehdr_vaddr;
3708               if (! m->p_paddr_valid)
3709                 p->p_paddr = filehdr_paddr;
3710             }
3711           else if (m->includes_phdrs)
3712             {
3713               p->p_vaddr = phdrs_vaddr;
3714               if (! m->p_paddr_valid)
3715                 p->p_paddr = phdrs_paddr;
3716             }
3717         }
3718     }
3719
3720   /* If additional nonloadable filepos adjustments are required,
3721      do them now. */
3722   if (bed->set_nonloadable_filepos)
3723     (*bed->set_nonloadable_filepos) (abfd, phdrs);
3724
3725   /* Clear out any program headers we allocated but did not use.  */
3726   for (; count < alloc; count++, p++)
3727     {
3728       memset (p, 0, sizeof *p);
3729       p->p_type = PT_NULL;
3730     }
3731
3732   elf_tdata (abfd)->phdr = phdrs;
3733
3734   elf_tdata (abfd)->next_file_pos = off;
3735
3736   /* Write out the program headers.  */
3737   if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
3738       || bed->s->write_out_phdrs (abfd, phdrs, alloc) != 0)
3739     return false;
3740
3741   return true;
3742 }
3743
3744 /* Get the size of the program header.
3745
3746    If this is called by the linker before any of the section VMA's are set, it
3747    can't calculate the correct value for a strange memory layout.  This only
3748    happens when SIZEOF_HEADERS is used in a linker script.  In this case,
3749    SORTED_HDRS is NULL and we assume the normal scenario of one text and one
3750    data segment (exclusive of .interp and .dynamic).
3751
3752    ??? User written scripts must either not use SIZEOF_HEADERS, or assume there
3753    will be two segments.  */
3754
3755 static bfd_size_type
3756 get_program_header_size (abfd)
3757      bfd *abfd;
3758 {
3759   size_t segs;
3760   asection *s;
3761   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3762
3763   /* We can't return a different result each time we're called.  */
3764   if (elf_tdata (abfd)->program_header_size != 0)
3765     return elf_tdata (abfd)->program_header_size;
3766
3767   if (elf_tdata (abfd)->segment_map != NULL)
3768     {
3769       struct elf_segment_map *m;
3770
3771       segs = 0;
3772       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
3773         ++segs;
3774       elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
3775       return elf_tdata (abfd)->program_header_size;
3776     }
3777
3778   /* Assume we will need exactly two PT_LOAD segments: one for text
3779      and one for data.  */
3780   segs = 2;
3781
3782   s = bfd_get_section_by_name (abfd, ".interp");
3783   if (s != NULL && (s->flags & SEC_LOAD) != 0)
3784     {
3785       /* If we have a loadable interpreter section, we need a
3786          PT_INTERP segment.  In this case, assume we also need a
3787          PT_PHDR segment, although that may not be true for all
3788          targets.  */
3789       segs += 2;
3790     }
3791
3792   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
3793     {
3794       /* We need a PT_DYNAMIC segment.  */
3795       ++segs;
3796     }
3797
3798   if (elf_tdata (abfd)->eh_frame_hdr
3799       && bfd_get_section_by_name (abfd, ".eh_frame_hdr") != NULL)
3800     {
3801       /* We need a PT_GNU_EH_FRAME segment.  */
3802       ++segs;
3803     }
3804
3805   for (s = abfd->sections; s != NULL; s = s->next)
3806     {
3807       if ((s->flags & SEC_LOAD) != 0
3808           && strncmp (s->name, ".note", 5) == 0)
3809         {
3810           /* We need a PT_NOTE segment.  */
3811           ++segs;
3812         }
3813     }
3814
3815   for (s = abfd->sections; s != NULL; s = s->next)
3816     {
3817       if (s->flags & SEC_THREAD_LOCAL)
3818         {
3819           /* We need a PT_TLS segment.  */
3820           ++segs;
3821           break;
3822         }
3823     }
3824
3825   /* Let the backend count up any program headers it might need.  */
3826   if (bed->elf_backend_additional_program_headers)
3827     {
3828       int a;
3829
3830       a = (*bed->elf_backend_additional_program_headers) (abfd);
3831       if (a == -1)
3832         abort ();
3833       segs += a;
3834     }
3835
3836   elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
3837   return elf_tdata (abfd)->program_header_size;
3838 }
3839
3840 /* Work out the file positions of all the sections.  This is called by
3841    _bfd_elf_compute_section_file_positions.  All the section sizes and
3842    VMAs must be known before this is called.
3843
3844    We do not consider reloc sections at this point, unless they form
3845    part of the loadable image.  Reloc sections are assigned file
3846    positions in assign_file_positions_for_relocs, which is called by
3847    write_object_contents and final_link.
3848
3849    We also don't set the positions of the .symtab and .strtab here.  */
3850
3851 static boolean
3852 assign_file_positions_except_relocs (abfd)
3853      bfd *abfd;
3854 {
3855   struct elf_obj_tdata * const tdata = elf_tdata (abfd);
3856   Elf_Internal_Ehdr * const i_ehdrp = elf_elfheader (abfd);
3857   Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
3858   unsigned int num_sec = elf_numsections (abfd);
3859   file_ptr off;
3860   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3861
3862   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
3863       && bfd_get_format (abfd) != bfd_core)
3864     {
3865       Elf_Internal_Shdr **hdrpp;
3866       unsigned int i;
3867
3868       /* Start after the ELF header.  */
3869       off = i_ehdrp->e_ehsize;
3870
3871       /* We are not creating an executable, which means that we are
3872          not creating a program header, and that the actual order of
3873          the sections in the file is unimportant.  */
3874       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
3875         {
3876           Elf_Internal_Shdr *hdr;
3877
3878           hdr = *hdrpp;
3879           if (hdr->sh_type == SHT_REL
3880               || hdr->sh_type == SHT_RELA
3881               || i == tdata->symtab_section
3882               || i == tdata->symtab_shndx_section
3883               || i == tdata->strtab_section)
3884             {
3885               hdr->sh_offset = -1;
3886             }
3887           else
3888             off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3889
3890           if (i == SHN_LORESERVE - 1)
3891             {
3892               i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
3893               hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
3894             }
3895         }
3896     }
3897   else
3898     {
3899       unsigned int i;
3900       Elf_Internal_Shdr **hdrpp;
3901
3902       /* Assign file positions for the loaded sections based on the
3903          assignment of sections to segments.  */
3904       if (! assign_file_positions_for_segments (abfd))
3905         return false;
3906
3907       /* Assign file positions for the other sections.  */
3908
3909       off = elf_tdata (abfd)->next_file_pos;
3910       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
3911         {
3912           Elf_Internal_Shdr *hdr;
3913
3914           hdr = *hdrpp;
3915           if (hdr->bfd_section != NULL
3916               && hdr->bfd_section->filepos != 0)
3917             hdr->sh_offset = hdr->bfd_section->filepos;
3918           else if ((hdr->sh_flags & SHF_ALLOC) != 0)
3919             {
3920               ((*_bfd_error_handler)
3921                (_("%s: warning: allocated section `%s' not in segment"),
3922                 bfd_get_filename (abfd),
3923                 (hdr->bfd_section == NULL
3924                  ? "*unknown*"
3925                  : hdr->bfd_section->name)));
3926               if ((abfd->flags & D_PAGED) != 0)
3927                 off += (hdr->sh_addr - off) % bed->maxpagesize;
3928               else
3929                 off += (hdr->sh_addr - off) % hdr->sh_addralign;
3930               off = _bfd_elf_assign_file_position_for_section (hdr, off,
3931                                                                false);
3932             }
3933           else if (hdr->sh_type == SHT_REL
3934                    || hdr->sh_type == SHT_RELA
3935                    || hdr == i_shdrpp[tdata->symtab_section]
3936                    || hdr == i_shdrpp[tdata->symtab_shndx_section]
3937                    || hdr == i_shdrpp[tdata->strtab_section])
3938             hdr->sh_offset = -1;
3939           else
3940             off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3941
3942           if (i == SHN_LORESERVE - 1)
3943             {
3944               i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
3945               hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
3946             }
3947         }
3948     }
3949
3950   /* Place the section headers.  */
3951   off = align_file_position (off, bed->s->file_align);
3952   i_ehdrp->e_shoff = off;
3953   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
3954
3955   elf_tdata (abfd)->next_file_pos = off;
3956
3957   return true;
3958 }
3959
3960 static boolean
3961 prep_headers (abfd)
3962      bfd *abfd;
3963 {
3964   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
3965   Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
3966   Elf_Internal_Shdr **i_shdrp;  /* Section header table, internal form */
3967   struct elf_strtab_hash *shstrtab;
3968   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3969
3970   i_ehdrp = elf_elfheader (abfd);
3971   i_shdrp = elf_elfsections (abfd);
3972
3973   shstrtab = _bfd_elf_strtab_init ();
3974   if (shstrtab == NULL)
3975     return false;
3976
3977   elf_shstrtab (abfd) = shstrtab;
3978
3979   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
3980   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
3981   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
3982   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
3983
3984   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
3985   i_ehdrp->e_ident[EI_DATA] =
3986     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
3987   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
3988
3989   if ((abfd->flags & DYNAMIC) != 0)
3990     i_ehdrp->e_type = ET_DYN;
3991   else if ((abfd->flags & EXEC_P) != 0)
3992     i_ehdrp->e_type = ET_EXEC;
3993   else if (bfd_get_format (abfd) == bfd_core)
3994     i_ehdrp->e_type = ET_CORE;
3995   else
3996     i_ehdrp->e_type = ET_REL;
3997
3998   switch (bfd_get_arch (abfd))
3999     {
4000     case bfd_arch_unknown:
4001       i_ehdrp->e_machine = EM_NONE;
4002       break;
4003
4004       /* There used to be a long list of cases here, each one setting
4005          e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
4006          in the corresponding bfd definition.  To avoid duplication,
4007          the switch was removed.  Machines that need special handling
4008          can generally do it in elf_backend_final_write_processing(),
4009          unless they need the information earlier than the final write.
4010          Such need can generally be supplied by replacing the tests for
4011          e_machine with the conditions used to determine it.  */
4012     default:
4013       if (get_elf_backend_data (abfd) != NULL)
4014         i_ehdrp->e_machine = get_elf_backend_data (abfd)->elf_machine_code;
4015       else
4016         i_ehdrp->e_machine = EM_NONE;
4017       }
4018
4019   i_ehdrp->e_version = bed->s->ev_current;
4020   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
4021
4022   /* No program header, for now.  */
4023   i_ehdrp->e_phoff = 0;
4024   i_ehdrp->e_phentsize = 0;
4025   i_ehdrp->e_phnum = 0;
4026
4027   /* Each bfd section is section header entry.  */
4028   i_ehdrp->e_entry = bfd_get_start_address (abfd);
4029   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
4030
4031   /* If we're building an executable, we'll need a program header table.  */
4032   if (abfd->flags & EXEC_P)
4033     {
4034       /* It all happens later.  */
4035 #if 0
4036       i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
4037
4038       /* elf_build_phdrs() returns a (NULL-terminated) array of
4039          Elf_Internal_Phdrs.  */
4040       i_phdrp = elf_build_phdrs (abfd, i_ehdrp, i_shdrp, &i_ehdrp->e_phnum);
4041       i_ehdrp->e_phoff = outbase;
4042       outbase += i_ehdrp->e_phentsize * i_ehdrp->e_phnum;
4043 #endif
4044     }
4045   else
4046     {
4047       i_ehdrp->e_phentsize = 0;
4048       i_phdrp = 0;
4049       i_ehdrp->e_phoff = 0;
4050     }
4051
4052   elf_tdata (abfd)->symtab_hdr.sh_name =
4053     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", false);
4054   elf_tdata (abfd)->strtab_hdr.sh_name =
4055     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", false);
4056   elf_tdata (abfd)->shstrtab_hdr.sh_name =
4057     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", false);
4058   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4059       || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4060       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
4061     return false;
4062
4063   return true;
4064 }
4065
4066 /* Assign file positions for all the reloc sections which are not part
4067    of the loadable file image.  */
4068
4069 void
4070 _bfd_elf_assign_file_positions_for_relocs (abfd)
4071      bfd *abfd;
4072 {
4073   file_ptr off;
4074   unsigned int i, num_sec;
4075   Elf_Internal_Shdr **shdrpp;
4076
4077   off = elf_tdata (abfd)->next_file_pos;
4078
4079   num_sec = elf_numsections (abfd);
4080   for (i = 1, shdrpp = elf_elfsections (abfd) + 1; i < num_sec; i++, shdrpp++)
4081     {
4082       Elf_Internal_Shdr *shdrp;
4083
4084       shdrp = *shdrpp;
4085       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
4086           && shdrp->sh_offset == -1)
4087         off = _bfd_elf_assign_file_position_for_section (shdrp, off, true);
4088     }
4089
4090   elf_tdata (abfd)->next_file_pos = off;
4091 }
4092
4093 boolean
4094 _bfd_elf_write_object_contents (abfd)
4095      bfd *abfd;
4096 {
4097   struct elf_backend_data *bed = get_elf_backend_data (abfd);
4098   Elf_Internal_Ehdr *i_ehdrp;
4099   Elf_Internal_Shdr **i_shdrp;
4100   boolean failed;
4101   unsigned int count, num_sec;
4102
4103   if (! abfd->output_has_begun
4104       && ! _bfd_elf_compute_section_file_positions
4105              (abfd, (struct bfd_link_info *) NULL))
4106     return false;
4107
4108   i_shdrp = elf_elfsections (abfd);
4109   i_ehdrp = elf_elfheader (abfd);
4110
4111   failed = false;
4112   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
4113   if (failed)
4114     return false;
4115
4116   _bfd_elf_assign_file_positions_for_relocs (abfd);
4117
4118   /* After writing the headers, we need to write the sections too...  */
4119   num_sec = elf_numsections (abfd);
4120   for (count = 1; count < num_sec; count++)
4121     {
4122       if (bed->elf_backend_section_processing)
4123         (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
4124       if (i_shdrp[count]->contents)
4125         {
4126           bfd_size_type amt = i_shdrp[count]->sh_size;
4127
4128           if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
4129               || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
4130             return false;
4131         }
4132       if (count == SHN_LORESERVE - 1)
4133         count += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4134     }
4135
4136   /* Write out the section header names.  */
4137   if (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
4138       || ! _bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd)))
4139     return false;
4140
4141   if (bed->elf_backend_final_write_processing)
4142     (*bed->elf_backend_final_write_processing) (abfd,
4143                                                 elf_tdata (abfd)->linker);
4144
4145   return bed->s->write_shdrs_and_ehdr (abfd);
4146 }
4147
4148 boolean
4149 _bfd_elf_write_corefile_contents (abfd)
4150      bfd *abfd;
4151 {
4152   /* Hopefully this can be done just like an object file.  */
4153   return _bfd_elf_write_object_contents (abfd);
4154 }
4155
4156 /* Given a section, search the header to find them.  */
4157
4158 int
4159 _bfd_elf_section_from_bfd_section (abfd, asect)
4160      bfd *abfd;
4161      struct sec *asect;
4162 {
4163   struct elf_backend_data *bed;
4164   int index;
4165
4166   if (elf_section_data (asect) != NULL
4167       && elf_section_data (asect)->this_idx != 0)
4168     return elf_section_data (asect)->this_idx;
4169
4170   if (bfd_is_abs_section (asect))
4171     index = SHN_ABS;
4172   else if (bfd_is_com_section (asect))
4173     index = SHN_COMMON;
4174   else if (bfd_is_und_section (asect))
4175     index = SHN_UNDEF;
4176   else
4177     {
4178       Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
4179       int maxindex = elf_numsections (abfd);
4180
4181       for (index = 1; index < maxindex; index++)
4182         {
4183           Elf_Internal_Shdr *hdr = i_shdrp[index];
4184
4185           if (hdr != NULL && hdr->bfd_section == asect)
4186             return index;
4187         }
4188       index = -1;
4189     }
4190
4191   bed = get_elf_backend_data (abfd);
4192   if (bed->elf_backend_section_from_bfd_section)
4193     {
4194       int retval = index;
4195
4196       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
4197         return retval;
4198     }
4199
4200   if (index == -1)
4201     bfd_set_error (bfd_error_nonrepresentable_section);
4202
4203   return index;
4204 }
4205
4206 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
4207    on error.  */
4208
4209 int
4210 _bfd_elf_symbol_from_bfd_symbol (abfd, asym_ptr_ptr)
4211      bfd *abfd;
4212      asymbol **asym_ptr_ptr;
4213 {
4214   asymbol *asym_ptr = *asym_ptr_ptr;
4215   int idx;
4216   flagword flags = asym_ptr->flags;
4217
4218   /* When gas creates relocations against local labels, it creates its
4219      own symbol for the section, but does put the symbol into the
4220      symbol chain, so udata is 0.  When the linker is generating
4221      relocatable output, this section symbol may be for one of the
4222      input sections rather than the output section.  */
4223   if (asym_ptr->udata.i == 0
4224       && (flags & BSF_SECTION_SYM)
4225       && asym_ptr->section)
4226     {
4227       int indx;
4228
4229       if (asym_ptr->section->output_section != NULL)
4230         indx = asym_ptr->section->output_section->index;
4231       else
4232         indx = asym_ptr->section->index;
4233       if (indx < elf_num_section_syms (abfd)
4234           && elf_section_syms (abfd)[indx] != NULL)
4235         asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
4236     }
4237
4238   idx = asym_ptr->udata.i;
4239
4240   if (idx == 0)
4241     {
4242       /* This case can occur when using --strip-symbol on a symbol
4243          which is used in a relocation entry.  */
4244       (*_bfd_error_handler)
4245         (_("%s: symbol `%s' required but not present"),
4246          bfd_archive_filename (abfd), bfd_asymbol_name (asym_ptr));
4247       bfd_set_error (bfd_error_no_symbols);
4248       return -1;
4249     }
4250
4251 #if DEBUG & 4
4252   {
4253     fprintf (stderr,
4254              "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx%s\n",
4255              (long) asym_ptr, asym_ptr->name, idx, flags,
4256              elf_symbol_flags (flags));
4257     fflush (stderr);
4258   }
4259 #endif
4260
4261   return idx;
4262 }
4263
4264 /* Copy private BFD data.  This copies any program header information.  */
4265
4266 static boolean
4267 copy_private_bfd_data (ibfd, obfd)
4268      bfd *ibfd;
4269      bfd *obfd;
4270 {
4271   Elf_Internal_Ehdr *       iehdr;
4272   struct elf_segment_map *  map;
4273   struct elf_segment_map *  map_first;
4274   struct elf_segment_map ** pointer_to_map;
4275   Elf_Internal_Phdr *       segment;
4276   asection *                section;
4277   unsigned int              i;
4278   unsigned int              num_segments;
4279   boolean                   phdr_included = false;
4280   bfd_vma                   maxpagesize;
4281   struct elf_segment_map *  phdr_adjust_seg = NULL;
4282   unsigned int              phdr_adjust_num = 0;
4283   struct elf_backend_data * bed;
4284
4285   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
4286       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
4287     return true;
4288
4289   if (elf_tdata (ibfd)->phdr == NULL)
4290     return true;
4291
4292   bed = get_elf_backend_data (ibfd);
4293   iehdr = elf_elfheader (ibfd);
4294
4295   map_first = NULL;
4296   pointer_to_map = &map_first;
4297
4298   num_segments = elf_elfheader (ibfd)->e_phnum;
4299   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
4300
4301   /* Returns the end address of the segment + 1.  */
4302 #define SEGMENT_END(segment, start)                     \
4303   (start + (segment->p_memsz > segment->p_filesz        \
4304    ? segment->p_memsz : segment->p_filesz))
4305
4306   /* Returns true if the given section is contained within
4307      the given segment.  VMA addresses are compared.  */
4308 #define IS_CONTAINED_BY_VMA(section, segment)           \
4309   (section->vma >= segment->p_vaddr                     \
4310    && (section->vma + section->_raw_size)               \
4311    <= (SEGMENT_END (segment, segment->p_vaddr)))
4312
4313   /* Returns true if the given section is contained within
4314      the given segment.  LMA addresses are compared.  */
4315 #define IS_CONTAINED_BY_LMA(section, segment, base)     \
4316     (section->lma >= base                               \
4317      && (section->lma + section->_raw_size)             \
4318      <= SEGMENT_END (segment, base))
4319
4320   /* Returns true if the given section is contained within the
4321      given segment.  Filepos addresses are compared in an elf
4322      backend function. */
4323 #define IS_CONTAINED_BY_FILEPOS(sec, seg, bed)          \
4324   (bed->is_contained_by_filepos                         \
4325    && (*bed->is_contained_by_filepos) (sec, seg))
4326
4327   /* Special case: corefile "NOTE" section containing regs, prpsinfo etc.  */
4328 #define IS_COREFILE_NOTE(p, s)                          \
4329             (p->p_type == PT_NOTE                       \
4330              && bfd_get_format (ibfd) == bfd_core       \
4331              && s->vma == 0 && s->lma == 0              \
4332              && (bfd_vma) s->filepos >= p->p_offset     \
4333              && (bfd_vma) s->filepos + s->_raw_size     \
4334              <= p->p_offset + p->p_filesz)
4335
4336   /* The complicated case when p_vaddr is 0 is to handle the Solaris
4337      linker, which generates a PT_INTERP section with p_vaddr and
4338      p_memsz set to 0.  */
4339 #define IS_SOLARIS_PT_INTERP(p, s)                      \
4340             (   p->p_vaddr == 0                         \
4341              && p->p_filesz > 0                         \
4342              && (s->flags & SEC_HAS_CONTENTS) != 0      \
4343              && s->_raw_size > 0                        \
4344              && (bfd_vma) s->filepos >= p->p_offset     \
4345              && ((bfd_vma) s->filepos + s->_raw_size    \
4346                      <= p->p_offset + p->p_filesz))
4347
4348   /* Decide if the given section should be included in the given segment.
4349      A section will be included if:
4350        1. It is within the address space of the segment -- we use the LMA
4351           if that is set for the segment and the VMA otherwise,
4352        2. It is an allocated segment,
4353        3. There is an output section associated with it,
4354        4. The section has not already been allocated to a previous segment.  */
4355 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)               \
4356   (((((segment->p_paddr                                                 \
4357        ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)       \
4358        : IS_CONTAINED_BY_VMA (section, segment))                        \
4359       || IS_SOLARIS_PT_INTERP (segment, section))                       \
4360      && (section->flags & SEC_ALLOC) != 0)                              \
4361     || IS_COREFILE_NOTE (segment, section)                              \
4362     || (IS_CONTAINED_BY_FILEPOS (section, segment, bed)                 \
4363         && (section->flags & SEC_ALLOC) == 0))                          \
4364    && section->output_section != NULL                                   \
4365    && section->segment_mark == false)
4366
4367   /* Returns true iff seg1 starts after the end of seg2.  */
4368 #define SEGMENT_AFTER_SEGMENT(seg1, seg2)               \
4369     (seg1->p_vaddr >= SEGMENT_END (seg2, seg2->p_vaddr))
4370
4371   /* Returns true iff seg1 and seg2 overlap.  */
4372 #define SEGMENT_OVERLAPS(seg1, seg2)                    \
4373   (!(SEGMENT_AFTER_SEGMENT (seg1, seg2) || SEGMENT_AFTER_SEGMENT (seg2, seg1)))
4374
4375   /* Initialise the segment mark field.  */
4376   for (section = ibfd->sections; section != NULL; section = section->next)
4377     section->segment_mark = false;
4378
4379   /* Scan through the segments specified in the program header
4380      of the input BFD.  For this first scan we look for overlaps
4381      in the loadable segments.  These can be created by weird
4382      parameters to objcopy.  */
4383   for (i = 0, segment = elf_tdata (ibfd)->phdr;
4384        i < num_segments;
4385        i++, segment++)
4386     {
4387       unsigned int j;
4388       Elf_Internal_Phdr *segment2;
4389
4390       if (segment->p_type != PT_LOAD)
4391         continue;
4392
4393       /* Determine if this segment overlaps any previous segments.  */
4394       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2 ++)
4395         {
4396           bfd_signed_vma extra_length;
4397
4398           if (segment2->p_type != PT_LOAD
4399               || ! SEGMENT_OVERLAPS (segment, segment2))
4400             continue;
4401
4402           /* Merge the two segments together.  */
4403           if (segment2->p_vaddr < segment->p_vaddr)
4404             {
4405               /* Extend SEGMENT2 to include SEGMENT and then delete
4406                  SEGMENT.  */
4407               extra_length =
4408                 SEGMENT_END (segment, segment->p_vaddr)
4409                 - SEGMENT_END (segment2, segment2->p_vaddr);
4410
4411               if (extra_length > 0)
4412                 {
4413                   segment2->p_memsz  += extra_length;
4414                   segment2->p_filesz += extra_length;
4415                 }
4416
4417               segment->p_type = PT_NULL;
4418
4419               /* Since we have deleted P we must restart the outer loop.  */
4420               i = 0;
4421               segment = elf_tdata (ibfd)->phdr;
4422               break;
4423             }
4424           else
4425             {
4426               /* Extend SEGMENT to include SEGMENT2 and then delete
4427                  SEGMENT2.  */
4428               extra_length =
4429                 SEGMENT_END (segment2, segment2->p_vaddr)
4430                 - SEGMENT_END (segment, segment->p_vaddr);
4431
4432               if (extra_length > 0)
4433                 {
4434                   segment->p_memsz  += extra_length;
4435                   segment->p_filesz += extra_length;
4436                 }
4437
4438               segment2->p_type = PT_NULL;
4439             }
4440         }
4441     }
4442
4443   /* The second scan attempts to assign sections to segments.  */
4444   for (i = 0, segment = elf_tdata (ibfd)->phdr;
4445        i < num_segments;
4446        i ++, segment ++)
4447     {
4448       unsigned int  section_count;
4449       asection **   sections;
4450       asection *    output_section;
4451       unsigned int  isec;
4452       bfd_vma       matching_lma;
4453       bfd_vma       suggested_lma;
4454       unsigned int  j;
4455       bfd_size_type amt;
4456
4457       if (segment->p_type == PT_NULL)
4458         continue;
4459
4460       /* Compute how many sections might be placed into this segment.  */
4461       section_count = 0;
4462       for (section = ibfd->sections; section != NULL; section = section->next)
4463         if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
4464           ++section_count;
4465
4466       /* Allocate a segment map big enough to contain all of the
4467          sections we have selected.  */
4468       amt = sizeof (struct elf_segment_map);
4469       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
4470       map = (struct elf_segment_map *) bfd_alloc (obfd, amt);
4471       if (map == NULL)
4472         return false;
4473
4474       /* Initialise the fields of the segment map.  Default to
4475          using the physical address of the segment in the input BFD.  */
4476       map->next          = NULL;
4477       map->p_type        = segment->p_type;
4478       map->p_flags       = segment->p_flags;
4479       map->p_flags_valid = 1;
4480       map->p_paddr       = segment->p_paddr;
4481       map->p_paddr_valid = 1;
4482
4483       /* Determine if this segment contains the ELF file header
4484          and if it contains the program headers themselves.  */
4485       map->includes_filehdr = (segment->p_offset == 0
4486                                && segment->p_filesz >= iehdr->e_ehsize);
4487
4488       map->includes_phdrs = 0;
4489
4490       if (! phdr_included || segment->p_type != PT_LOAD)
4491         {
4492           map->includes_phdrs =
4493             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
4494              && (segment->p_offset + segment->p_filesz
4495                  >= ((bfd_vma) iehdr->e_phoff
4496                      + iehdr->e_phnum * iehdr->e_phentsize)));
4497
4498           if (segment->p_type == PT_LOAD && map->includes_phdrs)
4499             phdr_included = true;
4500         }
4501
4502       if (section_count == 0)
4503         {
4504           /* Special segments, such as the PT_PHDR segment, may contain
4505              no sections, but ordinary, loadable segments should contain
4506              something.  */
4507           if (segment->p_type == PT_LOAD)
4508             (*_bfd_error_handler)
4509               (_("%s: warning: Empty loadable segment detected\n"),
4510                bfd_archive_filename (ibfd));
4511
4512           map->count = 0;
4513           *pointer_to_map = map;
4514           pointer_to_map = &map->next;
4515
4516           continue;
4517         }
4518
4519       /* Now scan the sections in the input BFD again and attempt
4520          to add their corresponding output sections to the segment map.
4521          The problem here is how to handle an output section which has
4522          been moved (ie had its LMA changed).  There are four possibilities:
4523
4524          1. None of the sections have been moved.
4525             In this case we can continue to use the segment LMA from the
4526             input BFD.
4527
4528          2. All of the sections have been moved by the same amount.
4529             In this case we can change the segment's LMA to match the LMA
4530             of the first section.
4531
4532          3. Some of the sections have been moved, others have not.
4533             In this case those sections which have not been moved can be
4534             placed in the current segment which will have to have its size,
4535             and possibly its LMA changed, and a new segment or segments will
4536             have to be created to contain the other sections.
4537
4538          4. The sections have been moved, but not be the same amount.
4539             In this case we can change the segment's LMA to match the LMA
4540             of the first section and we will have to create a new segment
4541             or segments to contain the other sections.
4542
4543          In order to save time, we allocate an array to hold the section
4544          pointers that we are interested in.  As these sections get assigned
4545          to a segment, they are removed from this array.  */
4546
4547       amt = (bfd_size_type) section_count * sizeof (asection *);
4548       sections = (asection **) bfd_malloc (amt);
4549       if (sections == NULL)
4550         return false;
4551
4552       /* Step One: Scan for segment vs section LMA conflicts.
4553          Also add the sections to the section array allocated above.
4554          Also add the sections to the current segment.  In the common
4555          case, where the sections have not been moved, this means that
4556          we have completely filled the segment, and there is nothing
4557          more to do.  */
4558       isec = 0;
4559       matching_lma = 0;
4560       suggested_lma = 0;
4561
4562       for (j = 0, section = ibfd->sections;
4563            section != NULL;
4564            section = section->next)
4565         {
4566           if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
4567             {
4568               output_section = section->output_section;
4569
4570               sections[j ++] = section;
4571
4572               /* The Solaris native linker always sets p_paddr to 0.
4573                  We try to catch that case here, and set it to the
4574                  correct value.  */
4575               if (segment->p_paddr == 0
4576                   && segment->p_vaddr != 0
4577                   && isec == 0
4578                   && output_section->lma != 0
4579                   && (output_section->vma == (segment->p_vaddr
4580                                               + (map->includes_filehdr
4581                                                  ? iehdr->e_ehsize
4582                                                  : 0)
4583                                               + (map->includes_phdrs
4584                                                  ? (iehdr->e_phnum
4585                                                     * iehdr->e_phentsize)
4586                                                  : 0))))
4587                 map->p_paddr = segment->p_vaddr;
4588
4589               /* Match up the physical address of the segment with the
4590                  LMA address of the output section.  */
4591               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
4592                   || IS_CONTAINED_BY_FILEPOS (section, segment, bed)
4593                   || IS_COREFILE_NOTE (segment, section))
4594                 {
4595                   if (matching_lma == 0)
4596                     matching_lma = output_section->lma;
4597
4598                   /* We assume that if the section fits within the segment
4599                      then it does not overlap any other section within that
4600                      segment.  */
4601                   map->sections[isec ++] = output_section;
4602                 }
4603               else if (suggested_lma == 0)
4604                 suggested_lma = output_section->lma;
4605             }
4606         }
4607
4608       BFD_ASSERT (j == section_count);
4609
4610       /* Step Two: Adjust the physical address of the current segment,
4611          if necessary.  */
4612       if (isec == section_count)
4613         {
4614           /* All of the sections fitted within the segment as currently
4615              specified.  This is the default case.  Add the segment to
4616              the list of built segments and carry on to process the next
4617              program header in the input BFD.  */
4618           map->count = section_count;
4619           *pointer_to_map = map;
4620           pointer_to_map = &map->next;
4621
4622           free (sections);
4623           continue;
4624         }
4625       else
4626         {
4627           if (matching_lma != 0)
4628             {
4629               /* At least one section fits inside the current segment.
4630                  Keep it, but modify its physical address to match the
4631                  LMA of the first section that fitted.  */
4632               map->p_paddr = matching_lma;
4633             }
4634           else
4635             {
4636               /* None of the sections fitted inside the current segment.
4637                  Change the current segment's physical address to match
4638                  the LMA of the first section.  */
4639               map->p_paddr = suggested_lma;
4640             }
4641
4642           /* Offset the segment physical address from the lma
4643              to allow for space taken up by elf headers.  */
4644           if (map->includes_filehdr)
4645             map->p_paddr -= iehdr->e_ehsize;
4646
4647           if (map->includes_phdrs)
4648             {
4649               map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
4650
4651               /* iehdr->e_phnum is just an estimate of the number
4652                  of program headers that we will need.  Make a note
4653                  here of the number we used and the segment we chose
4654                  to hold these headers, so that we can adjust the
4655                  offset when we know the correct value.  */
4656               phdr_adjust_num = iehdr->e_phnum;
4657               phdr_adjust_seg = map;
4658             }
4659         }
4660
4661       /* Step Three: Loop over the sections again, this time assigning
4662          those that fit to the current segment and removing them from the
4663          sections array; but making sure not to leave large gaps.  Once all
4664          possible sections have been assigned to the current segment it is
4665          added to the list of built segments and if sections still remain
4666          to be assigned, a new segment is constructed before repeating
4667          the loop.  */
4668       isec = 0;
4669       do
4670         {
4671           map->count = 0;
4672           suggested_lma = 0;
4673
4674           /* Fill the current segment with sections that fit.  */
4675           for (j = 0; j < section_count; j++)
4676             {
4677               section = sections[j];
4678
4679               if (section == NULL)
4680                 continue;
4681
4682               output_section = section->output_section;
4683
4684               BFD_ASSERT (output_section != NULL);
4685
4686               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
4687                   || IS_COREFILE_NOTE (segment, section))
4688                 {
4689                   if (map->count == 0)
4690                     {
4691                       /* If the first section in a segment does not start at
4692                          the beginning of the segment, then something is
4693                          wrong.  */
4694                       if (output_section->lma !=
4695                           (map->p_paddr
4696                            + (map->includes_filehdr ? iehdr->e_ehsize : 0)
4697                            + (map->includes_phdrs
4698                               ? iehdr->e_phnum * iehdr->e_phentsize
4699                               : 0)))
4700                         abort ();
4701                     }
4702                   else
4703                     {
4704                       asection * prev_sec;
4705
4706                       prev_sec = map->sections[map->count - 1];
4707
4708                       /* If the gap between the end of the previous section
4709                          and the start of this section is more than
4710                          maxpagesize then we need to start a new segment.  */
4711                       if ((BFD_ALIGN (prev_sec->lma + prev_sec->_raw_size,
4712                                       maxpagesize)
4713                            < BFD_ALIGN (output_section->lma, maxpagesize))
4714                           || ((prev_sec->lma + prev_sec->_raw_size)
4715                               > output_section->lma))
4716                         {
4717                           if (suggested_lma == 0)
4718                             suggested_lma = output_section->lma;
4719
4720                           continue;
4721                         }
4722                     }
4723
4724                   map->sections[map->count++] = output_section;
4725                   ++isec;
4726                   sections[j] = NULL;
4727                   section->segment_mark = true;
4728                 }
4729               else if (suggested_lma == 0)
4730                 suggested_lma = output_section->lma;
4731             }
4732
4733           BFD_ASSERT (map->count > 0);
4734
4735           /* Add the current segment to the list of built segments.  */
4736           *pointer_to_map = map;
4737           pointer_to_map = &map->next;
4738
4739           if (isec < section_count)
4740             {
4741               /* We still have not allocated all of the sections to
4742                  segments.  Create a new segment here, initialise it
4743                  and carry on looping.  */
4744               amt = sizeof (struct elf_segment_map);
4745               amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
4746               map = (struct elf_segment_map *) bfd_alloc (obfd, amt);
4747               if (map == NULL)
4748                 return false;
4749
4750               /* Initialise the fields of the segment map.  Set the physical
4751                  physical address to the LMA of the first section that has
4752                  not yet been assigned.  */
4753               map->next             = NULL;
4754               map->p_type           = segment->p_type;
4755               map->p_flags          = segment->p_flags;
4756               map->p_flags_valid    = 1;
4757               map->p_paddr          = suggested_lma;
4758               map->p_paddr_valid    = 1;
4759               map->includes_filehdr = 0;
4760               map->includes_phdrs   = 0;
4761             }
4762         }
4763       while (isec < section_count);
4764
4765       free (sections);
4766     }
4767
4768   /* The Solaris linker creates program headers in which all the
4769      p_paddr fields are zero.  When we try to objcopy or strip such a
4770      file, we get confused.  Check for this case, and if we find it
4771      reset the p_paddr_valid fields.  */
4772   for (map = map_first; map != NULL; map = map->next)
4773     if (map->p_paddr != 0)
4774       break;
4775   if (map == NULL)
4776     {
4777       for (map = map_first; map != NULL; map = map->next)
4778         map->p_paddr_valid = 0;
4779     }
4780
4781   elf_tdata (obfd)->segment_map = map_first;
4782
4783   /* If we had to estimate the number of program headers that were
4784      going to be needed, then check our estimate now and adjust
4785      the offset if necessary.  */
4786   if (phdr_adjust_seg != NULL)
4787     {
4788       unsigned int count;
4789
4790       for (count = 0, map = map_first; map != NULL; map = map->next)
4791         count++;
4792
4793       if (count > phdr_adjust_num)
4794         phdr_adjust_seg->p_paddr
4795           -= (count - phdr_adjust_num) * iehdr->e_phentsize;
4796     }
4797
4798 #if 0
4799   /* Final Step: Sort the segments into ascending order of physical
4800      address.  */
4801   if (map_first != NULL)
4802     {
4803       struct elf_segment_map *prev;
4804
4805       prev = map_first;
4806       for (map = map_first->next; map != NULL; prev = map, map = map->next)
4807         {
4808           /* Yes I know - its a bubble sort....  */
4809           if (map->next != NULL && (map->next->p_paddr < map->p_paddr))
4810             {
4811               /* Swap map and map->next.  */
4812               prev->next = map->next;
4813               map->next = map->next->next;
4814               prev->next->next = map;
4815
4816               /* Restart loop.  */
4817               map = map_first;
4818             }
4819         }
4820     }
4821 #endif
4822
4823 #undef SEGMENT_END
4824 #undef IS_CONTAINED_BY_VMA
4825 #undef IS_CONTAINED_BY_LMA
4826 #undef IS_CONTAINED_BY_FILEPOS
4827 #undef IS_COREFILE_NOTE
4828 #undef IS_SOLARIS_PT_INTERP
4829 #undef INCLUDE_SECTION_IN_SEGMENT
4830 #undef SEGMENT_AFTER_SEGMENT
4831 #undef SEGMENT_OVERLAPS
4832   return true;
4833 }
4834
4835 /* Copy private section information.  This copies over the entsize
4836    field, and sometimes the info field.  */
4837
4838 boolean
4839 _bfd_elf_copy_private_section_data (ibfd, isec, obfd, osec)
4840      bfd *ibfd;
4841      asection *isec;
4842      bfd *obfd;
4843      asection *osec;
4844 {
4845   Elf_Internal_Shdr *ihdr, *ohdr;
4846   const struct elf_backend_data *bed = get_elf_backend_data (ibfd);
4847
4848   if (ibfd->xvec->flavour != bfd_target_elf_flavour
4849       || obfd->xvec->flavour != bfd_target_elf_flavour)
4850     return true;
4851
4852   /* Copy over private BFD data if it has not already been copied.
4853      This must be done here, rather than in the copy_private_bfd_data
4854      entry point, because the latter is called after the section
4855      contents have been set, which means that the program headers have
4856      already been worked out.  The backend function provides a way to 
4857      override the test conditions and code path for the call to 
4858      copy_private_bfd_data.  */
4859   if (bed->copy_private_bfd_data_p)
4860     {
4861       if ((*bed->copy_private_bfd_data_p) (ibfd, isec, obfd, osec))
4862         if (! copy_private_bfd_data (ibfd, obfd))
4863           return false;
4864     } 
4865   else if (elf_tdata (obfd)->segment_map == NULL && elf_tdata (ibfd)->phdr != NULL)
4866     {
4867         asection *s;
4868
4869         /* Only set up the segments if there are no more SEC_ALLOC
4870            sections.  FIXME: This won't do the right thing if objcopy is
4871            used to remove the last SEC_ALLOC section, since objcopy
4872            won't call this routine in that case.  */
4873         for (s = isec->next; s != NULL; s = s->next)
4874           if ((s->flags & SEC_ALLOC) != 0)
4875             break;
4876         if (s == NULL)
4877           {
4878             if (! copy_private_bfd_data (ibfd, obfd))
4879               return false;
4880           }
4881     }
4882
4883   ihdr = &elf_section_data (isec)->this_hdr;
4884   ohdr = &elf_section_data (osec)->this_hdr;
4885
4886   ohdr->sh_entsize = ihdr->sh_entsize;
4887
4888   if (ihdr->sh_type == SHT_SYMTAB
4889       || ihdr->sh_type == SHT_DYNSYM
4890       || ihdr->sh_type == SHT_GNU_verneed
4891       || ihdr->sh_type == SHT_GNU_verdef)
4892     ohdr->sh_info = ihdr->sh_info;
4893
4894   elf_section_data (osec)->use_rela_p
4895     = elf_section_data (isec)->use_rela_p;
4896
4897   return true;
4898 }
4899
4900 /* Copy private symbol information.  If this symbol is in a section
4901    which we did not map into a BFD section, try to map the section
4902    index correctly.  We use special macro definitions for the mapped
4903    section indices; these definitions are interpreted by the
4904    swap_out_syms function.  */
4905
4906 #define MAP_ONESYMTAB (SHN_HIOS + 1)
4907 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
4908 #define MAP_STRTAB    (SHN_HIOS + 3)
4909 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
4910 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
4911
4912 boolean
4913 _bfd_elf_copy_private_symbol_data (ibfd, isymarg, obfd, osymarg)
4914      bfd *ibfd;
4915      asymbol *isymarg;
4916      bfd *obfd;
4917      asymbol *osymarg;
4918 {
4919   elf_symbol_type *isym, *osym;
4920
4921   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
4922       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
4923     return true;
4924
4925   isym = elf_symbol_from (ibfd, isymarg);
4926   osym = elf_symbol_from (obfd, osymarg);
4927
4928   if (isym != NULL
4929       && osym != NULL
4930       && bfd_is_abs_section (isym->symbol.section))
4931     {
4932       unsigned int shndx;
4933
4934       shndx = isym->internal_elf_sym.st_shndx;
4935       if (shndx == elf_onesymtab (ibfd))
4936         shndx = MAP_ONESYMTAB;
4937       else if (shndx == elf_dynsymtab (ibfd))
4938         shndx = MAP_DYNSYMTAB;
4939       else if (shndx == elf_tdata (ibfd)->strtab_section)
4940         shndx = MAP_STRTAB;
4941       else if (shndx == elf_tdata (ibfd)->shstrtab_section)
4942         shndx = MAP_SHSTRTAB;
4943       else if (shndx == elf_tdata (ibfd)->symtab_shndx_section)
4944         shndx = MAP_SYM_SHNDX;
4945       osym->internal_elf_sym.st_shndx = shndx;
4946     }
4947
4948   return true;
4949 }
4950
4951 /* Swap out the symbols.  */
4952
4953 static boolean
4954 swap_out_syms (abfd, sttp, relocatable_p)
4955      bfd *abfd;
4956      struct bfd_strtab_hash **sttp;
4957      int relocatable_p;
4958 {
4959   struct elf_backend_data *bed;
4960   int symcount;
4961   asymbol **syms;
4962   struct bfd_strtab_hash *stt;
4963   Elf_Internal_Shdr *symtab_hdr;
4964   Elf_Internal_Shdr *symtab_shndx_hdr;
4965   Elf_Internal_Shdr *symstrtab_hdr;
4966   char *outbound_syms;
4967   char *outbound_shndx;
4968   int idx;
4969   bfd_size_type amt;
4970
4971   if (!elf_map_symbols (abfd))
4972     return false;
4973
4974   /* Dump out the symtabs.  */
4975   stt = _bfd_elf_stringtab_init ();
4976   if (stt == NULL)
4977     return false;
4978
4979   bed = get_elf_backend_data (abfd);
4980   symcount = bfd_get_symcount (abfd);
4981   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
4982   symtab_hdr->sh_type = SHT_SYMTAB;
4983   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
4984   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
4985   symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
4986   symtab_hdr->sh_addralign = bed->s->file_align;
4987
4988   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
4989   symstrtab_hdr->sh_type = SHT_STRTAB;
4990
4991   amt = (bfd_size_type) (1 + symcount) * bed->s->sizeof_sym;
4992   outbound_syms = bfd_alloc (abfd, amt);
4993   if (outbound_syms == NULL)
4994     return false;
4995   symtab_hdr->contents = (PTR) outbound_syms;
4996
4997   outbound_shndx = NULL;
4998   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
4999   if (symtab_shndx_hdr->sh_name != 0)
5000     {
5001       amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
5002       outbound_shndx = bfd_alloc (abfd, amt);
5003       if (outbound_shndx == NULL)
5004         return false;
5005       memset (outbound_shndx, 0, (unsigned long) amt);
5006       symtab_shndx_hdr->contents = outbound_shndx;
5007       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
5008       symtab_shndx_hdr->sh_size = amt;
5009       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
5010       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
5011     }
5012
5013   /* now generate the data (for "contents") */
5014   {
5015     /* Fill in zeroth symbol and swap it out.  */
5016     Elf_Internal_Sym sym;
5017     sym.st_name = 0;
5018     sym.st_value = 0;
5019     sym.st_size = 0;
5020     sym.st_info = 0;
5021     sym.st_other = 0;
5022     sym.st_shndx = SHN_UNDEF;
5023     bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
5024     outbound_syms += bed->s->sizeof_sym;
5025     if (outbound_shndx != NULL)
5026       outbound_shndx += sizeof (Elf_External_Sym_Shndx);
5027   }
5028
5029   syms = bfd_get_outsymbols (abfd);
5030   for (idx = 0; idx < symcount; idx++)
5031     {
5032       Elf_Internal_Sym sym;
5033       bfd_vma value = syms[idx]->value;
5034       elf_symbol_type *type_ptr;
5035       flagword flags = syms[idx]->flags;
5036       int type;
5037
5038       if ((flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
5039         {
5040           /* Local section symbols have no name.  */
5041           sym.st_name = 0;
5042         }
5043       else
5044         {
5045           sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
5046                                                             syms[idx]->name,
5047                                                             true, false);
5048           if (sym.st_name == (unsigned long) -1)
5049             return false;
5050         }
5051
5052       type_ptr = elf_symbol_from (abfd, syms[idx]);
5053
5054       if ((flags & BSF_SECTION_SYM) == 0
5055           && bfd_is_com_section (syms[idx]->section))
5056         {
5057           /* ELF common symbols put the alignment into the `value' field,
5058              and the size into the `size' field.  This is backwards from
5059              how BFD handles it, so reverse it here.  */
5060           sym.st_size = value;
5061           if (type_ptr == NULL
5062               || type_ptr->internal_elf_sym.st_value == 0)
5063             sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
5064           else
5065             sym.st_value = type_ptr->internal_elf_sym.st_value;
5066           sym.st_shndx = _bfd_elf_section_from_bfd_section
5067             (abfd, syms[idx]->section);
5068         }
5069       else
5070         {
5071           asection *sec = syms[idx]->section;
5072           int shndx;
5073
5074           if (sec->output_section)
5075             {
5076               value += sec->output_offset;
5077               sec = sec->output_section;
5078             }
5079           /* Don't add in the section vma for relocatable output.  */
5080           if (! relocatable_p)
5081             value += sec->vma;
5082           sym.st_value = value;
5083           sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
5084
5085           if (bfd_is_abs_section (sec)
5086               && type_ptr != NULL
5087               && type_ptr->internal_elf_sym.st_shndx != 0)
5088             {
5089               /* This symbol is in a real ELF section which we did
5090                  not create as a BFD section.  Undo the mapping done
5091                  by copy_private_symbol_data.  */
5092               shndx = type_ptr->internal_elf_sym.st_shndx;
5093               switch (shndx)
5094                 {
5095                 case MAP_ONESYMTAB:
5096                   shndx = elf_onesymtab (abfd);
5097                   break;
5098                 case MAP_DYNSYMTAB:
5099                   shndx = elf_dynsymtab (abfd);
5100                   break;
5101                 case MAP_STRTAB:
5102                   shndx = elf_tdata (abfd)->strtab_section;
5103                   break;
5104                 case MAP_SHSTRTAB:
5105                   shndx = elf_tdata (abfd)->shstrtab_section;
5106                   break;
5107                 case MAP_SYM_SHNDX:
5108                   shndx = elf_tdata (abfd)->symtab_shndx_section;
5109                   break;
5110                 default:
5111                   break;
5112                 }
5113             }
5114           else
5115             {
5116               shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
5117
5118               if (shndx == -1)
5119                 {
5120                   asection *sec2;
5121
5122                   /* Writing this would be a hell of a lot easier if
5123                      we had some decent documentation on bfd, and
5124                      knew what to expect of the library, and what to
5125                      demand of applications.  For example, it
5126                      appears that `objcopy' might not set the
5127                      section of a symbol to be a section that is
5128                      actually in the output file.  */
5129                   sec2 = bfd_get_section_by_name (abfd, sec->name);
5130                   BFD_ASSERT (sec2 != 0);
5131                   shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
5132                   BFD_ASSERT (shndx != -1);
5133                 }
5134             }
5135
5136           sym.st_shndx = shndx;
5137         }
5138
5139       if ((flags & BSF_THREAD_LOCAL) != 0)
5140         type = STT_TLS;
5141       else if ((flags & BSF_FUNCTION) != 0)
5142         type = STT_FUNC;
5143       else if ((flags & BSF_OBJECT) != 0)
5144         type = STT_OBJECT;
5145       else
5146         type = STT_NOTYPE;
5147
5148       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
5149         type = STT_TLS;
5150
5151       /* Processor-specific types */
5152       if (type_ptr != NULL
5153           && bed->elf_backend_get_symbol_type)
5154         type = ((*bed->elf_backend_get_symbol_type)
5155                 (&type_ptr->internal_elf_sym, type));
5156
5157       if (flags & BSF_SECTION_SYM)
5158         {
5159           if (flags & BSF_GLOBAL)
5160             sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
5161           else
5162             sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
5163         }
5164       else if (bfd_is_com_section (syms[idx]->section))
5165         sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
5166       else if (bfd_is_und_section (syms[idx]->section))
5167         sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
5168                                     ? STB_WEAK
5169                                     : STB_GLOBAL),
5170                                    type);
5171       else if (flags & BSF_FILE)
5172         sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
5173       else
5174         {
5175           int bind = STB_LOCAL;
5176
5177           if (flags & BSF_LOCAL)
5178             bind = STB_LOCAL;
5179           else if (flags & BSF_WEAK)
5180             bind = STB_WEAK;
5181           else if (flags & BSF_GLOBAL)
5182             bind = STB_GLOBAL;
5183
5184           sym.st_info = ELF_ST_INFO (bind, type);
5185         }
5186
5187       if (type_ptr != NULL)
5188         sym.st_other = type_ptr->internal_elf_sym.st_other;
5189       else
5190         sym.st_other = 0;
5191
5192       bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
5193       outbound_syms += bed->s->sizeof_sym;
5194       if (outbound_shndx != NULL)
5195         outbound_shndx += sizeof (Elf_External_Sym_Shndx);
5196     }
5197
5198   *sttp = stt;
5199   symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
5200   symstrtab_hdr->sh_type = SHT_STRTAB;
5201
5202   symstrtab_hdr->sh_flags = 0;
5203   symstrtab_hdr->sh_addr = 0;
5204   symstrtab_hdr->sh_entsize = 0;
5205   symstrtab_hdr->sh_link = 0;
5206   symstrtab_hdr->sh_info = 0;
5207   symstrtab_hdr->sh_addralign = 1;
5208
5209   return true;
5210 }
5211
5212 /* Return the number of bytes required to hold the symtab vector.
5213
5214    Note that we base it on the count plus 1, since we will null terminate
5215    the vector allocated based on this size.  However, the ELF symbol table
5216    always has a dummy entry as symbol #0, so it ends up even.  */
5217
5218 long
5219 _bfd_elf_get_symtab_upper_bound (abfd)
5220      bfd *abfd;
5221 {
5222   long symcount;
5223   long symtab_size;
5224   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
5225
5226   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
5227   symtab_size = (symcount + 1) * (sizeof (asymbol *));
5228   if (symcount > 0)
5229     symtab_size -= sizeof (asymbol *);
5230
5231   return symtab_size;
5232 }
5233
5234 long
5235 _bfd_elf_get_dynamic_symtab_upper_bound (abfd)
5236      bfd *abfd;
5237 {
5238   long symcount;
5239   long symtab_size;
5240   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
5241
5242   if (elf_dynsymtab (abfd) == 0)
5243     {
5244       bfd_set_error (bfd_error_invalid_operation);
5245       return -1;
5246     }
5247
5248   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
5249   symtab_size = (symcount + 1) * (sizeof (asymbol *));
5250   if (symcount > 0)
5251     symtab_size -= sizeof (asymbol *);
5252
5253   return symtab_size;
5254 }
5255
5256 long
5257 _bfd_elf_get_reloc_upper_bound (abfd, asect)
5258      bfd *abfd ATTRIBUTE_UNUSED;
5259      sec_ptr asect;
5260 {
5261   return (asect->reloc_count + 1) * sizeof (arelent *);
5262 }
5263
5264 /* Canonicalize the relocs.  */
5265
5266 long
5267 _bfd_elf_canonicalize_reloc (abfd, section, relptr, symbols)
5268      bfd *abfd;
5269      sec_ptr section;
5270      arelent **relptr;
5271      asymbol **symbols;
5272 {
5273   arelent *tblptr;
5274   unsigned int i;
5275   struct elf_backend_data *bed = get_elf_backend_data (abfd);
5276
5277   if (! bed->s->slurp_reloc_table (abfd, section, symbols, false))
5278     return -1;
5279
5280   tblptr = section->relocation;
5281   for (i = 0; i < section->reloc_count; i++)
5282     *relptr++ = tblptr++;
5283
5284   *relptr = NULL;
5285
5286   return section->reloc_count;
5287 }
5288
5289 long
5290 _bfd_elf_get_symtab (abfd, alocation)
5291      bfd *abfd;
5292      asymbol **alocation;
5293 {
5294   struct elf_backend_data *bed = get_elf_backend_data (abfd);
5295   long symcount = bed->s->slurp_symbol_table (abfd, alocation, false);
5296
5297   if (symcount >= 0)
5298     bfd_get_symcount (abfd) = symcount;
5299   return symcount;
5300 }
5301
5302 long
5303 _bfd_elf_canonicalize_dynamic_symtab (abfd, alocation)
5304      bfd *abfd;
5305      asymbol **alocation;
5306 {
5307   struct elf_backend_data *bed = get_elf_backend_data (abfd);
5308   return bed->s->slurp_symbol_table (abfd, alocation, true);
5309 }
5310
5311 /* Return the size required for the dynamic reloc entries.  Any
5312    section that was actually installed in the BFD, and has type
5313    SHT_REL or SHT_RELA, and uses the dynamic symbol table, is
5314    considered to be a dynamic reloc section.  */
5315
5316 long
5317 _bfd_elf_get_dynamic_reloc_upper_bound (abfd)
5318      bfd *abfd;
5319 {
5320   long ret;
5321   asection *s;
5322
5323   if (elf_dynsymtab (abfd) == 0)
5324     {
5325       bfd_set_error (bfd_error_invalid_operation);
5326       return -1;
5327     }
5328
5329   ret = sizeof (arelent *);
5330   for (s = abfd->sections; s != NULL; s = s->next)
5331     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
5332         && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
5333             || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
5334       ret += ((s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize)
5335               * sizeof (arelent *));
5336
5337   return ret;
5338 }
5339
5340 /* Canonicalize the dynamic relocation entries.  Note that we return
5341    the dynamic relocations as a single block, although they are
5342    actually associated with particular sections; the interface, which
5343    was designed for SunOS style shared libraries, expects that there
5344    is only one set of dynamic relocs.  Any section that was actually
5345    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses
5346    the dynamic symbol table, is considered to be a dynamic reloc
5347    section.  */
5348
5349 long
5350 _bfd_elf_canonicalize_dynamic_reloc (abfd, storage, syms)
5351      bfd *abfd;
5352      arelent **storage;
5353      asymbol **syms;
5354 {
5355   boolean (*slurp_relocs) PARAMS ((bfd *, asection *, asymbol **, boolean));
5356   asection *s;
5357   long ret;
5358
5359   if (elf_dynsymtab (abfd) == 0)
5360     {
5361       bfd_set_error (bfd_error_invalid_operation);
5362       return -1;
5363     }
5364
5365   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
5366   ret = 0;
5367   for (s = abfd->sections; s != NULL; s = s->next)
5368     {
5369       if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
5370           && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
5371               || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
5372         {
5373           arelent *p;
5374           long count, i;
5375
5376           if (! (*slurp_relocs) (abfd, s, syms, true))
5377             return -1;
5378           count = s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize;
5379           p = s->relocation;
5380           for (i = 0; i < count; i++)
5381             *storage++ = p++;
5382           ret += count;
5383         }
5384     }
5385
5386   *storage = NULL;
5387
5388   return ret;
5389 }
5390 \f
5391 /* Read in the version information.  */
5392
5393 boolean
5394 _bfd_elf_slurp_version_tables (abfd)
5395      bfd *abfd;
5396 {
5397   bfd_byte *contents = NULL;
5398   bfd_size_type amt;
5399
5400   if (elf_dynverdef (abfd) != 0)
5401     {
5402       Elf_Internal_Shdr *hdr;
5403       Elf_External_Verdef *everdef;
5404       Elf_Internal_Verdef *iverdef;
5405       Elf_Internal_Verdef *iverdefarr;
5406       Elf_Internal_Verdef iverdefmem;
5407       unsigned int i;
5408       unsigned int maxidx;
5409
5410       hdr = &elf_tdata (abfd)->dynverdef_hdr;
5411
5412       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
5413       if (contents == NULL)
5414         goto error_return;
5415       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
5416           || bfd_bread ((PTR) contents, hdr->sh_size, abfd) != hdr->sh_size)
5417         goto error_return;
5418
5419       /* We know the number of entries in the section but not the maximum
5420          index.  Therefore we have to run through all entries and find
5421          the maximum.  */
5422       everdef = (Elf_External_Verdef *) contents;
5423       maxidx = 0;
5424       for (i = 0; i < hdr->sh_info; ++i)
5425         {
5426           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
5427
5428           if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
5429             maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
5430
5431           everdef = ((Elf_External_Verdef *)
5432                      ((bfd_byte *) everdef + iverdefmem.vd_next));
5433         }
5434
5435       amt = (bfd_size_type) maxidx * sizeof (Elf_Internal_Verdef);
5436       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *) bfd_zalloc (abfd, amt);
5437       if (elf_tdata (abfd)->verdef == NULL)
5438         goto error_return;
5439
5440       elf_tdata (abfd)->cverdefs = maxidx;
5441
5442       everdef = (Elf_External_Verdef *) contents;
5443       iverdefarr = elf_tdata (abfd)->verdef;
5444       for (i = 0; i < hdr->sh_info; i++)
5445         {
5446           Elf_External_Verdaux *everdaux;
5447           Elf_Internal_Verdaux *iverdaux;
5448           unsigned int j;
5449
5450           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
5451
5452           iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
5453           memcpy (iverdef, &iverdefmem, sizeof (Elf_Internal_Verdef));
5454
5455           iverdef->vd_bfd = abfd;
5456
5457           amt = (bfd_size_type) iverdef->vd_cnt * sizeof (Elf_Internal_Verdaux);
5458           iverdef->vd_auxptr = (Elf_Internal_Verdaux *) bfd_alloc (abfd, amt);
5459           if (iverdef->vd_auxptr == NULL)
5460             goto error_return;
5461
5462           everdaux = ((Elf_External_Verdaux *)
5463                       ((bfd_byte *) everdef + iverdef->vd_aux));
5464           iverdaux = iverdef->vd_auxptr;
5465           for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
5466             {
5467               _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
5468
5469               iverdaux->vda_nodename =
5470                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5471                                                  iverdaux->vda_name);
5472               if (iverdaux->vda_nodename == NULL)
5473                 goto error_return;
5474
5475               if (j + 1 < iverdef->vd_cnt)
5476                 iverdaux->vda_nextptr = iverdaux + 1;
5477               else
5478                 iverdaux->vda_nextptr = NULL;
5479
5480               everdaux = ((Elf_External_Verdaux *)
5481                           ((bfd_byte *) everdaux + iverdaux->vda_next));
5482             }
5483
5484           iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
5485
5486           if (i + 1 < hdr->sh_info)
5487             iverdef->vd_nextdef = iverdef + 1;
5488           else
5489             iverdef->vd_nextdef = NULL;
5490
5491           everdef = ((Elf_External_Verdef *)
5492                      ((bfd_byte *) everdef + iverdef->vd_next));
5493         }
5494
5495       free (contents);
5496       contents = NULL;
5497     }
5498
5499   if (elf_dynverref (abfd) != 0)
5500     {
5501       Elf_Internal_Shdr *hdr;
5502       Elf_External_Verneed *everneed;
5503       Elf_Internal_Verneed *iverneed;
5504       unsigned int i;
5505
5506       hdr = &elf_tdata (abfd)->dynverref_hdr;
5507
5508       amt = (bfd_size_type) hdr->sh_info * sizeof (Elf_Internal_Verneed);
5509       elf_tdata (abfd)->verref =
5510         (Elf_Internal_Verneed *) bfd_zalloc (abfd, amt);
5511       if (elf_tdata (abfd)->verref == NULL)
5512         goto error_return;
5513
5514       elf_tdata (abfd)->cverrefs = hdr->sh_info;
5515
5516       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
5517       if (contents == NULL)
5518         goto error_return;
5519       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
5520           || bfd_bread ((PTR) contents, hdr->sh_size, abfd) != hdr->sh_size)
5521         goto error_return;
5522
5523       everneed = (Elf_External_Verneed *) contents;
5524       iverneed = elf_tdata (abfd)->verref;
5525       for (i = 0; i < hdr->sh_info; i++, iverneed++)
5526         {
5527           Elf_External_Vernaux *evernaux;
5528           Elf_Internal_Vernaux *ivernaux;
5529           unsigned int j;
5530
5531           _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
5532
5533           iverneed->vn_bfd = abfd;
5534
5535           iverneed->vn_filename =
5536             bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5537                                              iverneed->vn_file);
5538           if (iverneed->vn_filename == NULL)
5539             goto error_return;
5540
5541           amt = iverneed->vn_cnt;
5542           amt *= sizeof (Elf_Internal_Vernaux);
5543           iverneed->vn_auxptr = (Elf_Internal_Vernaux *) bfd_alloc (abfd, amt);
5544
5545           evernaux = ((Elf_External_Vernaux *)
5546                       ((bfd_byte *) everneed + iverneed->vn_aux));
5547           ivernaux = iverneed->vn_auxptr;
5548           for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
5549             {
5550               _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
5551
5552               ivernaux->vna_nodename =
5553                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5554                                                  ivernaux->vna_name);
5555               if (ivernaux->vna_nodename == NULL)
5556                 goto error_return;
5557
5558               if (j + 1 < iverneed->vn_cnt)
5559                 ivernaux->vna_nextptr = ivernaux + 1;
5560               else
5561                 ivernaux->vna_nextptr = NULL;
5562
5563               evernaux = ((Elf_External_Vernaux *)
5564                           ((bfd_byte *) evernaux + ivernaux->vna_next));
5565             }
5566
5567           if (i + 1 < hdr->sh_info)
5568             iverneed->vn_nextref = iverneed + 1;
5569           else
5570             iverneed->vn_nextref = NULL;
5571
5572           everneed = ((Elf_External_Verneed *)
5573                       ((bfd_byte *) everneed + iverneed->vn_next));
5574         }
5575
5576       free (contents);
5577       contents = NULL;
5578     }
5579
5580   return true;
5581
5582  error_return:
5583   if (contents == NULL)
5584     free (contents);
5585   return false;
5586 }
5587 \f
5588 asymbol *
5589 _bfd_elf_make_empty_symbol (abfd)
5590      bfd *abfd;
5591 {
5592   elf_symbol_type *newsym;
5593   bfd_size_type amt = sizeof (elf_symbol_type);
5594
5595   newsym = (elf_symbol_type *) bfd_zalloc (abfd, amt);
5596   if (!newsym)
5597     return NULL;
5598   else
5599     {
5600       newsym->symbol.the_bfd = abfd;
5601       return &newsym->symbol;
5602     }
5603 }
5604
5605 void
5606 _bfd_elf_get_symbol_info (ignore_abfd, symbol, ret)
5607      bfd *ignore_abfd ATTRIBUTE_UNUSED;
5608      asymbol *symbol;
5609      symbol_info *ret;
5610 {
5611   bfd_symbol_info (symbol, ret);
5612 }
5613
5614 /* Return whether a symbol name implies a local symbol.  Most targets
5615    use this function for the is_local_label_name entry point, but some
5616    override it.  */
5617
5618 boolean
5619 _bfd_elf_is_local_label_name (abfd, name)
5620      bfd *abfd ATTRIBUTE_UNUSED;
5621      const char *name;
5622 {
5623   /* Normal local symbols start with ``.L''.  */
5624   if (name[0] == '.' && name[1] == 'L')
5625     return true;
5626
5627   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
5628      DWARF debugging symbols starting with ``..''.  */
5629   if (name[0] == '.' && name[1] == '.')
5630     return true;
5631
5632   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
5633      emitting DWARF debugging output.  I suspect this is actually a
5634      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
5635      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
5636      underscore to be emitted on some ELF targets).  For ease of use,
5637      we treat such symbols as local.  */
5638   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
5639     return true;
5640
5641   return false;
5642 }
5643
5644 alent *
5645 _bfd_elf_get_lineno (ignore_abfd, symbol)
5646      bfd *ignore_abfd ATTRIBUTE_UNUSED;
5647      asymbol *symbol ATTRIBUTE_UNUSED;
5648 {
5649   abort ();
5650   return NULL;
5651 }
5652
5653 boolean
5654 _bfd_elf_set_arch_mach (abfd, arch, machine)
5655      bfd *abfd;
5656      enum bfd_architecture arch;
5657      unsigned long machine;
5658 {
5659   /* If this isn't the right architecture for this backend, and this
5660      isn't the generic backend, fail.  */
5661   if (arch != get_elf_backend_data (abfd)->arch
5662       && arch != bfd_arch_unknown
5663       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
5664     return false;
5665
5666   return bfd_default_set_arch_mach (abfd, arch, machine);
5667 }
5668
5669 /* Find the function to a particular section and offset,
5670    for error reporting.  */
5671
5672 static boolean
5673 elf_find_function (abfd, section, symbols, offset,
5674                    filename_ptr, functionname_ptr)
5675      bfd *abfd ATTRIBUTE_UNUSED;
5676      asection *section;
5677      asymbol **symbols;
5678      bfd_vma offset;
5679      const char **filename_ptr;
5680      const char **functionname_ptr;
5681 {
5682   const char *filename;
5683   asymbol *func;
5684   bfd_vma low_func;
5685   asymbol **p;
5686
5687   filename = NULL;
5688   func = NULL;
5689   low_func = 0;
5690
5691   for (p = symbols; *p != NULL; p++)
5692     {
5693       elf_symbol_type *q;
5694
5695       q = (elf_symbol_type *) *p;
5696
5697       if (bfd_get_section (&q->symbol) != section)
5698         continue;
5699
5700       switch (ELF_ST_TYPE (q->internal_elf_sym.st_info))
5701         {
5702         default:
5703           break;
5704         case STT_FILE:
5705           filename = bfd_asymbol_name (&q->symbol);
5706           break;
5707         case STT_NOTYPE:
5708         case STT_FUNC:
5709           if (q->symbol.section == section
5710               && q->symbol.value >= low_func
5711               && q->symbol.value <= offset)
5712             {
5713               func = (asymbol *) q;
5714               low_func = q->symbol.value;
5715             }
5716           break;
5717         }
5718     }
5719
5720   if (func == NULL)
5721     return false;
5722
5723   if (filename_ptr)
5724     *filename_ptr = filename;
5725   if (functionname_ptr)
5726     *functionname_ptr = bfd_asymbol_name (func);
5727
5728   return true;
5729 }
5730
5731 /* Find the nearest line to a particular section and offset,
5732    for error reporting.  */
5733
5734 boolean
5735 _bfd_elf_find_nearest_line (abfd, section, symbols, offset,
5736                             filename_ptr, functionname_ptr, line_ptr)
5737      bfd *abfd;
5738      asection *section;
5739      asymbol **symbols;
5740      bfd_vma offset;
5741      const char **filename_ptr;
5742      const char **functionname_ptr;
5743      unsigned int *line_ptr;
5744 {
5745   boolean found;
5746
5747   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
5748                                      filename_ptr, functionname_ptr,
5749                                      line_ptr))
5750     {
5751       if (!*functionname_ptr)
5752         elf_find_function (abfd, section, symbols, offset,
5753                            *filename_ptr ? NULL : filename_ptr,
5754                            functionname_ptr);
5755
5756       return true;
5757     }
5758
5759   if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
5760                                      filename_ptr, functionname_ptr,
5761                                      line_ptr, 0,
5762                                      &elf_tdata (abfd)->dwarf2_find_line_info))
5763     {
5764       if (!*functionname_ptr)
5765         elf_find_function (abfd, section, symbols, offset,
5766                            *filename_ptr ? NULL : filename_ptr,
5767                            functionname_ptr);
5768
5769       return true;
5770     }
5771
5772   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
5773                                              &found, filename_ptr,
5774                                              functionname_ptr, line_ptr,
5775                                              &elf_tdata (abfd)->line_info))
5776     return false;
5777   if (found)
5778     return true;
5779
5780   if (symbols == NULL)
5781     return false;
5782
5783   if (! elf_find_function (abfd, section, symbols, offset,
5784                            filename_ptr, functionname_ptr))
5785     return false;
5786
5787   *line_ptr = 0;
5788   return true;
5789 }
5790
5791 int
5792 _bfd_elf_sizeof_headers (abfd, reloc)
5793      bfd *abfd;
5794      boolean reloc;
5795 {
5796   int ret;
5797
5798   ret = get_elf_backend_data (abfd)->s->sizeof_ehdr;
5799   if (! reloc)
5800     ret += get_program_header_size (abfd);
5801   return ret;
5802 }
5803
5804 boolean
5805 _bfd_elf_set_section_contents (abfd, section, location, offset, count)
5806      bfd *abfd;
5807      sec_ptr section;
5808      PTR location;
5809      file_ptr offset;
5810      bfd_size_type count;
5811 {
5812   Elf_Internal_Shdr *hdr;
5813   bfd_signed_vma pos;
5814
5815   if (! abfd->output_has_begun
5816       && ! _bfd_elf_compute_section_file_positions
5817       (abfd, (struct bfd_link_info *) NULL))
5818     return false;
5819
5820   hdr = &elf_section_data (section)->this_hdr;
5821   pos = hdr->sh_offset + offset;
5822   if (bfd_seek (abfd, pos, SEEK_SET) != 0
5823       || bfd_bwrite (location, count, abfd) != count)
5824     return false;
5825
5826   return true;
5827 }
5828
5829 void
5830 _bfd_elf_no_info_to_howto (abfd, cache_ptr, dst)
5831      bfd *abfd ATTRIBUTE_UNUSED;
5832      arelent *cache_ptr ATTRIBUTE_UNUSED;
5833      Elf_Internal_Rela *dst ATTRIBUTE_UNUSED;
5834 {
5835   abort ();
5836 }
5837
5838 #if 0
5839 void
5840 _bfd_elf_no_info_to_howto_rel (abfd, cache_ptr, dst)
5841      bfd *abfd;
5842      arelent *cache_ptr;
5843      Elf_Internal_Rel *dst;
5844 {
5845   abort ();
5846 }
5847 #endif
5848
5849 /* Try to convert a non-ELF reloc into an ELF one.  */
5850
5851 boolean
5852 _bfd_elf_validate_reloc (abfd, areloc)
5853      bfd *abfd;
5854      arelent *areloc;
5855 {
5856   /* Check whether we really have an ELF howto.  */
5857
5858   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
5859     {
5860       bfd_reloc_code_real_type code;
5861       reloc_howto_type *howto;
5862
5863       /* Alien reloc: Try to determine its type to replace it with an
5864          equivalent ELF reloc.  */
5865
5866       if (areloc->howto->pc_relative)
5867         {
5868           switch (areloc->howto->bitsize)
5869             {
5870             case 8:
5871               code = BFD_RELOC_8_PCREL;
5872               break;
5873             case 12:
5874               code = BFD_RELOC_12_PCREL;
5875               break;
5876             case 16:
5877               code = BFD_RELOC_16_PCREL;
5878               break;
5879             case 24:
5880               code = BFD_RELOC_24_PCREL;
5881               break;
5882             case 32:
5883               code = BFD_RELOC_32_PCREL;
5884               break;
5885             case 64:
5886               code = BFD_RELOC_64_PCREL;
5887               break;
5888             default:
5889               goto fail;
5890             }
5891
5892           howto = bfd_reloc_type_lookup (abfd, code);
5893
5894           if (areloc->howto->pcrel_offset != howto->pcrel_offset)
5895             {
5896               if (howto->pcrel_offset)
5897                 areloc->addend += areloc->address;
5898               else
5899                 areloc->addend -= areloc->address; /* addend is unsigned!! */
5900             }
5901         }
5902       else
5903         {
5904           switch (areloc->howto->bitsize)
5905             {
5906             case 8:
5907               code = BFD_RELOC_8;
5908               break;
5909             case 14:
5910               code = BFD_RELOC_14;
5911               break;
5912             case 16:
5913               code = BFD_RELOC_16;
5914               break;
5915             case 26:
5916               code = BFD_RELOC_26;
5917               break;
5918             case 32:
5919               code = BFD_RELOC_32;
5920               break;
5921             case 64:
5922               code = BFD_RELOC_64;
5923               break;
5924             default:
5925               goto fail;
5926             }
5927
5928           howto = bfd_reloc_type_lookup (abfd, code);
5929         }
5930
5931       if (howto)
5932         areloc->howto = howto;
5933       else
5934         goto fail;
5935     }
5936
5937   return true;
5938
5939  fail:
5940   (*_bfd_error_handler)
5941     (_("%s: unsupported relocation type %s"),
5942      bfd_archive_filename (abfd), areloc->howto->name);
5943   bfd_set_error (bfd_error_bad_value);
5944   return false;
5945 }
5946
5947 boolean
5948 _bfd_elf_close_and_cleanup (abfd)
5949      bfd *abfd;
5950 {
5951   if (bfd_get_format (abfd) == bfd_object)
5952     {
5953       if (elf_shstrtab (abfd) != NULL)
5954         _bfd_elf_strtab_free (elf_shstrtab (abfd));
5955     }
5956
5957   return _bfd_generic_close_and_cleanup (abfd);
5958 }
5959
5960 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
5961    in the relocation's offset.  Thus we cannot allow any sort of sanity
5962    range-checking to interfere.  There is nothing else to do in processing
5963    this reloc.  */
5964
5965 bfd_reloc_status_type
5966 _bfd_elf_rel_vtable_reloc_fn (abfd, re, symbol, data, is, obfd, errmsg)
5967      bfd *abfd ATTRIBUTE_UNUSED;
5968      arelent *re ATTRIBUTE_UNUSED;
5969      struct symbol_cache_entry *symbol ATTRIBUTE_UNUSED;
5970      PTR data ATTRIBUTE_UNUSED;
5971      asection *is ATTRIBUTE_UNUSED;
5972      bfd *obfd ATTRIBUTE_UNUSED;
5973      char **errmsg ATTRIBUTE_UNUSED;
5974 {
5975   return bfd_reloc_ok;
5976 }
5977 \f
5978 /* Elf core file support.  Much of this only works on native
5979    toolchains, since we rely on knowing the
5980    machine-dependent procfs structure in order to pick
5981    out details about the corefile.  */
5982
5983 #ifdef HAVE_SYS_PROCFS_H
5984 # include <sys/procfs.h>
5985 #endif
5986
5987 /* FIXME: this is kinda wrong, but it's what gdb wants.  */
5988
5989 static int
5990 elfcore_make_pid (abfd)
5991      bfd *abfd;
5992 {
5993   return ((elf_tdata (abfd)->core_lwpid << 16)
5994           + (elf_tdata (abfd)->core_pid));
5995 }
5996
5997 /* If there isn't a section called NAME, make one, using
5998    data from SECT.  Note, this function will generate a
5999    reference to NAME, so you shouldn't deallocate or
6000    overwrite it.  */
6001
6002 static boolean
6003 elfcore_maybe_make_sect (abfd, name, sect)
6004      bfd *abfd;
6005      char *name;
6006      asection *sect;
6007 {
6008   asection *sect2;
6009
6010   if (bfd_get_section_by_name (abfd, name) != NULL)
6011     return true;
6012
6013   sect2 = bfd_make_section (abfd, name);
6014   if (sect2 == NULL)
6015     return false;
6016
6017   sect2->_raw_size = sect->_raw_size;
6018   sect2->filepos = sect->filepos;
6019   sect2->flags = sect->flags;
6020   sect2->alignment_power = sect->alignment_power;
6021   return true;
6022 }
6023
6024 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
6025    actually creates up to two pseudosections:
6026    - For the single-threaded case, a section named NAME, unless
6027      such a section already exists.
6028    - For the multi-threaded case, a section named "NAME/PID", where
6029      PID is elfcore_make_pid (abfd).
6030    Both pseudosections have identical contents. */
6031 boolean
6032 _bfd_elfcore_make_pseudosection (abfd, name, size, filepos)
6033      bfd *abfd;
6034      char *name;
6035      size_t size;
6036      ufile_ptr filepos;
6037 {
6038   char buf[100];
6039   char *threaded_name;
6040   asection *sect;
6041
6042   /* Build the section name.  */
6043
6044   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
6045   threaded_name = bfd_alloc (abfd, (bfd_size_type) strlen (buf) + 1);
6046   if (threaded_name == NULL)
6047     return false;
6048   strcpy (threaded_name, buf);
6049
6050   sect = bfd_make_section (abfd, threaded_name);
6051   if (sect == NULL)
6052     return false;
6053   sect->_raw_size = size;
6054   sect->filepos = filepos;
6055   sect->flags = SEC_HAS_CONTENTS;
6056   sect->alignment_power = 2;
6057
6058   return elfcore_maybe_make_sect (abfd, name, sect);
6059 }
6060
6061 /* prstatus_t exists on:
6062      solaris 2.5+
6063      linux 2.[01] + glibc
6064      unixware 4.2
6065 */
6066
6067 #if defined (HAVE_PRSTATUS_T)
6068 static boolean elfcore_grok_prstatus PARAMS ((bfd *, Elf_Internal_Note *));
6069
6070 static boolean
6071 elfcore_grok_prstatus (abfd, note)
6072      bfd *abfd;
6073      Elf_Internal_Note *note;
6074 {
6075   size_t raw_size;
6076   int offset;
6077
6078   if (note->descsz == sizeof (prstatus_t))
6079     {
6080       prstatus_t prstat;
6081
6082       raw_size = sizeof (prstat.pr_reg);
6083       offset   = offsetof (prstatus_t, pr_reg);
6084       memcpy (&prstat, note->descdata, sizeof (prstat));
6085
6086       /* Do not overwrite the core signal if it
6087          has already been set by another thread.  */
6088       if (elf_tdata (abfd)->core_signal == 0)
6089         elf_tdata (abfd)->core_signal = prstat.pr_cursig;
6090       elf_tdata (abfd)->core_pid = prstat.pr_pid;
6091
6092       /* pr_who exists on:
6093          solaris 2.5+
6094          unixware 4.2
6095          pr_who doesn't exist on:
6096          linux 2.[01]
6097          */
6098 #if defined (HAVE_PRSTATUS_T_PR_WHO)
6099       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
6100 #endif
6101     }
6102 #if defined (HAVE_PRSTATUS32_T)
6103   else if (note->descsz == sizeof (prstatus32_t))
6104     {
6105       /* 64-bit host, 32-bit corefile */
6106       prstatus32_t prstat;
6107
6108       raw_size = sizeof (prstat.pr_reg);
6109       offset   = offsetof (prstatus32_t, pr_reg);
6110       memcpy (&prstat, note->descdata, sizeof (prstat));
6111
6112       /* Do not overwrite the core signal if it
6113          has already been set by another thread.  */
6114       if (elf_tdata (abfd)->core_signal == 0)
6115         elf_tdata (abfd)->core_signal = prstat.pr_cursig;
6116       elf_tdata (abfd)->core_pid = prstat.pr_pid;
6117
6118       /* pr_who exists on:
6119          solaris 2.5+
6120          unixware 4.2
6121          pr_who doesn't exist on:
6122          linux 2.[01]
6123          */
6124 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
6125       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
6126 #endif
6127     }
6128 #endif /* HAVE_PRSTATUS32_T */
6129   else
6130     {
6131       /* Fail - we don't know how to handle any other
6132          note size (ie. data object type).  */
6133       return true;
6134     }
6135
6136   /* Make a ".reg/999" section and a ".reg" section.  */
6137   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
6138                                           raw_size, note->descpos + offset);
6139 }
6140 #endif /* defined (HAVE_PRSTATUS_T) */
6141
6142 /* Create a pseudosection containing the exact contents of NOTE.  */
6143 static boolean
6144 elfcore_make_note_pseudosection (abfd, name, note)
6145      bfd *abfd;
6146      char *name;
6147      Elf_Internal_Note *note;
6148 {
6149   return _bfd_elfcore_make_pseudosection (abfd, name,
6150                                           note->descsz, note->descpos);
6151 }
6152
6153 /* There isn't a consistent prfpregset_t across platforms,
6154    but it doesn't matter, because we don't have to pick this
6155    data structure apart.  */
6156
6157 static boolean
6158 elfcore_grok_prfpreg (abfd, note)
6159      bfd *abfd;
6160      Elf_Internal_Note *note;
6161 {
6162   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6163 }
6164
6165 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
6166    type of 5 (NT_PRXFPREG).  Just include the whole note's contents
6167    literally.  */
6168
6169 static boolean
6170 elfcore_grok_prxfpreg (abfd, note)
6171      bfd *abfd;
6172      Elf_Internal_Note *note;
6173 {
6174   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
6175 }
6176
6177 #if defined (HAVE_PRPSINFO_T)
6178 typedef prpsinfo_t   elfcore_psinfo_t;
6179 #if defined (HAVE_PRPSINFO32_T)         /* Sparc64 cross Sparc32 */
6180 typedef prpsinfo32_t elfcore_psinfo32_t;
6181 #endif
6182 #endif
6183
6184 #if defined (HAVE_PSINFO_T)
6185 typedef psinfo_t   elfcore_psinfo_t;
6186 #if defined (HAVE_PSINFO32_T)           /* Sparc64 cross Sparc32 */
6187 typedef psinfo32_t elfcore_psinfo32_t;
6188 #endif
6189 #endif
6190
6191 /* return a malloc'ed copy of a string at START which is at
6192    most MAX bytes long, possibly without a terminating '\0'.
6193    the copy will always have a terminating '\0'.  */
6194
6195 char *
6196 _bfd_elfcore_strndup (abfd, start, max)
6197      bfd *abfd;
6198      char *start;
6199      size_t max;
6200 {
6201   char *dups;
6202   char *end = memchr (start, '\0', max);
6203   size_t len;
6204
6205   if (end == NULL)
6206     len = max;
6207   else
6208     len = end - start;
6209
6210   dups = bfd_alloc (abfd, (bfd_size_type) len + 1);
6211   if (dups == NULL)
6212     return NULL;
6213
6214   memcpy (dups, start, len);
6215   dups[len] = '\0';
6216
6217   return dups;
6218 }
6219
6220 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6221 static boolean elfcore_grok_psinfo PARAMS ((bfd *, Elf_Internal_Note *));
6222
6223 static boolean
6224 elfcore_grok_psinfo (abfd, note)
6225      bfd *abfd;
6226      Elf_Internal_Note *note;
6227 {
6228   if (note->descsz == sizeof (elfcore_psinfo_t))
6229     {
6230       elfcore_psinfo_t psinfo;
6231
6232       memcpy (&psinfo, note->descdata, sizeof (psinfo));
6233
6234       elf_tdata (abfd)->core_program
6235         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
6236                                 sizeof (psinfo.pr_fname));
6237
6238       elf_tdata (abfd)->core_command
6239         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
6240                                 sizeof (psinfo.pr_psargs));
6241     }
6242 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
6243   else if (note->descsz == sizeof (elfcore_psinfo32_t))
6244     {
6245       /* 64-bit host, 32-bit corefile */
6246       elfcore_psinfo32_t psinfo;
6247
6248       memcpy (&psinfo, note->descdata, sizeof (psinfo));
6249
6250       elf_tdata (abfd)->core_program
6251         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
6252                                 sizeof (psinfo.pr_fname));
6253
6254       elf_tdata (abfd)->core_command
6255         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
6256                                 sizeof (psinfo.pr_psargs));
6257     }
6258 #endif
6259
6260   else
6261     {
6262       /* Fail - we don't know how to handle any other
6263          note size (ie. data object type).  */
6264       return true;
6265     }
6266
6267   /* Note that for some reason, a spurious space is tacked
6268      onto the end of the args in some (at least one anyway)
6269      implementations, so strip it off if it exists.  */
6270
6271   {
6272     char *command = elf_tdata (abfd)->core_command;
6273     int n = strlen (command);
6274
6275     if (0 < n && command[n - 1] == ' ')
6276       command[n - 1] = '\0';
6277   }
6278
6279   return true;
6280 }
6281 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
6282
6283 #if defined (HAVE_PSTATUS_T)
6284 static boolean elfcore_grok_pstatus PARAMS ((bfd *, Elf_Internal_Note *));
6285
6286 static boolean
6287 elfcore_grok_pstatus (abfd, note)
6288      bfd *abfd;
6289      Elf_Internal_Note *note;
6290 {
6291   if (note->descsz == sizeof (pstatus_t)
6292 #if defined (HAVE_PXSTATUS_T)
6293       || note->descsz == sizeof (pxstatus_t)
6294 #endif
6295       )
6296     {
6297       pstatus_t pstat;
6298
6299       memcpy (&pstat, note->descdata, sizeof (pstat));
6300
6301       elf_tdata (abfd)->core_pid = pstat.pr_pid;
6302     }
6303 #if defined (HAVE_PSTATUS32_T)
6304   else if (note->descsz == sizeof (pstatus32_t))
6305     {
6306       /* 64-bit host, 32-bit corefile */
6307       pstatus32_t pstat;
6308
6309       memcpy (&pstat, note->descdata, sizeof (pstat));
6310
6311       elf_tdata (abfd)->core_pid = pstat.pr_pid;
6312     }
6313 #endif
6314   /* Could grab some more details from the "representative"
6315      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
6316      NT_LWPSTATUS note, presumably.  */
6317
6318   return true;
6319 }
6320 #endif /* defined (HAVE_PSTATUS_T) */
6321
6322 #if defined (HAVE_LWPSTATUS_T)
6323 static boolean elfcore_grok_lwpstatus PARAMS ((bfd *, Elf_Internal_Note *));
6324
6325 static boolean
6326 elfcore_grok_lwpstatus (abfd, note)
6327      bfd *abfd;
6328      Elf_Internal_Note *note;
6329 {
6330   lwpstatus_t lwpstat;
6331   char buf[100];
6332   char *name;
6333   asection *sect;
6334
6335   if (note->descsz != sizeof (lwpstat)
6336 #if defined (HAVE_LWPXSTATUS_T)
6337       && note->descsz != sizeof (lwpxstatus_t)
6338 #endif
6339       )
6340     return true;
6341
6342   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
6343
6344   elf_tdata (abfd)->core_lwpid = lwpstat.pr_lwpid;
6345   elf_tdata (abfd)->core_signal = lwpstat.pr_cursig;
6346
6347   /* Make a ".reg/999" section.  */
6348
6349   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
6350   name = bfd_alloc (abfd, (bfd_size_type) strlen (buf) + 1);
6351   if (name == NULL)
6352     return false;
6353   strcpy (name, buf);
6354
6355   sect = bfd_make_section (abfd, name);
6356   if (sect == NULL)
6357     return false;
6358
6359 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
6360   sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
6361   sect->filepos = note->descpos
6362     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
6363 #endif
6364
6365 #if defined (HAVE_LWPSTATUS_T_PR_REG)
6366   sect->_raw_size = sizeof (lwpstat.pr_reg);
6367   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
6368 #endif
6369
6370   sect->flags = SEC_HAS_CONTENTS;
6371   sect->alignment_power = 2;
6372
6373   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
6374     return false;
6375
6376   /* Make a ".reg2/999" section */
6377
6378   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
6379   name = bfd_alloc (abfd, (bfd_size_type) strlen (buf) + 1);
6380   if (name == NULL)
6381     return false;
6382   strcpy (name, buf);
6383
6384   sect = bfd_make_section (abfd, name);
6385   if (sect == NULL)
6386     return false;
6387
6388 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
6389   sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
6390   sect->filepos = note->descpos
6391     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
6392 #endif
6393
6394 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
6395   sect->_raw_size = sizeof (lwpstat.pr_fpreg);
6396   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
6397 #endif
6398
6399   sect->flags = SEC_HAS_CONTENTS;
6400   sect->alignment_power = 2;
6401
6402   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
6403 }
6404 #endif /* defined (HAVE_LWPSTATUS_T) */
6405
6406 #if defined (HAVE_WIN32_PSTATUS_T)
6407 static boolean
6408 elfcore_grok_win32pstatus (abfd, note)
6409      bfd *abfd;
6410      Elf_Internal_Note *note;
6411 {
6412   char buf[30];
6413   char *name;
6414   asection *sect;
6415   win32_pstatus_t pstatus;
6416
6417   if (note->descsz < sizeof (pstatus))
6418     return true;
6419
6420   memcpy (&pstatus, note->descdata, sizeof (pstatus));
6421
6422   switch (pstatus.data_type)
6423     {
6424     case NOTE_INFO_PROCESS:
6425       /* FIXME: need to add ->core_command.  */
6426       elf_tdata (abfd)->core_signal = pstatus.data.process_info.signal;
6427       elf_tdata (abfd)->core_pid = pstatus.data.process_info.pid;
6428       break;
6429
6430     case NOTE_INFO_THREAD:
6431       /* Make a ".reg/999" section.  */
6432       sprintf (buf, ".reg/%d", pstatus.data.thread_info.tid);
6433
6434       name = bfd_alloc (abfd, (bfd_size_type) strlen (buf) + 1);
6435       if (name == NULL)
6436         return false;
6437
6438       strcpy (name, buf);
6439
6440       sect = bfd_make_section (abfd, name);
6441       if (sect == NULL)
6442         return false;
6443
6444       sect->_raw_size = sizeof (pstatus.data.thread_info.thread_context);
6445       sect->filepos = (note->descpos
6446                        + offsetof (struct win32_pstatus,
6447                                    data.thread_info.thread_context));
6448       sect->flags = SEC_HAS_CONTENTS;
6449       sect->alignment_power = 2;
6450
6451       if (pstatus.data.thread_info.is_active_thread)
6452         if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
6453           return false;
6454       break;
6455
6456     case NOTE_INFO_MODULE:
6457       /* Make a ".module/xxxxxxxx" section.  */
6458       sprintf (buf, ".module/%08x", pstatus.data.module_info.base_address);
6459
6460       name = bfd_alloc (abfd, (bfd_size_type) strlen (buf) + 1);
6461       if (name == NULL)
6462         return false;
6463
6464       strcpy (name, buf);
6465
6466       sect = bfd_make_section (abfd, name);
6467
6468       if (sect == NULL)
6469         return false;
6470
6471       sect->_raw_size = note->descsz;
6472       sect->filepos = note->descpos;
6473       sect->flags = SEC_HAS_CONTENTS;
6474       sect->alignment_power = 2;
6475       break;
6476
6477     default:
6478       return true;
6479     }
6480
6481   return true;
6482 }
6483 #endif /* HAVE_WIN32_PSTATUS_T */
6484
6485 static boolean
6486 elfcore_grok_note (abfd, note)
6487      bfd *abfd;
6488      Elf_Internal_Note *note;
6489 {
6490   struct elf_backend_data *bed = get_elf_backend_data (abfd);
6491
6492   switch (note->type)
6493     {
6494     default:
6495       return true;
6496
6497     case NT_PRSTATUS:
6498       if (bed->elf_backend_grok_prstatus)
6499         if ((*bed->elf_backend_grok_prstatus) (abfd, note))
6500           return true;
6501 #if defined (HAVE_PRSTATUS_T)
6502       return elfcore_grok_prstatus (abfd, note);
6503 #else
6504       return true;
6505 #endif
6506
6507 #if defined (HAVE_PSTATUS_T)
6508     case NT_PSTATUS:
6509       return elfcore_grok_pstatus (abfd, note);
6510 #endif
6511
6512 #if defined (HAVE_LWPSTATUS_T)
6513     case NT_LWPSTATUS:
6514       return elfcore_grok_lwpstatus (abfd, note);
6515 #endif
6516
6517     case NT_FPREGSET:           /* FIXME: rename to NT_PRFPREG */
6518       return elfcore_grok_prfpreg (abfd, note);
6519
6520 #if defined (HAVE_WIN32_PSTATUS_T)
6521     case NT_WIN32PSTATUS:
6522       return elfcore_grok_win32pstatus (abfd, note);
6523 #endif
6524
6525     case NT_PRXFPREG:           /* Linux SSE extension */
6526       if (note->namesz == 5
6527           && ! strcmp (note->namedata, "LINUX"))
6528         return elfcore_grok_prxfpreg (abfd, note);
6529       else
6530         return true;
6531
6532     case NT_PRPSINFO:
6533     case NT_PSINFO:
6534       if (bed->elf_backend_grok_psinfo)
6535         if ((*bed->elf_backend_grok_psinfo) (abfd, note))
6536           return true;
6537 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6538       return elfcore_grok_psinfo (abfd, note);
6539 #else
6540       return true;
6541 #endif
6542     }
6543 }
6544
6545 static boolean
6546 elfcore_netbsd_get_lwpid (note, lwpidp)
6547      Elf_Internal_Note *note;
6548      int *lwpidp;
6549 {
6550   char *cp;
6551
6552   cp = strchr (note->namedata, '@');
6553   if (cp != NULL)
6554     {
6555       *lwpidp = atoi(cp + 1);
6556       return true;
6557     }
6558   return false;
6559 }
6560
6561 static boolean
6562 elfcore_grok_netbsd_procinfo (abfd, note)
6563      bfd *abfd;
6564      Elf_Internal_Note *note;
6565 {
6566
6567   /* Signal number at offset 0x08. */
6568   elf_tdata (abfd)->core_signal
6569     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
6570
6571   /* Process ID at offset 0x50. */
6572   elf_tdata (abfd)->core_pid
6573     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
6574
6575   /* Command name at 0x7c (max 32 bytes, including nul). */
6576   elf_tdata (abfd)->core_command
6577     = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
6578
6579   return true;
6580 }
6581
6582 static boolean
6583 elfcore_grok_netbsd_note (abfd, note)
6584      bfd *abfd;
6585      Elf_Internal_Note *note;
6586 {
6587   int lwp;
6588
6589   if (elfcore_netbsd_get_lwpid (note, &lwp))
6590     elf_tdata (abfd)->core_lwpid = lwp;
6591
6592   if (note->type == NT_NETBSDCORE_PROCINFO)
6593     {
6594       /* NetBSD-specific core "procinfo".  Note that we expect to
6595          find this note before any of the others, which is fine,
6596          since the kernel writes this note out first when it
6597          creates a core file.  */
6598       
6599       return elfcore_grok_netbsd_procinfo (abfd, note);
6600     }
6601
6602   /* As of Jan 2002 there are no other machine-independent notes
6603      defined for NetBSD core files.  If the note type is less
6604      than the start of the machine-dependent note types, we don't
6605      understand it.  */
6606   
6607   if (note->type < NT_NETBSDCORE_FIRSTMACH)
6608     return true;
6609
6610
6611   switch (bfd_get_arch (abfd))
6612     {
6613     /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
6614        PT_GETFPREGS == mach+2.  */
6615
6616     case bfd_arch_alpha:
6617     case bfd_arch_sparc:
6618       switch (note->type)
6619         {
6620         case NT_NETBSDCORE_FIRSTMACH+0:
6621           return elfcore_make_note_pseudosection (abfd, ".reg", note);
6622
6623         case NT_NETBSDCORE_FIRSTMACH+2:
6624           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6625
6626         default:
6627           return true;
6628         }
6629
6630     /* On all other arch's, PT_GETREGS == mach+1 and
6631        PT_GETFPREGS == mach+3.  */
6632
6633     default:
6634       switch (note->type)
6635         {
6636         case NT_NETBSDCORE_FIRSTMACH+1:
6637           return elfcore_make_note_pseudosection (abfd, ".reg", note);
6638
6639         case NT_NETBSDCORE_FIRSTMACH+3:
6640           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6641
6642         default:
6643           return true;
6644         }
6645     }
6646     /* NOTREACHED */
6647 }
6648
6649 /* Function: elfcore_write_note
6650
6651    Inputs: 
6652      buffer to hold note
6653      name of note
6654      type of note
6655      data for note
6656      size of data for note
6657
6658    Return:
6659    End of buffer containing note.  */
6660
6661 char *
6662 elfcore_write_note (abfd, buf, bufsiz, name, type, input, size)
6663      bfd  *abfd;
6664      char *buf;
6665      int  *bufsiz;
6666      char *name;
6667      int  type;
6668      void *input;
6669      int  size;
6670 {
6671   Elf_External_Note *xnp;
6672   int namesz = strlen (name);
6673   int newspace = BFD_ALIGN (sizeof (Elf_External_Note) + size + namesz - 1, 4);
6674   char *p, *dest;
6675
6676   p = realloc (buf, *bufsiz + newspace);
6677   dest = p + *bufsiz;
6678   *bufsiz += newspace;
6679   xnp = (Elf_External_Note *) dest;
6680   H_PUT_32 (abfd, namesz, xnp->namesz);
6681   H_PUT_32 (abfd, size, xnp->descsz);
6682   H_PUT_32 (abfd, type, xnp->type);
6683   strcpy (xnp->name, name);
6684   memcpy (xnp->name + BFD_ALIGN (namesz, 4), input, size);
6685   return p;
6686 }
6687
6688 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6689 char *
6690 elfcore_write_prpsinfo (abfd, buf, bufsiz, fname, psargs)
6691      bfd  *abfd;
6692      char *buf;
6693      int  *bufsiz;
6694      char *fname; 
6695      char *psargs;
6696 {
6697   int note_type;
6698   char *note_name = "CORE";
6699
6700 #if defined (HAVE_PSINFO_T)
6701   psinfo_t  data;
6702   note_type = NT_PSINFO;
6703 #else
6704   prpsinfo_t data;
6705   note_type = NT_PRPSINFO;
6706 #endif
6707
6708   memset (&data, 0, sizeof (data));
6709   strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
6710   strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
6711   return elfcore_write_note (abfd, buf, bufsiz, 
6712                              note_name, note_type, &data, sizeof (data));
6713 }
6714 #endif  /* PSINFO_T or PRPSINFO_T */
6715
6716 #if defined (HAVE_PRSTATUS_T)
6717 char *
6718 elfcore_write_prstatus (abfd, buf, bufsiz, pid, cursig, gregs)
6719      bfd *abfd;
6720      char *buf;
6721      int *bufsiz;
6722      long pid;
6723      int cursig;
6724      void *gregs;
6725 {
6726   prstatus_t prstat;
6727   char *note_name = "CORE";
6728
6729   memset (&prstat, 0, sizeof (prstat));
6730   prstat.pr_pid = pid;
6731   prstat.pr_cursig = cursig;
6732   memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
6733   return elfcore_write_note (abfd, buf, bufsiz, 
6734                              note_name, NT_PRSTATUS, &prstat, sizeof (prstat));
6735 }
6736 #endif /* HAVE_PRSTATUS_T */
6737
6738 #if defined (HAVE_LWPSTATUS_T)
6739 char *
6740 elfcore_write_lwpstatus (abfd, buf, bufsiz, pid, cursig, gregs)
6741      bfd *abfd;
6742      char *buf;
6743      int *bufsiz;
6744      long pid;
6745      int cursig;
6746      void *gregs;
6747 {
6748   lwpstatus_t lwpstat;
6749   char *note_name = "CORE";
6750
6751   memset (&lwpstat, 0, sizeof (lwpstat));
6752   lwpstat.pr_lwpid  = pid >> 16;
6753   lwpstat.pr_cursig = cursig;
6754 #if defined (HAVE_LWPSTATUS_T_PR_REG)
6755   memcpy (lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
6756 #elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
6757 #if !defined(gregs)
6758   memcpy (lwpstat.pr_context.uc_mcontext.gregs,
6759           gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
6760 #else
6761   memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
6762           gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
6763 #endif
6764 #endif
6765   return elfcore_write_note (abfd, buf, bufsiz, note_name, 
6766                              NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
6767 }
6768 #endif /* HAVE_LWPSTATUS_T */
6769
6770 #if defined (HAVE_PSTATUS_T)
6771 char *
6772 elfcore_write_pstatus (abfd, buf, bufsiz, pid, cursig, gregs)
6773      bfd *abfd;
6774      char *buf;
6775      int *bufsiz;
6776      long pid;
6777      int cursig;
6778      void *gregs;
6779 {
6780   pstatus_t pstat;
6781   char *note_name = "CORE";
6782
6783   memset (&pstat, 0, sizeof (pstat));
6784   pstat.pr_pid = pid & 0xffff;
6785   buf = elfcore_write_note (abfd, buf, bufsiz, note_name, 
6786                             NT_PSTATUS, &pstat, sizeof (pstat));
6787   return buf;
6788 }
6789 #endif /* HAVE_PSTATUS_T */
6790
6791 char *
6792 elfcore_write_prfpreg (abfd, buf, bufsiz, fpregs, size)
6793      bfd  *abfd;
6794      char *buf;
6795      int  *bufsiz;
6796      void *fpregs;
6797      int size;
6798 {
6799   char *note_name = "CORE";
6800   return elfcore_write_note (abfd, buf, bufsiz, 
6801                              note_name, NT_FPREGSET, fpregs, size);
6802 }
6803
6804 char *
6805 elfcore_write_prxfpreg (abfd, buf, bufsiz, xfpregs, size)
6806      bfd  *abfd;
6807      char *buf;
6808      int  *bufsiz;
6809      void *xfpregs;
6810      int size;
6811 {
6812   char *note_name = "LINUX";
6813   return elfcore_write_note (abfd, buf, bufsiz, 
6814                              note_name, NT_PRXFPREG, xfpregs, size);
6815 }
6816
6817 static boolean
6818 elfcore_read_notes (abfd, offset, size)
6819      bfd *abfd;
6820      file_ptr offset;
6821      bfd_size_type size;
6822 {
6823   char *buf;
6824   char *p;
6825
6826   if (size <= 0)
6827     return true;
6828
6829   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
6830     return false;
6831
6832   buf = bfd_malloc (size);
6833   if (buf == NULL)
6834     return false;
6835
6836   if (bfd_bread (buf, size, abfd) != size)
6837     {
6838     error:
6839       free (buf);
6840       return false;
6841     }
6842
6843   p = buf;
6844   while (p < buf + size)
6845     {
6846       /* FIXME: bad alignment assumption.  */
6847       Elf_External_Note *xnp = (Elf_External_Note *) p;
6848       Elf_Internal_Note in;
6849
6850       in.type = H_GET_32 (abfd, xnp->type);
6851
6852       in.namesz = H_GET_32 (abfd, xnp->namesz);
6853       in.namedata = xnp->name;
6854
6855       in.descsz = H_GET_32 (abfd, xnp->descsz);
6856       in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
6857       in.descpos = offset + (in.descdata - buf);
6858
6859       if (strncmp (in.namedata, "NetBSD-CORE", 11) == 0)
6860         {
6861           if (! elfcore_grok_netbsd_note (abfd, &in))
6862             goto error;
6863         }
6864       else
6865         {
6866           if (! elfcore_grok_note (abfd, &in))
6867             goto error;
6868         }
6869
6870       p = in.descdata + BFD_ALIGN (in.descsz, 4);
6871     }
6872
6873   free (buf);
6874   return true;
6875 }
6876 \f
6877 /* Providing external access to the ELF program header table.  */
6878
6879 /* Return an upper bound on the number of bytes required to store a
6880    copy of ABFD's program header table entries.  Return -1 if an error
6881    occurs; bfd_get_error will return an appropriate code.  */
6882
6883 long
6884 bfd_get_elf_phdr_upper_bound (abfd)
6885      bfd *abfd;
6886 {
6887   if (abfd->xvec->flavour != bfd_target_elf_flavour)
6888     {
6889       bfd_set_error (bfd_error_wrong_format);
6890       return -1;
6891     }
6892
6893   return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
6894 }
6895
6896 /* Copy ABFD's program header table entries to *PHDRS.  The entries
6897    will be stored as an array of Elf_Internal_Phdr structures, as
6898    defined in include/elf/internal.h.  To find out how large the
6899    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
6900
6901    Return the number of program header table entries read, or -1 if an
6902    error occurs; bfd_get_error will return an appropriate code.  */
6903
6904 int
6905 bfd_get_elf_phdrs (abfd, phdrs)
6906      bfd *abfd;
6907      void *phdrs;
6908 {
6909   int num_phdrs;
6910
6911   if (abfd->xvec->flavour != bfd_target_elf_flavour)
6912     {
6913       bfd_set_error (bfd_error_wrong_format);
6914       return -1;
6915     }
6916
6917   num_phdrs = elf_elfheader (abfd)->e_phnum;
6918   memcpy (phdrs, elf_tdata (abfd)->phdr,
6919           num_phdrs * sizeof (Elf_Internal_Phdr));
6920
6921   return num_phdrs;
6922 }
6923
6924 void
6925 _bfd_elf_sprintf_vma (abfd, buf, value)
6926      bfd *abfd ATTRIBUTE_UNUSED;
6927      char *buf;
6928      bfd_vma value;
6929 {
6930 #ifdef BFD64
6931   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
6932
6933   i_ehdrp = elf_elfheader (abfd);
6934   if (i_ehdrp == NULL)
6935     sprintf_vma (buf, value);
6936   else
6937     {
6938       if (i_ehdrp->e_ident[EI_CLASS] == ELFCLASS64)
6939         {
6940 #if BFD_HOST_64BIT_LONG
6941           sprintf (buf, "%016lx", value);
6942 #else
6943           sprintf (buf, "%08lx%08lx", _bfd_int64_high (value),
6944                    _bfd_int64_low (value));
6945 #endif
6946         }
6947       else
6948         sprintf (buf, "%08lx", (unsigned long) (value & 0xffffffff));
6949     }
6950 #else
6951   sprintf_vma (buf, value);
6952 #endif
6953 }
6954
6955 void
6956 _bfd_elf_fprintf_vma (abfd, stream, value)
6957      bfd *abfd ATTRIBUTE_UNUSED;
6958      PTR stream;
6959      bfd_vma value;
6960 {
6961 #ifdef BFD64
6962   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
6963
6964   i_ehdrp = elf_elfheader (abfd);
6965   if (i_ehdrp == NULL)
6966     fprintf_vma ((FILE *) stream, value);
6967   else
6968     {
6969       if (i_ehdrp->e_ident[EI_CLASS] == ELFCLASS64)
6970         {
6971 #if BFD_HOST_64BIT_LONG
6972           fprintf ((FILE *) stream, "%016lx", value);
6973 #else
6974           fprintf ((FILE *) stream, "%08lx%08lx",
6975                    _bfd_int64_high (value), _bfd_int64_low (value));
6976 #endif
6977         }
6978       else
6979         fprintf ((FILE *) stream, "%08lx",
6980                  (unsigned long) (value & 0xffffffff));
6981     }
6982 #else
6983   fprintf_vma ((FILE *) stream, value);
6984 #endif
6985 }
6986
6987 enum elf_reloc_type_class
6988 _bfd_elf_reloc_type_class (rela)
6989      const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED;
6990 {
6991   return reloc_class_normal;
6992 }
6993
6994 /* For RELA architectures, return what the relocation value for
6995    relocation against a local symbol.  */
6996
6997 bfd_vma
6998 _bfd_elf_rela_local_sym (abfd, sym, sec, rel)
6999      bfd *abfd;
7000      Elf_Internal_Sym *sym;
7001      asection *sec;
7002      Elf_Internal_Rela *rel;
7003 {
7004   bfd_vma relocation;
7005
7006   relocation = (sec->output_section->vma
7007                 + sec->output_offset
7008                 + sym->st_value);
7009   if ((sec->flags & SEC_MERGE)
7010       && ELF_ST_TYPE (sym->st_info) == STT_SECTION
7011       && elf_section_data (sec)->sec_info_type == ELF_INFO_TYPE_MERGE)
7012     {
7013       asection *msec;
7014
7015       msec = sec;
7016       rel->r_addend =
7017         _bfd_merged_section_offset (abfd, &msec,
7018                                     elf_section_data (sec)->sec_info,
7019                                     sym->st_value + rel->r_addend,
7020                                     (bfd_vma) 0)
7021         - relocation;
7022       rel->r_addend += msec->output_section->vma + msec->output_offset;
7023     }
7024   return relocation;
7025 }
7026
7027 bfd_vma
7028 _bfd_elf_rel_local_sym (abfd, sym, psec, addend)
7029      bfd *abfd;
7030      Elf_Internal_Sym *sym;
7031      asection **psec;
7032      bfd_vma addend;
7033 {     
7034   asection *sec = *psec;
7035
7036   if (elf_section_data (sec)->sec_info_type != ELF_INFO_TYPE_MERGE)
7037     return sym->st_value + addend;
7038
7039   return _bfd_merged_section_offset (abfd, psec,
7040                                      elf_section_data (sec)->sec_info,
7041                                      sym->st_value + addend, (bfd_vma) 0);
7042 }
7043
7044 bfd_vma
7045 _bfd_elf_section_offset (abfd, info, sec, offset)
7046      bfd *abfd;
7047      struct bfd_link_info *info;
7048      asection *sec;
7049      bfd_vma offset;
7050 {
7051   struct bfd_elf_section_data *sec_data;
7052
7053   sec_data = elf_section_data (sec);
7054   switch (sec_data->sec_info_type)
7055     {
7056     case ELF_INFO_TYPE_STABS:
7057       return _bfd_stab_section_offset
7058         (abfd, &elf_hash_table (info)->merge_info, sec, &sec_data->sec_info,
7059          offset);
7060     case ELF_INFO_TYPE_EH_FRAME:
7061       return _bfd_elf_eh_frame_section_offset (abfd, sec, offset);
7062     default:
7063       return offset;
7064     }
7065 }
This page took 0.432351 seconds and 4 git commands to generate.