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