]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/binutils/bfd/elf.c
Merge ^vendor/binutils/dist@214033 into contrib/binutils.
[FreeBSD/FreeBSD.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   { ".gnu.linkonce.b",15, -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE },
2030   { ".comment",        8,  0, SHT_PROGBITS, 0 },
2031   { ".data",           5, -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
2032   { ".data1",          6,  0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
2033   { ".debug",          6,  0, SHT_PROGBITS, 0 },
2034   { ".fini",           5,  0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
2035   { ".init",           5,  0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
2036   { ".line",           5,  0, SHT_PROGBITS, 0 },
2037   { ".rodata",         7, -2, SHT_PROGBITS, SHF_ALLOC },
2038   { ".rodata1",        8,  0, SHT_PROGBITS, SHF_ALLOC },
2039   { ".tbss",           5, -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE + SHF_TLS },
2040   { ".tdata",          6, -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_TLS },
2041   { ".text",           5, -2, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
2042   { ".init_array",    11,  0, SHT_INIT_ARRAY, SHF_ALLOC + SHF_WRITE },
2043   { ".fini_array",    11,  0, SHT_FINI_ARRAY, SHF_ALLOC + SHF_WRITE },
2044   { ".preinit_array", 14,  0, SHT_PREINIT_ARRAY, SHF_ALLOC + SHF_WRITE },
2045   { ".debug_line",    11,  0, SHT_PROGBITS, 0 },
2046   { ".debug_info",    11,  0, SHT_PROGBITS, 0 },
2047   { ".debug_abbrev",  13,  0, SHT_PROGBITS, 0 },
2048   { ".debug_aranges", 14,  0, SHT_PROGBITS, 0 },
2049   { ".dynamic",        8,  0, SHT_DYNAMIC,  SHF_ALLOC },
2050   { ".dynstr",         7,  0, SHT_STRTAB,   SHF_ALLOC },
2051   { ".dynsym",         7,  0, SHT_DYNSYM,   SHF_ALLOC },
2052   { ".got",            4,  0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
2053   { ".hash",           5,  0, SHT_HASH,     SHF_ALLOC },
2054   { ".interp",         7,  0, SHT_PROGBITS, 0 },
2055   { ".plt",            4,  0, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
2056   { ".shstrtab",       9,  0, SHT_STRTAB,   0 },
2057   { ".strtab",         7,  0, SHT_STRTAB,   0 },
2058   { ".symtab",         7,  0, SHT_SYMTAB,   0 },
2059   { ".gnu.version",   12,  0, SHT_GNU_versym, 0 },
2060   { ".gnu.version_d", 14,  0, SHT_GNU_verdef, 0 },
2061   { ".gnu.version_r", 14,  0, SHT_GNU_verneed, 0 },
2062   { ".note",           5, -1, SHT_NOTE,     0 },
2063   { ".rela",           5, -1, SHT_RELA,     0 },
2064   { ".rel",            4, -1, SHT_REL,      0 },
2065   { ".stabstr",        5,  3, SHT_STRTAB,   0 },
2066   { NULL,              0,  0, 0,            0 }
2067 };
2068
2069 static const struct bfd_elf_special_section *
2070 get_special_section (const char *name,
2071                      const struct bfd_elf_special_section *special_sections,
2072                      unsigned int rela)
2073 {
2074   int i;
2075   int len = strlen (name);
2076
2077   for (i = 0; special_sections[i].prefix != NULL; i++)
2078     {
2079       int suffix_len;
2080       int prefix_len = special_sections[i].prefix_length;
2081
2082       if (len < prefix_len)
2083         continue;
2084       if (memcmp (name, special_sections[i].prefix, prefix_len) != 0)
2085         continue;
2086
2087       suffix_len = special_sections[i].suffix_length;
2088       if (suffix_len <= 0)
2089         {
2090           if (name[prefix_len] != 0)
2091             {
2092               if (suffix_len == 0)
2093                 continue;
2094               if (name[prefix_len] != '.'
2095                   && (suffix_len == -2
2096                       || (rela && special_sections[i].type == SHT_REL)))
2097                 continue;
2098             }
2099         }
2100       else
2101         {
2102           if (len < prefix_len + suffix_len)
2103             continue;
2104           if (memcmp (name + len - suffix_len,
2105                       special_sections[i].prefix + prefix_len,
2106                       suffix_len) != 0)
2107             continue;
2108         }
2109       return &special_sections[i];
2110     }
2111
2112   return NULL;
2113 }
2114
2115 const struct bfd_elf_special_section *
2116 _bfd_elf_get_sec_type_attr (bfd *abfd, const char *name)
2117 {
2118   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2119   const struct bfd_elf_special_section *ssect = NULL;
2120
2121   /* See if this is one of the special sections.  */
2122   if (name)
2123     {
2124       unsigned int rela = bed->default_use_rela_p;
2125
2126       if (bed->special_sections)
2127         ssect = get_special_section (name, bed->special_sections, rela);
2128
2129       if (! ssect)
2130         ssect = get_special_section (name, special_sections, rela);
2131     }
2132
2133   return ssect;
2134 }
2135
2136 bfd_boolean
2137 _bfd_elf_new_section_hook (bfd *abfd, asection *sec)
2138 {
2139   struct bfd_elf_section_data *sdata;
2140   const struct bfd_elf_special_section *ssect;
2141
2142   sdata = (struct bfd_elf_section_data *) sec->used_by_bfd;
2143   if (sdata == NULL)
2144     {
2145       sdata = bfd_zalloc (abfd, sizeof (*sdata));
2146       if (sdata == NULL)
2147         return FALSE;
2148       sec->used_by_bfd = sdata;
2149     }
2150
2151   elf_section_type (sec) = SHT_NULL;
2152   ssect = _bfd_elf_get_sec_type_attr (abfd, sec->name);
2153   if (ssect != NULL)
2154     {
2155       elf_section_type (sec) = ssect->type;
2156       elf_section_flags (sec) = ssect->attr;
2157     }
2158
2159   /* Indicate whether or not this section should use RELA relocations.  */
2160   sec->use_rela_p = get_elf_backend_data (abfd)->default_use_rela_p;
2161
2162   return TRUE;
2163 }
2164
2165 /* Create a new bfd section from an ELF program header.
2166
2167    Since program segments have no names, we generate a synthetic name
2168    of the form segment<NUM>, where NUM is generally the index in the
2169    program header table.  For segments that are split (see below) we
2170    generate the names segment<NUM>a and segment<NUM>b.
2171
2172    Note that some program segments may have a file size that is different than
2173    (less than) the memory size.  All this means is that at execution the
2174    system must allocate the amount of memory specified by the memory size,
2175    but only initialize it with the first "file size" bytes read from the
2176    file.  This would occur for example, with program segments consisting
2177    of combined data+bss.
2178
2179    To handle the above situation, this routine generates TWO bfd sections
2180    for the single program segment.  The first has the length specified by
2181    the file size of the segment, and the second has the length specified
2182    by the difference between the two sizes.  In effect, the segment is split
2183    into it's initialized and uninitialized parts.
2184
2185  */
2186
2187 bfd_boolean
2188 _bfd_elf_make_section_from_phdr (bfd *abfd,
2189                                  Elf_Internal_Phdr *hdr,
2190                                  int index,
2191                                  const char *typename)
2192 {
2193   asection *newsect;
2194   char *name;
2195   char namebuf[64];
2196   size_t len;
2197   int split;
2198
2199   split = ((hdr->p_memsz > 0)
2200             && (hdr->p_filesz > 0)
2201             && (hdr->p_memsz > hdr->p_filesz));
2202   sprintf (namebuf, "%s%d%s", typename, index, split ? "a" : "");
2203   len = strlen (namebuf) + 1;
2204   name = bfd_alloc (abfd, len);
2205   if (!name)
2206     return FALSE;
2207   memcpy (name, namebuf, len);
2208   newsect = bfd_make_section (abfd, name);
2209   if (newsect == NULL)
2210     return FALSE;
2211   newsect->vma = hdr->p_vaddr;
2212   newsect->lma = hdr->p_paddr;
2213   newsect->_raw_size = hdr->p_filesz;
2214   newsect->filepos = hdr->p_offset;
2215   newsect->flags |= SEC_HAS_CONTENTS;
2216   newsect->alignment_power = bfd_log2 (hdr->p_align);
2217   if (hdr->p_type == PT_LOAD)
2218     {
2219       newsect->flags |= SEC_ALLOC;
2220       newsect->flags |= SEC_LOAD;
2221       if (hdr->p_flags & PF_X)
2222         {
2223           /* FIXME: all we known is that it has execute PERMISSION,
2224              may be data.  */
2225           newsect->flags |= SEC_CODE;
2226         }
2227     }
2228   if (!(hdr->p_flags & PF_W))
2229     {
2230       newsect->flags |= SEC_READONLY;
2231     }
2232
2233   if (split)
2234     {
2235       sprintf (namebuf, "%s%db", typename, index);
2236       len = strlen (namebuf) + 1;
2237       name = bfd_alloc (abfd, len);
2238       if (!name)
2239         return FALSE;
2240       memcpy (name, namebuf, len);
2241       newsect = bfd_make_section (abfd, name);
2242       if (newsect == NULL)
2243         return FALSE;
2244       newsect->vma = hdr->p_vaddr + hdr->p_filesz;
2245       newsect->lma = hdr->p_paddr + hdr->p_filesz;
2246       newsect->_raw_size = hdr->p_memsz - hdr->p_filesz;
2247       if (hdr->p_type == PT_LOAD)
2248         {
2249           newsect->flags |= SEC_ALLOC;
2250           if (hdr->p_flags & PF_X)
2251             newsect->flags |= SEC_CODE;
2252         }
2253       if (!(hdr->p_flags & PF_W))
2254         newsect->flags |= SEC_READONLY;
2255     }
2256
2257   return TRUE;
2258 }
2259
2260 bfd_boolean
2261 bfd_section_from_phdr (bfd *abfd, Elf_Internal_Phdr *hdr, int index)
2262 {
2263   const struct elf_backend_data *bed;
2264
2265   switch (hdr->p_type)
2266     {
2267     case PT_NULL:
2268       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "null");
2269
2270     case PT_LOAD:
2271       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "load");
2272
2273     case PT_DYNAMIC:
2274       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "dynamic");
2275
2276     case PT_INTERP:
2277       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "interp");
2278
2279     case PT_NOTE:
2280       if (! _bfd_elf_make_section_from_phdr (abfd, hdr, index, "note"))
2281         return FALSE;
2282       if (! elfcore_read_notes (abfd, hdr->p_offset, hdr->p_filesz))
2283         return FALSE;
2284       return TRUE;
2285
2286     case PT_SHLIB:
2287       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "shlib");
2288
2289     case PT_PHDR:
2290       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "phdr");
2291
2292     case PT_GNU_EH_FRAME:
2293       return _bfd_elf_make_section_from_phdr (abfd, hdr, index,
2294                                               "eh_frame_hdr");
2295
2296     case PT_GNU_STACK:
2297       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "stack");
2298
2299     default:
2300       /* Check for any processor-specific program segment types.
2301          If no handler for them, default to making "segment" sections.  */
2302       bed = get_elf_backend_data (abfd);
2303       if (bed->elf_backend_section_from_phdr)
2304         return (*bed->elf_backend_section_from_phdr) (abfd, hdr, index);
2305       else
2306         return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "segment");
2307     }
2308 }
2309
2310 /* Initialize REL_HDR, the section-header for new section, containing
2311    relocations against ASECT.  If USE_RELA_P is TRUE, we use RELA
2312    relocations; otherwise, we use REL relocations.  */
2313
2314 bfd_boolean
2315 _bfd_elf_init_reloc_shdr (bfd *abfd,
2316                           Elf_Internal_Shdr *rel_hdr,
2317                           asection *asect,
2318                           bfd_boolean use_rela_p)
2319 {
2320   char *name;
2321   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2322   bfd_size_type amt = sizeof ".rela" + strlen (asect->name);
2323
2324   name = bfd_alloc (abfd, amt);
2325   if (name == NULL)
2326     return FALSE;
2327   sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", asect->name);
2328   rel_hdr->sh_name =
2329     (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd), name,
2330                                         FALSE);
2331   if (rel_hdr->sh_name == (unsigned int) -1)
2332     return FALSE;
2333   rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
2334   rel_hdr->sh_entsize = (use_rela_p
2335                          ? bed->s->sizeof_rela
2336                          : bed->s->sizeof_rel);
2337   rel_hdr->sh_addralign = 1 << bed->s->log_file_align;
2338   rel_hdr->sh_flags = 0;
2339   rel_hdr->sh_addr = 0;
2340   rel_hdr->sh_size = 0;
2341   rel_hdr->sh_offset = 0;
2342
2343   return TRUE;
2344 }
2345
2346 /* Set up an ELF internal section header for a section.  */
2347
2348 static void
2349 elf_fake_sections (bfd *abfd, asection *asect, void *failedptrarg)
2350 {
2351   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2352   bfd_boolean *failedptr = failedptrarg;
2353   Elf_Internal_Shdr *this_hdr;
2354
2355   if (*failedptr)
2356     {
2357       /* We already failed; just get out of the bfd_map_over_sections
2358          loop.  */
2359       return;
2360     }
2361
2362   this_hdr = &elf_section_data (asect)->this_hdr;
2363
2364   this_hdr->sh_name = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
2365                                                           asect->name, FALSE);
2366   if (this_hdr->sh_name == (unsigned int) -1)
2367     {
2368       *failedptr = TRUE;
2369       return;
2370     }
2371
2372   this_hdr->sh_flags = 0;
2373
2374   if ((asect->flags & SEC_ALLOC) != 0
2375       || asect->user_set_vma)
2376     this_hdr->sh_addr = asect->vma;
2377   else
2378     this_hdr->sh_addr = 0;
2379
2380   this_hdr->sh_offset = 0;
2381   this_hdr->sh_size = asect->_raw_size;
2382   this_hdr->sh_link = 0;
2383   this_hdr->sh_addralign = 1 << asect->alignment_power;
2384   /* The sh_entsize and sh_info fields may have been set already by
2385      copy_private_section_data.  */
2386
2387   this_hdr->bfd_section = asect;
2388   this_hdr->contents = NULL;
2389
2390   /* If the section type is unspecified, we set it based on
2391      asect->flags.  */
2392   if (this_hdr->sh_type == SHT_NULL)
2393     {
2394       if ((asect->flags & SEC_ALLOC) != 0
2395           && (((asect->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2396               || (asect->flags & SEC_NEVER_LOAD) != 0))
2397         this_hdr->sh_type = SHT_NOBITS;
2398       else
2399         this_hdr->sh_type = SHT_PROGBITS;
2400     }
2401
2402   switch (this_hdr->sh_type)
2403     {
2404     default:
2405       break;
2406
2407     case SHT_STRTAB:
2408     case SHT_INIT_ARRAY:
2409     case SHT_FINI_ARRAY:
2410     case SHT_PREINIT_ARRAY:
2411     case SHT_NOTE:
2412     case SHT_NOBITS:
2413     case SHT_PROGBITS:
2414       break;
2415
2416     case SHT_HASH:
2417       this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
2418       break;
2419
2420     case SHT_DYNSYM:
2421       this_hdr->sh_entsize = bed->s->sizeof_sym;
2422       break;
2423
2424     case SHT_DYNAMIC:
2425       this_hdr->sh_entsize = bed->s->sizeof_dyn;
2426       break;
2427
2428     case SHT_RELA:
2429       if (get_elf_backend_data (abfd)->may_use_rela_p)
2430         this_hdr->sh_entsize = bed->s->sizeof_rela;
2431       break;
2432
2433      case SHT_REL:
2434       if (get_elf_backend_data (abfd)->may_use_rel_p)
2435         this_hdr->sh_entsize = bed->s->sizeof_rel;
2436       break;
2437
2438      case SHT_GNU_versym:
2439       this_hdr->sh_entsize = sizeof (Elf_External_Versym);
2440       break;
2441
2442      case SHT_GNU_verdef:
2443       this_hdr->sh_entsize = 0;
2444       /* objcopy or strip will copy over sh_info, but may not set
2445          cverdefs.  The linker will set cverdefs, but sh_info will be
2446          zero.  */
2447       if (this_hdr->sh_info == 0)
2448         this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
2449       else
2450         BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
2451                     || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
2452       break;
2453
2454     case SHT_GNU_verneed:
2455       this_hdr->sh_entsize = 0;
2456       /* objcopy or strip will copy over sh_info, but may not set
2457          cverrefs.  The linker will set cverrefs, but sh_info will be
2458          zero.  */
2459       if (this_hdr->sh_info == 0)
2460         this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
2461       else
2462         BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
2463                     || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
2464       break;
2465
2466     case SHT_GROUP:
2467       this_hdr->sh_entsize = 4;
2468       break;
2469     }
2470
2471   if ((asect->flags & SEC_ALLOC) != 0)
2472     this_hdr->sh_flags |= SHF_ALLOC;
2473   if ((asect->flags & SEC_READONLY) == 0)
2474     this_hdr->sh_flags |= SHF_WRITE;
2475   if ((asect->flags & SEC_CODE) != 0)
2476     this_hdr->sh_flags |= SHF_EXECINSTR;
2477   if ((asect->flags & SEC_MERGE) != 0)
2478     {
2479       this_hdr->sh_flags |= SHF_MERGE;
2480       this_hdr->sh_entsize = asect->entsize;
2481       if ((asect->flags & SEC_STRINGS) != 0)
2482         this_hdr->sh_flags |= SHF_STRINGS;
2483     }
2484   if ((asect->flags & SEC_GROUP) == 0 && elf_group_name (asect) != NULL)
2485     this_hdr->sh_flags |= SHF_GROUP;
2486   if ((asect->flags & SEC_THREAD_LOCAL) != 0)
2487     {
2488       this_hdr->sh_flags |= SHF_TLS;
2489       if (asect->_raw_size == 0 && (asect->flags & SEC_HAS_CONTENTS) == 0)
2490         {
2491           struct bfd_link_order *o;
2492
2493           this_hdr->sh_size = 0;
2494           for (o = asect->link_order_head; o != NULL; o = o->next)
2495             if (this_hdr->sh_size < o->offset + o->size)
2496               this_hdr->sh_size = o->offset + o->size;
2497           if (this_hdr->sh_size)
2498             this_hdr->sh_type = SHT_NOBITS;
2499         }
2500     }
2501
2502   /* Check for processor-specific section types.  */
2503   if (bed->elf_backend_fake_sections
2504       && !(*bed->elf_backend_fake_sections) (abfd, this_hdr, asect))
2505     *failedptr = TRUE;
2506
2507   /* If the section has relocs, set up a section header for the
2508      SHT_REL[A] section.  If two relocation sections are required for
2509      this section, it is up to the processor-specific back-end to
2510      create the other.  */
2511   if ((asect->flags & SEC_RELOC) != 0
2512       && !_bfd_elf_init_reloc_shdr (abfd,
2513                                     &elf_section_data (asect)->rel_hdr,
2514                                     asect,
2515                                     asect->use_rela_p))
2516     *failedptr = TRUE;
2517 }
2518
2519 /* Fill in the contents of a SHT_GROUP section.  */
2520
2521 void
2522 bfd_elf_set_group_contents (bfd *abfd, asection *sec, void *failedptrarg)
2523 {
2524   bfd_boolean *failedptr = failedptrarg;
2525   unsigned long symindx;
2526   asection *elt, *first;
2527   unsigned char *loc;
2528   struct bfd_link_order *l;
2529   bfd_boolean gas;
2530
2531   if (elf_section_data (sec)->this_hdr.sh_type != SHT_GROUP
2532       || *failedptr)
2533     return;
2534
2535   symindx = 0;
2536   if (elf_group_id (sec) != NULL)
2537     symindx = elf_group_id (sec)->udata.i;
2538
2539   if (symindx == 0)
2540     {
2541       /* If called from the assembler, swap_out_syms will have set up
2542          elf_section_syms;  If called for "ld -r", use target_index.  */
2543       if (elf_section_syms (abfd) != NULL)
2544         symindx = elf_section_syms (abfd)[sec->index]->udata.i;
2545       else
2546         symindx = sec->target_index;
2547     }
2548   elf_section_data (sec)->this_hdr.sh_info = symindx;
2549
2550   /* The contents won't be allocated for "ld -r" or objcopy.  */
2551   gas = TRUE;
2552   if (sec->contents == NULL)
2553     {
2554       gas = FALSE;
2555       sec->contents = bfd_alloc (abfd, sec->_raw_size);
2556
2557       /* Arrange for the section to be written out.  */
2558       elf_section_data (sec)->this_hdr.contents = sec->contents;
2559       if (sec->contents == NULL)
2560         {
2561           *failedptr = TRUE;
2562           return;
2563         }
2564     }
2565
2566   loc = sec->contents + sec->_raw_size;
2567
2568   /* Get the pointer to the first section in the group that gas
2569      squirreled away here.  objcopy arranges for this to be set to the
2570      start of the input section group.  */
2571   first = elt = elf_next_in_group (sec);
2572
2573   /* First element is a flag word.  Rest of section is elf section
2574      indices for all the sections of the group.  Write them backwards
2575      just to keep the group in the same order as given in .section
2576      directives, not that it matters.  */
2577   while (elt != NULL)
2578     {
2579       asection *s;
2580       unsigned int idx;
2581
2582       loc -= 4;
2583       s = elt;
2584       if (!gas)
2585         s = s->output_section;
2586       idx = 0;
2587       if (s != NULL)
2588         idx = elf_section_data (s)->this_idx;
2589       H_PUT_32 (abfd, idx, loc);
2590       elt = elf_next_in_group (elt);
2591       if (elt == first)
2592         break;
2593     }
2594
2595   /* If this is a relocatable link, then the above did nothing because
2596      SEC is the output section.  Look through the input sections
2597      instead.  */
2598   for (l = sec->link_order_head; l != NULL; l = l->next)
2599     if (l->type == bfd_indirect_link_order
2600         && (elt = elf_next_in_group (l->u.indirect.section)) != NULL)
2601       do
2602         {
2603           loc -= 4;
2604           H_PUT_32 (abfd,
2605                     elf_section_data (elt->output_section)->this_idx, loc);
2606           elt = elf_next_in_group (elt);
2607           /* During a relocatable link, the lists are circular.  */
2608         }
2609       while (elt != elf_next_in_group (l->u.indirect.section));
2610
2611   /* With ld -r, merging SHT_GROUP sections results in wasted space
2612      due to allowing for the flag word on each input.  We may well
2613      duplicate entries too.  */
2614   while ((loc -= 4) > sec->contents)
2615     H_PUT_32 (abfd, 0, loc);
2616
2617   if (loc != sec->contents)
2618     abort ();
2619
2620   H_PUT_32 (abfd, sec->flags & SEC_LINK_ONCE ? GRP_COMDAT : 0, loc);
2621 }
2622
2623 /* Assign all ELF section numbers.  The dummy first section is handled here
2624    too.  The link/info pointers for the standard section types are filled
2625    in here too, while we're at it.  */
2626
2627 static bfd_boolean
2628 assign_section_numbers (bfd *abfd)
2629 {
2630   struct elf_obj_tdata *t = elf_tdata (abfd);
2631   asection *sec;
2632   unsigned int section_number, secn;
2633   Elf_Internal_Shdr **i_shdrp;
2634   bfd_size_type amt;
2635
2636   section_number = 1;
2637
2638   _bfd_elf_strtab_clear_all_refs (elf_shstrtab (abfd));
2639
2640   for (sec = abfd->sections; sec; sec = sec->next)
2641     {
2642       struct bfd_elf_section_data *d = elf_section_data (sec);
2643
2644       if (section_number == SHN_LORESERVE)
2645         section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2646       d->this_idx = section_number++;
2647       _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->this_hdr.sh_name);
2648       if ((sec->flags & SEC_RELOC) == 0)
2649         d->rel_idx = 0;
2650       else
2651         {
2652           if (section_number == SHN_LORESERVE)
2653             section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2654           d->rel_idx = section_number++;
2655           _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel_hdr.sh_name);
2656         }
2657
2658       if (d->rel_hdr2)
2659         {
2660           if (section_number == SHN_LORESERVE)
2661             section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2662           d->rel_idx2 = section_number++;
2663           _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel_hdr2->sh_name);
2664         }
2665       else
2666         d->rel_idx2 = 0;
2667     }
2668
2669   if (section_number == SHN_LORESERVE)
2670     section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2671   t->shstrtab_section = section_number++;
2672   _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->shstrtab_hdr.sh_name);
2673   elf_elfheader (abfd)->e_shstrndx = t->shstrtab_section;
2674
2675   if (bfd_get_symcount (abfd) > 0)
2676     {
2677       if (section_number == SHN_LORESERVE)
2678         section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2679       t->symtab_section = section_number++;
2680       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->symtab_hdr.sh_name);
2681       if (section_number > SHN_LORESERVE - 2)
2682         {
2683           if (section_number == SHN_LORESERVE)
2684             section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2685           t->symtab_shndx_section = section_number++;
2686           t->symtab_shndx_hdr.sh_name
2687             = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
2688                                                   ".symtab_shndx", FALSE);
2689           if (t->symtab_shndx_hdr.sh_name == (unsigned int) -1)
2690             return FALSE;
2691         }
2692       if (section_number == SHN_LORESERVE)
2693         section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
2694       t->strtab_section = section_number++;
2695       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->strtab_hdr.sh_name);
2696     }
2697
2698   _bfd_elf_strtab_finalize (elf_shstrtab (abfd));
2699   t->shstrtab_hdr.sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
2700
2701   elf_numsections (abfd) = section_number;
2702   elf_elfheader (abfd)->e_shnum = section_number;
2703   if (section_number > SHN_LORESERVE)
2704     elf_elfheader (abfd)->e_shnum -= SHN_HIRESERVE + 1 - SHN_LORESERVE;
2705
2706   /* Set up the list of section header pointers, in agreement with the
2707      indices.  */
2708   amt = section_number * sizeof (Elf_Internal_Shdr *);
2709   i_shdrp = bfd_zalloc (abfd, amt);
2710   if (i_shdrp == NULL)
2711     return FALSE;
2712
2713   amt = sizeof (Elf_Internal_Shdr);
2714   i_shdrp[0] = bfd_zalloc (abfd, amt);
2715   if (i_shdrp[0] == NULL)
2716     {
2717       bfd_release (abfd, i_shdrp);
2718       return FALSE;
2719     }
2720
2721   elf_elfsections (abfd) = i_shdrp;
2722
2723   i_shdrp[t->shstrtab_section] = &t->shstrtab_hdr;
2724   if (bfd_get_symcount (abfd) > 0)
2725     {
2726       i_shdrp[t->symtab_section] = &t->symtab_hdr;
2727       if (elf_numsections (abfd) > SHN_LORESERVE)
2728         {
2729           i_shdrp[t->symtab_shndx_section] = &t->symtab_shndx_hdr;
2730           t->symtab_shndx_hdr.sh_link = t->symtab_section;
2731         }
2732       i_shdrp[t->strtab_section] = &t->strtab_hdr;
2733       t->symtab_hdr.sh_link = t->strtab_section;
2734     }
2735   for (sec = abfd->sections; sec; sec = sec->next)
2736     {
2737       struct bfd_elf_section_data *d = elf_section_data (sec);
2738       asection *s;
2739       const char *name;
2740
2741       i_shdrp[d->this_idx] = &d->this_hdr;
2742       if (d->rel_idx != 0)
2743         i_shdrp[d->rel_idx] = &d->rel_hdr;
2744       if (d->rel_idx2 != 0)
2745         i_shdrp[d->rel_idx2] = d->rel_hdr2;
2746
2747       /* Fill in the sh_link and sh_info fields while we're at it.  */
2748
2749       /* sh_link of a reloc section is the section index of the symbol
2750          table.  sh_info is the section index of the section to which
2751          the relocation entries apply.  */
2752       if (d->rel_idx != 0)
2753         {
2754           d->rel_hdr.sh_link = t->symtab_section;
2755           d->rel_hdr.sh_info = d->this_idx;
2756         }
2757       if (d->rel_idx2 != 0)
2758         {
2759           d->rel_hdr2->sh_link = t->symtab_section;
2760           d->rel_hdr2->sh_info = d->this_idx;
2761         }
2762
2763       switch (d->this_hdr.sh_type)
2764         {
2765         case SHT_REL:
2766         case SHT_RELA:
2767           /* A reloc section which we are treating as a normal BFD
2768              section.  sh_link is the section index of the symbol
2769              table.  sh_info is the section index of the section to
2770              which the relocation entries apply.  We assume that an
2771              allocated reloc section uses the dynamic symbol table.
2772              FIXME: How can we be sure?  */
2773           s = bfd_get_section_by_name (abfd, ".dynsym");
2774           if (s != NULL)
2775             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
2776
2777           /* We look up the section the relocs apply to by name.  */
2778           name = sec->name;
2779           if (d->this_hdr.sh_type == SHT_REL)
2780             name += 4;
2781           else
2782             name += 5;
2783           s = bfd_get_section_by_name (abfd, name);
2784           if (s != NULL)
2785             d->this_hdr.sh_info = elf_section_data (s)->this_idx;
2786           break;
2787
2788         case SHT_STRTAB:
2789           /* We assume that a section named .stab*str is a stabs
2790              string section.  We look for a section with the same name
2791              but without the trailing ``str'', and set its sh_link
2792              field to point to this section.  */
2793           if (strncmp (sec->name, ".stab", sizeof ".stab" - 1) == 0
2794               && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
2795             {
2796               size_t len;
2797               char *alc;
2798
2799               len = strlen (sec->name);
2800               alc = bfd_malloc (len - 2);
2801               if (alc == NULL)
2802                 return FALSE;
2803               memcpy (alc, sec->name, len - 3);
2804               alc[len - 3] = '\0';
2805               s = bfd_get_section_by_name (abfd, alc);
2806               free (alc);
2807               if (s != NULL)
2808                 {
2809                   elf_section_data (s)->this_hdr.sh_link = d->this_idx;
2810
2811                   /* This is a .stab section.  */
2812                   if (elf_section_data (s)->this_hdr.sh_entsize == 0)
2813                     elf_section_data (s)->this_hdr.sh_entsize
2814                       = 4 + 2 * bfd_get_arch_size (abfd) / 8;
2815                 }
2816             }
2817           break;
2818
2819         case SHT_DYNAMIC:
2820         case SHT_DYNSYM:
2821         case SHT_GNU_verneed:
2822         case SHT_GNU_verdef:
2823           /* sh_link is the section header index of the string table
2824              used for the dynamic entries, or the symbol table, or the
2825              version strings.  */
2826           s = bfd_get_section_by_name (abfd, ".dynstr");
2827           if (s != NULL)
2828             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
2829           break;
2830
2831         case SHT_HASH:
2832         case SHT_GNU_versym:
2833           /* sh_link is the section header index of the symbol table
2834              this hash table or version table is for.  */
2835           s = bfd_get_section_by_name (abfd, ".dynsym");
2836           if (s != NULL)
2837             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
2838           break;
2839
2840         case SHT_GROUP:
2841           d->this_hdr.sh_link = t->symtab_section;
2842         }
2843     }
2844
2845   for (secn = 1; secn < section_number; ++secn)
2846     if (i_shdrp[secn] == NULL)
2847       i_shdrp[secn] = i_shdrp[0];
2848     else
2849       i_shdrp[secn]->sh_name = _bfd_elf_strtab_offset (elf_shstrtab (abfd),
2850                                                        i_shdrp[secn]->sh_name);
2851   return TRUE;
2852 }
2853
2854 /* Map symbol from it's internal number to the external number, moving
2855    all local symbols to be at the head of the list.  */
2856
2857 static int
2858 sym_is_global (bfd *abfd, asymbol *sym)
2859 {
2860   /* If the backend has a special mapping, use it.  */
2861   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2862   if (bed->elf_backend_sym_is_global)
2863     return (*bed->elf_backend_sym_is_global) (abfd, sym);
2864
2865   return ((sym->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
2866           || bfd_is_und_section (bfd_get_section (sym))
2867           || bfd_is_com_section (bfd_get_section (sym)));
2868 }
2869
2870 static bfd_boolean
2871 elf_map_symbols (bfd *abfd)
2872 {
2873   unsigned int symcount = bfd_get_symcount (abfd);
2874   asymbol **syms = bfd_get_outsymbols (abfd);
2875   asymbol **sect_syms;
2876   unsigned int num_locals = 0;
2877   unsigned int num_globals = 0;
2878   unsigned int num_locals2 = 0;
2879   unsigned int num_globals2 = 0;
2880   int max_index = 0;
2881   unsigned int idx;
2882   asection *asect;
2883   asymbol **new_syms;
2884   bfd_size_type amt;
2885
2886 #ifdef DEBUG
2887   fprintf (stderr, "elf_map_symbols\n");
2888   fflush (stderr);
2889 #endif
2890
2891   for (asect = abfd->sections; asect; asect = asect->next)
2892     {
2893       if (max_index < asect->index)
2894         max_index = asect->index;
2895     }
2896
2897   max_index++;
2898   amt = max_index * sizeof (asymbol *);
2899   sect_syms = bfd_zalloc (abfd, amt);
2900   if (sect_syms == NULL)
2901     return FALSE;
2902   elf_section_syms (abfd) = sect_syms;
2903   elf_num_section_syms (abfd) = max_index;
2904
2905   /* Init sect_syms entries for any section symbols we have already
2906      decided to output.  */
2907   for (idx = 0; idx < symcount; idx++)
2908     {
2909       asymbol *sym = syms[idx];
2910
2911       if ((sym->flags & BSF_SECTION_SYM) != 0
2912           && sym->value == 0)
2913         {
2914           asection *sec;
2915
2916           sec = sym->section;
2917
2918           if (sec->owner != NULL)
2919             {
2920               if (sec->owner != abfd)
2921                 {
2922                   if (sec->output_offset != 0)
2923                     continue;
2924
2925                   sec = sec->output_section;
2926
2927                   /* Empty sections in the input files may have had a
2928                      section symbol created for them.  (See the comment
2929                      near the end of _bfd_generic_link_output_symbols in
2930                      linker.c).  If the linker script discards such
2931                      sections then we will reach this point.  Since we know
2932                      that we cannot avoid this case, we detect it and skip
2933                      the abort and the assignment to the sect_syms array.
2934                      To reproduce this particular case try running the
2935                      linker testsuite test ld-scripts/weak.exp for an ELF
2936                      port that uses the generic linker.  */
2937                   if (sec->owner == NULL)
2938                     continue;
2939
2940                   BFD_ASSERT (sec->owner == abfd);
2941                 }
2942               sect_syms[sec->index] = syms[idx];
2943             }
2944         }
2945     }
2946
2947   /* Classify all of the symbols.  */
2948   for (idx = 0; idx < symcount; idx++)
2949     {
2950       if (!sym_is_global (abfd, syms[idx]))
2951         num_locals++;
2952       else
2953         num_globals++;
2954     }
2955
2956   /* We will be adding a section symbol for each BFD section.  Most normal
2957      sections will already have a section symbol in outsymbols, but
2958      eg. SHT_GROUP sections will not, and we need the section symbol mapped
2959      at least in that case.  */
2960   for (asect = abfd->sections; asect; asect = asect->next)
2961     {
2962       if (sect_syms[asect->index] == NULL)
2963         {
2964           if (!sym_is_global (abfd, asect->symbol))
2965             num_locals++;
2966           else
2967             num_globals++;
2968         }
2969     }
2970
2971   /* Now sort the symbols so the local symbols are first.  */
2972   amt = (num_locals + num_globals) * sizeof (asymbol *);
2973   new_syms = bfd_alloc (abfd, amt);
2974
2975   if (new_syms == NULL)
2976     return FALSE;
2977
2978   for (idx = 0; idx < symcount; idx++)
2979     {
2980       asymbol *sym = syms[idx];
2981       unsigned int i;
2982
2983       if (!sym_is_global (abfd, sym))
2984         i = num_locals2++;
2985       else
2986         i = num_locals + num_globals2++;
2987       new_syms[i] = sym;
2988       sym->udata.i = i + 1;
2989     }
2990   for (asect = abfd->sections; asect; asect = asect->next)
2991     {
2992       if (sect_syms[asect->index] == NULL)
2993         {
2994           asymbol *sym = asect->symbol;
2995           unsigned int i;
2996
2997           sect_syms[asect->index] = sym;
2998           if (!sym_is_global (abfd, sym))
2999             i = num_locals2++;
3000           else
3001             i = num_locals + num_globals2++;
3002           new_syms[i] = sym;
3003           sym->udata.i = i + 1;
3004         }
3005     }
3006
3007   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
3008
3009   elf_num_locals (abfd) = num_locals;
3010   elf_num_globals (abfd) = num_globals;
3011   return TRUE;
3012 }
3013
3014 /* Align to the maximum file alignment that could be required for any
3015    ELF data structure.  */
3016
3017 static inline file_ptr
3018 align_file_position (file_ptr off, int align)
3019 {
3020   return (off + align - 1) & ~(align - 1);
3021 }
3022
3023 /* Assign a file position to a section, optionally aligning to the
3024    required section alignment.  */
3025
3026 file_ptr
3027 _bfd_elf_assign_file_position_for_section (Elf_Internal_Shdr *i_shdrp,
3028                                            file_ptr offset,
3029                                            bfd_boolean align)
3030 {
3031   if (align)
3032     {
3033       unsigned int al;
3034
3035       al = i_shdrp->sh_addralign;
3036       if (al > 1)
3037         offset = BFD_ALIGN (offset, al);
3038     }
3039   i_shdrp->sh_offset = offset;
3040   if (i_shdrp->bfd_section != NULL)
3041     i_shdrp->bfd_section->filepos = offset;
3042   if (i_shdrp->sh_type != SHT_NOBITS)
3043     offset += i_shdrp->sh_size;
3044   return offset;
3045 }
3046
3047 /* Compute the file positions we are going to put the sections at, and
3048    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
3049    is not NULL, this is being called by the ELF backend linker.  */
3050
3051 bfd_boolean
3052 _bfd_elf_compute_section_file_positions (bfd *abfd,
3053                                          struct bfd_link_info *link_info)
3054 {
3055   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3056   bfd_boolean failed;
3057   struct bfd_strtab_hash *strtab;
3058   Elf_Internal_Shdr *shstrtab_hdr;
3059
3060   if (abfd->output_has_begun)
3061     return TRUE;
3062
3063   /* Do any elf backend specific processing first.  */
3064   if (bed->elf_backend_begin_write_processing)
3065     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
3066
3067   if (! prep_headers (abfd))
3068     return FALSE;
3069
3070   /* Post process the headers if necessary.  */
3071   if (bed->elf_backend_post_process_headers)
3072     (*bed->elf_backend_post_process_headers) (abfd, link_info);
3073
3074   failed = FALSE;
3075   bfd_map_over_sections (abfd, elf_fake_sections, &failed);
3076   if (failed)
3077     return FALSE;
3078
3079   if (!assign_section_numbers (abfd))
3080     return FALSE;
3081
3082   /* The backend linker builds symbol table information itself.  */
3083   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
3084     {
3085       /* Non-zero if doing a relocatable link.  */
3086       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
3087
3088       if (! swap_out_syms (abfd, &strtab, relocatable_p))
3089         return FALSE;
3090     }
3091
3092   if (link_info == NULL)
3093     {
3094       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
3095       if (failed)
3096         return FALSE;
3097     }
3098
3099   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
3100   /* sh_name was set in prep_headers.  */
3101   shstrtab_hdr->sh_type = SHT_STRTAB;
3102   shstrtab_hdr->sh_flags = 0;
3103   shstrtab_hdr->sh_addr = 0;
3104   shstrtab_hdr->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
3105   shstrtab_hdr->sh_entsize = 0;
3106   shstrtab_hdr->sh_link = 0;
3107   shstrtab_hdr->sh_info = 0;
3108   /* sh_offset is set in assign_file_positions_except_relocs.  */
3109   shstrtab_hdr->sh_addralign = 1;
3110
3111   if (!assign_file_positions_except_relocs (abfd, link_info))
3112     return FALSE;
3113
3114   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
3115     {
3116       file_ptr off;
3117       Elf_Internal_Shdr *hdr;
3118
3119       off = elf_tdata (abfd)->next_file_pos;
3120
3121       hdr = &elf_tdata (abfd)->symtab_hdr;
3122       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3123
3124       hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
3125       if (hdr->sh_size != 0)
3126         off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3127
3128       hdr = &elf_tdata (abfd)->strtab_hdr;
3129       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3130
3131       elf_tdata (abfd)->next_file_pos = off;
3132
3133       /* Now that we know where the .strtab section goes, write it
3134          out.  */
3135       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
3136           || ! _bfd_stringtab_emit (abfd, strtab))
3137         return FALSE;
3138       _bfd_stringtab_free (strtab);
3139     }
3140
3141   abfd->output_has_begun = TRUE;
3142
3143   return TRUE;
3144 }
3145
3146 /* Create a mapping from a set of sections to a program segment.  */
3147
3148 static struct elf_segment_map *
3149 make_mapping (bfd *abfd,
3150               asection **sections,
3151               unsigned int from,
3152               unsigned int to,
3153               bfd_boolean phdr)
3154 {
3155   struct elf_segment_map *m;
3156   unsigned int i;
3157   asection **hdrpp;
3158   bfd_size_type amt;
3159
3160   amt = sizeof (struct elf_segment_map);
3161   amt += (to - from - 1) * sizeof (asection *);
3162   m = bfd_zalloc (abfd, amt);
3163   if (m == NULL)
3164     return NULL;
3165   m->next = NULL;
3166   m->p_type = PT_LOAD;
3167   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
3168     m->sections[i - from] = *hdrpp;
3169   m->count = to - from;
3170
3171   if (from == 0 && phdr)
3172     {
3173       /* Include the headers in the first PT_LOAD segment.  */
3174       m->includes_filehdr = 1;
3175       m->includes_phdrs = 1;
3176     }
3177
3178   return m;
3179 }
3180
3181 /* Set up a mapping from BFD sections to program segments.  */
3182
3183 static bfd_boolean
3184 map_sections_to_segments (bfd *abfd)
3185 {
3186   asection **sections = NULL;
3187   asection *s;
3188   unsigned int i;
3189   unsigned int count;
3190   struct elf_segment_map *mfirst;
3191   struct elf_segment_map **pm;
3192   struct elf_segment_map *m;
3193   asection *last_hdr;
3194   bfd_vma last_size;
3195   unsigned int phdr_index;
3196   bfd_vma maxpagesize;
3197   asection **hdrpp;
3198   bfd_boolean phdr_in_segment = TRUE;
3199   bfd_boolean writable;
3200   int tls_count = 0;
3201   asection *first_tls = NULL;
3202   asection *dynsec, *eh_frame_hdr;
3203   bfd_size_type amt;
3204
3205   if (elf_tdata (abfd)->segment_map != NULL)
3206     return TRUE;
3207
3208   if (bfd_count_sections (abfd) == 0)
3209     return TRUE;
3210
3211   /* Select the allocated sections, and sort them.  */
3212
3213   amt = bfd_count_sections (abfd) * sizeof (asection *);
3214   sections = bfd_malloc (amt);
3215   if (sections == NULL)
3216     goto error_return;
3217
3218   i = 0;
3219   for (s = abfd->sections; s != NULL; s = s->next)
3220     {
3221       if ((s->flags & SEC_ALLOC) != 0)
3222         {
3223           sections[i] = s;
3224           ++i;
3225         }
3226     }
3227   BFD_ASSERT (i <= bfd_count_sections (abfd));
3228   count = i;
3229
3230   qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
3231
3232   /* Build the mapping.  */
3233
3234   mfirst = NULL;
3235   pm = &mfirst;
3236
3237   /* If we have a .interp section, then create a PT_PHDR segment for
3238      the program headers and a PT_INTERP segment for the .interp
3239      section.  */
3240   s = bfd_get_section_by_name (abfd, ".interp");
3241   if (s != NULL && (s->flags & SEC_LOAD) != 0)
3242     {
3243       amt = sizeof (struct elf_segment_map);
3244       m = bfd_zalloc (abfd, amt);
3245       if (m == NULL)
3246         goto error_return;
3247       m->next = NULL;
3248       m->p_type = PT_PHDR;
3249       /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
3250       m->p_flags = PF_R | PF_X;
3251       m->p_flags_valid = 1;
3252       m->includes_phdrs = 1;
3253
3254       *pm = m;
3255       pm = &m->next;
3256
3257       amt = sizeof (struct elf_segment_map);
3258       m = bfd_zalloc (abfd, amt);
3259       if (m == NULL)
3260         goto error_return;
3261       m->next = NULL;
3262       m->p_type = PT_INTERP;
3263       m->count = 1;
3264       m->sections[0] = s;
3265
3266       *pm = m;
3267       pm = &m->next;
3268     }
3269
3270   /* Look through the sections.  We put sections in the same program
3271      segment when the start of the second section can be placed within
3272      a few bytes of the end of the first section.  */
3273   last_hdr = NULL;
3274   last_size = 0;
3275   phdr_index = 0;
3276   maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
3277   writable = FALSE;
3278   dynsec = bfd_get_section_by_name (abfd, ".dynamic");
3279   if (dynsec != NULL
3280       && (dynsec->flags & SEC_LOAD) == 0)
3281     dynsec = NULL;
3282
3283   /* Deal with -Ttext or something similar such that the first section
3284      is not adjacent to the program headers.  This is an
3285      approximation, since at this point we don't know exactly how many
3286      program headers we will need.  */
3287   if (count > 0)
3288     {
3289       bfd_size_type phdr_size;
3290
3291       phdr_size = elf_tdata (abfd)->program_header_size;
3292       if (phdr_size == 0)
3293         phdr_size = get_elf_backend_data (abfd)->s->sizeof_phdr;
3294       if ((abfd->flags & D_PAGED) == 0
3295           || sections[0]->lma < phdr_size
3296           || sections[0]->lma % maxpagesize < phdr_size % maxpagesize)
3297         phdr_in_segment = FALSE;
3298     }
3299
3300   for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
3301     {
3302       asection *hdr;
3303       bfd_boolean new_segment;
3304
3305       hdr = *hdrpp;
3306
3307       /* See if this section and the last one will fit in the same
3308          segment.  */
3309
3310       if (last_hdr == NULL)
3311         {
3312           /* If we don't have a segment yet, then we don't need a new
3313              one (we build the last one after this loop).  */
3314           new_segment = FALSE;
3315         }
3316       else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
3317         {
3318           /* If this section has a different relation between the
3319              virtual address and the load address, then we need a new
3320              segment.  */
3321           new_segment = TRUE;
3322         }
3323       else if (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize)
3324                < BFD_ALIGN (hdr->lma, maxpagesize))
3325         {
3326           /* If putting this section in this segment would force us to
3327              skip a page in the segment, then we need a new segment.  */
3328           new_segment = TRUE;
3329         }
3330       else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
3331                && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0)
3332         {
3333           /* We don't want to put a loadable section after a
3334              nonloadable section in the same segment.
3335              Consider .tbss sections as loadable for this purpose.  */
3336           new_segment = TRUE;
3337         }
3338       else if ((abfd->flags & D_PAGED) == 0)
3339         {
3340           /* If the file is not demand paged, which means that we
3341              don't require the sections to be correctly aligned in the
3342              file, then there is no other reason for a new segment.  */
3343           new_segment = FALSE;
3344         }
3345       else if (! writable
3346                && (hdr->flags & SEC_READONLY) == 0
3347                && (((last_hdr->lma + last_size - 1)
3348                     & ~(maxpagesize - 1))
3349                    != (hdr->lma & ~(maxpagesize - 1))))
3350         {
3351           /* We don't want to put a writable section in a read only
3352              segment, unless they are on the same page in memory
3353              anyhow.  We already know that the last section does not
3354              bring us past the current section on the page, so the
3355              only case in which the new section is not on the same
3356              page as the previous section is when the previous section
3357              ends precisely on a page boundary.  */
3358           new_segment = TRUE;
3359         }
3360       else
3361         {
3362           /* Otherwise, we can use the same segment.  */
3363           new_segment = FALSE;
3364         }
3365
3366       if (! new_segment)
3367         {
3368           if ((hdr->flags & SEC_READONLY) == 0)
3369             writable = TRUE;
3370           last_hdr = hdr;
3371           /* .tbss sections effectively have zero size.  */
3372           if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
3373             last_size = hdr->_raw_size;
3374           else
3375             last_size = 0;
3376           continue;
3377         }
3378
3379       /* We need a new program segment.  We must create a new program
3380          header holding all the sections from phdr_index until hdr.  */
3381
3382       m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
3383       if (m == NULL)
3384         goto error_return;
3385
3386       *pm = m;
3387       pm = &m->next;
3388
3389       if ((hdr->flags & SEC_READONLY) == 0)
3390         writable = TRUE;
3391       else
3392         writable = FALSE;
3393
3394       last_hdr = hdr;
3395       /* .tbss sections effectively have zero size.  */
3396       if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
3397         last_size = hdr->_raw_size;
3398       else
3399         last_size = 0;
3400       phdr_index = i;
3401       phdr_in_segment = FALSE;
3402     }
3403
3404   /* Create a final PT_LOAD program segment.  */
3405   if (last_hdr != NULL)
3406     {
3407       m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
3408       if (m == NULL)
3409         goto error_return;
3410
3411       *pm = m;
3412       pm = &m->next;
3413     }
3414
3415   /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
3416   if (dynsec != NULL)
3417     {
3418       amt = sizeof (struct elf_segment_map);
3419       m = bfd_zalloc (abfd, amt);
3420       if (m == NULL)
3421         goto error_return;
3422       m->next = NULL;
3423       m->p_type = PT_DYNAMIC;
3424       m->count = 1;
3425       m->sections[0] = dynsec;
3426
3427       *pm = m;
3428       pm = &m->next;
3429     }
3430
3431   /* For each loadable .note section, add a PT_NOTE segment.  We don't
3432      use bfd_get_section_by_name, because if we link together
3433      nonloadable .note sections and loadable .note sections, we will
3434      generate two .note sections in the output file.  FIXME: Using
3435      names for section types is bogus anyhow.  */
3436   for (s = abfd->sections; s != NULL; s = s->next)
3437     {
3438       if ((s->flags & SEC_LOAD) != 0
3439           && strncmp (s->name, ".note", 5) == 0)
3440         {
3441           amt = sizeof (struct elf_segment_map);
3442           m = bfd_zalloc (abfd, amt);
3443           if (m == NULL)
3444             goto error_return;
3445           m->next = NULL;
3446           m->p_type = PT_NOTE;
3447           m->count = 1;
3448           m->sections[0] = s;
3449
3450           *pm = m;
3451           pm = &m->next;
3452         }
3453       if (s->flags & SEC_THREAD_LOCAL)
3454         {
3455           if (! tls_count)
3456             first_tls = s;
3457           tls_count++;
3458         }
3459     }
3460
3461   /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
3462   if (tls_count > 0)
3463     {
3464       int i;
3465
3466       amt = sizeof (struct elf_segment_map);
3467       amt += (tls_count - 1) * sizeof (asection *);
3468       m = bfd_zalloc (abfd, amt);
3469       if (m == NULL)
3470         goto error_return;
3471       m->next = NULL;
3472       m->p_type = PT_TLS;
3473       m->count = tls_count;
3474       /* Mandated PF_R.  */
3475       m->p_flags = PF_R;
3476       m->p_flags_valid = 1;
3477       for (i = 0; i < tls_count; ++i)
3478         {
3479           BFD_ASSERT (first_tls->flags & SEC_THREAD_LOCAL);
3480           m->sections[i] = first_tls;
3481           first_tls = first_tls->next;
3482         }
3483
3484       *pm = m;
3485       pm = &m->next;
3486     }
3487
3488   /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
3489      segment.  */
3490   eh_frame_hdr = elf_tdata (abfd)->eh_frame_hdr;
3491   if (eh_frame_hdr != NULL
3492       && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
3493     {
3494       amt = sizeof (struct elf_segment_map);
3495       m = bfd_zalloc (abfd, amt);
3496       if (m == NULL)
3497         goto error_return;
3498       m->next = NULL;
3499       m->p_type = PT_GNU_EH_FRAME;
3500       m->count = 1;
3501       m->sections[0] = eh_frame_hdr->output_section;
3502
3503       *pm = m;
3504       pm = &m->next;
3505     }
3506
3507   if (elf_tdata (abfd)->stack_flags)
3508     {
3509       amt = sizeof (struct elf_segment_map);
3510       m = bfd_zalloc (abfd, amt);
3511       if (m == NULL)
3512         goto error_return;
3513       m->next = NULL;
3514       m->p_type = PT_GNU_STACK;
3515       m->p_flags = elf_tdata (abfd)->stack_flags;
3516       m->p_flags_valid = 1;
3517
3518       *pm = m;
3519       pm = &m->next;
3520     }
3521
3522   free (sections);
3523   sections = NULL;
3524
3525   elf_tdata (abfd)->segment_map = mfirst;
3526   return TRUE;
3527
3528  error_return:
3529   if (sections != NULL)
3530     free (sections);
3531   return FALSE;
3532 }
3533
3534 /* Sort sections by address.  */
3535
3536 static int
3537 elf_sort_sections (const void *arg1, const void *arg2)
3538 {
3539   const asection *sec1 = *(const asection **) arg1;
3540   const asection *sec2 = *(const asection **) arg2;
3541   bfd_size_type size1, size2;
3542
3543   /* Sort by LMA first, since this is the address used to
3544      place the section into a segment.  */
3545   if (sec1->lma < sec2->lma)
3546     return -1;
3547   else if (sec1->lma > sec2->lma)
3548     return 1;
3549
3550   /* Then sort by VMA.  Normally the LMA and the VMA will be
3551      the same, and this will do nothing.  */
3552   if (sec1->vma < sec2->vma)
3553     return -1;
3554   else if (sec1->vma > sec2->vma)
3555     return 1;
3556
3557   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
3558
3559 #define TOEND(x) (((x)->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0)
3560
3561   if (TOEND (sec1))
3562     {
3563       if (TOEND (sec2))
3564         {
3565           /* If the indicies are the same, do not return 0
3566              here, but continue to try the next comparison.  */
3567           if (sec1->target_index - sec2->target_index != 0)
3568             return sec1->target_index - sec2->target_index;
3569         }
3570       else
3571         return 1;
3572     }
3573   else if (TOEND (sec2))
3574     return -1;
3575
3576 #undef TOEND
3577
3578   /* Sort by size, to put zero sized sections
3579      before others at the same address.  */
3580
3581   size1 = (sec1->flags & SEC_LOAD) ? sec1->_raw_size : 0;
3582   size2 = (sec2->flags & SEC_LOAD) ? sec2->_raw_size : 0;
3583
3584   if (size1 < size2)
3585     return -1;
3586   if (size1 > size2)
3587     return 1;
3588
3589   return sec1->target_index - sec2->target_index;
3590 }
3591
3592 /* Ian Lance Taylor writes:
3593
3594    We shouldn't be using % with a negative signed number.  That's just
3595    not good.  We have to make sure either that the number is not
3596    negative, or that the number has an unsigned type.  When the types
3597    are all the same size they wind up as unsigned.  When file_ptr is a
3598    larger signed type, the arithmetic winds up as signed long long,
3599    which is wrong.
3600
3601    What we're trying to say here is something like ``increase OFF by
3602    the least amount that will cause it to be equal to the VMA modulo
3603    the page size.''  */
3604 /* In other words, something like:
3605
3606    vma_offset = m->sections[0]->vma % bed->maxpagesize;
3607    off_offset = off % bed->maxpagesize;
3608    if (vma_offset < off_offset)
3609      adjustment = vma_offset + bed->maxpagesize - off_offset;
3610    else
3611      adjustment = vma_offset - off_offset;
3612      
3613    which can can be collapsed into the expression below.  */
3614
3615 static file_ptr
3616 vma_page_aligned_bias (bfd_vma vma, ufile_ptr off, bfd_vma maxpagesize)
3617 {
3618   return ((vma - off) % maxpagesize);
3619 }
3620
3621 /* Assign file positions to the sections based on the mapping from
3622    sections to segments.  This function also sets up some fields in
3623    the file header, and writes out the program headers.  */
3624
3625 static bfd_boolean
3626 assign_file_positions_for_segments (bfd *abfd, struct bfd_link_info *link_info)
3627 {
3628   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3629   unsigned int count;
3630   struct elf_segment_map *m;
3631   unsigned int alloc;
3632   Elf_Internal_Phdr *phdrs;
3633   file_ptr off, voff;
3634   bfd_vma filehdr_vaddr, filehdr_paddr;
3635   bfd_vma phdrs_vaddr, phdrs_paddr;
3636   Elf_Internal_Phdr *p;
3637   bfd_size_type amt;
3638
3639   if (elf_tdata (abfd)->segment_map == NULL)
3640     {
3641       if (! map_sections_to_segments (abfd))
3642         return FALSE;
3643     }
3644   else
3645     {
3646       /* The placement algorithm assumes that non allocated sections are
3647          not in PT_LOAD segments.  We ensure this here by removing such
3648          sections from the segment map.  */
3649       for (m = elf_tdata (abfd)->segment_map;
3650            m != NULL;
3651            m = m->next)
3652         {
3653           unsigned int new_count;
3654           unsigned int i;
3655
3656           if (m->p_type != PT_LOAD)
3657             continue;
3658
3659           new_count = 0;
3660           for (i = 0; i < m->count; i ++)
3661             {
3662               if ((m->sections[i]->flags & SEC_ALLOC) != 0)
3663                 {
3664                   if (i != new_count)
3665                     m->sections[new_count] = m->sections[i];
3666
3667                   new_count ++;
3668                 }
3669             }
3670
3671           if (new_count != m->count)
3672             m->count = new_count;
3673         }
3674     }
3675
3676   if (bed->elf_backend_modify_segment_map)
3677     {
3678       if (! (*bed->elf_backend_modify_segment_map) (abfd, link_info))
3679         return FALSE;
3680     }
3681
3682   count = 0;
3683   for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
3684     ++count;
3685
3686   elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
3687   elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
3688   elf_elfheader (abfd)->e_phnum = count;
3689
3690   if (count == 0)
3691     return TRUE;
3692
3693   /* If we already counted the number of program segments, make sure
3694      that we allocated enough space.  This happens when SIZEOF_HEADERS
3695      is used in a linker script.  */
3696   alloc = elf_tdata (abfd)->program_header_size / bed->s->sizeof_phdr;
3697   if (alloc != 0 && count > alloc)
3698     {
3699       ((*_bfd_error_handler)
3700        (_("%s: Not enough room for program headers (allocated %u, need %u)"),
3701         bfd_get_filename (abfd), alloc, count));
3702       bfd_set_error (bfd_error_bad_value);
3703       return FALSE;
3704     }
3705
3706   if (alloc == 0)
3707     alloc = count;
3708
3709   amt = alloc * sizeof (Elf_Internal_Phdr);
3710   phdrs = bfd_alloc (abfd, amt);
3711   if (phdrs == NULL)
3712     return FALSE;
3713
3714   off = bed->s->sizeof_ehdr;
3715   off += alloc * bed->s->sizeof_phdr;
3716
3717   filehdr_vaddr = 0;
3718   filehdr_paddr = 0;
3719   phdrs_vaddr = 0;
3720   phdrs_paddr = 0;
3721
3722   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
3723        m != NULL;
3724        m = m->next, p++)
3725     {
3726       unsigned int i;
3727       asection **secpp;
3728
3729       /* If elf_segment_map is not from map_sections_to_segments, the
3730          sections may not be correctly ordered.  NOTE: sorting should
3731          not be done to the PT_NOTE section of a corefile, which may
3732          contain several pseudo-sections artificially created by bfd.
3733          Sorting these pseudo-sections breaks things badly.  */
3734       if (m->count > 1
3735           && !(elf_elfheader (abfd)->e_type == ET_CORE
3736                && m->p_type == PT_NOTE))
3737         qsort (m->sections, (size_t) m->count, sizeof (asection *),
3738                elf_sort_sections);
3739
3740       p->p_type = m->p_type;
3741       p->p_flags = m->p_flags;
3742
3743       if (p->p_type == PT_LOAD
3744           && m->count > 0
3745           && (m->sections[0]->flags & SEC_ALLOC) != 0)
3746         {
3747           if ((abfd->flags & D_PAGED) != 0)
3748             off += vma_page_aligned_bias (m->sections[0]->vma, off,
3749                                           bed->maxpagesize);
3750           else
3751             {
3752               bfd_size_type align;
3753
3754               align = 0;
3755               for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
3756                 {
3757                   bfd_size_type secalign;
3758
3759                   secalign = bfd_get_section_alignment (abfd, *secpp);
3760                   if (secalign > align)
3761                     align = secalign;
3762                 }
3763
3764               off += vma_page_aligned_bias (m->sections[0]->vma, off,
3765                                             1 << align);
3766             }
3767         }
3768
3769       if (m->count == 0)
3770         p->p_vaddr = 0;
3771       else
3772         p->p_vaddr = m->sections[0]->vma;
3773
3774       if (m->p_paddr_valid)
3775         p->p_paddr = m->p_paddr;
3776       else if (m->count == 0)
3777         p->p_paddr = 0;
3778       else
3779         p->p_paddr = m->sections[0]->lma;
3780
3781       if (p->p_type == PT_LOAD
3782           && (abfd->flags & D_PAGED) != 0)
3783         p->p_align = bed->maxpagesize;
3784       else if (m->count == 0)
3785         p->p_align = 1 << bed->s->log_file_align;
3786       else
3787         p->p_align = 0;
3788
3789       p->p_offset = 0;
3790       p->p_filesz = 0;
3791       p->p_memsz = 0;
3792
3793       if (m->includes_filehdr)
3794         {
3795           if (! m->p_flags_valid)
3796             p->p_flags |= PF_R;
3797           p->p_offset = 0;
3798           p->p_filesz = bed->s->sizeof_ehdr;
3799           p->p_memsz = bed->s->sizeof_ehdr;
3800           if (m->count > 0)
3801             {
3802               BFD_ASSERT (p->p_type == PT_LOAD);
3803
3804               if (p->p_vaddr < (bfd_vma) off)
3805                 {
3806                   (*_bfd_error_handler)
3807                     (_("%s: Not enough room for program headers, try linking with -N"),
3808                      bfd_get_filename (abfd));
3809                   bfd_set_error (bfd_error_bad_value);
3810                   return FALSE;
3811                 }
3812
3813               p->p_vaddr -= off;
3814               if (! m->p_paddr_valid)
3815                 p->p_paddr -= off;
3816             }
3817           if (p->p_type == PT_LOAD)
3818             {
3819               filehdr_vaddr = p->p_vaddr;
3820               filehdr_paddr = p->p_paddr;
3821             }
3822         }
3823
3824       if (m->includes_phdrs)
3825         {
3826           if (! m->p_flags_valid)
3827             p->p_flags |= PF_R;
3828
3829           if (m->includes_filehdr)
3830             {
3831               if (p->p_type == PT_LOAD)
3832                 {
3833                   phdrs_vaddr = p->p_vaddr + bed->s->sizeof_ehdr;
3834                   phdrs_paddr = p->p_paddr + bed->s->sizeof_ehdr;
3835                 }
3836             }
3837           else
3838             {
3839               p->p_offset = bed->s->sizeof_ehdr;
3840
3841               if (m->count > 0)
3842                 {
3843                   BFD_ASSERT (p->p_type == PT_LOAD);
3844                   p->p_vaddr -= off - p->p_offset;
3845                   if (! m->p_paddr_valid)
3846                     p->p_paddr -= off - p->p_offset;
3847                 }
3848
3849               if (p->p_type == PT_LOAD)
3850                 {
3851                   phdrs_vaddr = p->p_vaddr;
3852                   phdrs_paddr = p->p_paddr;
3853                 }
3854               else
3855                 phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
3856             }
3857
3858           p->p_filesz += alloc * bed->s->sizeof_phdr;
3859           p->p_memsz += alloc * bed->s->sizeof_phdr;
3860         }
3861
3862       if (p->p_type == PT_LOAD
3863           || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
3864         {
3865           if (! m->includes_filehdr && ! m->includes_phdrs)
3866             p->p_offset = off;
3867           else
3868             {
3869               file_ptr adjust;
3870
3871               adjust = off - (p->p_offset + p->p_filesz);
3872               p->p_filesz += adjust;
3873               p->p_memsz += adjust;
3874             }
3875         }
3876
3877       voff = off;
3878
3879       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
3880         {
3881           asection *sec;
3882           flagword flags;
3883           bfd_size_type align;
3884
3885           sec = *secpp;
3886           flags = sec->flags;
3887           align = 1 << bfd_get_section_alignment (abfd, sec);
3888
3889           /* The section may have artificial alignment forced by a
3890              link script.  Notice this case by the gap between the
3891              cumulative phdr lma and the section's lma.  */
3892           if (p->p_paddr + p->p_memsz < sec->lma)
3893             {
3894               bfd_vma adjust = sec->lma - (p->p_paddr + p->p_memsz);
3895
3896               p->p_memsz += adjust;
3897               if (p->p_type == PT_LOAD
3898                   || (p->p_type == PT_NOTE
3899                       && bfd_get_format (abfd) == bfd_core))
3900                 {
3901                   off += adjust;
3902                   voff += adjust;
3903                 }
3904               if ((flags & SEC_LOAD) != 0
3905                   || (flags & SEC_THREAD_LOCAL) != 0)
3906                 p->p_filesz += adjust;
3907             }
3908
3909           if (p->p_type == PT_LOAD)
3910             {
3911               bfd_signed_vma adjust;
3912
3913               if ((flags & SEC_LOAD) != 0)
3914                 {
3915                   adjust = sec->lma - (p->p_paddr + p->p_memsz);
3916                   if (adjust < 0)
3917                     adjust = 0;
3918                 }
3919               else if ((flags & SEC_ALLOC) != 0)
3920                 {
3921                   /* The section VMA must equal the file position
3922                      modulo the page size.  FIXME: I'm not sure if
3923                      this adjustment is really necessary.  We used to
3924                      not have the SEC_LOAD case just above, and then
3925                      this was necessary, but now I'm not sure.  */
3926                   if ((abfd->flags & D_PAGED) != 0)
3927                     adjust = vma_page_aligned_bias (sec->vma, voff,
3928                                                     bed->maxpagesize);
3929                   else
3930                     adjust = vma_page_aligned_bias (sec->vma, voff,
3931                                                     align);
3932                 }
3933               else
3934                 adjust = 0;
3935
3936               if (adjust != 0)
3937                 {
3938                   if (i == 0)
3939                     {
3940                       (* _bfd_error_handler) (_("\
3941 Error: First section in segment (%s) starts at 0x%x whereas the segment starts at 0x%x"),
3942                                               bfd_section_name (abfd, sec),
3943                                               sec->lma,
3944                                               p->p_paddr);
3945                       return FALSE;
3946                     }
3947                   p->p_memsz += adjust;
3948                   off += adjust;
3949                   voff += adjust;
3950                   if ((flags & SEC_LOAD) != 0)
3951                     p->p_filesz += adjust;
3952                 }
3953
3954               sec->filepos = off;
3955
3956               /* We check SEC_HAS_CONTENTS here because if NOLOAD is
3957                  used in a linker script we may have a section with
3958                  SEC_LOAD clear but which is supposed to have
3959                  contents.  */
3960               if ((flags & SEC_LOAD) != 0
3961                   || (flags & SEC_HAS_CONTENTS) != 0)
3962                 off += sec->_raw_size;
3963
3964               if ((flags & SEC_ALLOC) != 0
3965                   && ((flags & SEC_LOAD) != 0
3966                       || (flags & SEC_THREAD_LOCAL) == 0))
3967                 voff += sec->_raw_size;
3968             }
3969
3970           if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
3971             {
3972               /* The actual "note" segment has i == 0.
3973                  This is the one that actually contains everything.  */
3974               if (i == 0)
3975                 {
3976                   sec->filepos = off;
3977                   p->p_filesz = sec->_raw_size;
3978                   off += sec->_raw_size;
3979                   voff = off;
3980                 }
3981               else
3982                 {
3983                   /* Fake sections -- don't need to be written.  */
3984                   sec->filepos = 0;
3985                   sec->_raw_size = 0;
3986                   flags = sec->flags = 0;
3987                 }
3988               p->p_memsz = 0;
3989               p->p_align = 1;
3990             }
3991           else
3992             {
3993               if ((sec->flags & SEC_LOAD) != 0
3994                   || (sec->flags & SEC_THREAD_LOCAL) == 0
3995                   || p->p_type == PT_TLS)
3996               p->p_memsz += sec->_raw_size;
3997
3998               if ((flags & SEC_LOAD) != 0)
3999                 p->p_filesz += sec->_raw_size;
4000
4001               if (p->p_type == PT_TLS
4002                   && sec->_raw_size == 0
4003                   && (sec->flags & SEC_HAS_CONTENTS) == 0)
4004                 {
4005                   struct bfd_link_order *o;
4006                   bfd_vma tbss_size = 0;
4007
4008                   for (o = sec->link_order_head; o != NULL; o = o->next)
4009                     if (tbss_size < o->offset + o->size)
4010                       tbss_size = o->offset + o->size;
4011
4012                   p->p_memsz += tbss_size;
4013                 }
4014
4015               if (align > p->p_align
4016                   && (p->p_type != PT_LOAD || (abfd->flags & D_PAGED) == 0))
4017                 p->p_align = align;
4018             }
4019
4020           if (! m->p_flags_valid)
4021             {
4022               p->p_flags |= PF_R;
4023               if ((flags & SEC_CODE) != 0)
4024                 p->p_flags |= PF_X;
4025               if ((flags & SEC_READONLY) == 0)
4026                 p->p_flags |= PF_W;
4027             }
4028         }
4029     }
4030
4031   /* Now that we have set the section file positions, we can set up
4032      the file positions for the non PT_LOAD segments.  */
4033   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
4034        m != NULL;
4035        m = m->next, p++)
4036     {
4037       if (p->p_type != PT_LOAD && m->count > 0)
4038         {
4039           BFD_ASSERT (! m->includes_filehdr && ! m->includes_phdrs);
4040           p->p_offset = m->sections[0]->filepos;
4041         }
4042       if (m->count == 0)
4043         {
4044           if (m->includes_filehdr)
4045             {
4046               p->p_vaddr = filehdr_vaddr;
4047               if (! m->p_paddr_valid)
4048                 p->p_paddr = filehdr_paddr;
4049             }
4050           else if (m->includes_phdrs)
4051             {
4052               p->p_vaddr = phdrs_vaddr;
4053               if (! m->p_paddr_valid)
4054                 p->p_paddr = phdrs_paddr;
4055             }
4056         }
4057     }
4058
4059   /* Clear out any program headers we allocated but did not use.  */
4060   for (; count < alloc; count++, p++)
4061     {
4062       memset (p, 0, sizeof *p);
4063       p->p_type = PT_NULL;
4064     }
4065
4066   elf_tdata (abfd)->phdr = phdrs;
4067
4068   elf_tdata (abfd)->next_file_pos = off;
4069
4070   /* Write out the program headers.  */
4071   if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
4072       || bed->s->write_out_phdrs (abfd, phdrs, alloc) != 0)
4073     return FALSE;
4074
4075   return TRUE;
4076 }
4077
4078 /* Get the size of the program header.
4079
4080    If this is called by the linker before any of the section VMA's are set, it
4081    can't calculate the correct value for a strange memory layout.  This only
4082    happens when SIZEOF_HEADERS is used in a linker script.  In this case,
4083    SORTED_HDRS is NULL and we assume the normal scenario of one text and one
4084    data segment (exclusive of .interp and .dynamic).
4085
4086    ??? User written scripts must either not use SIZEOF_HEADERS, or assume there
4087    will be two segments.  */
4088
4089 static bfd_size_type
4090 get_program_header_size (bfd *abfd)
4091 {
4092   size_t segs;
4093   asection *s;
4094   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4095
4096   /* We can't return a different result each time we're called.  */
4097   if (elf_tdata (abfd)->program_header_size != 0)
4098     return elf_tdata (abfd)->program_header_size;
4099
4100   if (elf_tdata (abfd)->segment_map != NULL)
4101     {
4102       struct elf_segment_map *m;
4103
4104       segs = 0;
4105       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
4106         ++segs;
4107       elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
4108       return elf_tdata (abfd)->program_header_size;
4109     }
4110
4111   /* Assume we will need exactly two PT_LOAD segments: one for text
4112      and one for data.  */
4113   segs = 2;
4114
4115   s = bfd_get_section_by_name (abfd, ".interp");
4116   if (s != NULL && (s->flags & SEC_LOAD) != 0)
4117     {
4118       /* If we have a loadable interpreter section, we need a
4119          PT_INTERP segment.  In this case, assume we also need a
4120          PT_PHDR segment, although that may not be true for all
4121          targets.  */
4122       segs += 2;
4123     }
4124
4125   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
4126     {
4127       /* We need a PT_DYNAMIC segment.  */
4128       ++segs;
4129     }
4130
4131   if (elf_tdata (abfd)->eh_frame_hdr)
4132     {
4133       /* We need a PT_GNU_EH_FRAME segment.  */
4134       ++segs;
4135     }
4136
4137   if (elf_tdata (abfd)->stack_flags)
4138     {
4139       /* We need a PT_GNU_STACK segment.  */
4140       ++segs;
4141     }
4142
4143   for (s = abfd->sections; s != NULL; s = s->next)
4144     {
4145       if ((s->flags & SEC_LOAD) != 0
4146           && strncmp (s->name, ".note", 5) == 0)
4147         {
4148           /* We need a PT_NOTE segment.  */
4149           ++segs;
4150         }
4151     }
4152
4153   for (s = abfd->sections; s != NULL; s = s->next)
4154     {
4155       if (s->flags & SEC_THREAD_LOCAL)
4156         {
4157           /* We need a PT_TLS segment.  */
4158           ++segs;
4159           break;
4160         }
4161     }
4162
4163   /* Let the backend count up any program headers it might need.  */
4164   if (bed->elf_backend_additional_program_headers)
4165     {
4166       int a;
4167
4168       a = (*bed->elf_backend_additional_program_headers) (abfd);
4169       if (a == -1)
4170         abort ();
4171       segs += a;
4172     }
4173
4174   elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
4175   return elf_tdata (abfd)->program_header_size;
4176 }
4177
4178 /* Work out the file positions of all the sections.  This is called by
4179    _bfd_elf_compute_section_file_positions.  All the section sizes and
4180    VMAs must be known before this is called.
4181
4182    We do not consider reloc sections at this point, unless they form
4183    part of the loadable image.  Reloc sections are assigned file
4184    positions in assign_file_positions_for_relocs, which is called by
4185    write_object_contents and final_link.
4186
4187    We also don't set the positions of the .symtab and .strtab here.  */
4188
4189 static bfd_boolean
4190 assign_file_positions_except_relocs (bfd *abfd,
4191                                      struct bfd_link_info *link_info)
4192 {
4193   struct elf_obj_tdata * const tdata = elf_tdata (abfd);
4194   Elf_Internal_Ehdr * const i_ehdrp = elf_elfheader (abfd);
4195   Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
4196   unsigned int num_sec = elf_numsections (abfd);
4197   file_ptr off;
4198   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4199
4200   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
4201       && bfd_get_format (abfd) != bfd_core)
4202     {
4203       Elf_Internal_Shdr **hdrpp;
4204       unsigned int i;
4205
4206       /* Start after the ELF header.  */
4207       off = i_ehdrp->e_ehsize;
4208
4209       /* We are not creating an executable, which means that we are
4210          not creating a program header, and that the actual order of
4211          the sections in the file is unimportant.  */
4212       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
4213         {
4214           Elf_Internal_Shdr *hdr;
4215
4216           hdr = *hdrpp;
4217           if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
4218                && hdr->bfd_section == NULL)
4219               || i == tdata->symtab_section
4220               || i == tdata->symtab_shndx_section
4221               || i == tdata->strtab_section)
4222             {
4223               hdr->sh_offset = -1;
4224             }
4225           else
4226             off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4227
4228           if (i == SHN_LORESERVE - 1)
4229             {
4230               i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4231               hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4232             }
4233         }
4234     }
4235   else
4236     {
4237       unsigned int i;
4238       Elf_Internal_Shdr **hdrpp;
4239
4240       /* Assign file positions for the loaded sections based on the
4241          assignment of sections to segments.  */
4242       if (! assign_file_positions_for_segments (abfd, link_info))
4243         return FALSE;
4244
4245       /* Assign file positions for the other sections.  */
4246
4247       off = elf_tdata (abfd)->next_file_pos;
4248       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
4249         {
4250           Elf_Internal_Shdr *hdr;
4251
4252           hdr = *hdrpp;
4253           if (hdr->bfd_section != NULL
4254               && hdr->bfd_section->filepos != 0)
4255             hdr->sh_offset = hdr->bfd_section->filepos;
4256           else if ((hdr->sh_flags & SHF_ALLOC) != 0)
4257             {
4258               ((*_bfd_error_handler)
4259                (_("%s: warning: allocated section `%s' not in segment"),
4260                 bfd_get_filename (abfd),
4261                 (hdr->bfd_section == NULL
4262                  ? "*unknown*"
4263                  : hdr->bfd_section->name)));
4264               if ((abfd->flags & D_PAGED) != 0)
4265                 off += vma_page_aligned_bias (hdr->sh_addr, off,
4266                                               bed->maxpagesize);
4267               else
4268                 off += vma_page_aligned_bias (hdr->sh_addr, off,
4269                                               hdr->sh_addralign);
4270               off = _bfd_elf_assign_file_position_for_section (hdr, off,
4271                                                                FALSE);
4272             }
4273           else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
4274                     && hdr->bfd_section == NULL)
4275                    || hdr == i_shdrpp[tdata->symtab_section]
4276                    || hdr == i_shdrpp[tdata->symtab_shndx_section]
4277                    || hdr == i_shdrpp[tdata->strtab_section])
4278             hdr->sh_offset = -1;
4279           else
4280             off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4281
4282           if (i == SHN_LORESERVE - 1)
4283             {
4284               i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4285               hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4286             }
4287         }
4288     }
4289
4290   /* Place the section headers.  */
4291   off = align_file_position (off, 1 << bed->s->log_file_align);
4292   i_ehdrp->e_shoff = off;
4293   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
4294
4295   elf_tdata (abfd)->next_file_pos = off;
4296
4297   return TRUE;
4298 }
4299
4300 static bfd_boolean
4301 prep_headers (bfd *abfd)
4302 {
4303   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
4304   Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
4305   Elf_Internal_Shdr **i_shdrp;  /* Section header table, internal form */
4306   struct elf_strtab_hash *shstrtab;
4307   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4308
4309   i_ehdrp = elf_elfheader (abfd);
4310   i_shdrp = elf_elfsections (abfd);
4311
4312   shstrtab = _bfd_elf_strtab_init ();
4313   if (shstrtab == NULL)
4314     return FALSE;
4315
4316   elf_shstrtab (abfd) = shstrtab;
4317
4318   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
4319   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
4320   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
4321   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
4322
4323   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
4324   i_ehdrp->e_ident[EI_DATA] =
4325     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
4326   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
4327
4328   i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
4329
4330   if ((abfd->flags & DYNAMIC) != 0)
4331     i_ehdrp->e_type = ET_DYN;
4332   else if ((abfd->flags & EXEC_P) != 0)
4333     i_ehdrp->e_type = ET_EXEC;
4334   else if (bfd_get_format (abfd) == bfd_core)
4335     i_ehdrp->e_type = ET_CORE;
4336   else
4337     i_ehdrp->e_type = ET_REL;
4338
4339   switch (bfd_get_arch (abfd))
4340     {
4341     case bfd_arch_unknown:
4342       i_ehdrp->e_machine = EM_NONE;
4343       break;
4344
4345       /* There used to be a long list of cases here, each one setting
4346          e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
4347          in the corresponding bfd definition.  To avoid duplication,
4348          the switch was removed.  Machines that need special handling
4349          can generally do it in elf_backend_final_write_processing(),
4350          unless they need the information earlier than the final write.
4351          Such need can generally be supplied by replacing the tests for
4352          e_machine with the conditions used to determine it.  */
4353     default:
4354       i_ehdrp->e_machine = bed->elf_machine_code;
4355     }
4356
4357   i_ehdrp->e_version = bed->s->ev_current;
4358   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
4359
4360   /* No program header, for now.  */
4361   i_ehdrp->e_phoff = 0;
4362   i_ehdrp->e_phentsize = 0;
4363   i_ehdrp->e_phnum = 0;
4364
4365   /* Each bfd section is section header entry.  */
4366   i_ehdrp->e_entry = bfd_get_start_address (abfd);
4367   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
4368
4369   /* If we're building an executable, we'll need a program header table.  */
4370   if (abfd->flags & EXEC_P)
4371     {
4372       /* It all happens later.  */
4373 #if 0
4374       i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
4375
4376       /* elf_build_phdrs() returns a (NULL-terminated) array of
4377          Elf_Internal_Phdrs.  */
4378       i_phdrp = elf_build_phdrs (abfd, i_ehdrp, i_shdrp, &i_ehdrp->e_phnum);
4379       i_ehdrp->e_phoff = outbase;
4380       outbase += i_ehdrp->e_phentsize * i_ehdrp->e_phnum;
4381 #endif
4382     }
4383   else
4384     {
4385       i_ehdrp->e_phentsize = 0;
4386       i_phdrp = 0;
4387       i_ehdrp->e_phoff = 0;
4388     }
4389
4390   elf_tdata (abfd)->symtab_hdr.sh_name =
4391     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", FALSE);
4392   elf_tdata (abfd)->strtab_hdr.sh_name =
4393     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", FALSE);
4394   elf_tdata (abfd)->shstrtab_hdr.sh_name =
4395     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", FALSE);
4396   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4397       || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4398       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
4399     return FALSE;
4400
4401   return TRUE;
4402 }
4403
4404 /* Assign file positions for all the reloc sections which are not part
4405    of the loadable file image.  */
4406
4407 void
4408 _bfd_elf_assign_file_positions_for_relocs (bfd *abfd)
4409 {
4410   file_ptr off;
4411   unsigned int i, num_sec;
4412   Elf_Internal_Shdr **shdrpp;
4413
4414   off = elf_tdata (abfd)->next_file_pos;
4415
4416   num_sec = elf_numsections (abfd);
4417   for (i = 1, shdrpp = elf_elfsections (abfd) + 1; i < num_sec; i++, shdrpp++)
4418     {
4419       Elf_Internal_Shdr *shdrp;
4420
4421       shdrp = *shdrpp;
4422       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
4423           && shdrp->sh_offset == -1)
4424         off = _bfd_elf_assign_file_position_for_section (shdrp, off, TRUE);
4425     }
4426
4427   elf_tdata (abfd)->next_file_pos = off;
4428 }
4429
4430 bfd_boolean
4431 _bfd_elf_write_object_contents (bfd *abfd)
4432 {
4433   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4434   Elf_Internal_Ehdr *i_ehdrp;
4435   Elf_Internal_Shdr **i_shdrp;
4436   bfd_boolean failed;
4437   unsigned int count, num_sec;
4438
4439   if (! abfd->output_has_begun
4440       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
4441     return FALSE;
4442
4443   i_shdrp = elf_elfsections (abfd);
4444   i_ehdrp = elf_elfheader (abfd);
4445
4446   failed = FALSE;
4447   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
4448   if (failed)
4449     return FALSE;
4450
4451   _bfd_elf_assign_file_positions_for_relocs (abfd);
4452
4453   /* After writing the headers, we need to write the sections too...  */
4454   num_sec = elf_numsections (abfd);
4455   for (count = 1; count < num_sec; count++)
4456     {
4457       if (bed->elf_backend_section_processing)
4458         (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
4459       if (i_shdrp[count]->contents)
4460         {
4461           bfd_size_type amt = i_shdrp[count]->sh_size;
4462
4463           if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
4464               || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
4465             return FALSE;
4466         }
4467       if (count == SHN_LORESERVE - 1)
4468         count += SHN_HIRESERVE + 1 - SHN_LORESERVE;
4469     }
4470
4471   /* Write out the section header names.  */
4472   if (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
4473       || ! _bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd)))
4474     return FALSE;
4475
4476   if (bed->elf_backend_final_write_processing)
4477     (*bed->elf_backend_final_write_processing) (abfd,
4478                                                 elf_tdata (abfd)->linker);
4479
4480   return bed->s->write_shdrs_and_ehdr (abfd);
4481 }
4482
4483 bfd_boolean
4484 _bfd_elf_write_corefile_contents (bfd *abfd)
4485 {
4486   /* Hopefully this can be done just like an object file.  */
4487   return _bfd_elf_write_object_contents (abfd);
4488 }
4489
4490 /* Given a section, search the header to find them.  */
4491
4492 int
4493 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
4494 {
4495   const struct elf_backend_data *bed;
4496   int index;
4497
4498   if (elf_section_data (asect) != NULL
4499       && elf_section_data (asect)->this_idx != 0)
4500     return elf_section_data (asect)->this_idx;
4501
4502   if (bfd_is_abs_section (asect))
4503     index = SHN_ABS;
4504   else if (bfd_is_com_section (asect))
4505     index = SHN_COMMON;
4506   else if (bfd_is_und_section (asect))
4507     index = SHN_UNDEF;
4508   else
4509     {
4510       Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
4511       int maxindex = elf_numsections (abfd);
4512
4513       for (index = 1; index < maxindex; index++)
4514         {
4515           Elf_Internal_Shdr *hdr = i_shdrp[index];
4516
4517           if (hdr != NULL && hdr->bfd_section == asect)
4518             return index;
4519         }
4520       index = -1;
4521     }
4522
4523   bed = get_elf_backend_data (abfd);
4524   if (bed->elf_backend_section_from_bfd_section)
4525     {
4526       int retval = index;
4527
4528       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
4529         return retval;
4530     }
4531
4532   if (index == -1)
4533     bfd_set_error (bfd_error_nonrepresentable_section);
4534
4535   return index;
4536 }
4537
4538 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
4539    on error.  */
4540
4541 int
4542 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
4543 {
4544   asymbol *asym_ptr = *asym_ptr_ptr;
4545   int idx;
4546   flagword flags = asym_ptr->flags;
4547
4548   /* When gas creates relocations against local labels, it creates its
4549      own symbol for the section, but does put the symbol into the
4550      symbol chain, so udata is 0.  When the linker is generating
4551      relocatable output, this section symbol may be for one of the
4552      input sections rather than the output section.  */
4553   if (asym_ptr->udata.i == 0
4554       && (flags & BSF_SECTION_SYM)
4555       && asym_ptr->section)
4556     {
4557       int indx;
4558
4559       if (asym_ptr->section->output_section != NULL)
4560         indx = asym_ptr->section->output_section->index;
4561       else
4562         indx = asym_ptr->section->index;
4563       if (indx < elf_num_section_syms (abfd)
4564           && elf_section_syms (abfd)[indx] != NULL)
4565         asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
4566     }
4567
4568   idx = asym_ptr->udata.i;
4569
4570   if (idx == 0)
4571     {
4572       /* This case can occur when using --strip-symbol on a symbol
4573          which is used in a relocation entry.  */
4574       (*_bfd_error_handler)
4575         (_("%s: symbol `%s' required but not present"),
4576          bfd_archive_filename (abfd), bfd_asymbol_name (asym_ptr));
4577       bfd_set_error (bfd_error_no_symbols);
4578       return -1;
4579     }
4580
4581 #if DEBUG & 4
4582   {
4583     fprintf (stderr,
4584              "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx%s\n",
4585              (long) asym_ptr, asym_ptr->name, idx, flags,
4586              elf_symbol_flags (flags));
4587     fflush (stderr);
4588   }
4589 #endif
4590
4591   return idx;
4592 }
4593
4594 /* Copy private BFD data.  This copies any program header information.  */
4595
4596 static bfd_boolean
4597 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
4598 {
4599   Elf_Internal_Ehdr *iehdr;
4600   struct elf_segment_map *map;
4601   struct elf_segment_map *map_first;
4602   struct elf_segment_map **pointer_to_map;
4603   Elf_Internal_Phdr *segment;
4604   asection *section;
4605   unsigned int i;
4606   unsigned int num_segments;
4607   bfd_boolean phdr_included = FALSE;
4608   bfd_vma maxpagesize;
4609   struct elf_segment_map *phdr_adjust_seg = NULL;
4610   unsigned int phdr_adjust_num = 0;
4611   const struct elf_backend_data *bed;
4612
4613   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
4614       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
4615     return TRUE;
4616
4617   if (elf_tdata (ibfd)->phdr == NULL)
4618     return TRUE;
4619
4620   bed = get_elf_backend_data (ibfd);
4621   iehdr = elf_elfheader (ibfd);
4622
4623   map_first = NULL;
4624   pointer_to_map = &map_first;
4625
4626   num_segments = elf_elfheader (ibfd)->e_phnum;
4627   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
4628
4629   /* Returns the end address of the segment + 1.  */
4630 #define SEGMENT_END(segment, start)                                     \
4631   (start + (segment->p_memsz > segment->p_filesz                        \
4632             ? segment->p_memsz : segment->p_filesz))
4633
4634 #define SECTION_SIZE(section, segment)                                  \
4635   (((section->flags & (SEC_HAS_CONTENTS | SEC_THREAD_LOCAL))            \
4636     != SEC_THREAD_LOCAL || segment->p_type == PT_TLS)                   \
4637    ? section->_raw_size : 0)
4638
4639   /* Returns TRUE if the given section is contained within
4640      the given segment.  VMA addresses are compared.  */
4641 #define IS_CONTAINED_BY_VMA(section, segment)                           \
4642   (section->vma >= segment->p_vaddr                                     \
4643    && (section->vma + SECTION_SIZE (section, segment)                   \
4644        <= (SEGMENT_END (segment, segment->p_vaddr))))
4645
4646   /* Returns TRUE if the given section is contained within
4647      the given segment.  LMA addresses are compared.  */
4648 #define IS_CONTAINED_BY_LMA(section, segment, base)                     \
4649   (section->lma >= base                                                 \
4650    && (section->lma + SECTION_SIZE (section, segment)                   \
4651        <= SEGMENT_END (segment, base)))
4652
4653   /* Special case: corefile "NOTE" section containing regs, prpsinfo etc.  */
4654 #define IS_COREFILE_NOTE(p, s)                                          \
4655   (p->p_type == PT_NOTE                                                 \
4656    && bfd_get_format (ibfd) == bfd_core                                 \
4657    && s->vma == 0 && s->lma == 0                                        \
4658    && (bfd_vma) s->filepos >= p->p_offset                               \
4659    && ((bfd_vma) s->filepos + s->_raw_size                              \
4660        <= p->p_offset + p->p_filesz))
4661
4662   /* The complicated case when p_vaddr is 0 is to handle the Solaris
4663      linker, which generates a PT_INTERP section with p_vaddr and
4664      p_memsz set to 0.  */
4665 #define IS_SOLARIS_PT_INTERP(p, s)                                      \
4666   (p->p_vaddr == 0                                                      \
4667    && p->p_paddr == 0                                                   \
4668    && p->p_memsz == 0                                                   \
4669    && p->p_filesz > 0                                                   \
4670    && (s->flags & SEC_HAS_CONTENTS) != 0                                \
4671    && s->_raw_size > 0                                                  \
4672    && (bfd_vma) s->filepos >= p->p_offset                               \
4673    && ((bfd_vma) s->filepos + s->_raw_size                              \
4674        <= p->p_offset + p->p_filesz))
4675
4676   /* Decide if the given section should be included in the given segment.
4677      A section will be included if:
4678        1. It is within the address space of the segment -- we use the LMA
4679           if that is set for the segment and the VMA otherwise,
4680        2. It is an allocated segment,
4681        3. There is an output section associated with it,
4682        4. The section has not already been allocated to a previous segment.
4683        5. PT_GNU_STACK segments do not include any sections.
4684        6. PT_TLS segment includes only SHF_TLS sections.
4685        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.  */
4686 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)               \
4687   ((((segment->p_paddr                                                  \
4688       ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)        \
4689       : IS_CONTAINED_BY_VMA (section, segment))                         \
4690      && (section->flags & SEC_ALLOC) != 0)                              \
4691     || IS_COREFILE_NOTE (segment, section))                             \
4692    && section->output_section != NULL                                   \
4693    && segment->p_type != PT_GNU_STACK                                   \
4694    && (segment->p_type != PT_TLS                                        \
4695        || (section->flags & SEC_THREAD_LOCAL))                          \
4696    && (segment->p_type == PT_LOAD                                       \
4697        || segment->p_type == PT_TLS                                     \
4698        || (section->flags & SEC_THREAD_LOCAL) == 0)                     \
4699    && ! section->segment_mark)
4700
4701   /* Returns TRUE iff seg1 starts after the end of seg2.  */
4702 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)                        \
4703   (seg1->field >= SEGMENT_END (seg2, seg2->field))
4704
4705   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
4706      their VMA address ranges and their LMA address ranges overlap.
4707      It is possible to have overlapping VMA ranges without overlapping LMA
4708      ranges.  RedBoot images for example can have both .data and .bss mapped
4709      to the same VMA range, but with the .data section mapped to a different
4710      LMA.  */
4711 #define SEGMENT_OVERLAPS(seg1, seg2)                                    \
4712   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)                     \
4713         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))                 \
4714    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)                     \
4715         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
4716
4717   /* Initialise the segment mark field.  */
4718   for (section = ibfd->sections; section != NULL; section = section->next)
4719     section->segment_mark = FALSE;
4720
4721   /* Scan through the segments specified in the program header
4722      of the input BFD.  For this first scan we look for overlaps
4723      in the loadable segments.  These can be created by weird
4724      parameters to objcopy.  Also, fix some solaris weirdness.  */
4725   for (i = 0, segment = elf_tdata (ibfd)->phdr;
4726        i < num_segments;
4727        i++, segment++)
4728     {
4729       unsigned int j;
4730       Elf_Internal_Phdr *segment2;
4731
4732       if (segment->p_type == PT_INTERP)
4733         for (section = ibfd->sections; section; section = section->next)
4734           if (IS_SOLARIS_PT_INTERP (segment, section))
4735             {
4736               /* Mininal change so that the normal section to segment
4737                  assignment code will work.  */
4738               segment->p_vaddr = section->vma;
4739               break;
4740             }
4741
4742       if (segment->p_type != PT_LOAD)
4743         continue;
4744
4745       /* Determine if this segment overlaps any previous segments.  */
4746       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2 ++)
4747         {
4748           bfd_signed_vma extra_length;
4749
4750           if (segment2->p_type != PT_LOAD
4751               || ! SEGMENT_OVERLAPS (segment, segment2))
4752             continue;
4753
4754           /* Merge the two segments together.  */
4755           if (segment2->p_vaddr < segment->p_vaddr)
4756             {
4757               /* Extend SEGMENT2 to include SEGMENT and then delete
4758                  SEGMENT.  */
4759               extra_length =
4760                 SEGMENT_END (segment, segment->p_vaddr)
4761                 - SEGMENT_END (segment2, segment2->p_vaddr);
4762
4763               if (extra_length > 0)
4764                 {
4765                   segment2->p_memsz  += extra_length;
4766                   segment2->p_filesz += extra_length;
4767                 }
4768
4769               segment->p_type = PT_NULL;
4770
4771               /* Since we have deleted P we must restart the outer loop.  */
4772               i = 0;
4773               segment = elf_tdata (ibfd)->phdr;
4774               break;
4775             }
4776           else
4777             {
4778               /* Extend SEGMENT to include SEGMENT2 and then delete
4779                  SEGMENT2.  */
4780               extra_length =
4781                 SEGMENT_END (segment2, segment2->p_vaddr)
4782                 - SEGMENT_END (segment, segment->p_vaddr);
4783
4784               if (extra_length > 0)
4785                 {
4786                   segment->p_memsz  += extra_length;
4787                   segment->p_filesz += extra_length;
4788                 }
4789
4790               segment2->p_type = PT_NULL;
4791             }
4792         }
4793     }
4794
4795   /* The second scan attempts to assign sections to segments.  */
4796   for (i = 0, segment = elf_tdata (ibfd)->phdr;
4797        i < num_segments;
4798        i ++, segment ++)
4799     {
4800       unsigned int  section_count;
4801       asection **   sections;
4802       asection *    output_section;
4803       unsigned int  isec;
4804       bfd_vma       matching_lma;
4805       bfd_vma       suggested_lma;
4806       unsigned int  j;
4807       bfd_size_type amt;
4808
4809       if (segment->p_type == PT_NULL)
4810         continue;
4811
4812       /* Compute how many sections might be placed into this segment.  */
4813       for (section = ibfd->sections, section_count = 0;
4814            section != NULL;
4815            section = section->next)
4816         if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
4817           ++section_count;
4818
4819       /* Allocate a segment map big enough to contain
4820          all of the sections we have selected.  */
4821       amt = sizeof (struct elf_segment_map);
4822       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
4823       map = bfd_alloc (obfd, amt);
4824       if (map == NULL)
4825         return FALSE;
4826
4827       /* Initialise the fields of the segment map.  Default to
4828          using the physical address of the segment in the input BFD.  */
4829       map->next          = NULL;
4830       map->p_type        = segment->p_type;
4831       map->p_flags       = segment->p_flags;
4832       map->p_flags_valid = 1;
4833       map->p_paddr       = segment->p_paddr;
4834       map->p_paddr_valid = 1;
4835
4836       /* Determine if this segment contains the ELF file header
4837          and if it contains the program headers themselves.  */
4838       map->includes_filehdr = (segment->p_offset == 0
4839                                && segment->p_filesz >= iehdr->e_ehsize);
4840
4841       map->includes_phdrs = 0;
4842
4843       if (! phdr_included || segment->p_type != PT_LOAD)
4844         {
4845           map->includes_phdrs =
4846             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
4847              && (segment->p_offset + segment->p_filesz
4848                  >= ((bfd_vma) iehdr->e_phoff
4849                      + iehdr->e_phnum * iehdr->e_phentsize)));
4850
4851           if (segment->p_type == PT_LOAD && map->includes_phdrs)
4852             phdr_included = TRUE;
4853         }
4854
4855       if (section_count == 0)
4856         {
4857           /* Special segments, such as the PT_PHDR segment, may contain
4858              no sections, but ordinary, loadable segments should contain
4859              something.  They are allowed by the ELF spec however, so only
4860              a warning is produced.  */
4861           if (segment->p_type == PT_LOAD)
4862             (*_bfd_error_handler)
4863               (_("%s: warning: Empty loadable segment detected, is this intentional ?\n"),
4864                bfd_archive_filename (ibfd));
4865
4866           map->count = 0;
4867           *pointer_to_map = map;
4868           pointer_to_map = &map->next;
4869
4870           continue;
4871         }
4872
4873       /* Now scan the sections in the input BFD again and attempt
4874          to add their corresponding output sections to the segment map.
4875          The problem here is how to handle an output section which has
4876          been moved (ie had its LMA changed).  There are four possibilities:
4877
4878          1. None of the sections have been moved.
4879             In this case we can continue to use the segment LMA from the
4880             input BFD.
4881
4882          2. All of the sections have been moved by the same amount.
4883             In this case we can change the segment's LMA to match the LMA
4884             of the first section.
4885
4886          3. Some of the sections have been moved, others have not.
4887             In this case those sections which have not been moved can be
4888             placed in the current segment which will have to have its size,
4889             and possibly its LMA changed, and a new segment or segments will
4890             have to be created to contain the other sections.
4891
4892          4. The sections have been moved, but not by the same amount.
4893             In this case we can change the segment's LMA to match the LMA
4894             of the first section and we will have to create a new segment
4895             or segments to contain the other sections.
4896
4897          In order to save time, we allocate an array to hold the section
4898          pointers that we are interested in.  As these sections get assigned
4899          to a segment, they are removed from this array.  */
4900
4901       /* Gcc 2.96 miscompiles this code on mips. Don't do casting here
4902          to work around this long long bug.  */
4903       amt = section_count * sizeof (asection *);
4904       sections = bfd_malloc (amt);
4905       if (sections == NULL)
4906         return FALSE;
4907
4908       /* Step One: Scan for segment vs section LMA conflicts.
4909          Also add the sections to the section array allocated above.
4910          Also add the sections to the current segment.  In the common
4911          case, where the sections have not been moved, this means that
4912          we have completely filled the segment, and there is nothing
4913          more to do.  */
4914       isec = 0;
4915       matching_lma = 0;
4916       suggested_lma = 0;
4917
4918       for (j = 0, section = ibfd->sections;
4919            section != NULL;
4920            section = section->next)
4921         {
4922           if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
4923             {
4924               output_section = section->output_section;
4925
4926               sections[j ++] = section;
4927
4928               /* The Solaris native linker always sets p_paddr to 0.
4929                  We try to catch that case here, and set it to the
4930                  correct value.  Note - some backends require that
4931                  p_paddr be left as zero.  */
4932               if (segment->p_paddr == 0
4933                   && segment->p_vaddr != 0
4934                   && (! bed->want_p_paddr_set_to_zero)
4935                   && isec == 0
4936                   && output_section->lma != 0
4937                   && (output_section->vma == (segment->p_vaddr
4938                                               + (map->includes_filehdr
4939                                                  ? iehdr->e_ehsize
4940                                                  : 0)
4941                                               + (map->includes_phdrs
4942                                                  ? (iehdr->e_phnum
4943                                                     * iehdr->e_phentsize)
4944                                                  : 0))))
4945                 map->p_paddr = segment->p_vaddr;
4946
4947               /* Match up the physical address of the segment with the
4948                  LMA address of the output section.  */
4949               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
4950                   || IS_COREFILE_NOTE (segment, section)
4951                   || (bed->want_p_paddr_set_to_zero &&
4952                       IS_CONTAINED_BY_VMA (output_section, segment))
4953                 )
4954                 {
4955                   if (matching_lma == 0)
4956                     matching_lma = output_section->lma;
4957
4958                   /* We assume that if the section fits within the segment
4959                      then it does not overlap any other section within that
4960                      segment.  */
4961                   map->sections[isec ++] = output_section;
4962                 }
4963               else if (suggested_lma == 0)
4964                 suggested_lma = output_section->lma;
4965             }
4966         }
4967
4968       BFD_ASSERT (j == section_count);
4969
4970       /* Step Two: Adjust the physical address of the current segment,
4971          if necessary.  */
4972       if (isec == section_count)
4973         {
4974           /* All of the sections fitted within the segment as currently
4975              specified.  This is the default case.  Add the segment to
4976              the list of built segments and carry on to process the next
4977              program header in the input BFD.  */
4978           map->count = section_count;
4979           *pointer_to_map = map;
4980           pointer_to_map = &map->next;
4981
4982           free (sections);
4983           continue;
4984         }
4985       else
4986         {
4987           if (matching_lma != 0)
4988             {
4989               /* At least one section fits inside the current segment.
4990                  Keep it, but modify its physical address to match the
4991                  LMA of the first section that fitted.  */
4992               map->p_paddr = matching_lma;
4993             }
4994           else
4995             {
4996               /* None of the sections fitted inside the current segment.
4997                  Change the current segment's physical address to match
4998                  the LMA of the first section.  */
4999               map->p_paddr = suggested_lma;
5000             }
5001
5002           /* Offset the segment physical address from the lma
5003              to allow for space taken up by elf headers.  */
5004           if (map->includes_filehdr)
5005             map->p_paddr -= iehdr->e_ehsize;
5006
5007           if (map->includes_phdrs)
5008             {
5009               map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
5010
5011               /* iehdr->e_phnum is just an estimate of the number
5012                  of program headers that we will need.  Make a note
5013                  here of the number we used and the segment we chose
5014                  to hold these headers, so that we can adjust the
5015                  offset when we know the correct value.  */
5016               phdr_adjust_num = iehdr->e_phnum;
5017               phdr_adjust_seg = map;
5018             }
5019         }
5020
5021       /* Step Three: Loop over the sections again, this time assigning
5022          those that fit to the current segment and removing them from the
5023          sections array; but making sure not to leave large gaps.  Once all
5024          possible sections have been assigned to the current segment it is
5025          added to the list of built segments and if sections still remain
5026          to be assigned, a new segment is constructed before repeating
5027          the loop.  */
5028       isec = 0;
5029       do
5030         {
5031           map->count = 0;
5032           suggested_lma = 0;
5033
5034           /* Fill the current segment with sections that fit.  */
5035           for (j = 0; j < section_count; j++)
5036             {
5037               section = sections[j];
5038
5039               if (section == NULL)
5040                 continue;
5041
5042               output_section = section->output_section;
5043
5044               BFD_ASSERT (output_section != NULL);
5045
5046               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
5047                   || IS_COREFILE_NOTE (segment, section))
5048                 {
5049                   if (map->count == 0)
5050                     {
5051                       /* If the first section in a segment does not start at
5052                          the beginning of the segment, then something is
5053                          wrong.  */
5054                       if (output_section->lma !=
5055                           (map->p_paddr
5056                            + (map->includes_filehdr ? iehdr->e_ehsize : 0)
5057                            + (map->includes_phdrs
5058                               ? iehdr->e_phnum * iehdr->e_phentsize
5059                               : 0)))
5060                         abort ();
5061                     }
5062                   else
5063                     {
5064                       asection * prev_sec;
5065
5066                       prev_sec = map->sections[map->count - 1];
5067
5068                       /* If the gap between the end of the previous section
5069                          and the start of this section is more than
5070                          maxpagesize then we need to start a new segment.  */
5071                       if ((BFD_ALIGN (prev_sec->lma + prev_sec->_raw_size,
5072                                       maxpagesize)
5073                            < BFD_ALIGN (output_section->lma, maxpagesize))
5074                           || ((prev_sec->lma + prev_sec->_raw_size)
5075                               > output_section->lma))
5076                         {
5077                           if (suggested_lma == 0)
5078                             suggested_lma = output_section->lma;
5079
5080                           continue;
5081                         }
5082                     }
5083
5084                   map->sections[map->count++] = output_section;
5085                   ++isec;
5086                   sections[j] = NULL;
5087                   section->segment_mark = TRUE;
5088                 }
5089               else if (suggested_lma == 0)
5090                 suggested_lma = output_section->lma;
5091             }
5092
5093           BFD_ASSERT (map->count > 0);
5094
5095           /* Add the current segment to the list of built segments.  */
5096           *pointer_to_map = map;
5097           pointer_to_map = &map->next;
5098
5099           if (isec < section_count)
5100             {
5101               /* We still have not allocated all of the sections to
5102                  segments.  Create a new segment here, initialise it
5103                  and carry on looping.  */
5104               amt = sizeof (struct elf_segment_map);
5105               amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
5106               map = bfd_alloc (obfd, amt);
5107               if (map == NULL)
5108                 {
5109                   free (sections);
5110                   return FALSE;
5111                 }
5112
5113               /* Initialise the fields of the segment map.  Set the physical
5114                  physical address to the LMA of the first section that has
5115                  not yet been assigned.  */
5116               map->next             = NULL;
5117               map->p_type           = segment->p_type;
5118               map->p_flags          = segment->p_flags;
5119               map->p_flags_valid    = 1;
5120               map->p_paddr          = suggested_lma;
5121               map->p_paddr_valid    = 1;
5122               map->includes_filehdr = 0;
5123               map->includes_phdrs   = 0;
5124             }
5125         }
5126       while (isec < section_count);
5127
5128       free (sections);
5129     }
5130
5131   /* The Solaris linker creates program headers in which all the
5132      p_paddr fields are zero.  When we try to objcopy or strip such a
5133      file, we get confused.  Check for this case, and if we find it
5134      reset the p_paddr_valid fields.  */
5135   for (map = map_first; map != NULL; map = map->next)
5136     if (map->p_paddr != 0)
5137       break;
5138   if (map == NULL)
5139     for (map = map_first; map != NULL; map = map->next)
5140       map->p_paddr_valid = 0;
5141
5142   elf_tdata (obfd)->segment_map = map_first;
5143
5144   /* If we had to estimate the number of program headers that were
5145      going to be needed, then check our estimate now and adjust
5146      the offset if necessary.  */
5147   if (phdr_adjust_seg != NULL)
5148     {
5149       unsigned int count;
5150
5151       for (count = 0, map = map_first; map != NULL; map = map->next)
5152         count++;
5153
5154       if (count > phdr_adjust_num)
5155         phdr_adjust_seg->p_paddr
5156           -= (count - phdr_adjust_num) * iehdr->e_phentsize;
5157     }
5158
5159 #if 0
5160   /* Final Step: Sort the segments into ascending order of physical
5161      address.  */
5162   if (map_first != NULL)
5163     {
5164       struct elf_segment_map *prev;
5165
5166       prev = map_first;
5167       for (map = map_first->next; map != NULL; prev = map, map = map->next)
5168         {
5169           /* Yes I know - its a bubble sort....  */
5170           if (map->next != NULL && (map->next->p_paddr < map->p_paddr))
5171             {
5172               /* Swap map and map->next.  */
5173               prev->next = map->next;
5174               map->next = map->next->next;
5175               prev->next->next = map;
5176
5177               /* Restart loop.  */
5178               map = map_first;
5179             }
5180         }
5181     }
5182 #endif
5183
5184 #undef SEGMENT_END
5185 #undef SECTION_SIZE
5186 #undef IS_CONTAINED_BY_VMA
5187 #undef IS_CONTAINED_BY_LMA
5188 #undef IS_COREFILE_NOTE
5189 #undef IS_SOLARIS_PT_INTERP
5190 #undef INCLUDE_SECTION_IN_SEGMENT
5191 #undef SEGMENT_AFTER_SEGMENT
5192 #undef SEGMENT_OVERLAPS
5193   return TRUE;
5194 }
5195
5196 /* Copy private section information.  This copies over the entsize
5197    field, and sometimes the info field.  */
5198
5199 bfd_boolean
5200 _bfd_elf_copy_private_section_data (bfd *ibfd,
5201                                     asection *isec,
5202                                     bfd *obfd,
5203                                     asection *osec)
5204 {
5205   Elf_Internal_Shdr *ihdr, *ohdr;
5206
5207   if (ibfd->xvec->flavour != bfd_target_elf_flavour
5208       || obfd->xvec->flavour != bfd_target_elf_flavour)
5209     return TRUE;
5210
5211   if (elf_tdata (obfd)->segment_map == NULL && elf_tdata (ibfd)->phdr != NULL)
5212     {
5213         asection *s;
5214
5215         /* Only set up the segments if there are no more SEC_ALLOC
5216            sections.  FIXME: This won't do the right thing if objcopy is
5217            used to remove the last SEC_ALLOC section, since objcopy
5218            won't call this routine in that case.  */
5219         for (s = isec->next; s != NULL; s = s->next)
5220           if ((s->flags & SEC_ALLOC) != 0)
5221             break;
5222         if (s == NULL)
5223           {
5224             if (! copy_private_bfd_data (ibfd, obfd))
5225               return FALSE;
5226           }
5227     }
5228
5229   ihdr = &elf_section_data (isec)->this_hdr;
5230   ohdr = &elf_section_data (osec)->this_hdr;
5231
5232   ohdr->sh_entsize = ihdr->sh_entsize;
5233
5234   if (ihdr->sh_type == SHT_SYMTAB
5235       || ihdr->sh_type == SHT_DYNSYM
5236       || ihdr->sh_type == SHT_GNU_verneed
5237       || ihdr->sh_type == SHT_GNU_verdef)
5238     ohdr->sh_info = ihdr->sh_info;
5239
5240   /* Set things up for objcopy.  The output SHT_GROUP section will
5241      have its elf_next_in_group pointing back to the input group
5242      members.  */
5243   elf_next_in_group (osec) = elf_next_in_group (isec);
5244   elf_group_name (osec) = elf_group_name (isec);
5245
5246   osec->use_rela_p = isec->use_rela_p;
5247
5248   return TRUE;
5249 }
5250
5251 /* Copy private symbol information.  If this symbol is in a section
5252    which we did not map into a BFD section, try to map the section
5253    index correctly.  We use special macro definitions for the mapped
5254    section indices; these definitions are interpreted by the
5255    swap_out_syms function.  */
5256
5257 #define MAP_ONESYMTAB (SHN_HIOS + 1)
5258 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
5259 #define MAP_STRTAB    (SHN_HIOS + 3)
5260 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
5261 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
5262
5263 bfd_boolean
5264 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
5265                                    asymbol *isymarg,
5266                                    bfd *obfd,
5267                                    asymbol *osymarg)
5268 {
5269   elf_symbol_type *isym, *osym;
5270
5271   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
5272       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
5273     return TRUE;
5274
5275   isym = elf_symbol_from (ibfd, isymarg);
5276   osym = elf_symbol_from (obfd, osymarg);
5277
5278   if (isym != NULL
5279       && osym != NULL
5280       && bfd_is_abs_section (isym->symbol.section))
5281     {
5282       unsigned int shndx;
5283
5284       shndx = isym->internal_elf_sym.st_shndx;
5285       if (shndx == elf_onesymtab (ibfd))
5286         shndx = MAP_ONESYMTAB;
5287       else if (shndx == elf_dynsymtab (ibfd))
5288         shndx = MAP_DYNSYMTAB;
5289       else if (shndx == elf_tdata (ibfd)->strtab_section)
5290         shndx = MAP_STRTAB;
5291       else if (shndx == elf_tdata (ibfd)->shstrtab_section)
5292         shndx = MAP_SHSTRTAB;
5293       else if (shndx == elf_tdata (ibfd)->symtab_shndx_section)
5294         shndx = MAP_SYM_SHNDX;
5295       osym->internal_elf_sym.st_shndx = shndx;
5296     }
5297
5298   return TRUE;
5299 }
5300
5301 /* Swap out the symbols.  */
5302
5303 static bfd_boolean
5304 swap_out_syms (bfd *abfd,
5305                struct bfd_strtab_hash **sttp,
5306                int relocatable_p)
5307 {
5308   const struct elf_backend_data *bed;
5309   int symcount;
5310   asymbol **syms;
5311   struct bfd_strtab_hash *stt;
5312   Elf_Internal_Shdr *symtab_hdr;
5313   Elf_Internal_Shdr *symtab_shndx_hdr;
5314   Elf_Internal_Shdr *symstrtab_hdr;
5315   char *outbound_syms;
5316   char *outbound_shndx;
5317   int idx;
5318   bfd_size_type amt;
5319   bfd_boolean name_local_sections;
5320
5321   if (!elf_map_symbols (abfd))
5322     return FALSE;
5323
5324   /* Dump out the symtabs.  */
5325   stt = _bfd_elf_stringtab_init ();
5326   if (stt == NULL)
5327     return FALSE;
5328
5329   bed = get_elf_backend_data (abfd);
5330   symcount = bfd_get_symcount (abfd);
5331   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
5332   symtab_hdr->sh_type = SHT_SYMTAB;
5333   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
5334   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
5335   symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
5336   symtab_hdr->sh_addralign = 1 << bed->s->log_file_align;
5337
5338   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
5339   symstrtab_hdr->sh_type = SHT_STRTAB;
5340
5341   amt = (bfd_size_type) (1 + symcount) * bed->s->sizeof_sym;
5342   outbound_syms = bfd_alloc (abfd, amt);
5343   if (outbound_syms == NULL)
5344     {
5345       _bfd_stringtab_free (stt);
5346       return FALSE;
5347     }
5348   symtab_hdr->contents = outbound_syms;
5349
5350   outbound_shndx = NULL;
5351   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
5352   if (symtab_shndx_hdr->sh_name != 0)
5353     {
5354       amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
5355       outbound_shndx = bfd_zalloc (abfd, amt);
5356       if (outbound_shndx == NULL)
5357         {
5358           _bfd_stringtab_free (stt);
5359           return FALSE;
5360         }
5361
5362       symtab_shndx_hdr->contents = outbound_shndx;
5363       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
5364       symtab_shndx_hdr->sh_size = amt;
5365       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
5366       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
5367     }
5368
5369   /* Now generate the data (for "contents").  */
5370   {
5371     /* Fill in zeroth symbol and swap it out.  */
5372     Elf_Internal_Sym sym;
5373     sym.st_name = 0;
5374     sym.st_value = 0;
5375     sym.st_size = 0;
5376     sym.st_info = 0;
5377     sym.st_other = 0;
5378     sym.st_shndx = SHN_UNDEF;
5379     bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
5380     outbound_syms += bed->s->sizeof_sym;
5381     if (outbound_shndx != NULL)
5382       outbound_shndx += sizeof (Elf_External_Sym_Shndx);
5383   }
5384
5385   name_local_sections
5386     = (bed->elf_backend_name_local_section_symbols
5387        && bed->elf_backend_name_local_section_symbols (abfd));
5388
5389   syms = bfd_get_outsymbols (abfd);
5390   for (idx = 0; idx < symcount; idx++)
5391     {
5392       Elf_Internal_Sym sym;
5393       bfd_vma value = syms[idx]->value;
5394       elf_symbol_type *type_ptr;
5395       flagword flags = syms[idx]->flags;
5396       int type;
5397
5398       if (!name_local_sections
5399           && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
5400         {
5401           /* Local section symbols have no name.  */
5402           sym.st_name = 0;
5403         }
5404       else
5405         {
5406           sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
5407                                                             syms[idx]->name,
5408                                                             TRUE, FALSE);
5409           if (sym.st_name == (unsigned long) -1)
5410             {
5411               _bfd_stringtab_free (stt);
5412               return FALSE;
5413             }
5414         }
5415
5416       type_ptr = elf_symbol_from (abfd, syms[idx]);
5417
5418       if ((flags & BSF_SECTION_SYM) == 0
5419           && bfd_is_com_section (syms[idx]->section))
5420         {
5421           /* ELF common symbols put the alignment into the `value' field,
5422              and the size into the `size' field.  This is backwards from
5423              how BFD handles it, so reverse it here.  */
5424           sym.st_size = value;
5425           if (type_ptr == NULL
5426               || type_ptr->internal_elf_sym.st_value == 0)
5427             sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
5428           else
5429             sym.st_value = type_ptr->internal_elf_sym.st_value;
5430           sym.st_shndx = _bfd_elf_section_from_bfd_section
5431             (abfd, syms[idx]->section);
5432         }
5433       else
5434         {
5435           asection *sec = syms[idx]->section;
5436           int shndx;
5437
5438           if (sec->output_section)
5439             {
5440               value += sec->output_offset;
5441               sec = sec->output_section;
5442             }
5443
5444           /* Don't add in the section vma for relocatable output.  */
5445           if (! relocatable_p)
5446             value += sec->vma;
5447           sym.st_value = value;
5448           sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
5449
5450           if (bfd_is_abs_section (sec)
5451               && type_ptr != NULL
5452               && type_ptr->internal_elf_sym.st_shndx != 0)
5453             {
5454               /* This symbol is in a real ELF section which we did
5455                  not create as a BFD section.  Undo the mapping done
5456                  by copy_private_symbol_data.  */
5457               shndx = type_ptr->internal_elf_sym.st_shndx;
5458               switch (shndx)
5459                 {
5460                 case MAP_ONESYMTAB:
5461                   shndx = elf_onesymtab (abfd);
5462                   break;
5463                 case MAP_DYNSYMTAB:
5464                   shndx = elf_dynsymtab (abfd);
5465                   break;
5466                 case MAP_STRTAB:
5467                   shndx = elf_tdata (abfd)->strtab_section;
5468                   break;
5469                 case MAP_SHSTRTAB:
5470                   shndx = elf_tdata (abfd)->shstrtab_section;
5471                   break;
5472                 case MAP_SYM_SHNDX:
5473                   shndx = elf_tdata (abfd)->symtab_shndx_section;
5474                   break;
5475                 default:
5476                   break;
5477                 }
5478             }
5479           else
5480             {
5481               shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
5482
5483               if (shndx == -1)
5484                 {
5485                   asection *sec2;
5486
5487                   /* Writing this would be a hell of a lot easier if
5488                      we had some decent documentation on bfd, and
5489                      knew what to expect of the library, and what to
5490                      demand of applications.  For example, it
5491                      appears that `objcopy' might not set the
5492                      section of a symbol to be a section that is
5493                      actually in the output file.  */
5494                   sec2 = bfd_get_section_by_name (abfd, sec->name);
5495                   if (sec2 == NULL)
5496                     {
5497                       _bfd_error_handler (_("\
5498 Unable to find equivalent output section for symbol '%s' from section '%s'"),
5499                                           syms[idx]->name ? syms[idx]->name : "<Local sym>",
5500                                           sec->name);
5501                       bfd_set_error (bfd_error_invalid_operation);
5502                       _bfd_stringtab_free (stt);
5503                       return FALSE;
5504                     }
5505
5506                   shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
5507                   BFD_ASSERT (shndx != -1);
5508                 }
5509             }
5510
5511           sym.st_shndx = shndx;
5512         }
5513
5514       if ((flags & BSF_THREAD_LOCAL) != 0)
5515         type = STT_TLS;
5516       else if ((flags & BSF_FUNCTION) != 0)
5517         type = STT_FUNC;
5518       else if ((flags & BSF_OBJECT) != 0)
5519         type = STT_OBJECT;
5520       else
5521         type = STT_NOTYPE;
5522
5523       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
5524         type = STT_TLS;
5525
5526       /* Processor-specific types.  */
5527       if (type_ptr != NULL
5528           && bed->elf_backend_get_symbol_type)
5529         type = ((*bed->elf_backend_get_symbol_type)
5530                 (&type_ptr->internal_elf_sym, type));
5531
5532       if (flags & BSF_SECTION_SYM)
5533         {
5534           if (flags & BSF_GLOBAL)
5535             sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
5536           else
5537             sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
5538         }
5539       else if (bfd_is_com_section (syms[idx]->section))
5540         sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
5541       else if (bfd_is_und_section (syms[idx]->section))
5542         sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
5543                                     ? STB_WEAK
5544                                     : STB_GLOBAL),
5545                                    type);
5546       else if (flags & BSF_FILE)
5547         sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
5548       else
5549         {
5550           int bind = STB_LOCAL;
5551
5552           if (flags & BSF_LOCAL)
5553             bind = STB_LOCAL;
5554           else if (flags & BSF_WEAK)
5555             bind = STB_WEAK;
5556           else if (flags & BSF_GLOBAL)
5557             bind = STB_GLOBAL;
5558
5559           sym.st_info = ELF_ST_INFO (bind, type);
5560         }
5561
5562       if (type_ptr != NULL)
5563         sym.st_other = type_ptr->internal_elf_sym.st_other;
5564       else
5565         sym.st_other = 0;
5566
5567       bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
5568       outbound_syms += bed->s->sizeof_sym;
5569       if (outbound_shndx != NULL)
5570         outbound_shndx += sizeof (Elf_External_Sym_Shndx);
5571     }
5572
5573   *sttp = stt;
5574   symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
5575   symstrtab_hdr->sh_type = SHT_STRTAB;
5576
5577   symstrtab_hdr->sh_flags = 0;
5578   symstrtab_hdr->sh_addr = 0;
5579   symstrtab_hdr->sh_entsize = 0;
5580   symstrtab_hdr->sh_link = 0;
5581   symstrtab_hdr->sh_info = 0;
5582   symstrtab_hdr->sh_addralign = 1;
5583
5584   return TRUE;
5585 }
5586
5587 /* Return the number of bytes required to hold the symtab vector.
5588
5589    Note that we base it on the count plus 1, since we will null terminate
5590    the vector allocated based on this size.  However, the ELF symbol table
5591    always has a dummy entry as symbol #0, so it ends up even.  */
5592
5593 long
5594 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
5595 {
5596   long symcount;
5597   long symtab_size;
5598   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
5599
5600   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
5601   symtab_size = (symcount + 1) * (sizeof (asymbol *));
5602   if (symcount > 0)
5603     symtab_size -= sizeof (asymbol *);
5604
5605   return symtab_size;
5606 }
5607
5608 long
5609 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
5610 {
5611   long symcount;
5612   long symtab_size;
5613   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
5614
5615   if (elf_dynsymtab (abfd) == 0)
5616     {
5617       bfd_set_error (bfd_error_invalid_operation);
5618       return -1;
5619     }
5620
5621   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
5622   symtab_size = (symcount + 1) * (sizeof (asymbol *));
5623   if (symcount > 0)
5624     symtab_size -= sizeof (asymbol *);
5625
5626   return symtab_size;
5627 }
5628
5629 long
5630 _bfd_elf_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
5631                                 sec_ptr asect)
5632 {
5633   return (asect->reloc_count + 1) * sizeof (arelent *);
5634 }
5635
5636 /* Canonicalize the relocs.  */
5637
5638 long
5639 _bfd_elf_canonicalize_reloc (bfd *abfd,
5640                              sec_ptr section,
5641                              arelent **relptr,
5642                              asymbol **symbols)
5643 {
5644   arelent *tblptr;
5645   unsigned int i;
5646   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5647
5648   if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
5649     return -1;
5650
5651   tblptr = section->relocation;
5652   for (i = 0; i < section->reloc_count; i++)
5653     *relptr++ = tblptr++;
5654
5655   *relptr = NULL;
5656
5657   return section->reloc_count;
5658 }
5659
5660 long
5661 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
5662 {
5663   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5664   long symcount = bed->s->slurp_symbol_table (abfd, allocation, FALSE);
5665
5666   if (symcount >= 0)
5667     bfd_get_symcount (abfd) = symcount;
5668   return symcount;
5669 }
5670
5671 long
5672 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
5673                                       asymbol **allocation)
5674 {
5675   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5676   long symcount = bed->s->slurp_symbol_table (abfd, allocation, TRUE);
5677
5678   if (symcount >= 0)
5679     bfd_get_dynamic_symcount (abfd) = symcount;
5680   return symcount;
5681 }
5682
5683 /* Return the size required for the dynamic reloc entries.  Any
5684    section that was actually installed in the BFD, and has type
5685    SHT_REL or SHT_RELA, and uses the dynamic symbol table, is
5686    considered to be a dynamic reloc section.  */
5687
5688 long
5689 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
5690 {
5691   long ret;
5692   asection *s;
5693
5694   if (elf_dynsymtab (abfd) == 0)
5695     {
5696       bfd_set_error (bfd_error_invalid_operation);
5697       return -1;
5698     }
5699
5700   ret = sizeof (arelent *);
5701   for (s = abfd->sections; s != NULL; s = s->next)
5702     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
5703         && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
5704             || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
5705       ret += ((s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize)
5706               * sizeof (arelent *));
5707
5708   return ret;
5709 }
5710
5711 /* Canonicalize the dynamic relocation entries.  Note that we return
5712    the dynamic relocations as a single block, although they are
5713    actually associated with particular sections; the interface, which
5714    was designed for SunOS style shared libraries, expects that there
5715    is only one set of dynamic relocs.  Any section that was actually
5716    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses
5717    the dynamic symbol table, is considered to be a dynamic reloc
5718    section.  */
5719
5720 long
5721 _bfd_elf_canonicalize_dynamic_reloc (bfd *abfd,
5722                                      arelent **storage,
5723                                      asymbol **syms)
5724 {
5725   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
5726   asection *s;
5727   long ret;
5728
5729   if (elf_dynsymtab (abfd) == 0)
5730     {
5731       bfd_set_error (bfd_error_invalid_operation);
5732       return -1;
5733     }
5734
5735   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
5736   ret = 0;
5737   for (s = abfd->sections; s != NULL; s = s->next)
5738     {
5739       if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
5740           && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
5741               || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
5742         {
5743           arelent *p;
5744           long count, i;
5745
5746           if (! (*slurp_relocs) (abfd, s, syms, TRUE))
5747             return -1;
5748           count = s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize;
5749           p = s->relocation;
5750           for (i = 0; i < count; i++)
5751             *storage++ = p++;
5752           ret += count;
5753         }
5754     }
5755
5756   *storage = NULL;
5757
5758   return ret;
5759 }
5760 \f
5761 /* Read in the version information.  */
5762
5763 bfd_boolean
5764 _bfd_elf_slurp_version_tables (bfd *abfd)
5765 {
5766   bfd_byte *contents = NULL;
5767   bfd_size_type amt;
5768
5769   if (elf_dynverdef (abfd) != 0)
5770     {
5771       Elf_Internal_Shdr *hdr;
5772       Elf_External_Verdef *everdef;
5773       Elf_Internal_Verdef *iverdef;
5774       Elf_Internal_Verdef *iverdefarr;
5775       Elf_Internal_Verdef iverdefmem;
5776       unsigned int i;
5777       unsigned int maxidx;
5778
5779       hdr = &elf_tdata (abfd)->dynverdef_hdr;
5780
5781       contents = bfd_malloc (hdr->sh_size);
5782       if (contents == NULL)
5783         goto error_return;
5784       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
5785           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
5786         goto error_return;
5787
5788       /* We know the number of entries in the section but not the maximum
5789          index.  Therefore we have to run through all entries and find
5790          the maximum.  */
5791       everdef = (Elf_External_Verdef *) contents;
5792       maxidx = 0;
5793       for (i = 0; i < hdr->sh_info; ++i)
5794         {
5795           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
5796
5797           if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
5798             maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
5799
5800           everdef = ((Elf_External_Verdef *)
5801                      ((bfd_byte *) everdef + iverdefmem.vd_next));
5802         }
5803
5804       amt = (bfd_size_type) maxidx * sizeof (Elf_Internal_Verdef);
5805       elf_tdata (abfd)->verdef = bfd_zalloc (abfd, amt);
5806       if (elf_tdata (abfd)->verdef == NULL)
5807         goto error_return;
5808
5809       elf_tdata (abfd)->cverdefs = maxidx;
5810
5811       everdef = (Elf_External_Verdef *) contents;
5812       iverdefarr = elf_tdata (abfd)->verdef;
5813       for (i = 0; i < hdr->sh_info; i++)
5814         {
5815           Elf_External_Verdaux *everdaux;
5816           Elf_Internal_Verdaux *iverdaux;
5817           unsigned int j;
5818
5819           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
5820
5821           iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
5822           memcpy (iverdef, &iverdefmem, sizeof (Elf_Internal_Verdef));
5823
5824           iverdef->vd_bfd = abfd;
5825
5826           amt = (bfd_size_type) iverdef->vd_cnt * sizeof (Elf_Internal_Verdaux);
5827           iverdef->vd_auxptr = bfd_alloc (abfd, amt);
5828           if (iverdef->vd_auxptr == NULL)
5829             goto error_return;
5830
5831           everdaux = ((Elf_External_Verdaux *)
5832                       ((bfd_byte *) everdef + iverdef->vd_aux));
5833           iverdaux = iverdef->vd_auxptr;
5834           for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
5835             {
5836               _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
5837
5838               iverdaux->vda_nodename =
5839                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5840                                                  iverdaux->vda_name);
5841               if (iverdaux->vda_nodename == NULL)
5842                 goto error_return;
5843
5844               if (j + 1 < iverdef->vd_cnt)
5845                 iverdaux->vda_nextptr = iverdaux + 1;
5846               else
5847                 iverdaux->vda_nextptr = NULL;
5848
5849               everdaux = ((Elf_External_Verdaux *)
5850                           ((bfd_byte *) everdaux + iverdaux->vda_next));
5851             }
5852
5853           iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
5854
5855           if (i + 1 < hdr->sh_info)
5856             iverdef->vd_nextdef = iverdef + 1;
5857           else
5858             iverdef->vd_nextdef = NULL;
5859
5860           everdef = ((Elf_External_Verdef *)
5861                      ((bfd_byte *) everdef + iverdef->vd_next));
5862         }
5863
5864       free (contents);
5865       contents = NULL;
5866     }
5867
5868   if (elf_dynverref (abfd) != 0)
5869     {
5870       Elf_Internal_Shdr *hdr;
5871       Elf_External_Verneed *everneed;
5872       Elf_Internal_Verneed *iverneed;
5873       unsigned int i;
5874
5875       hdr = &elf_tdata (abfd)->dynverref_hdr;
5876
5877       amt = (bfd_size_type) hdr->sh_info * sizeof (Elf_Internal_Verneed);
5878       elf_tdata (abfd)->verref = bfd_zalloc (abfd, amt);
5879       if (elf_tdata (abfd)->verref == NULL)
5880         goto error_return;
5881
5882       elf_tdata (abfd)->cverrefs = hdr->sh_info;
5883
5884       contents = bfd_malloc (hdr->sh_size);
5885       if (contents == NULL)
5886         goto error_return;
5887       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
5888           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
5889         goto error_return;
5890
5891       everneed = (Elf_External_Verneed *) contents;
5892       iverneed = elf_tdata (abfd)->verref;
5893       for (i = 0; i < hdr->sh_info; i++, iverneed++)
5894         {
5895           Elf_External_Vernaux *evernaux;
5896           Elf_Internal_Vernaux *ivernaux;
5897           unsigned int j;
5898
5899           _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
5900
5901           iverneed->vn_bfd = abfd;
5902
5903           iverneed->vn_filename =
5904             bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5905                                              iverneed->vn_file);
5906           if (iverneed->vn_filename == NULL)
5907             goto error_return;
5908
5909           amt = iverneed->vn_cnt;
5910           amt *= sizeof (Elf_Internal_Vernaux);
5911           iverneed->vn_auxptr = bfd_alloc (abfd, amt);
5912
5913           evernaux = ((Elf_External_Vernaux *)
5914                       ((bfd_byte *) everneed + iverneed->vn_aux));
5915           ivernaux = iverneed->vn_auxptr;
5916           for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
5917             {
5918               _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
5919
5920               ivernaux->vna_nodename =
5921                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
5922                                                  ivernaux->vna_name);
5923               if (ivernaux->vna_nodename == NULL)
5924                 goto error_return;
5925
5926               if (j + 1 < iverneed->vn_cnt)
5927                 ivernaux->vna_nextptr = ivernaux + 1;
5928               else
5929                 ivernaux->vna_nextptr = NULL;
5930
5931               evernaux = ((Elf_External_Vernaux *)
5932                           ((bfd_byte *) evernaux + ivernaux->vna_next));
5933             }
5934
5935           if (i + 1 < hdr->sh_info)
5936             iverneed->vn_nextref = iverneed + 1;
5937           else
5938             iverneed->vn_nextref = NULL;
5939
5940           everneed = ((Elf_External_Verneed *)
5941                       ((bfd_byte *) everneed + iverneed->vn_next));
5942         }
5943
5944       free (contents);
5945       contents = NULL;
5946     }
5947
5948   return TRUE;
5949
5950  error_return:
5951   if (contents != NULL)
5952     free (contents);
5953   return FALSE;
5954 }
5955 \f
5956 asymbol *
5957 _bfd_elf_make_empty_symbol (bfd *abfd)
5958 {
5959   elf_symbol_type *newsym;
5960   bfd_size_type amt = sizeof (elf_symbol_type);
5961
5962   newsym = bfd_zalloc (abfd, amt);
5963   if (!newsym)
5964     return NULL;
5965   else
5966     {
5967       newsym->symbol.the_bfd = abfd;
5968       return &newsym->symbol;
5969     }
5970 }
5971
5972 void
5973 _bfd_elf_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
5974                           asymbol *symbol,
5975                           symbol_info *ret)
5976 {
5977   bfd_symbol_info (symbol, ret);
5978 }
5979
5980 /* Return whether a symbol name implies a local symbol.  Most targets
5981    use this function for the is_local_label_name entry point, but some
5982    override it.  */
5983
5984 bfd_boolean
5985 _bfd_elf_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
5986                               const char *name)
5987 {
5988   /* Normal local symbols start with ``.L''.  */
5989   if (name[0] == '.' && name[1] == 'L')
5990     return TRUE;
5991
5992   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
5993      DWARF debugging symbols starting with ``..''.  */
5994   if (name[0] == '.' && name[1] == '.')
5995     return TRUE;
5996
5997   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
5998      emitting DWARF debugging output.  I suspect this is actually a
5999      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
6000      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
6001      underscore to be emitted on some ELF targets).  For ease of use,
6002      we treat such symbols as local.  */
6003   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
6004     return TRUE;
6005
6006   return FALSE;
6007 }
6008
6009 alent *
6010 _bfd_elf_get_lineno (bfd *abfd ATTRIBUTE_UNUSED,
6011                      asymbol *symbol ATTRIBUTE_UNUSED)
6012 {
6013   abort ();
6014   return NULL;
6015 }
6016
6017 bfd_boolean
6018 _bfd_elf_set_arch_mach (bfd *abfd,
6019                         enum bfd_architecture arch,
6020                         unsigned long machine)
6021 {
6022   /* If this isn't the right architecture for this backend, and this
6023      isn't the generic backend, fail.  */
6024   if (arch != get_elf_backend_data (abfd)->arch
6025       && arch != bfd_arch_unknown
6026       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
6027     return FALSE;
6028
6029   return bfd_default_set_arch_mach (abfd, arch, machine);
6030 }
6031
6032 /* Find the function to a particular section and offset,
6033    for error reporting.  */
6034
6035 static bfd_boolean
6036 elf_find_function (bfd *abfd ATTRIBUTE_UNUSED,
6037                    asection *section,
6038                    asymbol **symbols,
6039                    bfd_vma offset,
6040                    const char **filename_ptr,
6041                    const char **functionname_ptr)
6042 {
6043   const char *filename;
6044   asymbol *func;
6045   bfd_vma low_func;
6046   asymbol **p;
6047
6048   filename = NULL;
6049   func = NULL;
6050   low_func = 0;
6051
6052   for (p = symbols; *p != NULL; p++)
6053     {
6054       elf_symbol_type *q;
6055
6056       q = (elf_symbol_type *) *p;
6057
6058       if (bfd_get_section (&q->symbol) != section)
6059         continue;
6060
6061       switch (ELF_ST_TYPE (q->internal_elf_sym.st_info))
6062         {
6063         default:
6064           break;
6065         case STT_FILE:
6066           filename = bfd_asymbol_name (&q->symbol);
6067           break;
6068         case STT_NOTYPE:
6069         case STT_FUNC:
6070           if (q->symbol.section == section
6071               && q->symbol.value >= low_func
6072               && q->symbol.value <= offset)
6073             {
6074               func = (asymbol *) q;
6075               low_func = q->symbol.value;
6076             }
6077           break;
6078         }
6079     }
6080
6081   if (func == NULL)
6082     return FALSE;
6083
6084   if (filename_ptr)
6085     *filename_ptr = filename;
6086   if (functionname_ptr)
6087     *functionname_ptr = bfd_asymbol_name (func);
6088
6089   return TRUE;
6090 }
6091
6092 /* Find the nearest line to a particular section and offset,
6093    for error reporting.  */
6094
6095 bfd_boolean
6096 _bfd_elf_find_nearest_line (bfd *abfd,
6097                             asection *section,
6098                             asymbol **symbols,
6099                             bfd_vma offset,
6100                             const char **filename_ptr,
6101                             const char **functionname_ptr,
6102                             unsigned int *line_ptr)
6103 {
6104   bfd_boolean found;
6105
6106   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
6107                                      filename_ptr, functionname_ptr,
6108                                      line_ptr))
6109     {
6110       if (!*functionname_ptr)
6111         elf_find_function (abfd, section, symbols, offset,
6112                            *filename_ptr ? NULL : filename_ptr,
6113                            functionname_ptr);
6114
6115       return TRUE;
6116     }
6117
6118   if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
6119                                      filename_ptr, functionname_ptr,
6120                                      line_ptr, 0,
6121                                      &elf_tdata (abfd)->dwarf2_find_line_info))
6122     {
6123       if (!*functionname_ptr)
6124         elf_find_function (abfd, section, symbols, offset,
6125                            *filename_ptr ? NULL : filename_ptr,
6126                            functionname_ptr);
6127
6128       return TRUE;
6129     }
6130
6131   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
6132                                              &found, filename_ptr,
6133                                              functionname_ptr, line_ptr,
6134                                              &elf_tdata (abfd)->line_info))
6135     return FALSE;
6136   if (found && (*functionname_ptr || *line_ptr))
6137     return TRUE;
6138
6139   if (symbols == NULL)
6140     return FALSE;
6141
6142   if (! elf_find_function (abfd, section, symbols, offset,
6143                            filename_ptr, functionname_ptr))
6144     return FALSE;
6145
6146   *line_ptr = 0;
6147   return TRUE;
6148 }
6149
6150 int
6151 _bfd_elf_sizeof_headers (bfd *abfd, bfd_boolean reloc)
6152 {
6153   int ret;
6154
6155   ret = get_elf_backend_data (abfd)->s->sizeof_ehdr;
6156   if (! reloc)
6157     ret += get_program_header_size (abfd);
6158   return ret;
6159 }
6160
6161 bfd_boolean
6162 _bfd_elf_set_section_contents (bfd *abfd,
6163                                sec_ptr section,
6164                                const void *location,
6165                                file_ptr offset,
6166                                bfd_size_type count)
6167 {
6168   Elf_Internal_Shdr *hdr;
6169   bfd_signed_vma pos;
6170
6171   if (! abfd->output_has_begun
6172       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
6173     return FALSE;
6174
6175   hdr = &elf_section_data (section)->this_hdr;
6176   pos = hdr->sh_offset + offset;
6177   if (bfd_seek (abfd, pos, SEEK_SET) != 0
6178       || bfd_bwrite (location, count, abfd) != count)
6179     return FALSE;
6180
6181   return TRUE;
6182 }
6183
6184 void
6185 _bfd_elf_no_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
6186                            arelent *cache_ptr ATTRIBUTE_UNUSED,
6187                            Elf_Internal_Rela *dst ATTRIBUTE_UNUSED)
6188 {
6189   abort ();
6190 }
6191
6192 /* Try to convert a non-ELF reloc into an ELF one.  */
6193
6194 bfd_boolean
6195 _bfd_elf_validate_reloc (bfd *abfd, arelent *areloc)
6196 {
6197   /* Check whether we really have an ELF howto.  */
6198
6199   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
6200     {
6201       bfd_reloc_code_real_type code;
6202       reloc_howto_type *howto;
6203
6204       /* Alien reloc: Try to determine its type to replace it with an
6205          equivalent ELF reloc.  */
6206
6207       if (areloc->howto->pc_relative)
6208         {
6209           switch (areloc->howto->bitsize)
6210             {
6211             case 8:
6212               code = BFD_RELOC_8_PCREL;
6213               break;
6214             case 12:
6215               code = BFD_RELOC_12_PCREL;
6216               break;
6217             case 16:
6218               code = BFD_RELOC_16_PCREL;
6219               break;
6220             case 24:
6221               code = BFD_RELOC_24_PCREL;
6222               break;
6223             case 32:
6224               code = BFD_RELOC_32_PCREL;
6225               break;
6226             case 64:
6227               code = BFD_RELOC_64_PCREL;
6228               break;
6229             default:
6230               goto fail;
6231             }
6232
6233           howto = bfd_reloc_type_lookup (abfd, code);
6234
6235           if (areloc->howto->pcrel_offset != howto->pcrel_offset)
6236             {
6237               if (howto->pcrel_offset)
6238                 areloc->addend += areloc->address;
6239               else
6240                 areloc->addend -= areloc->address; /* addend is unsigned!! */
6241             }
6242         }
6243       else
6244         {
6245           switch (areloc->howto->bitsize)
6246             {
6247             case 8:
6248               code = BFD_RELOC_8;
6249               break;
6250             case 14:
6251               code = BFD_RELOC_14;
6252               break;
6253             case 16:
6254               code = BFD_RELOC_16;
6255               break;
6256             case 26:
6257               code = BFD_RELOC_26;
6258               break;
6259             case 32:
6260               code = BFD_RELOC_32;
6261               break;
6262             case 64:
6263               code = BFD_RELOC_64;
6264               break;
6265             default:
6266               goto fail;
6267             }
6268
6269           howto = bfd_reloc_type_lookup (abfd, code);
6270         }
6271
6272       if (howto)
6273         areloc->howto = howto;
6274       else
6275         goto fail;
6276     }
6277
6278   return TRUE;
6279
6280  fail:
6281   (*_bfd_error_handler)
6282     (_("%s: unsupported relocation type %s"),
6283      bfd_archive_filename (abfd), areloc->howto->name);
6284   bfd_set_error (bfd_error_bad_value);
6285   return FALSE;
6286 }
6287
6288 bfd_boolean
6289 _bfd_elf_close_and_cleanup (bfd *abfd)
6290 {
6291   if (bfd_get_format (abfd) == bfd_object)
6292     {
6293       if (elf_shstrtab (abfd) != NULL)
6294         _bfd_elf_strtab_free (elf_shstrtab (abfd));
6295     }
6296
6297   return _bfd_generic_close_and_cleanup (abfd);
6298 }
6299
6300 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
6301    in the relocation's offset.  Thus we cannot allow any sort of sanity
6302    range-checking to interfere.  There is nothing else to do in processing
6303    this reloc.  */
6304
6305 bfd_reloc_status_type
6306 _bfd_elf_rel_vtable_reloc_fn
6307   (bfd *abfd ATTRIBUTE_UNUSED, arelent *re ATTRIBUTE_UNUSED,
6308    struct bfd_symbol *symbol ATTRIBUTE_UNUSED,
6309    void *data ATTRIBUTE_UNUSED, asection *is ATTRIBUTE_UNUSED,
6310    bfd *obfd ATTRIBUTE_UNUSED, char **errmsg ATTRIBUTE_UNUSED)
6311 {
6312   return bfd_reloc_ok;
6313 }
6314 \f
6315 /* Elf core file support.  Much of this only works on native
6316    toolchains, since we rely on knowing the
6317    machine-dependent procfs structure in order to pick
6318    out details about the corefile.  */
6319
6320 #ifdef HAVE_SYS_PROCFS_H
6321 # include <sys/procfs.h>
6322 #endif
6323
6324 /* FIXME: this is kinda wrong, but it's what gdb wants.  */
6325
6326 static int
6327 elfcore_make_pid (bfd *abfd)
6328 {
6329   return ((elf_tdata (abfd)->core_lwpid << 16)
6330           + (elf_tdata (abfd)->core_pid));
6331 }
6332
6333 /* If there isn't a section called NAME, make one, using
6334    data from SECT.  Note, this function will generate a
6335    reference to NAME, so you shouldn't deallocate or
6336    overwrite it.  */
6337
6338 static bfd_boolean
6339 elfcore_maybe_make_sect (bfd *abfd, char *name, asection *sect)
6340 {
6341   asection *sect2;
6342
6343   if (bfd_get_section_by_name (abfd, name) != NULL)
6344     return TRUE;
6345
6346   sect2 = bfd_make_section (abfd, name);
6347   if (sect2 == NULL)
6348     return FALSE;
6349
6350   sect2->_raw_size = sect->_raw_size;
6351   sect2->filepos = sect->filepos;
6352   sect2->flags = sect->flags;
6353   sect2->alignment_power = sect->alignment_power;
6354   return TRUE;
6355 }
6356
6357 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
6358    actually creates up to two pseudosections:
6359    - For the single-threaded case, a section named NAME, unless
6360      such a section already exists.
6361    - For the multi-threaded case, a section named "NAME/PID", where
6362      PID is elfcore_make_pid (abfd).
6363    Both pseudosections have identical contents. */
6364 bfd_boolean
6365 _bfd_elfcore_make_pseudosection (bfd *abfd,
6366                                  char *name,
6367                                  size_t size,
6368                                  ufile_ptr filepos)
6369 {
6370   char buf[100];
6371   char *threaded_name;
6372   size_t len;
6373   asection *sect;
6374
6375   /* Build the section name.  */
6376
6377   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
6378   len = strlen (buf) + 1;
6379   threaded_name = bfd_alloc (abfd, len);
6380   if (threaded_name == NULL)
6381     return FALSE;
6382   memcpy (threaded_name, buf, len);
6383
6384   sect = bfd_make_section_anyway (abfd, threaded_name);
6385   if (sect == NULL)
6386     return FALSE;
6387   sect->_raw_size = size;
6388   sect->filepos = filepos;
6389   sect->flags = SEC_HAS_CONTENTS;
6390   sect->alignment_power = 2;
6391
6392   return elfcore_maybe_make_sect (abfd, name, sect);
6393 }
6394
6395 /* prstatus_t exists on:
6396      solaris 2.5+
6397      linux 2.[01] + glibc
6398      unixware 4.2
6399 */
6400
6401 #if defined (HAVE_PRSTATUS_T)
6402
6403 static bfd_boolean
6404 elfcore_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
6405 {
6406   size_t raw_size;
6407   int offset;
6408
6409   if (note->descsz == sizeof (prstatus_t))
6410     {
6411       prstatus_t prstat;
6412
6413       raw_size = sizeof (prstat.pr_reg);
6414       offset   = offsetof (prstatus_t, pr_reg);
6415       memcpy (&prstat, note->descdata, sizeof (prstat));
6416
6417       /* Do not overwrite the core signal if it
6418          has already been set by another thread.  */
6419       if (elf_tdata (abfd)->core_signal == 0)
6420         elf_tdata (abfd)->core_signal = prstat.pr_cursig;
6421       elf_tdata (abfd)->core_pid = prstat.pr_pid;
6422
6423       /* pr_who exists on:
6424          solaris 2.5+
6425          unixware 4.2
6426          pr_who doesn't exist on:
6427          linux 2.[01]
6428          */
6429 #if defined (HAVE_PRSTATUS_T_PR_WHO)
6430       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
6431 #endif
6432     }
6433 #if defined (HAVE_PRSTATUS32_T)
6434   else if (note->descsz == sizeof (prstatus32_t))
6435     {
6436       /* 64-bit host, 32-bit corefile */
6437       prstatus32_t prstat;
6438
6439       raw_size = sizeof (prstat.pr_reg);
6440       offset   = offsetof (prstatus32_t, pr_reg);
6441       memcpy (&prstat, note->descdata, sizeof (prstat));
6442
6443       /* Do not overwrite the core signal if it
6444          has already been set by another thread.  */
6445       if (elf_tdata (abfd)->core_signal == 0)
6446         elf_tdata (abfd)->core_signal = prstat.pr_cursig;
6447       elf_tdata (abfd)->core_pid = prstat.pr_pid;
6448
6449       /* pr_who exists on:
6450          solaris 2.5+
6451          unixware 4.2
6452          pr_who doesn't exist on:
6453          linux 2.[01]
6454          */
6455 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
6456       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
6457 #endif
6458     }
6459 #endif /* HAVE_PRSTATUS32_T */
6460   else
6461     {
6462       /* Fail - we don't know how to handle any other
6463          note size (ie. data object type).  */
6464       return TRUE;
6465     }
6466
6467   /* Make a ".reg/999" section and a ".reg" section.  */
6468   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
6469                                           raw_size, note->descpos + offset);
6470 }
6471 #endif /* defined (HAVE_PRSTATUS_T) */
6472
6473 /* Create a pseudosection containing the exact contents of NOTE.  */
6474 static bfd_boolean
6475 elfcore_make_note_pseudosection (bfd *abfd,
6476                                  char *name,
6477                                  Elf_Internal_Note *note)
6478 {
6479   return _bfd_elfcore_make_pseudosection (abfd, name,
6480                                           note->descsz, note->descpos);
6481 }
6482
6483 /* There isn't a consistent prfpregset_t across platforms,
6484    but it doesn't matter, because we don't have to pick this
6485    data structure apart.  */
6486
6487 static bfd_boolean
6488 elfcore_grok_prfpreg (bfd *abfd, Elf_Internal_Note *note)
6489 {
6490   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6491 }
6492
6493 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
6494    type of 5 (NT_PRXFPREG).  Just include the whole note's contents
6495    literally.  */
6496
6497 static bfd_boolean
6498 elfcore_grok_prxfpreg (bfd *abfd, Elf_Internal_Note *note)
6499 {
6500   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
6501 }
6502
6503 #if defined (HAVE_PRPSINFO_T)
6504 typedef prpsinfo_t   elfcore_psinfo_t;
6505 #if defined (HAVE_PRPSINFO32_T)         /* Sparc64 cross Sparc32 */
6506 typedef prpsinfo32_t elfcore_psinfo32_t;
6507 #endif
6508 #endif
6509
6510 #if defined (HAVE_PSINFO_T)
6511 typedef psinfo_t   elfcore_psinfo_t;
6512 #if defined (HAVE_PSINFO32_T)           /* Sparc64 cross Sparc32 */
6513 typedef psinfo32_t elfcore_psinfo32_t;
6514 #endif
6515 #endif
6516
6517 /* return a malloc'ed copy of a string at START which is at
6518    most MAX bytes long, possibly without a terminating '\0'.
6519    the copy will always have a terminating '\0'.  */
6520
6521 char *
6522 _bfd_elfcore_strndup (bfd *abfd, char *start, size_t max)
6523 {
6524   char *dups;
6525   char *end = memchr (start, '\0', max);
6526   size_t len;
6527
6528   if (end == NULL)
6529     len = max;
6530   else
6531     len = end - start;
6532
6533   dups = bfd_alloc (abfd, len + 1);
6534   if (dups == NULL)
6535     return NULL;
6536
6537   memcpy (dups, start, len);
6538   dups[len] = '\0';
6539
6540   return dups;
6541 }
6542
6543 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6544 static bfd_boolean
6545 elfcore_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
6546 {
6547   if (note->descsz == sizeof (elfcore_psinfo_t))
6548     {
6549       elfcore_psinfo_t psinfo;
6550
6551       memcpy (&psinfo, note->descdata, sizeof (psinfo));
6552
6553       elf_tdata (abfd)->core_program
6554         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
6555                                 sizeof (psinfo.pr_fname));
6556
6557       elf_tdata (abfd)->core_command
6558         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
6559                                 sizeof (psinfo.pr_psargs));
6560     }
6561 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
6562   else if (note->descsz == sizeof (elfcore_psinfo32_t))
6563     {
6564       /* 64-bit host, 32-bit corefile */
6565       elfcore_psinfo32_t psinfo;
6566
6567       memcpy (&psinfo, note->descdata, sizeof (psinfo));
6568
6569       elf_tdata (abfd)->core_program
6570         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
6571                                 sizeof (psinfo.pr_fname));
6572
6573       elf_tdata (abfd)->core_command
6574         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
6575                                 sizeof (psinfo.pr_psargs));
6576     }
6577 #endif
6578
6579   else
6580     {
6581       /* Fail - we don't know how to handle any other
6582          note size (ie. data object type).  */
6583       return TRUE;
6584     }
6585
6586   /* Note that for some reason, a spurious space is tacked
6587      onto the end of the args in some (at least one anyway)
6588      implementations, so strip it off if it exists.  */
6589
6590   {
6591     char *command = elf_tdata (abfd)->core_command;
6592     int n = strlen (command);
6593
6594     if (0 < n && command[n - 1] == ' ')
6595       command[n - 1] = '\0';
6596   }
6597
6598   return TRUE;
6599 }
6600 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
6601
6602 #if defined (HAVE_PSTATUS_T)
6603 static bfd_boolean
6604 elfcore_grok_pstatus (bfd *abfd, Elf_Internal_Note *note)
6605 {
6606   if (note->descsz == sizeof (pstatus_t)
6607 #if defined (HAVE_PXSTATUS_T)
6608       || note->descsz == sizeof (pxstatus_t)
6609 #endif
6610       )
6611     {
6612       pstatus_t pstat;
6613
6614       memcpy (&pstat, note->descdata, sizeof (pstat));
6615
6616       elf_tdata (abfd)->core_pid = pstat.pr_pid;
6617     }
6618 #if defined (HAVE_PSTATUS32_T)
6619   else if (note->descsz == sizeof (pstatus32_t))
6620     {
6621       /* 64-bit host, 32-bit corefile */
6622       pstatus32_t pstat;
6623
6624       memcpy (&pstat, note->descdata, sizeof (pstat));
6625
6626       elf_tdata (abfd)->core_pid = pstat.pr_pid;
6627     }
6628 #endif
6629   /* Could grab some more details from the "representative"
6630      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
6631      NT_LWPSTATUS note, presumably.  */
6632
6633   return TRUE;
6634 }
6635 #endif /* defined (HAVE_PSTATUS_T) */
6636
6637 #if defined (HAVE_LWPSTATUS_T)
6638 static bfd_boolean
6639 elfcore_grok_lwpstatus (bfd *abfd, Elf_Internal_Note *note)
6640 {
6641   lwpstatus_t lwpstat;
6642   char buf[100];
6643   char *name;
6644   size_t len;
6645   asection *sect;
6646
6647   if (note->descsz != sizeof (lwpstat)
6648 #if defined (HAVE_LWPXSTATUS_T)
6649       && note->descsz != sizeof (lwpxstatus_t)
6650 #endif
6651       )
6652     return TRUE;
6653
6654   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
6655
6656   elf_tdata (abfd)->core_lwpid = lwpstat.pr_lwpid;
6657   elf_tdata (abfd)->core_signal = lwpstat.pr_cursig;
6658
6659   /* Make a ".reg/999" section.  */
6660
6661   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
6662   len = strlen (buf) + 1;
6663   name = bfd_alloc (abfd, len);
6664   if (name == NULL)
6665     return FALSE;
6666   memcpy (name, buf, len);
6667
6668   sect = bfd_make_section_anyway (abfd, name);
6669   if (sect == NULL)
6670     return FALSE;
6671
6672 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
6673   sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
6674   sect->filepos = note->descpos
6675     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
6676 #endif
6677
6678 #if defined (HAVE_LWPSTATUS_T_PR_REG)
6679   sect->_raw_size = sizeof (lwpstat.pr_reg);
6680   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
6681 #endif
6682
6683   sect->flags = SEC_HAS_CONTENTS;
6684   sect->alignment_power = 2;
6685
6686   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
6687     return FALSE;
6688
6689   /* Make a ".reg2/999" section */
6690
6691   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
6692   len = strlen (buf) + 1;
6693   name = bfd_alloc (abfd, len);
6694   if (name == NULL)
6695     return FALSE;
6696   memcpy (name, buf, len);
6697
6698   sect = bfd_make_section_anyway (abfd, name);
6699   if (sect == NULL)
6700     return FALSE;
6701
6702 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
6703   sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
6704   sect->filepos = note->descpos
6705     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
6706 #endif
6707
6708 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
6709   sect->_raw_size = sizeof (lwpstat.pr_fpreg);
6710   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
6711 #endif
6712
6713   sect->flags = SEC_HAS_CONTENTS;
6714   sect->alignment_power = 2;
6715
6716   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
6717 }
6718 #endif /* defined (HAVE_LWPSTATUS_T) */
6719
6720 #if defined (HAVE_WIN32_PSTATUS_T)
6721 static bfd_boolean
6722 elfcore_grok_win32pstatus (bfd *abfd, Elf_Internal_Note *note)
6723 {
6724   char buf[30];
6725   char *name;
6726   size_t len;
6727   asection *sect;
6728   win32_pstatus_t pstatus;
6729
6730   if (note->descsz < sizeof (pstatus))
6731     return TRUE;
6732
6733   memcpy (&pstatus, note->descdata, sizeof (pstatus));
6734
6735   switch (pstatus.data_type)
6736     {
6737     case NOTE_INFO_PROCESS:
6738       /* FIXME: need to add ->core_command.  */
6739       elf_tdata (abfd)->core_signal = pstatus.data.process_info.signal;
6740       elf_tdata (abfd)->core_pid = pstatus.data.process_info.pid;
6741       break;
6742
6743     case NOTE_INFO_THREAD:
6744       /* Make a ".reg/999" section.  */
6745       sprintf (buf, ".reg/%d", pstatus.data.thread_info.tid);
6746
6747       len = strlen (buf) + 1;
6748       name = bfd_alloc (abfd, len);
6749       if (name == NULL)
6750         return FALSE;
6751
6752       memcpy (name, buf, len);
6753
6754       sect = bfd_make_section_anyway (abfd, name);
6755       if (sect == NULL)
6756         return FALSE;
6757
6758       sect->_raw_size = sizeof (pstatus.data.thread_info.thread_context);
6759       sect->filepos = (note->descpos
6760                        + offsetof (struct win32_pstatus,
6761                                    data.thread_info.thread_context));
6762       sect->flags = SEC_HAS_CONTENTS;
6763       sect->alignment_power = 2;
6764
6765       if (pstatus.data.thread_info.is_active_thread)
6766         if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
6767           return FALSE;
6768       break;
6769
6770     case NOTE_INFO_MODULE:
6771       /* Make a ".module/xxxxxxxx" section.  */
6772       sprintf (buf, ".module/%08x", pstatus.data.module_info.base_address);
6773
6774       len = strlen (buf) + 1;
6775       name = bfd_alloc (abfd, len);
6776       if (name == NULL)
6777         return FALSE;
6778
6779       memcpy (name, buf, len);
6780
6781       sect = bfd_make_section_anyway (abfd, name);
6782
6783       if (sect == NULL)
6784         return FALSE;
6785
6786       sect->_raw_size = note->descsz;
6787       sect->filepos = note->descpos;
6788       sect->flags = SEC_HAS_CONTENTS;
6789       sect->alignment_power = 2;
6790       break;
6791
6792     default:
6793       return TRUE;
6794     }
6795
6796   return TRUE;
6797 }
6798 #endif /* HAVE_WIN32_PSTATUS_T */
6799
6800 static bfd_boolean
6801 elfcore_grok_note (bfd *abfd, Elf_Internal_Note *note)
6802 {
6803   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6804
6805   switch (note->type)
6806     {
6807     default:
6808       return TRUE;
6809
6810     case NT_PRSTATUS:
6811       if (bed->elf_backend_grok_prstatus)
6812         if ((*bed->elf_backend_grok_prstatus) (abfd, note))
6813           return TRUE;
6814 #if defined (HAVE_PRSTATUS_T)
6815       return elfcore_grok_prstatus (abfd, note);
6816 #else
6817       return TRUE;
6818 #endif
6819
6820 #if defined (HAVE_PSTATUS_T)
6821     case NT_PSTATUS:
6822       return elfcore_grok_pstatus (abfd, note);
6823 #endif
6824
6825 #if defined (HAVE_LWPSTATUS_T)
6826     case NT_LWPSTATUS:
6827       return elfcore_grok_lwpstatus (abfd, note);
6828 #endif
6829
6830     case NT_FPREGSET:           /* FIXME: rename to NT_PRFPREG */
6831       return elfcore_grok_prfpreg (abfd, note);
6832
6833 #if defined (HAVE_WIN32_PSTATUS_T)
6834     case NT_WIN32PSTATUS:
6835       return elfcore_grok_win32pstatus (abfd, note);
6836 #endif
6837
6838     case NT_PRXFPREG:           /* Linux SSE extension */
6839       if (note->namesz == 6
6840           && strcmp (note->namedata, "LINUX") == 0)
6841         return elfcore_grok_prxfpreg (abfd, note);
6842       else
6843         return TRUE;
6844
6845     case NT_PRPSINFO:
6846     case NT_PSINFO:
6847       if (bed->elf_backend_grok_psinfo)
6848         if ((*bed->elf_backend_grok_psinfo) (abfd, note))
6849           return TRUE;
6850 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
6851       return elfcore_grok_psinfo (abfd, note);
6852 #else
6853       return TRUE;
6854 #endif
6855
6856     case NT_AUXV:
6857       {
6858         asection *sect = bfd_make_section_anyway (abfd, ".auxv");
6859
6860         if (sect == NULL)
6861           return FALSE;
6862         sect->_raw_size = note->descsz;
6863         sect->filepos = note->descpos;
6864         sect->flags = SEC_HAS_CONTENTS;
6865         sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
6866
6867         return TRUE;
6868       }
6869     }
6870 }
6871
6872 static bfd_boolean
6873 elfcore_netbsd_get_lwpid (Elf_Internal_Note *note, int *lwpidp)
6874 {
6875   char *cp;
6876
6877   cp = strchr (note->namedata, '@');
6878   if (cp != NULL)
6879     {
6880       *lwpidp = atoi(cp + 1);
6881       return TRUE;
6882     }
6883   return FALSE;
6884 }
6885
6886 static bfd_boolean
6887 elfcore_grok_netbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
6888 {
6889
6890   /* Signal number at offset 0x08. */
6891   elf_tdata (abfd)->core_signal
6892     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
6893
6894   /* Process ID at offset 0x50. */
6895   elf_tdata (abfd)->core_pid
6896     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
6897
6898   /* Command name at 0x7c (max 32 bytes, including nul). */
6899   elf_tdata (abfd)->core_command
6900     = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
6901
6902   return elfcore_make_note_pseudosection (abfd, ".note.netbsdcore.procinfo",
6903                                           note);
6904 }
6905
6906 static bfd_boolean
6907 elfcore_grok_netbsd_note (bfd *abfd, Elf_Internal_Note *note)
6908 {
6909   int lwp;
6910
6911   if (elfcore_netbsd_get_lwpid (note, &lwp))
6912     elf_tdata (abfd)->core_lwpid = lwp;
6913
6914   if (note->type == NT_NETBSDCORE_PROCINFO)
6915     {
6916       /* NetBSD-specific core "procinfo".  Note that we expect to
6917          find this note before any of the others, which is fine,
6918          since the kernel writes this note out first when it
6919          creates a core file.  */
6920
6921       return elfcore_grok_netbsd_procinfo (abfd, note);
6922     }
6923
6924   /* As of Jan 2002 there are no other machine-independent notes
6925      defined for NetBSD core files.  If the note type is less
6926      than the start of the machine-dependent note types, we don't
6927      understand it.  */
6928
6929   if (note->type < NT_NETBSDCORE_FIRSTMACH)
6930     return TRUE;
6931
6932
6933   switch (bfd_get_arch (abfd))
6934     {
6935     /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
6936        PT_GETFPREGS == mach+2.  */
6937
6938     case bfd_arch_alpha:
6939     case bfd_arch_sparc:
6940       switch (note->type)
6941         {
6942         case NT_NETBSDCORE_FIRSTMACH+0:
6943           return elfcore_make_note_pseudosection (abfd, ".reg", note);
6944
6945         case NT_NETBSDCORE_FIRSTMACH+2:
6946           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6947
6948         default:
6949           return TRUE;
6950         }
6951
6952     /* On all other arch's, PT_GETREGS == mach+1 and
6953        PT_GETFPREGS == mach+3.  */
6954
6955     default:
6956       switch (note->type)
6957         {
6958         case NT_NETBSDCORE_FIRSTMACH+1:
6959           return elfcore_make_note_pseudosection (abfd, ".reg", note);
6960
6961         case NT_NETBSDCORE_FIRSTMACH+3:
6962           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
6963
6964         default:
6965           return TRUE;
6966         }
6967     }
6968     /* NOTREACHED */
6969 }
6970
6971 static bfd_boolean
6972 elfcore_grok_nto_status (bfd *abfd, Elf_Internal_Note *note, pid_t *tid)
6973 {
6974   void *ddata = note->descdata;
6975   char buf[100];
6976   char *name;
6977   asection *sect;
6978   short sig;
6979   unsigned flags;
6980
6981   /* nto_procfs_status 'pid' field is at offset 0.  */
6982   elf_tdata (abfd)->core_pid = bfd_get_32 (abfd, (bfd_byte *) ddata);
6983
6984   /* nto_procfs_status 'tid' field is at offset 4.  Pass it back.  */
6985   *tid = bfd_get_32 (abfd, (bfd_byte *) ddata + 4);
6986
6987   /* nto_procfs_status 'flags' field is at offset 8.  */
6988   flags = bfd_get_32 (abfd, (bfd_byte *) ddata + 8);
6989
6990   /* nto_procfs_status 'what' field is at offset 14.  */
6991   if ((sig = bfd_get_16 (abfd, (bfd_byte *) ddata + 14)) > 0)
6992     {
6993       elf_tdata (abfd)->core_signal = sig;
6994       elf_tdata (abfd)->core_lwpid = *tid;
6995     }
6996
6997   /* _DEBUG_FLAG_CURTID (current thread) is 0x80.  Some cores
6998      do not come from signals so we make sure we set the current
6999      thread just in case.  */
7000   if (flags & 0x00000080)
7001     elf_tdata (abfd)->core_lwpid = *tid;
7002
7003   /* Make a ".qnx_core_status/%d" section.  */
7004   sprintf (buf, ".qnx_core_status/%d", *tid);
7005
7006   name = bfd_alloc (abfd, strlen (buf) + 1);
7007   if (name == NULL)
7008     return FALSE;
7009   strcpy (name, buf);
7010
7011   sect = bfd_make_section_anyway (abfd, name);
7012   if (sect == NULL)
7013     return FALSE;
7014
7015   sect->_raw_size       = note->descsz;
7016   sect->filepos         = note->descpos;
7017   sect->flags           = SEC_HAS_CONTENTS;
7018   sect->alignment_power = 2;
7019
7020   return (elfcore_maybe_make_sect (abfd, ".qnx_core_status", sect));
7021 }
7022
7023 static bfd_boolean
7024 elfcore_grok_nto_gregs (bfd *abfd, Elf_Internal_Note *note, pid_t tid)
7025 {
7026   char buf[100];
7027   char *name;
7028   asection *sect;
7029
7030   /* Make a ".reg/%d" section.  */
7031   sprintf (buf, ".reg/%d", tid);
7032
7033   name = bfd_alloc (abfd, strlen (buf) + 1);
7034   if (name == NULL)
7035     return FALSE;
7036   strcpy (name, buf);
7037
7038   sect = bfd_make_section_anyway (abfd, name);
7039   if (sect == NULL)
7040     return FALSE;
7041
7042   sect->_raw_size       = note->descsz;
7043   sect->filepos         = note->descpos;
7044   sect->flags           = SEC_HAS_CONTENTS;
7045   sect->alignment_power = 2;
7046
7047   /* This is the current thread.  */
7048   if (elf_tdata (abfd)->core_lwpid == tid)
7049     return elfcore_maybe_make_sect (abfd, ".reg", sect);
7050
7051   return TRUE;
7052 }
7053
7054 #define BFD_QNT_CORE_INFO       7
7055 #define BFD_QNT_CORE_STATUS     8
7056 #define BFD_QNT_CORE_GREG       9
7057 #define BFD_QNT_CORE_FPREG      10
7058
7059 static bfd_boolean
7060 elfcore_grok_nto_note (bfd *abfd, Elf_Internal_Note *note)
7061 {
7062   /* Every GREG section has a STATUS section before it.  Store the
7063      tid from the previous call to pass down to the next gregs
7064      function.  */
7065   static pid_t tid = 1;
7066
7067   switch (note->type)
7068     {
7069     case BFD_QNT_CORE_INFO:   return elfcore_make_note_pseudosection (abfd, ".qnx_core_info", note);
7070     case BFD_QNT_CORE_STATUS: return elfcore_grok_nto_status (abfd, note, &tid);
7071     case BFD_QNT_CORE_GREG:   return elfcore_grok_nto_gregs (abfd, note, tid);
7072     case BFD_QNT_CORE_FPREG:  return elfcore_grok_prfpreg (abfd, note);
7073     default:                  return TRUE;
7074     }
7075 }
7076
7077 /* Function: elfcore_write_note
7078
7079    Inputs:
7080      buffer to hold note
7081      name of note
7082      type of note
7083      data for note
7084      size of data for note
7085
7086    Return:
7087    End of buffer containing note.  */
7088
7089 char *
7090 elfcore_write_note (bfd  *abfd,
7091                     char *buf,
7092                     int  *bufsiz,
7093                     const char *name,
7094                     int  type,
7095                     const void *input,
7096                     int  size)
7097 {
7098   Elf_External_Note *xnp;
7099   size_t namesz;
7100   size_t pad;
7101   size_t newspace;
7102   char *p, *dest;
7103
7104   namesz = 0;
7105   pad = 0;
7106   if (name != NULL)
7107     {
7108       const struct elf_backend_data *bed;
7109
7110       namesz = strlen (name) + 1;
7111       bed = get_elf_backend_data (abfd);
7112       pad = -namesz & ((1 << bed->s->log_file_align) - 1);
7113     }
7114
7115   newspace = 12 + namesz + pad + size;
7116
7117   p = realloc (buf, *bufsiz + newspace);
7118   dest = p + *bufsiz;
7119   *bufsiz += newspace;
7120   xnp = (Elf_External_Note *) dest;
7121   H_PUT_32 (abfd, namesz, xnp->namesz);
7122   H_PUT_32 (abfd, size, xnp->descsz);
7123   H_PUT_32 (abfd, type, xnp->type);
7124   dest = xnp->name;
7125   if (name != NULL)
7126     {
7127       memcpy (dest, name, namesz);
7128       dest += namesz;
7129       while (pad != 0)
7130         {
7131           *dest++ = '\0';
7132           --pad;
7133         }
7134     }
7135   memcpy (dest, input, size);
7136   return p;
7137 }
7138
7139 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
7140 char *
7141 elfcore_write_prpsinfo (bfd  *abfd,
7142                         char *buf,
7143                         int  *bufsiz,
7144                         const char *fname,
7145                         const char *psargs)
7146 {
7147   int note_type;
7148   char *note_name = "CORE";
7149
7150 #if defined (HAVE_PSINFO_T)
7151   psinfo_t  data;
7152   note_type = NT_PSINFO;
7153 #else
7154   prpsinfo_t data;
7155   note_type = NT_PRPSINFO;
7156 #endif
7157
7158   memset (&data, 0, sizeof (data));
7159   strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
7160   strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
7161   return elfcore_write_note (abfd, buf, bufsiz,
7162                              note_name, note_type, &data, sizeof (data));
7163 }
7164 #endif  /* PSINFO_T or PRPSINFO_T */
7165
7166 #if defined (HAVE_PRSTATUS_T)
7167 char *
7168 elfcore_write_prstatus (bfd *abfd,
7169                         char *buf,
7170                         int *bufsiz,
7171                         long pid,
7172                         int cursig,
7173                         const void *gregs)
7174 {
7175   prstatus_t prstat;
7176   char *note_name = "CORE";
7177
7178   memset (&prstat, 0, sizeof (prstat));
7179   prstat.pr_pid = pid;
7180   prstat.pr_cursig = cursig;
7181   memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
7182   return elfcore_write_note (abfd, buf, bufsiz,
7183                              note_name, NT_PRSTATUS, &prstat, sizeof (prstat));
7184 }
7185 #endif /* HAVE_PRSTATUS_T */
7186
7187 #if defined (HAVE_LWPSTATUS_T)
7188 char *
7189 elfcore_write_lwpstatus (bfd *abfd,
7190                          char *buf,
7191                          int *bufsiz,
7192                          long pid,
7193                          int cursig,
7194                          const void *gregs)
7195 {
7196   lwpstatus_t lwpstat;
7197   char *note_name = "CORE";
7198
7199   memset (&lwpstat, 0, sizeof (lwpstat));
7200   lwpstat.pr_lwpid  = pid >> 16;
7201   lwpstat.pr_cursig = cursig;
7202 #if defined (HAVE_LWPSTATUS_T_PR_REG)
7203   memcpy (lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
7204 #elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
7205 #if !defined(gregs)
7206   memcpy (lwpstat.pr_context.uc_mcontext.gregs,
7207           gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
7208 #else
7209   memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
7210           gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
7211 #endif
7212 #endif
7213   return elfcore_write_note (abfd, buf, bufsiz, note_name,
7214                              NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
7215 }
7216 #endif /* HAVE_LWPSTATUS_T */
7217
7218 #if defined (HAVE_PSTATUS_T)
7219 char *
7220 elfcore_write_pstatus (bfd *abfd,
7221                        char *buf,
7222                        int *bufsiz,
7223                        long pid,
7224                        int cursig,
7225                        const void *gregs)
7226 {
7227   pstatus_t pstat;
7228   char *note_name = "CORE";
7229
7230   memset (&pstat, 0, sizeof (pstat));
7231   pstat.pr_pid = pid & 0xffff;
7232   buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
7233                             NT_PSTATUS, &pstat, sizeof (pstat));
7234   return buf;
7235 }
7236 #endif /* HAVE_PSTATUS_T */
7237
7238 char *
7239 elfcore_write_prfpreg (bfd *abfd,
7240                        char *buf,
7241                        int *bufsiz,
7242                        const void *fpregs,
7243                        int size)
7244 {
7245   char *note_name = "CORE";
7246   return elfcore_write_note (abfd, buf, bufsiz,
7247                              note_name, NT_FPREGSET, fpregs, size);
7248 }
7249
7250 char *
7251 elfcore_write_prxfpreg (bfd *abfd,
7252                         char *buf,
7253                         int *bufsiz,
7254                         const void *xfpregs,
7255                         int size)
7256 {
7257   char *note_name = "LINUX";
7258   return elfcore_write_note (abfd, buf, bufsiz,
7259                              note_name, NT_PRXFPREG, xfpregs, size);
7260 }
7261
7262 static bfd_boolean
7263 elfcore_read_notes (bfd *abfd, file_ptr offset, bfd_size_type size)
7264 {
7265   char *buf;
7266   char *p;
7267
7268   if (size <= 0)
7269     return TRUE;
7270
7271   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
7272     return FALSE;
7273
7274   buf = bfd_malloc (size);
7275   if (buf == NULL)
7276     return FALSE;
7277
7278   if (bfd_bread (buf, size, abfd) != size)
7279     {
7280     error:
7281       free (buf);
7282       return FALSE;
7283     }
7284
7285   p = buf;
7286   while (p < buf + size)
7287     {
7288       /* FIXME: bad alignment assumption.  */
7289       Elf_External_Note *xnp = (Elf_External_Note *) p;
7290       Elf_Internal_Note in;
7291
7292       in.type = H_GET_32 (abfd, xnp->type);
7293
7294       in.namesz = H_GET_32 (abfd, xnp->namesz);
7295       in.namedata = xnp->name;
7296
7297       in.descsz = H_GET_32 (abfd, xnp->descsz);
7298       in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
7299       in.descpos = offset + (in.descdata - buf);
7300
7301       if (strncmp (in.namedata, "NetBSD-CORE", 11) == 0)
7302         {
7303           if (! elfcore_grok_netbsd_note (abfd, &in))
7304             goto error;
7305         }
7306       else if (strncmp (in.namedata, "QNX", 3) == 0)
7307         {
7308           if (! elfcore_grok_nto_note (abfd, &in))
7309             goto error;
7310         }
7311       else
7312         {
7313           if (! elfcore_grok_note (abfd, &in))
7314             goto error;
7315         }
7316
7317       p = in.descdata + BFD_ALIGN (in.descsz, 4);
7318     }
7319
7320   free (buf);
7321   return TRUE;
7322 }
7323 \f
7324 /* Providing external access to the ELF program header table.  */
7325
7326 /* Return an upper bound on the number of bytes required to store a
7327    copy of ABFD's program header table entries.  Return -1 if an error
7328    occurs; bfd_get_error will return an appropriate code.  */
7329
7330 long
7331 bfd_get_elf_phdr_upper_bound (bfd *abfd)
7332 {
7333   if (abfd->xvec->flavour != bfd_target_elf_flavour)
7334     {
7335       bfd_set_error (bfd_error_wrong_format);
7336       return -1;
7337     }
7338
7339   return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
7340 }
7341
7342 /* Copy ABFD's program header table entries to *PHDRS.  The entries
7343    will be stored as an array of Elf_Internal_Phdr structures, as
7344    defined in include/elf/internal.h.  To find out how large the
7345    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
7346
7347    Return the number of program header table entries read, or -1 if an
7348    error occurs; bfd_get_error will return an appropriate code.  */
7349
7350 int
7351 bfd_get_elf_phdrs (bfd *abfd, void *phdrs)
7352 {
7353   int num_phdrs;
7354
7355   if (abfd->xvec->flavour != bfd_target_elf_flavour)
7356     {
7357       bfd_set_error (bfd_error_wrong_format);
7358       return -1;
7359     }
7360
7361   num_phdrs = elf_elfheader (abfd)->e_phnum;
7362   memcpy (phdrs, elf_tdata (abfd)->phdr,
7363           num_phdrs * sizeof (Elf_Internal_Phdr));
7364
7365   return num_phdrs;
7366 }
7367
7368 void
7369 _bfd_elf_sprintf_vma (bfd *abfd ATTRIBUTE_UNUSED, char *buf, bfd_vma value)
7370 {
7371 #ifdef BFD64
7372   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
7373
7374   i_ehdrp = elf_elfheader (abfd);
7375   if (i_ehdrp == NULL)
7376     sprintf_vma (buf, value);
7377   else
7378     {
7379       if (i_ehdrp->e_ident[EI_CLASS] == ELFCLASS64)
7380         {
7381 #if BFD_HOST_64BIT_LONG
7382           sprintf (buf, "%016lx", value);
7383 #else
7384           sprintf (buf, "%08lx%08lx", _bfd_int64_high (value),
7385                    _bfd_int64_low (value));
7386 #endif
7387         }
7388       else
7389         sprintf (buf, "%08lx", (unsigned long) (value & 0xffffffff));
7390     }
7391 #else
7392   sprintf_vma (buf, value);
7393 #endif
7394 }
7395
7396 void
7397 _bfd_elf_fprintf_vma (bfd *abfd ATTRIBUTE_UNUSED, void *stream, bfd_vma value)
7398 {
7399 #ifdef BFD64
7400   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
7401
7402   i_ehdrp = elf_elfheader (abfd);
7403   if (i_ehdrp == NULL)
7404     fprintf_vma ((FILE *) stream, value);
7405   else
7406     {
7407       if (i_ehdrp->e_ident[EI_CLASS] == ELFCLASS64)
7408         {
7409 #if BFD_HOST_64BIT_LONG
7410           fprintf ((FILE *) stream, "%016lx", value);
7411 #else
7412           fprintf ((FILE *) stream, "%08lx%08lx",
7413                    _bfd_int64_high (value), _bfd_int64_low (value));
7414 #endif
7415         }
7416       else
7417         fprintf ((FILE *) stream, "%08lx",
7418                  (unsigned long) (value & 0xffffffff));
7419     }
7420 #else
7421   fprintf_vma ((FILE *) stream, value);
7422 #endif
7423 }
7424
7425 enum elf_reloc_type_class
7426 _bfd_elf_reloc_type_class (const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED)
7427 {
7428   return reloc_class_normal;
7429 }
7430
7431 /* For RELA architectures, return the relocation value for a
7432    relocation against a local symbol.  */
7433
7434 bfd_vma
7435 _bfd_elf_rela_local_sym (bfd *abfd,
7436                          Elf_Internal_Sym *sym,
7437                          asection **psec,
7438                          Elf_Internal_Rela *rel)
7439 {
7440   asection *sec = *psec;
7441   bfd_vma relocation;
7442
7443   relocation = (sec->output_section->vma
7444                 + sec->output_offset
7445                 + sym->st_value);
7446   if ((sec->flags & SEC_MERGE)
7447       && ELF_ST_TYPE (sym->st_info) == STT_SECTION
7448       && sec->sec_info_type == ELF_INFO_TYPE_MERGE)
7449     {
7450       rel->r_addend =
7451         _bfd_merged_section_offset (abfd, psec,
7452                                     elf_section_data (sec)->sec_info,
7453                                     sym->st_value + rel->r_addend,
7454                                     0);
7455       sec = *psec;
7456       rel->r_addend -= relocation;
7457       rel->r_addend += sec->output_section->vma + sec->output_offset;
7458     }
7459   return relocation;
7460 }
7461
7462 bfd_vma
7463 _bfd_elf_rel_local_sym (bfd *abfd,
7464                         Elf_Internal_Sym *sym,
7465                         asection **psec,
7466                         bfd_vma addend)
7467 {
7468   asection *sec = *psec;
7469
7470   if (sec->sec_info_type != ELF_INFO_TYPE_MERGE)
7471     return sym->st_value + addend;
7472
7473   return _bfd_merged_section_offset (abfd, psec,
7474                                      elf_section_data (sec)->sec_info,
7475                                      sym->st_value + addend, 0);
7476 }
7477
7478 bfd_vma
7479 _bfd_elf_section_offset (bfd *abfd,
7480                          struct bfd_link_info *info,
7481                          asection *sec,
7482                          bfd_vma offset)
7483 {
7484   struct bfd_elf_section_data *sec_data;
7485
7486   sec_data = elf_section_data (sec);
7487   switch (sec->sec_info_type)
7488     {
7489     case ELF_INFO_TYPE_STABS:
7490       return _bfd_stab_section_offset (abfd,
7491                                        &elf_hash_table (info)->merge_info,
7492                                        sec, &sec_data->sec_info, offset);
7493     case ELF_INFO_TYPE_EH_FRAME:
7494       return _bfd_elf_eh_frame_section_offset (abfd, sec, offset);
7495     default:
7496       return offset;
7497     }
7498 }
7499 \f
7500 /* Create a new BFD as if by bfd_openr.  Rather than opening a file,
7501    reconstruct an ELF file by reading the segments out of remote memory
7502    based on the ELF file header at EHDR_VMA and the ELF program headers it
7503    points to.  If not null, *LOADBASEP is filled in with the difference
7504    between the VMAs from which the segments were read, and the VMAs the
7505    file headers (and hence BFD's idea of each section's VMA) put them at.
7506
7507    The function TARGET_READ_MEMORY is called to copy LEN bytes from the
7508    remote memory at target address VMA into the local buffer at MYADDR; it
7509    should return zero on success or an `errno' code on failure.  TEMPL must
7510    be a BFD for an ELF target with the word size and byte order found in
7511    the remote memory.  */
7512
7513 bfd *
7514 bfd_elf_bfd_from_remote_memory
7515   (bfd *templ,
7516    bfd_vma ehdr_vma,
7517    bfd_vma *loadbasep,
7518    int (*target_read_memory) (bfd_vma, char *, int))
7519 {
7520   return (*get_elf_backend_data (templ)->elf_backend_bfd_from_remote_memory)
7521     (templ, ehdr_vma, loadbasep, target_read_memory);
7522 }