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