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