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