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