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