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