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