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