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 (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 = (bfd_vma) 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 = (bfd_vma) 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 && i_shdrp->sh_addralign > 1)
3225     offset = BFD_ALIGN (offset, i_shdrp->sh_addralign);
3226   i_shdrp->sh_offset = offset;
3227   if (i_shdrp->bfd_section != NULL)
3228     i_shdrp->bfd_section->filepos = offset;
3229   if (i_shdrp->sh_type != SHT_NOBITS)
3230     offset += i_shdrp->sh_size;
3231   return offset;
3232 }
3233
3234 /* Compute the file positions we are going to put the sections at, and
3235    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
3236    is not NULL, this is being called by the ELF backend linker.  */
3237
3238 bfd_boolean
3239 _bfd_elf_compute_section_file_positions (bfd *abfd,
3240                                          struct bfd_link_info *link_info)
3241 {
3242   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3243   bfd_boolean failed;
3244   struct bfd_strtab_hash *strtab = NULL;
3245   Elf_Internal_Shdr *shstrtab_hdr;
3246
3247   if (abfd->output_has_begun)
3248     return TRUE;
3249
3250   /* Do any elf backend specific processing first.  */
3251   if (bed->elf_backend_begin_write_processing)
3252     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
3253
3254   if (! prep_headers (abfd))
3255     return FALSE;
3256
3257   /* Post process the headers if necessary.  */
3258   if (bed->elf_backend_post_process_headers)
3259     (*bed->elf_backend_post_process_headers) (abfd, link_info);
3260
3261   failed = FALSE;
3262   bfd_map_over_sections (abfd, elf_fake_sections, &failed);
3263   if (failed)
3264     return FALSE;
3265
3266   if (!assign_section_numbers (abfd, link_info))
3267     return FALSE;
3268
3269   /* The backend linker builds symbol table information itself.  */
3270   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
3271     {
3272       /* Non-zero if doing a relocatable link.  */
3273       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
3274
3275       if (! swap_out_syms (abfd, &strtab, relocatable_p))
3276         return FALSE;
3277     }
3278
3279   if (link_info == NULL)
3280     {
3281       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
3282       if (failed)
3283         return FALSE;
3284     }
3285
3286   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
3287   /* sh_name was set in prep_headers.  */
3288   shstrtab_hdr->sh_type = SHT_STRTAB;
3289   shstrtab_hdr->sh_flags = 0;
3290   shstrtab_hdr->sh_addr = 0;
3291   shstrtab_hdr->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
3292   shstrtab_hdr->sh_entsize = 0;
3293   shstrtab_hdr->sh_link = 0;
3294   shstrtab_hdr->sh_info = 0;
3295   /* sh_offset is set in assign_file_positions_except_relocs.  */
3296   shstrtab_hdr->sh_addralign = 1;
3297
3298   if (!assign_file_positions_except_relocs (abfd, link_info))
3299     return FALSE;
3300
3301   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
3302     {
3303       file_ptr off;
3304       Elf_Internal_Shdr *hdr;
3305
3306       off = elf_tdata (abfd)->next_file_pos;
3307
3308       hdr = &elf_tdata (abfd)->symtab_hdr;
3309       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3310
3311       hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
3312       if (hdr->sh_size != 0)
3313         off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3314
3315       hdr = &elf_tdata (abfd)->strtab_hdr;
3316       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3317
3318       elf_tdata (abfd)->next_file_pos = off;
3319
3320       /* Now that we know where the .strtab section goes, write it
3321          out.  */
3322       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
3323           || ! _bfd_stringtab_emit (abfd, strtab))
3324         return FALSE;
3325       _bfd_stringtab_free (strtab);
3326     }
3327
3328   abfd->output_has_begun = TRUE;
3329
3330   return TRUE;
3331 }
3332
3333 /* Make an initial estimate of the size of the program header.  If we
3334    get the number wrong here, we'll redo section placement.  */
3335
3336 static bfd_size_type
3337 get_program_header_size (bfd *abfd, struct bfd_link_info *info)
3338 {
3339   size_t segs;
3340   asection *s;
3341   const struct elf_backend_data *bed;
3342
3343   /* Assume we will need exactly two PT_LOAD segments: one for text
3344      and one for data.  */
3345   segs = 2;
3346
3347   s = bfd_get_section_by_name (abfd, ".interp");
3348   if (s != NULL && (s->flags & SEC_LOAD) != 0)
3349     {
3350       /* If we have a loadable interpreter section, we need a
3351          PT_INTERP segment.  In this case, assume we also need a
3352          PT_PHDR segment, although that may not be true for all
3353          targets.  */
3354       segs += 2;
3355     }
3356
3357   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
3358     {
3359       /* We need a PT_DYNAMIC segment.  */
3360       ++segs;
3361     }
3362
3363   if (info->relro)
3364     {
3365       /* We need a PT_GNU_RELRO segment.  */
3366       ++segs;
3367     }
3368
3369   if (elf_tdata (abfd)->eh_frame_hdr)
3370     {
3371       /* We need a PT_GNU_EH_FRAME segment.  */
3372       ++segs;
3373     }
3374
3375   if (elf_tdata (abfd)->stack_flags)
3376     {
3377       /* We need a PT_GNU_STACK segment.  */
3378       ++segs;
3379     }
3380
3381   for (s = abfd->sections; s != NULL; s = s->next)
3382     {
3383       if ((s->flags & SEC_LOAD) != 0
3384           && CONST_STRNEQ (s->name, ".note"))
3385         {
3386           /* We need a PT_NOTE segment.  */
3387           ++segs;
3388           /* Try to create just one PT_NOTE segment
3389              for all adjacent loadable .note* sections.
3390              gABI requires that within a PT_NOTE segment
3391              (and also inside of each SHT_NOTE section)
3392              each note is padded to a multiple of 4 size,
3393              so we check whether the sections are correctly
3394              aligned.  */
3395           if (s->alignment_power == 2)
3396             while (s->next != NULL
3397                    && s->next->alignment_power == 2
3398                    && (s->next->flags & SEC_LOAD) != 0
3399                    && CONST_STRNEQ (s->next->name, ".note"))
3400               s = s->next;
3401         }
3402     }
3403
3404   for (s = abfd->sections; s != NULL; s = s->next)
3405     {
3406       if (s->flags & SEC_THREAD_LOCAL)
3407         {
3408           /* We need a PT_TLS segment.  */
3409           ++segs;
3410           break;
3411         }
3412     }
3413
3414   /* Let the backend count up any program headers it might need.  */
3415   bed = get_elf_backend_data (abfd);
3416   if (bed->elf_backend_additional_program_headers)
3417     {
3418       int a;
3419
3420       a = (*bed->elf_backend_additional_program_headers) (abfd, info);
3421       if (a == -1)
3422         abort ();
3423       segs += a;
3424     }
3425
3426   return segs * bed->s->sizeof_phdr;
3427 }
3428
3429 /* Find the segment that contains the output_section of section.  */
3430
3431 Elf_Internal_Phdr *
3432 _bfd_elf_find_segment_containing_section (bfd * abfd, asection * section)
3433 {
3434   struct elf_segment_map *m;
3435   Elf_Internal_Phdr *p;
3436
3437   for (m = elf_tdata (abfd)->segment_map,
3438          p = elf_tdata (abfd)->phdr;
3439        m != NULL;
3440        m = m->next, p++)
3441     {
3442       int i;
3443
3444       for (i = m->count - 1; i >= 0; i--)
3445         if (m->sections[i] == section)
3446           return p;
3447     }
3448
3449   return NULL;
3450 }
3451
3452 /* Create a mapping from a set of sections to a program segment.  */
3453
3454 static struct elf_segment_map *
3455 make_mapping (bfd *abfd,
3456               asection **sections,
3457               unsigned int from,
3458               unsigned int to,
3459               bfd_boolean phdr)
3460 {
3461   struct elf_segment_map *m;
3462   unsigned int i;
3463   asection **hdrpp;
3464   bfd_size_type amt;
3465
3466   amt = sizeof (struct elf_segment_map);
3467   amt += (to - from - 1) * sizeof (asection *);
3468   m = bfd_zalloc (abfd, amt);
3469   if (m == NULL)
3470     return NULL;
3471   m->next = NULL;
3472   m->p_type = PT_LOAD;
3473   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
3474     m->sections[i - from] = *hdrpp;
3475   m->count = to - from;
3476
3477   if (from == 0 && phdr)
3478     {
3479       /* Include the headers in the first PT_LOAD segment.  */
3480       m->includes_filehdr = 1;
3481       m->includes_phdrs = 1;
3482     }
3483
3484   return m;
3485 }
3486
3487 /* Create the PT_DYNAMIC segment, which includes DYNSEC.  Returns NULL
3488    on failure.  */
3489
3490 struct elf_segment_map *
3491 _bfd_elf_make_dynamic_segment (bfd *abfd, asection *dynsec)
3492 {
3493   struct elf_segment_map *m;
3494
3495   m = bfd_zalloc (abfd, sizeof (struct elf_segment_map));
3496   if (m == NULL)
3497     return NULL;
3498   m->next = NULL;
3499   m->p_type = PT_DYNAMIC;
3500   m->count = 1;
3501   m->sections[0] = dynsec;
3502
3503   return m;
3504 }
3505
3506 /* Possibly add or remove segments from the segment map.  */
3507
3508 static bfd_boolean
3509 elf_modify_segment_map (bfd *abfd,
3510                         struct bfd_link_info *info,
3511                         bfd_boolean remove_empty_load)
3512 {
3513   struct elf_segment_map **m;
3514   const struct elf_backend_data *bed;
3515
3516   /* The placement algorithm assumes that non allocated sections are
3517      not in PT_LOAD segments.  We ensure this here by removing such
3518      sections from the segment map.  We also remove excluded
3519      sections.  Finally, any PT_LOAD segment without sections is
3520      removed.  */
3521   m = &elf_tdata (abfd)->segment_map;
3522   while (*m)
3523     {
3524       unsigned int i, new_count;
3525
3526       for (new_count = 0, i = 0; i < (*m)->count; i++)
3527         {
3528           if (((*m)->sections[i]->flags & SEC_EXCLUDE) == 0
3529               && (((*m)->sections[i]->flags & SEC_ALLOC) != 0
3530                   || (*m)->p_type != PT_LOAD))
3531             {
3532               (*m)->sections[new_count] = (*m)->sections[i];
3533               new_count++;
3534             }
3535         }
3536       (*m)->count = new_count;
3537
3538       if (remove_empty_load && (*m)->p_type == PT_LOAD && (*m)->count == 0)
3539         *m = (*m)->next;
3540       else
3541         m = &(*m)->next;
3542     }
3543
3544   bed = get_elf_backend_data (abfd);
3545   if (bed->elf_backend_modify_segment_map != NULL)
3546     {
3547       if (!(*bed->elf_backend_modify_segment_map) (abfd, info))
3548         return FALSE;
3549     }
3550
3551   return TRUE;
3552 }
3553
3554 /* Set up a mapping from BFD sections to program segments.  */
3555
3556 bfd_boolean
3557 _bfd_elf_map_sections_to_segments (bfd *abfd, struct bfd_link_info *info)
3558 {
3559   unsigned int count;
3560   struct elf_segment_map *m;
3561   asection **sections = NULL;
3562   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3563   bfd_boolean no_user_phdrs;
3564
3565   no_user_phdrs = elf_tdata (abfd)->segment_map == NULL;
3566   if (no_user_phdrs && bfd_count_sections (abfd) != 0)
3567     {
3568       asection *s;
3569       unsigned int i;
3570       struct elf_segment_map *mfirst;
3571       struct elf_segment_map **pm;
3572       asection *last_hdr;
3573       bfd_vma last_size;
3574       unsigned int phdr_index;
3575       bfd_vma maxpagesize;
3576       asection **hdrpp;
3577       bfd_boolean phdr_in_segment = TRUE;
3578       bfd_boolean writable;
3579       int tls_count = 0;
3580       asection *first_tls = NULL;
3581       asection *dynsec, *eh_frame_hdr;
3582       bfd_size_type amt;
3583
3584       /* Select the allocated sections, and sort them.  */
3585
3586       sections = bfd_malloc2 (bfd_count_sections (abfd), sizeof (asection *));
3587       if (sections == NULL)
3588         goto error_return;
3589
3590       i = 0;
3591       for (s = abfd->sections; s != NULL; s = s->next)
3592         {
3593           if ((s->flags & SEC_ALLOC) != 0)
3594             {
3595               sections[i] = s;
3596               ++i;
3597             }
3598         }
3599       BFD_ASSERT (i <= bfd_count_sections (abfd));
3600       count = i;
3601
3602       qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
3603
3604       /* Build the mapping.  */
3605
3606       mfirst = NULL;
3607       pm = &mfirst;
3608
3609       /* If we have a .interp section, then create a PT_PHDR segment for
3610          the program headers and a PT_INTERP segment for the .interp
3611          section.  */
3612       s = bfd_get_section_by_name (abfd, ".interp");
3613       if (s != NULL && (s->flags & SEC_LOAD) != 0)
3614         {
3615           amt = sizeof (struct elf_segment_map);
3616           m = bfd_zalloc (abfd, amt);
3617           if (m == NULL)
3618             goto error_return;
3619           m->next = NULL;
3620           m->p_type = PT_PHDR;
3621           /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
3622           m->p_flags = PF_R | PF_X;
3623           m->p_flags_valid = 1;
3624           m->includes_phdrs = 1;
3625
3626           *pm = m;
3627           pm = &m->next;
3628
3629           amt = sizeof (struct elf_segment_map);
3630           m = bfd_zalloc (abfd, amt);
3631           if (m == NULL)
3632             goto error_return;
3633           m->next = NULL;
3634           m->p_type = PT_INTERP;
3635           m->count = 1;
3636           m->sections[0] = s;
3637
3638           *pm = m;
3639           pm = &m->next;
3640         }
3641
3642       /* Look through the sections.  We put sections in the same program
3643          segment when the start of the second section can be placed within
3644          a few bytes of the end of the first section.  */
3645       last_hdr = NULL;
3646       last_size = 0;
3647       phdr_index = 0;
3648       maxpagesize = bed->maxpagesize;
3649       writable = FALSE;
3650       dynsec = bfd_get_section_by_name (abfd, ".dynamic");
3651       if (dynsec != NULL
3652           && (dynsec->flags & SEC_LOAD) == 0)
3653         dynsec = NULL;
3654
3655       /* Deal with -Ttext or something similar such that the first section
3656          is not adjacent to the program headers.  This is an
3657          approximation, since at this point we don't know exactly how many
3658          program headers we will need.  */
3659       if (count > 0)
3660         {
3661           bfd_size_type phdr_size = elf_tdata (abfd)->program_header_size;
3662
3663           if (phdr_size == (bfd_size_type) -1)
3664             phdr_size = get_program_header_size (abfd, info);
3665           if ((abfd->flags & D_PAGED) == 0
3666               || sections[0]->lma < phdr_size
3667               || sections[0]->lma % maxpagesize < phdr_size % maxpagesize)
3668             phdr_in_segment = FALSE;
3669         }
3670
3671       for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
3672         {
3673           asection *hdr;
3674           bfd_boolean new_segment;
3675
3676           hdr = *hdrpp;
3677
3678           /* See if this section and the last one will fit in the same
3679              segment.  */
3680
3681           if (last_hdr == NULL)
3682             {
3683               /* If we don't have a segment yet, then we don't need a new
3684                  one (we build the last one after this loop).  */
3685               new_segment = FALSE;
3686             }
3687           else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
3688             {
3689               /* If this section has a different relation between the
3690                  virtual address and the load address, then we need a new
3691                  segment.  */
3692               new_segment = TRUE;
3693             }
3694           else if (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize)
3695                    < BFD_ALIGN (hdr->lma, maxpagesize))
3696             {
3697               /* If putting this section in this segment would force us to
3698                  skip a page in the segment, then we need a new segment.  */
3699               new_segment = TRUE;
3700             }
3701           else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
3702                    && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0)
3703             {
3704               /* We don't want to put a loadable section after a
3705                  nonloadable section in the same segment.
3706                  Consider .tbss sections as loadable for this purpose.  */
3707               new_segment = TRUE;
3708             }
3709           else if ((abfd->flags & D_PAGED) == 0)
3710             {
3711               /* If the file is not demand paged, which means that we
3712                  don't require the sections to be correctly aligned in the
3713                  file, then there is no other reason for a new segment.  */
3714               new_segment = FALSE;
3715             }
3716           else if (! writable
3717                    && (hdr->flags & SEC_READONLY) == 0
3718                    && (((last_hdr->lma + last_size - 1)
3719                         & ~(maxpagesize - 1))
3720                        != (hdr->lma & ~(maxpagesize - 1))))
3721             {
3722               /* We don't want to put a writable section in a read only
3723                  segment, unless they are on the same page in memory
3724                  anyhow.  We already know that the last section does not
3725                  bring us past the current section on the page, so the
3726                  only case in which the new section is not on the same
3727                  page as the previous section is when the previous section
3728                  ends precisely on a page boundary.  */
3729               new_segment = TRUE;
3730             }
3731           else
3732             {
3733               /* Otherwise, we can use the same segment.  */
3734               new_segment = FALSE;
3735             }
3736
3737           /* Allow interested parties a chance to override our decision.  */
3738           if (last_hdr && info->callbacks->override_segment_assignment)
3739             new_segment = info->callbacks->override_segment_assignment (info, abfd, hdr, last_hdr, new_segment);
3740
3741           if (! new_segment)
3742             {
3743               if ((hdr->flags & SEC_READONLY) == 0)
3744                 writable = TRUE;
3745               last_hdr = hdr;
3746               /* .tbss sections effectively have zero size.  */
3747               if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
3748                   != SEC_THREAD_LOCAL)
3749                 last_size = hdr->size;
3750               else
3751                 last_size = 0;
3752               continue;
3753             }
3754
3755           /* We need a new program segment.  We must create a new program
3756              header holding all the sections from phdr_index until hdr.  */
3757
3758           m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
3759           if (m == NULL)
3760             goto error_return;
3761
3762           *pm = m;
3763           pm = &m->next;
3764
3765           if ((hdr->flags & SEC_READONLY) == 0)
3766             writable = TRUE;
3767           else
3768             writable = FALSE;
3769
3770           last_hdr = hdr;
3771           /* .tbss sections effectively have zero size.  */
3772           if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
3773             last_size = hdr->size;
3774           else
3775             last_size = 0;
3776           phdr_index = i;
3777           phdr_in_segment = FALSE;
3778         }
3779
3780       /* Create a final PT_LOAD program segment.  */
3781       if (last_hdr != NULL)
3782         {
3783           m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
3784           if (m == NULL)
3785             goto error_return;
3786
3787           *pm = m;
3788           pm = &m->next;
3789         }
3790
3791       /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
3792       if (dynsec != NULL)
3793         {
3794           m = _bfd_elf_make_dynamic_segment (abfd, dynsec);
3795           if (m == NULL)
3796             goto error_return;
3797           *pm = m;
3798           pm = &m->next;
3799         }
3800
3801       /* For each batch of consecutive loadable .note sections,
3802          add a PT_NOTE segment.  We don't use bfd_get_section_by_name,
3803          because if we link together nonloadable .note sections and
3804          loadable .note sections, we will generate two .note sections
3805          in the output file.  FIXME: Using names for section types is
3806          bogus anyhow.  */
3807       for (s = abfd->sections; s != NULL; s = s->next)
3808         {
3809           if ((s->flags & SEC_LOAD) != 0
3810               && CONST_STRNEQ (s->name, ".note"))
3811             {
3812               asection *s2;
3813               unsigned count = 1;
3814               amt = sizeof (struct elf_segment_map);
3815               if (s->alignment_power == 2)
3816                 for (s2 = s; s2->next != NULL; s2 = s2->next)
3817                   {
3818                     if (s2->next->alignment_power == 2
3819                         && (s2->next->flags & SEC_LOAD) != 0
3820                         && CONST_STRNEQ (s2->next->name, ".note")
3821                         && align_power (s2->vma + s2->size, 2)
3822                            == s2->next->vma)
3823                       count++;
3824                     else
3825                       break;
3826                   }
3827               amt += (count - 1) * sizeof (asection *);
3828               m = bfd_zalloc (abfd, amt);
3829               if (m == NULL)
3830                 goto error_return;
3831               m->next = NULL;
3832               m->p_type = PT_NOTE;
3833               m->count = count;
3834               while (count > 1)
3835                 {
3836                   m->sections[m->count - count--] = s;
3837                   BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
3838                   s = s->next;
3839                 }
3840               m->sections[m->count - 1] = s;
3841               BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
3842               *pm = m;
3843               pm = &m->next;
3844             }
3845           if (s->flags & SEC_THREAD_LOCAL)
3846             {
3847               if (! tls_count)
3848                 first_tls = s;
3849               tls_count++;
3850             }
3851         }
3852
3853       /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
3854       if (tls_count > 0)
3855         {
3856           int i;
3857
3858           amt = sizeof (struct elf_segment_map);
3859           amt += (tls_count - 1) * sizeof (asection *);
3860           m = bfd_zalloc (abfd, amt);
3861           if (m == NULL)
3862             goto error_return;
3863           m->next = NULL;
3864           m->p_type = PT_TLS;
3865           m->count = tls_count;
3866           /* Mandated PF_R.  */
3867           m->p_flags = PF_R;
3868           m->p_flags_valid = 1;
3869           for (i = 0; i < tls_count; ++i)
3870             {
3871               BFD_ASSERT (first_tls->flags & SEC_THREAD_LOCAL);
3872               m->sections[i] = first_tls;
3873               first_tls = first_tls->next;
3874             }
3875
3876           *pm = m;
3877           pm = &m->next;
3878         }
3879
3880       /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
3881          segment.  */
3882       eh_frame_hdr = elf_tdata (abfd)->eh_frame_hdr;
3883       if (eh_frame_hdr != NULL
3884           && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
3885         {
3886           amt = sizeof (struct elf_segment_map);
3887           m = bfd_zalloc (abfd, amt);
3888           if (m == NULL)
3889             goto error_return;
3890           m->next = NULL;
3891           m->p_type = PT_GNU_EH_FRAME;
3892           m->count = 1;
3893           m->sections[0] = eh_frame_hdr->output_section;
3894
3895           *pm = m;
3896           pm = &m->next;
3897         }
3898
3899       if (elf_tdata (abfd)->stack_flags)
3900         {
3901           amt = sizeof (struct elf_segment_map);
3902           m = bfd_zalloc (abfd, amt);
3903           if (m == NULL)
3904             goto error_return;
3905           m->next = NULL;
3906           m->p_type = PT_GNU_STACK;
3907           m->p_flags = elf_tdata (abfd)->stack_flags;
3908           m->p_flags_valid = 1;
3909
3910           *pm = m;
3911           pm = &m->next;
3912         }
3913
3914       if (info->relro)
3915         {
3916           for (m = mfirst; m != NULL; m = m->next)
3917             {
3918               if (m->p_type == PT_LOAD)
3919                 {
3920                   asection *last = m->sections[m->count - 1];
3921                   bfd_vma vaddr = m->sections[0]->vma;
3922                   bfd_vma filesz = last->vma - vaddr + last->size;
3923
3924                   if (vaddr < info->relro_end
3925                       && vaddr >= info->relro_start
3926                       && (vaddr + filesz) >= info->relro_end)
3927                     break;
3928                 }
3929               }
3930
3931           /* Make a PT_GNU_RELRO segment only when it isn't empty.  */
3932           if (m != NULL)
3933             {
3934               amt = sizeof (struct elf_segment_map);
3935               m = bfd_zalloc (abfd, amt);
3936               if (m == NULL)
3937                 goto error_return;
3938               m->next = NULL;
3939               m->p_type = PT_GNU_RELRO;
3940               m->p_flags = PF_R;
3941               m->p_flags_valid = 1;
3942
3943               *pm = m;
3944               pm = &m->next;
3945             }
3946         }
3947
3948       free (sections);
3949       elf_tdata (abfd)->segment_map = mfirst;
3950     }
3951
3952   if (!elf_modify_segment_map (abfd, info, no_user_phdrs))
3953     return FALSE;
3954
3955   for (count = 0, m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
3956     ++count;
3957   elf_tdata (abfd)->program_header_size = count * bed->s->sizeof_phdr;
3958
3959   return TRUE;
3960
3961  error_return:
3962   if (sections != NULL)
3963     free (sections);
3964   return FALSE;
3965 }
3966
3967 /* Sort sections by address.  */
3968
3969 static int
3970 elf_sort_sections (const void *arg1, const void *arg2)
3971 {
3972   const asection *sec1 = *(const asection **) arg1;
3973   const asection *sec2 = *(const asection **) arg2;
3974   bfd_size_type size1, size2;
3975
3976   /* Sort by LMA first, since this is the address used to
3977      place the section into a segment.  */
3978   if (sec1->lma < sec2->lma)
3979     return -1;
3980   else if (sec1->lma > sec2->lma)
3981     return 1;
3982
3983   /* Then sort by VMA.  Normally the LMA and the VMA will be
3984      the same, and this will do nothing.  */
3985   if (sec1->vma < sec2->vma)
3986     return -1;
3987   else if (sec1->vma > sec2->vma)
3988     return 1;
3989
3990   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
3991
3992 #define TOEND(x) (((x)->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0)
3993
3994   if (TOEND (sec1))
3995     {
3996       if (TOEND (sec2))
3997         {
3998           /* If the indicies are the same, do not return 0
3999              here, but continue to try the next comparison.  */
4000           if (sec1->target_index - sec2->target_index != 0)
4001             return sec1->target_index - sec2->target_index;
4002         }
4003       else
4004         return 1;
4005     }
4006   else if (TOEND (sec2))
4007     return -1;
4008
4009 #undef TOEND
4010
4011   /* Sort by size, to put zero sized sections
4012      before others at the same address.  */
4013
4014   size1 = (sec1->flags & SEC_LOAD) ? sec1->size : 0;
4015   size2 = (sec2->flags & SEC_LOAD) ? sec2->size : 0;
4016
4017   if (size1 < size2)
4018     return -1;
4019   if (size1 > size2)
4020     return 1;
4021
4022   return sec1->target_index - sec2->target_index;
4023 }
4024
4025 /* Ian Lance Taylor writes:
4026
4027    We shouldn't be using % with a negative signed number.  That's just
4028    not good.  We have to make sure either that the number is not
4029    negative, or that the number has an unsigned type.  When the types
4030    are all the same size they wind up as unsigned.  When file_ptr is a
4031    larger signed type, the arithmetic winds up as signed long long,
4032    which is wrong.
4033
4034    What we're trying to say here is something like ``increase OFF by
4035    the least amount that will cause it to be equal to the VMA modulo
4036    the page size.''  */
4037 /* In other words, something like:
4038
4039    vma_offset = m->sections[0]->vma % bed->maxpagesize;
4040    off_offset = off % bed->maxpagesize;
4041    if (vma_offset < off_offset)
4042      adjustment = vma_offset + bed->maxpagesize - off_offset;
4043    else
4044      adjustment = vma_offset - off_offset;
4045
4046    which can can be collapsed into the expression below.  */
4047
4048 static file_ptr
4049 vma_page_aligned_bias (bfd_vma vma, ufile_ptr off, bfd_vma maxpagesize)
4050 {
4051   return ((vma - off) % maxpagesize);
4052 }
4053
4054 static void
4055 print_segment_map (const struct elf_segment_map *m)
4056 {
4057   unsigned int j;
4058   const char *pt = get_segment_type (m->p_type);
4059   char buf[32];
4060
4061   if (pt == NULL)
4062     {
4063       if (m->p_type >= PT_LOPROC && m->p_type <= PT_HIPROC)
4064         sprintf (buf, "LOPROC+%7.7x",
4065                  (unsigned int) (m->p_type - PT_LOPROC));
4066       else if (m->p_type >= PT_LOOS && m->p_type <= PT_HIOS)
4067         sprintf (buf, "LOOS+%7.7x",
4068                  (unsigned int) (m->p_type - PT_LOOS));
4069       else
4070         snprintf (buf, sizeof (buf), "%8.8x",
4071                   (unsigned int) m->p_type);
4072       pt = buf;
4073     }
4074   fprintf (stderr, "%s:", pt);
4075   for (j = 0; j < m->count; j++)
4076     fprintf (stderr, " %s", m->sections [j]->name);
4077   putc ('\n',stderr);
4078 }
4079
4080 /* Assign file positions to the sections based on the mapping from
4081    sections to segments.  This function also sets up some fields in
4082    the file header.  */
4083
4084 static bfd_boolean
4085 assign_file_positions_for_load_sections (bfd *abfd,
4086                                          struct bfd_link_info *link_info)
4087 {
4088   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4089   struct elf_segment_map *m;
4090   Elf_Internal_Phdr *phdrs;
4091   Elf_Internal_Phdr *p;
4092   file_ptr off;
4093   bfd_size_type maxpagesize;
4094   unsigned int alloc;
4095   unsigned int i, j;
4096
4097   if (link_info == NULL
4098       && !elf_modify_segment_map (abfd, link_info, FALSE))
4099     return FALSE;
4100
4101   alloc = 0;
4102   for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
4103     ++alloc;
4104
4105   elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
4106   elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
4107   elf_elfheader (abfd)->e_phnum = alloc;
4108
4109   if (elf_tdata (abfd)->program_header_size == (bfd_size_type) -1)
4110     elf_tdata (abfd)->program_header_size = alloc * bed->s->sizeof_phdr;
4111   else
4112     BFD_ASSERT (elf_tdata (abfd)->program_header_size
4113                 >= alloc * bed->s->sizeof_phdr);
4114
4115   if (alloc == 0)
4116     {
4117       elf_tdata (abfd)->next_file_pos = bed->s->sizeof_ehdr;
4118       return TRUE;
4119     }
4120
4121   phdrs = bfd_alloc2 (abfd, alloc, sizeof (Elf_Internal_Phdr));
4122   elf_tdata (abfd)->phdr = phdrs;
4123   if (phdrs == NULL)
4124     return FALSE;
4125
4126   maxpagesize = 1;
4127   if ((abfd->flags & D_PAGED) != 0)
4128     maxpagesize = bed->maxpagesize;
4129
4130   off = bed->s->sizeof_ehdr;
4131   off += alloc * bed->s->sizeof_phdr;
4132
4133   for (m = elf_tdata (abfd)->segment_map, p = phdrs, j = 0;
4134        m != NULL;
4135        m = m->next, p++, j++)
4136     {
4137       asection **secpp;
4138       bfd_vma off_adjust;
4139       bfd_boolean no_contents;
4140
4141       /* If elf_segment_map is not from map_sections_to_segments, the
4142          sections may not be correctly ordered.  NOTE: sorting should
4143          not be done to the PT_NOTE section of a corefile, which may
4144          contain several pseudo-sections artificially created by bfd.
4145          Sorting these pseudo-sections breaks things badly.  */
4146       if (m->count > 1
4147           && !(elf_elfheader (abfd)->e_type == ET_CORE
4148                && m->p_type == PT_NOTE))
4149         qsort (m->sections, (size_t) m->count, sizeof (asection *),
4150                elf_sort_sections);
4151
4152       /* An ELF segment (described by Elf_Internal_Phdr) may contain a
4153          number of sections with contents contributing to both p_filesz
4154          and p_memsz, followed by a number of sections with no contents
4155          that just contribute to p_memsz.  In this loop, OFF tracks next
4156          available file offset for PT_LOAD and PT_NOTE segments.  */
4157       p->p_type = m->p_type;
4158       p->p_flags = m->p_flags;
4159
4160       if (m->count == 0)
4161         p->p_vaddr = 0;
4162       else
4163         p->p_vaddr = m->sections[0]->vma - m->p_vaddr_offset;
4164
4165       if (m->p_paddr_valid)
4166         p->p_paddr = m->p_paddr;
4167       else if (m->count == 0)
4168         p->p_paddr = 0;
4169       else
4170         p->p_paddr = m->sections[0]->lma - m->p_vaddr_offset;
4171
4172       if (p->p_type == PT_LOAD
4173           && (abfd->flags & D_PAGED) != 0)
4174         {
4175           /* p_align in demand paged PT_LOAD segments effectively stores
4176              the maximum page size.  When copying an executable with
4177              objcopy, we set m->p_align from the input file.  Use this
4178              value for maxpagesize rather than bed->maxpagesize, which
4179              may be different.  Note that we use maxpagesize for PT_TLS
4180              segment alignment later in this function, so we are relying
4181              on at least one PT_LOAD segment appearing before a PT_TLS
4182              segment.  */
4183           if (m->p_align_valid)
4184             maxpagesize = m->p_align;
4185
4186           p->p_align = maxpagesize;
4187         }
4188       else if (m->p_align_valid)
4189         p->p_align = m->p_align;
4190       else if (m->count == 0)
4191         p->p_align = 1 << bed->s->log_file_align;
4192       else
4193         p->p_align = 0;
4194
4195       no_contents = FALSE;
4196       off_adjust = 0;
4197       if (p->p_type == PT_LOAD
4198           && m->count > 0)
4199         {
4200           bfd_size_type align;
4201           unsigned int align_power = 0;
4202
4203           if (m->p_align_valid)
4204             align = p->p_align;
4205           else
4206             {
4207               for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
4208                 {
4209                   unsigned int secalign;
4210
4211                   secalign = bfd_get_section_alignment (abfd, *secpp);
4212                   if (secalign > align_power)
4213                     align_power = secalign;
4214                 }
4215               align = (bfd_size_type) 1 << align_power;
4216               if (align < maxpagesize)
4217                 align = maxpagesize;
4218             }
4219
4220           for (i = 0; i < m->count; i++)
4221             if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
4222               /* If we aren't making room for this section, then
4223                  it must be SHT_NOBITS regardless of what we've
4224                  set via struct bfd_elf_special_section.  */
4225               elf_section_type (m->sections[i]) = SHT_NOBITS;
4226
4227           /* Find out whether this segment contains any loadable
4228              sections.  If the first section isn't loadable, the same
4229              holds for any other sections.  */
4230           i = 0;
4231           while (elf_section_type (m->sections[i]) == SHT_NOBITS)
4232             {
4233               /* If a segment starts with .tbss, we need to look
4234                  at the next section to decide whether the segment
4235                  has any loadable sections.  */
4236               if ((elf_section_flags (m->sections[i]) & SHF_TLS) == 0
4237                   || ++i >= m->count)
4238                 {
4239                   no_contents = TRUE;
4240                   break;
4241                 }
4242             }
4243
4244           off_adjust = vma_page_aligned_bias (m->sections[0]->vma, off, align);
4245           off += off_adjust;
4246           if (no_contents)
4247             {
4248               /* We shouldn't need to align the segment on disk since
4249                  the segment doesn't need file space, but the gABI
4250                  arguably requires the alignment and glibc ld.so
4251                  checks it.  So to comply with the alignment
4252                  requirement but not waste file space, we adjust
4253                  p_offset for just this segment.  (OFF_ADJUST is
4254                  subtracted from OFF later.)  This may put p_offset
4255                  past the end of file, but that shouldn't matter.  */
4256             }
4257           else
4258             off_adjust = 0;
4259         }
4260       /* Make sure the .dynamic section is the first section in the
4261          PT_DYNAMIC segment.  */
4262       else if (p->p_type == PT_DYNAMIC
4263                && m->count > 1
4264                && strcmp (m->sections[0]->name, ".dynamic") != 0)
4265         {
4266           _bfd_error_handler
4267             (_("%B: The first section in the PT_DYNAMIC segment is not the .dynamic section"),
4268              abfd);
4269           bfd_set_error (bfd_error_bad_value);
4270           return FALSE;
4271         }
4272       /* Set the note section type to SHT_NOTE.  */
4273       else if (p->p_type == PT_NOTE)
4274         for (i = 0; i < m->count; i++)
4275           elf_section_type (m->sections[i]) = SHT_NOTE;
4276
4277       p->p_offset = 0;
4278       p->p_filesz = 0;
4279       p->p_memsz = 0;
4280
4281       if (m->includes_filehdr)
4282         {
4283           if (!m->p_flags_valid)
4284             p->p_flags |= PF_R;
4285           p->p_filesz = bed->s->sizeof_ehdr;
4286           p->p_memsz = bed->s->sizeof_ehdr;
4287           if (m->count > 0)
4288             {
4289               BFD_ASSERT (p->p_type == PT_LOAD);
4290
4291               if (p->p_vaddr < (bfd_vma) off)
4292                 {
4293                   (*_bfd_error_handler)
4294                     (_("%B: Not enough room for program headers, try linking with -N"),
4295                      abfd);
4296                   bfd_set_error (bfd_error_bad_value);
4297                   return FALSE;
4298                 }
4299
4300               p->p_vaddr -= off;
4301               if (!m->p_paddr_valid)
4302                 p->p_paddr -= off;
4303             }
4304         }
4305
4306       if (m->includes_phdrs)
4307         {
4308           if (!m->p_flags_valid)
4309             p->p_flags |= PF_R;
4310
4311           if (!m->includes_filehdr)
4312             {
4313               p->p_offset = bed->s->sizeof_ehdr;
4314
4315               if (m->count > 0)
4316                 {
4317                   BFD_ASSERT (p->p_type == PT_LOAD);
4318                   p->p_vaddr -= off - p->p_offset;
4319                   if (!m->p_paddr_valid)
4320                     p->p_paddr -= off - p->p_offset;
4321                 }
4322             }
4323
4324           p->p_filesz += alloc * bed->s->sizeof_phdr;
4325           p->p_memsz += alloc * bed->s->sizeof_phdr;
4326         }
4327
4328       if (p->p_type == PT_LOAD
4329           || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
4330         {
4331           if (!m->includes_filehdr && !m->includes_phdrs)
4332             p->p_offset = off;
4333           else
4334             {
4335               file_ptr adjust;
4336
4337               adjust = off - (p->p_offset + p->p_filesz);
4338               if (!no_contents)
4339                 p->p_filesz += adjust;
4340               p->p_memsz += adjust;
4341             }
4342         }
4343
4344       /* Set up p_filesz, p_memsz, p_align and p_flags from the section
4345          maps.  Set filepos for sections in PT_LOAD segments, and in
4346          core files, for sections in PT_NOTE segments.
4347          assign_file_positions_for_non_load_sections will set filepos
4348          for other sections and update p_filesz for other segments.  */
4349       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
4350         {
4351           asection *sec;
4352           bfd_size_type align;
4353           Elf_Internal_Shdr *this_hdr;
4354
4355           sec = *secpp;
4356           this_hdr = &elf_section_data (sec)->this_hdr;
4357           align = (bfd_size_type) 1 << bfd_get_section_alignment (abfd, sec);
4358
4359           if (p->p_type == PT_LOAD
4360               || p->p_type == PT_TLS)
4361             {
4362               bfd_signed_vma adjust = sec->lma - (p->p_paddr + p->p_memsz);
4363
4364               if (this_hdr->sh_type != SHT_NOBITS
4365                   || ((this_hdr->sh_flags & SHF_ALLOC) != 0
4366                       && ((this_hdr->sh_flags & SHF_TLS) == 0
4367                           || p->p_type == PT_TLS)))
4368                 {
4369                   if (adjust < 0)
4370                     {
4371                       (*_bfd_error_handler)
4372                         (_("%B: section %A lma 0x%lx overlaps previous sections"),
4373                          abfd, sec, (unsigned long) sec->lma);
4374                       adjust = 0;
4375                     }
4376                   p->p_memsz += adjust;
4377
4378                   if (this_hdr->sh_type != SHT_NOBITS)
4379                     {
4380                       off += adjust;
4381                       p->p_filesz += adjust;
4382                     }
4383                 }
4384             }
4385
4386           if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
4387             {
4388               /* The section at i == 0 is the one that actually contains
4389                  everything.  */
4390               if (i == 0)
4391                 {
4392                   this_hdr->sh_offset = sec->filepos = off;
4393                   off += this_hdr->sh_size;
4394                   p->p_filesz = this_hdr->sh_size;
4395                   p->p_memsz = 0;
4396                   p->p_align = 1;
4397                 }
4398               else
4399                 {
4400                   /* The rest are fake sections that shouldn't be written.  */
4401                   sec->filepos = 0;
4402                   sec->size = 0;
4403                   sec->flags = 0;
4404                   continue;
4405                 }
4406             }
4407           else
4408             {
4409               if (p->p_type == PT_LOAD)
4410                 {
4411                   this_hdr->sh_offset = sec->filepos = off;
4412                   if (this_hdr->sh_type != SHT_NOBITS)
4413                     off += this_hdr->sh_size;
4414                 }
4415
4416               if (this_hdr->sh_type != SHT_NOBITS)
4417                 {
4418                   p->p_filesz += this_hdr->sh_size;
4419                   /* A load section without SHF_ALLOC is something like
4420                      a note section in a PT_NOTE segment.  These take
4421                      file space but are not loaded into memory.  */
4422                   if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
4423                     p->p_memsz += this_hdr->sh_size;
4424                 }
4425               else if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
4426                 {
4427                   if (p->p_type == PT_TLS)
4428                     p->p_memsz += this_hdr->sh_size;
4429
4430                   /* .tbss is special.  It doesn't contribute to p_memsz of
4431                      normal segments.  */
4432                   else if ((this_hdr->sh_flags & SHF_TLS) == 0)
4433                     p->p_memsz += this_hdr->sh_size;
4434                 }
4435
4436               if (align > p->p_align
4437                   && !m->p_align_valid
4438                   && (p->p_type != PT_LOAD
4439                       || (abfd->flags & D_PAGED) == 0))
4440                 p->p_align = align;
4441             }
4442
4443           if (!m->p_flags_valid)
4444             {
4445               p->p_flags |= PF_R;
4446               if ((this_hdr->sh_flags & SHF_EXECINSTR) != 0)
4447                 p->p_flags |= PF_X;
4448               if ((this_hdr->sh_flags & SHF_WRITE) != 0)
4449                 p->p_flags |= PF_W;
4450             }
4451         }
4452       off -= off_adjust;
4453
4454       /* Check that all sections are in a PT_LOAD segment.
4455          Don't check funky gdb generated core files.  */
4456       if (p->p_type == PT_LOAD && bfd_get_format (abfd) != bfd_core)
4457         for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
4458           {
4459             Elf_Internal_Shdr *this_hdr;
4460             asection *sec;
4461
4462             sec = *secpp;
4463             this_hdr = &(elf_section_data(sec)->this_hdr);
4464             if (this_hdr->sh_size != 0
4465                 && !ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, p))
4466               {
4467                 (*_bfd_error_handler)
4468                   (_("%B: section `%A' can't be allocated in segment %d"),
4469                    abfd, sec, j);
4470                 print_segment_map (m);
4471                 bfd_set_error (bfd_error_bad_value);
4472                 return FALSE;
4473               }
4474           }
4475     }
4476
4477   elf_tdata (abfd)->next_file_pos = off;
4478   return TRUE;
4479 }
4480
4481 /* Assign file positions for the other sections.  */
4482
4483 static bfd_boolean
4484 assign_file_positions_for_non_load_sections (bfd *abfd,
4485                                              struct bfd_link_info *link_info)
4486 {
4487   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4488   Elf_Internal_Shdr **i_shdrpp;
4489   Elf_Internal_Shdr **hdrpp;
4490   Elf_Internal_Phdr *phdrs;
4491   Elf_Internal_Phdr *p;
4492   struct elf_segment_map *m;
4493   bfd_vma filehdr_vaddr, filehdr_paddr;
4494   bfd_vma phdrs_vaddr, phdrs_paddr;
4495   file_ptr off;
4496   unsigned int num_sec;
4497   unsigned int i;
4498   unsigned int count;
4499
4500   i_shdrpp = elf_elfsections (abfd);
4501   num_sec = elf_numsections (abfd);
4502   off = elf_tdata (abfd)->next_file_pos;
4503   for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
4504     {
4505       struct elf_obj_tdata *tdata = elf_tdata (abfd);
4506       Elf_Internal_Shdr *hdr;
4507
4508       hdr = *hdrpp;
4509       if (hdr->bfd_section != NULL
4510           && (hdr->bfd_section->filepos != 0
4511               || (hdr->sh_type == SHT_NOBITS
4512                   && hdr->contents == NULL)))
4513         BFD_ASSERT (hdr->sh_offset == hdr->bfd_section->filepos);
4514       else if ((hdr->sh_flags & SHF_ALLOC) != 0)
4515         {
4516           if (hdr->sh_size != 0)
4517             ((*_bfd_error_handler)
4518              (_("%B: warning: allocated section `%s' not in segment"),
4519               abfd,
4520               (hdr->bfd_section == NULL
4521                ? "*unknown*"
4522                : hdr->bfd_section->name)));
4523           /* We don't need to page align empty sections.  */
4524           if ((abfd->flags & D_PAGED) != 0 && hdr->sh_size != 0)
4525             off += vma_page_aligned_bias (hdr->sh_addr, off,
4526                                           bed->maxpagesize);
4527           else
4528             off += vma_page_aligned_bias (hdr->sh_addr, off,
4529                                           hdr->sh_addralign);
4530           off = _bfd_elf_assign_file_position_for_section (hdr, off,
4531                                                            FALSE);
4532         }
4533       else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
4534                 && hdr->bfd_section == NULL)
4535                || hdr == i_shdrpp[tdata->symtab_section]
4536                || hdr == i_shdrpp[tdata->symtab_shndx_section]
4537                || hdr == i_shdrpp[tdata->strtab_section])
4538         hdr->sh_offset = -1;
4539       else
4540         off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4541     }
4542
4543   /* Now that we have set the section file positions, we can set up
4544      the file positions for the non PT_LOAD segments.  */
4545   count = 0;
4546   filehdr_vaddr = 0;
4547   filehdr_paddr = 0;
4548   phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
4549   phdrs_paddr = 0;
4550   phdrs = elf_tdata (abfd)->phdr;
4551   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
4552        m != NULL;
4553        m = m->next, p++)
4554     {
4555       ++count;
4556       if (p->p_type != PT_LOAD)
4557         continue;
4558
4559       if (m->includes_filehdr)
4560         {
4561           filehdr_vaddr = p->p_vaddr;
4562           filehdr_paddr = p->p_paddr;
4563         }
4564       if (m->includes_phdrs)
4565         {
4566           phdrs_vaddr = p->p_vaddr;
4567           phdrs_paddr = p->p_paddr;
4568           if (m->includes_filehdr)
4569             {
4570               phdrs_vaddr += bed->s->sizeof_ehdr;
4571               phdrs_paddr += bed->s->sizeof_ehdr;
4572             }
4573         }
4574     }
4575
4576   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
4577        m != NULL;
4578        m = m->next, p++)
4579     {
4580       if (m->count != 0)
4581         {
4582           if (p->p_type != PT_LOAD
4583               && (p->p_type != PT_NOTE
4584                   || bfd_get_format (abfd) != bfd_core))
4585             {
4586               Elf_Internal_Shdr *hdr;
4587               asection *sect;
4588
4589               BFD_ASSERT (!m->includes_filehdr && !m->includes_phdrs);
4590
4591               sect = m->sections[m->count - 1];
4592               hdr = &elf_section_data (sect)->this_hdr;
4593               p->p_filesz = sect->filepos - m->sections[0]->filepos;
4594               if (hdr->sh_type != SHT_NOBITS)
4595                 p->p_filesz += hdr->sh_size;
4596
4597               if (p->p_type == PT_GNU_RELRO)
4598                 {
4599                   /* When we get here, we are copying executable
4600                      or shared library. But we need to use the same
4601                      linker logic.  */
4602                   Elf_Internal_Phdr *lp;
4603
4604                   for (lp = phdrs; lp < phdrs + count; ++lp)
4605                     {
4606                       if (lp->p_type == PT_LOAD
4607                           && lp->p_paddr == p->p_paddr)
4608                         break;
4609                     }
4610           
4611                   if (lp < phdrs + count)
4612                     {
4613                       /* We should use p_size if it is valid since it
4614                          may contain the first few bytes of the next
4615                          SEC_ALLOC section.  */
4616                       if (m->p_size_valid)
4617                         p->p_filesz = m->p_size;
4618                       else
4619                         abort ();
4620                       p->p_vaddr = lp->p_vaddr;
4621                       p->p_offset = lp->p_offset;
4622                       p->p_memsz = p->p_filesz;
4623                       p->p_align = 1;
4624                     }
4625                   else
4626                     abort ();
4627                 }
4628               else
4629                 p->p_offset = m->sections[0]->filepos;
4630             }
4631         }
4632       else
4633         {
4634           if (m->includes_filehdr)
4635             {
4636               p->p_vaddr = filehdr_vaddr;
4637               if (! m->p_paddr_valid)
4638                 p->p_paddr = filehdr_paddr;
4639             }
4640           else if (m->includes_phdrs)
4641             {
4642               p->p_vaddr = phdrs_vaddr;
4643               if (! m->p_paddr_valid)
4644                 p->p_paddr = phdrs_paddr;
4645             }
4646           else if (p->p_type == PT_GNU_RELRO)
4647             {
4648               Elf_Internal_Phdr *lp;
4649
4650               for (lp = phdrs; lp < phdrs + count; ++lp)
4651                 {
4652                   if (lp->p_type == PT_LOAD
4653                       && lp->p_vaddr <= link_info->relro_end
4654                       && lp->p_vaddr >= link_info->relro_start
4655                       && (lp->p_vaddr + lp->p_filesz
4656                           >= link_info->relro_end))
4657                     break;
4658                 }
4659
4660               if (lp < phdrs + count
4661                   && link_info->relro_end > lp->p_vaddr)
4662                 {
4663                   p->p_vaddr = lp->p_vaddr;
4664                   p->p_paddr = lp->p_paddr;
4665                   p->p_offset = lp->p_offset;
4666                   p->p_filesz = link_info->relro_end - lp->p_vaddr;
4667                   p->p_memsz = p->p_filesz;
4668                   p->p_align = 1;
4669                   p->p_flags = (lp->p_flags & ~PF_W);
4670                 }
4671               else
4672                 {
4673                   memset (p, 0, sizeof *p);
4674                   p->p_type = PT_NULL;
4675                 }
4676             }
4677         }
4678     }
4679
4680   elf_tdata (abfd)->next_file_pos = off;
4681
4682   return TRUE;
4683 }
4684
4685 /* Work out the file positions of all the sections.  This is called by
4686    _bfd_elf_compute_section_file_positions.  All the section sizes and
4687    VMAs must be known before this is called.
4688
4689    Reloc sections come in two flavours: Those processed specially as
4690    "side-channel" data attached to a section to which they apply, and
4691    those that bfd doesn't process as relocations.  The latter sort are
4692    stored in a normal bfd section by bfd_section_from_shdr.   We don't
4693    consider the former sort here, unless they form part of the loadable
4694    image.  Reloc sections not assigned here will be handled later by
4695    assign_file_positions_for_relocs.
4696
4697    We also don't set the positions of the .symtab and .strtab here.  */
4698
4699 static bfd_boolean
4700 assign_file_positions_except_relocs (bfd *abfd,
4701                                      struct bfd_link_info *link_info)
4702 {
4703   struct elf_obj_tdata *tdata = elf_tdata (abfd);
4704   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
4705   file_ptr off;
4706   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4707
4708   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
4709       && bfd_get_format (abfd) != bfd_core)
4710     {
4711       Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
4712       unsigned int num_sec = elf_numsections (abfd);
4713       Elf_Internal_Shdr **hdrpp;
4714       unsigned int i;
4715
4716       /* Start after the ELF header.  */
4717       off = i_ehdrp->e_ehsize;
4718
4719       /* We are not creating an executable, which means that we are
4720          not creating a program header, and that the actual order of
4721          the sections in the file is unimportant.  */
4722       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
4723         {
4724           Elf_Internal_Shdr *hdr;
4725
4726           hdr = *hdrpp;
4727           if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
4728                && hdr->bfd_section == NULL)
4729               || i == tdata->symtab_section
4730               || i == tdata->symtab_shndx_section
4731               || i == tdata->strtab_section)
4732             {
4733               hdr->sh_offset = -1;
4734             }
4735           else
4736             off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4737         }
4738     }
4739   else
4740     {
4741       unsigned int alloc;
4742
4743       /* Assign file positions for the loaded sections based on the
4744          assignment of sections to segments.  */
4745       if (!assign_file_positions_for_load_sections (abfd, link_info))
4746         return FALSE;
4747
4748       /* And for non-load sections.  */
4749       if (!assign_file_positions_for_non_load_sections (abfd, link_info))
4750         return FALSE;
4751
4752       if (bed->elf_backend_modify_program_headers != NULL)
4753         {
4754           if (!(*bed->elf_backend_modify_program_headers) (abfd, link_info))
4755             return FALSE;
4756         }
4757
4758       /* Write out the program headers.  */
4759       alloc = tdata->program_header_size / bed->s->sizeof_phdr;
4760       if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
4761           || bed->s->write_out_phdrs (abfd, tdata->phdr, alloc) != 0)
4762         return FALSE;
4763
4764       off = tdata->next_file_pos;
4765     }
4766
4767   /* Place the section headers.  */
4768   off = align_file_position (off, 1 << bed->s->log_file_align);
4769   i_ehdrp->e_shoff = off;
4770   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
4771
4772   tdata->next_file_pos = off;
4773
4774   return TRUE;
4775 }
4776
4777 static bfd_boolean
4778 prep_headers (bfd *abfd)
4779 {
4780   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
4781   Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
4782   struct elf_strtab_hash *shstrtab;
4783   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4784
4785   i_ehdrp = elf_elfheader (abfd);
4786
4787   shstrtab = _bfd_elf_strtab_init ();
4788   if (shstrtab == NULL)
4789     return FALSE;
4790
4791   elf_shstrtab (abfd) = shstrtab;
4792
4793   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
4794   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
4795   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
4796   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
4797
4798   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
4799   i_ehdrp->e_ident[EI_DATA] =
4800     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
4801   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
4802
4803   if ((abfd->flags & DYNAMIC) != 0)
4804     i_ehdrp->e_type = ET_DYN;
4805   else if ((abfd->flags & EXEC_P) != 0)
4806     i_ehdrp->e_type = ET_EXEC;
4807   else if (bfd_get_format (abfd) == bfd_core)
4808     i_ehdrp->e_type = ET_CORE;
4809   else
4810     i_ehdrp->e_type = ET_REL;
4811
4812   switch (bfd_get_arch (abfd))
4813     {
4814     case bfd_arch_unknown:
4815       i_ehdrp->e_machine = EM_NONE;
4816       break;
4817
4818       /* There used to be a long list of cases here, each one setting
4819          e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
4820          in the corresponding bfd definition.  To avoid duplication,
4821          the switch was removed.  Machines that need special handling
4822          can generally do it in elf_backend_final_write_processing(),
4823          unless they need the information earlier than the final write.
4824          Such need can generally be supplied by replacing the tests for
4825          e_machine with the conditions used to determine it.  */
4826     default:
4827       i_ehdrp->e_machine = bed->elf_machine_code;
4828     }
4829
4830   i_ehdrp->e_version = bed->s->ev_current;
4831   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
4832
4833   /* No program header, for now.  */
4834   i_ehdrp->e_phoff = 0;
4835   i_ehdrp->e_phentsize = 0;
4836   i_ehdrp->e_phnum = 0;
4837
4838   /* Each bfd section is section header entry.  */
4839   i_ehdrp->e_entry = bfd_get_start_address (abfd);
4840   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
4841
4842   /* If we're building an executable, we'll need a program header table.  */
4843   if (abfd->flags & EXEC_P)
4844     /* It all happens later.  */
4845     ;
4846   else
4847     {
4848       i_ehdrp->e_phentsize = 0;
4849       i_phdrp = 0;
4850       i_ehdrp->e_phoff = 0;
4851     }
4852
4853   elf_tdata (abfd)->symtab_hdr.sh_name =
4854     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", FALSE);
4855   elf_tdata (abfd)->strtab_hdr.sh_name =
4856     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", FALSE);
4857   elf_tdata (abfd)->shstrtab_hdr.sh_name =
4858     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", FALSE);
4859   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4860       || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
4861       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
4862     return FALSE;
4863
4864   return TRUE;
4865 }
4866
4867 /* Assign file positions for all the reloc sections which are not part
4868    of the loadable file image.  */
4869
4870 void
4871 _bfd_elf_assign_file_positions_for_relocs (bfd *abfd)
4872 {
4873   file_ptr off;
4874   unsigned int i, num_sec;
4875   Elf_Internal_Shdr **shdrpp;
4876
4877   off = elf_tdata (abfd)->next_file_pos;
4878
4879   num_sec = elf_numsections (abfd);
4880   for (i = 1, shdrpp = elf_elfsections (abfd) + 1; i < num_sec; i++, shdrpp++)
4881     {
4882       Elf_Internal_Shdr *shdrp;
4883
4884       shdrp = *shdrpp;
4885       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
4886           && shdrp->sh_offset == -1)
4887         off = _bfd_elf_assign_file_position_for_section (shdrp, off, TRUE);
4888     }
4889
4890   elf_tdata (abfd)->next_file_pos = off;
4891 }
4892
4893 bfd_boolean
4894 _bfd_elf_write_object_contents (bfd *abfd)
4895 {
4896   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4897   Elf_Internal_Ehdr *i_ehdrp;
4898   Elf_Internal_Shdr **i_shdrp;
4899   bfd_boolean failed;
4900   unsigned int count, num_sec;
4901
4902   if (! abfd->output_has_begun
4903       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
4904     return FALSE;
4905
4906   i_shdrp = elf_elfsections (abfd);
4907   i_ehdrp = elf_elfheader (abfd);
4908
4909   failed = FALSE;
4910   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
4911   if (failed)
4912     return FALSE;
4913
4914   _bfd_elf_assign_file_positions_for_relocs (abfd);
4915
4916   /* After writing the headers, we need to write the sections too...  */
4917   num_sec = elf_numsections (abfd);
4918   for (count = 1; count < num_sec; count++)
4919     {
4920       if (bed->elf_backend_section_processing)
4921         (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
4922       if (i_shdrp[count]->contents)
4923         {
4924           bfd_size_type amt = i_shdrp[count]->sh_size;
4925
4926           if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
4927               || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
4928             return FALSE;
4929         }
4930     }
4931
4932   /* Write out the section header names.  */
4933   if (elf_shstrtab (abfd) != NULL
4934       && (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
4935           || !_bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd))))
4936     return FALSE;
4937
4938   if (bed->elf_backend_final_write_processing)
4939     (*bed->elf_backend_final_write_processing) (abfd,
4940                                                 elf_tdata (abfd)->linker);
4941
4942   if (!bed->s->write_shdrs_and_ehdr (abfd))
4943     return FALSE;
4944
4945   /* This is last since write_shdrs_and_ehdr can touch i_shdrp[0].  */
4946   if (elf_tdata (abfd)->after_write_object_contents)
4947     return (*elf_tdata (abfd)->after_write_object_contents) (abfd);
4948
4949   return TRUE;
4950 }
4951
4952 bfd_boolean
4953 _bfd_elf_write_corefile_contents (bfd *abfd)
4954 {
4955   /* Hopefully this can be done just like an object file.  */
4956   return _bfd_elf_write_object_contents (abfd);
4957 }
4958
4959 /* Given a section, search the header to find them.  */
4960
4961 unsigned int
4962 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
4963 {
4964   const struct elf_backend_data *bed;
4965   unsigned int index;
4966
4967   if (elf_section_data (asect) != NULL
4968       && elf_section_data (asect)->this_idx != 0)
4969     return elf_section_data (asect)->this_idx;
4970
4971   if (bfd_is_abs_section (asect))
4972     index = SHN_ABS;
4973   else if (bfd_is_com_section (asect))
4974     index = SHN_COMMON;
4975   else if (bfd_is_und_section (asect))
4976     index = SHN_UNDEF;
4977   else
4978     index = SHN_BAD;
4979
4980   bed = get_elf_backend_data (abfd);
4981   if (bed->elf_backend_section_from_bfd_section)
4982     {
4983       int retval = index;
4984
4985       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
4986         return retval;
4987     }
4988
4989   if (index == SHN_BAD)
4990     bfd_set_error (bfd_error_nonrepresentable_section);
4991
4992   return index;
4993 }
4994
4995 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
4996    on error.  */
4997
4998 int
4999 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
5000 {
5001   asymbol *asym_ptr = *asym_ptr_ptr;
5002   int idx;
5003   flagword flags = asym_ptr->flags;
5004
5005   /* When gas creates relocations against local labels, it creates its
5006      own symbol for the section, but does put the symbol into the
5007      symbol chain, so udata is 0.  When the linker is generating
5008      relocatable output, this section symbol may be for one of the
5009      input sections rather than the output section.  */
5010   if (asym_ptr->udata.i == 0
5011       && (flags & BSF_SECTION_SYM)
5012       && asym_ptr->section)
5013     {
5014       asection *sec;
5015       int indx;
5016
5017       sec = asym_ptr->section;
5018       if (sec->owner != abfd && sec->output_section != NULL)
5019         sec = sec->output_section;
5020       if (sec->owner == abfd
5021           && (indx = sec->index) < elf_num_section_syms (abfd)
5022           && elf_section_syms (abfd)[indx] != NULL)
5023         asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
5024     }
5025
5026   idx = asym_ptr->udata.i;
5027
5028   if (idx == 0)
5029     {
5030       /* This case can occur when using --strip-symbol on a symbol
5031          which is used in a relocation entry.  */
5032       (*_bfd_error_handler)
5033         (_("%B: symbol `%s' required but not present"),
5034          abfd, bfd_asymbol_name (asym_ptr));
5035       bfd_set_error (bfd_error_no_symbols);
5036       return -1;
5037     }
5038
5039 #if DEBUG & 4
5040   {
5041     fprintf (stderr,
5042              "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx%s\n",
5043              (long) asym_ptr, asym_ptr->name, idx, flags,
5044              elf_symbol_flags (flags));
5045     fflush (stderr);
5046   }
5047 #endif
5048
5049   return idx;
5050 }
5051
5052 /* Rewrite program header information.  */
5053
5054 static bfd_boolean
5055 rewrite_elf_program_header (bfd *ibfd, bfd *obfd)
5056 {
5057   Elf_Internal_Ehdr *iehdr;
5058   struct elf_segment_map *map;
5059   struct elf_segment_map *map_first;
5060   struct elf_segment_map **pointer_to_map;
5061   Elf_Internal_Phdr *segment;
5062   asection *section;
5063   unsigned int i;
5064   unsigned int num_segments;
5065   bfd_boolean phdr_included = FALSE;
5066   bfd_vma maxpagesize;
5067   struct elf_segment_map *phdr_adjust_seg = NULL;
5068   unsigned int phdr_adjust_num = 0;
5069   const struct elf_backend_data *bed;
5070
5071   bed = get_elf_backend_data (ibfd);
5072   iehdr = elf_elfheader (ibfd);
5073
5074   map_first = NULL;
5075   pointer_to_map = &map_first;
5076
5077   num_segments = elf_elfheader (ibfd)->e_phnum;
5078   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
5079
5080   /* Returns the end address of the segment + 1.  */
5081 #define SEGMENT_END(segment, start)                                     \
5082   (start + (segment->p_memsz > segment->p_filesz                        \
5083             ? segment->p_memsz : segment->p_filesz))
5084
5085 #define SECTION_SIZE(section, segment)                                  \
5086   (((section->flags & (SEC_HAS_CONTENTS | SEC_THREAD_LOCAL))            \
5087     != SEC_THREAD_LOCAL || segment->p_type == PT_TLS)                   \
5088    ? section->size : 0)
5089
5090   /* Returns TRUE if the given section is contained within
5091      the given segment.  VMA addresses are compared.  */
5092 #define IS_CONTAINED_BY_VMA(section, segment)                           \
5093   (section->vma >= segment->p_vaddr                                     \
5094    && (section->vma + SECTION_SIZE (section, segment)                   \
5095        <= (SEGMENT_END (segment, segment->p_vaddr))))
5096
5097   /* Returns TRUE if the given section is contained within
5098      the given segment.  LMA addresses are compared.  */
5099 #define IS_CONTAINED_BY_LMA(section, segment, base)                     \
5100   (section->lma >= base                                                 \
5101    && (section->lma + SECTION_SIZE (section, segment)                   \
5102        <= SEGMENT_END (segment, base)))
5103
5104   /* Handle PT_NOTE segment.  */
5105 #define IS_NOTE(p, s)                                                   \
5106   (p->p_type == PT_NOTE                                                 \
5107    && elf_section_type (s) == SHT_NOTE                                  \
5108    && (bfd_vma) s->filepos >= p->p_offset                               \
5109    && ((bfd_vma) s->filepos + s->size                                   \
5110        <= p->p_offset + p->p_filesz))
5111
5112   /* Special case: corefile "NOTE" section containing regs, prpsinfo
5113      etc.  */
5114 #define IS_COREFILE_NOTE(p, s)                                          \
5115   (IS_NOTE (p, s)                                                       \
5116    && bfd_get_format (ibfd) == bfd_core                                 \
5117    && s->vma == 0                                                       \
5118    && s->lma == 0)
5119
5120   /* The complicated case when p_vaddr is 0 is to handle the Solaris
5121      linker, which generates a PT_INTERP section with p_vaddr and
5122      p_memsz set to 0.  */
5123 #define IS_SOLARIS_PT_INTERP(p, s)                                      \
5124   (p->p_vaddr == 0                                                      \
5125    && p->p_paddr == 0                                                   \
5126    && p->p_memsz == 0                                                   \
5127    && p->p_filesz > 0                                                   \
5128    && (s->flags & SEC_HAS_CONTENTS) != 0                                \
5129    && s->size > 0                                                       \
5130    && (bfd_vma) s->filepos >= p->p_offset                               \
5131    && ((bfd_vma) s->filepos + s->size                                   \
5132        <= p->p_offset + p->p_filesz))
5133
5134   /* Decide if the given section should be included in the given segment.
5135      A section will be included if:
5136        1. It is within the address space of the segment -- we use the LMA
5137           if that is set for the segment and the VMA otherwise,
5138        2. It is an allocated section or a NOTE section in a PT_NOTE
5139           segment.         
5140        3. There is an output section associated with it,
5141        4. The section has not already been allocated to a previous segment.
5142        5. PT_GNU_STACK segments do not include any sections.
5143        6. PT_TLS segment includes only SHF_TLS sections.
5144        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.
5145        8. PT_DYNAMIC should not contain empty sections at the beginning
5146           (with the possible exception of .dynamic).  */
5147 #define IS_SECTION_IN_INPUT_SEGMENT(section, segment, bed)              \
5148   ((((segment->p_paddr                                                  \
5149       ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)        \
5150       : IS_CONTAINED_BY_VMA (section, segment))                         \
5151      && (section->flags & SEC_ALLOC) != 0)                              \
5152     || IS_NOTE (segment, section))                                      \
5153    && segment->p_type != PT_GNU_STACK                                   \
5154    && (segment->p_type != PT_TLS                                        \
5155        || (section->flags & SEC_THREAD_LOCAL))                          \
5156    && (segment->p_type == PT_LOAD                                       \
5157        || segment->p_type == PT_TLS                                     \
5158        || (section->flags & SEC_THREAD_LOCAL) == 0)                     \
5159    && (segment->p_type != PT_DYNAMIC                                    \
5160        || SECTION_SIZE (section, segment) > 0                           \
5161        || (segment->p_paddr                                             \
5162            ? segment->p_paddr != section->lma                           \
5163            : segment->p_vaddr != section->vma)                          \
5164        || (strcmp (bfd_get_section_name (ibfd, section), ".dynamic")    \
5165            == 0))                                                       \
5166    && !section->segment_mark)
5167
5168 /* If the output section of a section in the input segment is NULL,
5169    it is removed from the corresponding output segment.   */
5170 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)               \
5171   (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed)          \
5172    && section->output_section != NULL)
5173
5174   /* Returns TRUE iff seg1 starts after the end of seg2.  */
5175 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)                        \
5176   (seg1->field >= SEGMENT_END (seg2, seg2->field))
5177
5178   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
5179      their VMA address ranges and their LMA address ranges overlap.
5180      It is possible to have overlapping VMA ranges without overlapping LMA
5181      ranges.  RedBoot images for example can have both .data and .bss mapped
5182      to the same VMA range, but with the .data section mapped to a different
5183      LMA.  */
5184 #define SEGMENT_OVERLAPS(seg1, seg2)                                    \
5185   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)                     \
5186         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))                 \
5187    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)                     \
5188         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
5189
5190   /* Initialise the segment mark field.  */
5191   for (section = ibfd->sections; section != NULL; section = section->next)
5192     section->segment_mark = FALSE;
5193
5194   /* Scan through the segments specified in the program header
5195      of the input BFD.  For this first scan we look for overlaps
5196      in the loadable segments.  These can be created by weird
5197      parameters to objcopy.  Also, fix some solaris weirdness.  */
5198   for (i = 0, segment = elf_tdata (ibfd)->phdr;
5199        i < num_segments;
5200        i++, segment++)
5201     {
5202       unsigned int j;
5203       Elf_Internal_Phdr *segment2;
5204
5205       if (segment->p_type == PT_INTERP)
5206         for (section = ibfd->sections; section; section = section->next)
5207           if (IS_SOLARIS_PT_INTERP (segment, section))
5208             {
5209               /* Mininal change so that the normal section to segment
5210                  assignment code will work.  */
5211               segment->p_vaddr = section->vma;
5212               break;
5213             }
5214
5215       if (segment->p_type != PT_LOAD)
5216         {
5217           /* Remove PT_GNU_RELRO segment.  */
5218           if (segment->p_type == PT_GNU_RELRO)
5219             segment->p_type = PT_NULL;
5220           continue;
5221         }
5222
5223       /* Determine if this segment overlaps any previous segments.  */
5224       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2++)
5225         {
5226           bfd_signed_vma extra_length;
5227
5228           if (segment2->p_type != PT_LOAD
5229               || !SEGMENT_OVERLAPS (segment, segment2))
5230             continue;
5231
5232           /* Merge the two segments together.  */
5233           if (segment2->p_vaddr < segment->p_vaddr)
5234             {
5235               /* Extend SEGMENT2 to include SEGMENT and then delete
5236                  SEGMENT.  */
5237               extra_length = (SEGMENT_END (segment, segment->p_vaddr)
5238                               - SEGMENT_END (segment2, segment2->p_vaddr));
5239
5240               if (extra_length > 0)
5241                 {
5242                   segment2->p_memsz += extra_length;
5243                   segment2->p_filesz += extra_length;
5244                 }
5245
5246               segment->p_type = PT_NULL;
5247
5248               /* Since we have deleted P we must restart the outer loop.  */
5249               i = 0;
5250               segment = elf_tdata (ibfd)->phdr;
5251               break;
5252             }
5253           else
5254             {
5255               /* Extend SEGMENT to include SEGMENT2 and then delete
5256                  SEGMENT2.  */
5257               extra_length = (SEGMENT_END (segment2, segment2->p_vaddr)
5258                               - SEGMENT_END (segment, segment->p_vaddr));
5259
5260               if (extra_length > 0)
5261                 {
5262                   segment->p_memsz += extra_length;
5263                   segment->p_filesz += extra_length;
5264                 }
5265
5266               segment2->p_type = PT_NULL;
5267             }
5268         }
5269     }
5270
5271   /* The second scan attempts to assign sections to segments.  */
5272   for (i = 0, segment = elf_tdata (ibfd)->phdr;
5273        i < num_segments;
5274        i++, segment++)
5275     {
5276       unsigned int section_count;
5277       asection **sections;
5278       asection *output_section;
5279       unsigned int isec;
5280       bfd_vma matching_lma;
5281       bfd_vma suggested_lma;
5282       unsigned int j;
5283       bfd_size_type amt;
5284       asection *first_section;
5285       bfd_boolean first_matching_lma;
5286       bfd_boolean first_suggested_lma;
5287
5288       if (segment->p_type == PT_NULL)
5289         continue;
5290
5291       first_section = NULL;
5292       /* Compute how many sections might be placed into this segment.  */
5293       for (section = ibfd->sections, section_count = 0;
5294            section != NULL;
5295            section = section->next)
5296         {
5297           /* Find the first section in the input segment, which may be
5298              removed from the corresponding output segment.   */
5299           if (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed))
5300             {
5301               if (first_section == NULL)
5302                 first_section = section;
5303               if (section->output_section != NULL)
5304                 ++section_count;
5305             }
5306         }
5307
5308       /* Allocate a segment map big enough to contain
5309          all of the sections we have selected.  */
5310       amt = sizeof (struct elf_segment_map);
5311       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
5312       map = bfd_zalloc (obfd, amt);
5313       if (map == NULL)
5314         return FALSE;
5315
5316       /* Initialise the fields of the segment map.  Default to
5317          using the physical address of the segment in the input BFD.  */
5318       map->next = NULL;
5319       map->p_type = segment->p_type;
5320       map->p_flags = segment->p_flags;
5321       map->p_flags_valid = 1;
5322
5323       /* If the first section in the input segment is removed, there is
5324          no need to preserve segment physical address in the corresponding
5325          output segment.  */
5326       if (!first_section || first_section->output_section != NULL)
5327         {
5328           map->p_paddr = segment->p_paddr;
5329           map->p_paddr_valid = 1;
5330         }
5331
5332       /* Determine if this segment contains the ELF file header
5333          and if it contains the program headers themselves.  */
5334       map->includes_filehdr = (segment->p_offset == 0
5335                                && segment->p_filesz >= iehdr->e_ehsize);
5336       map->includes_phdrs = 0;
5337
5338       if (!phdr_included || segment->p_type != PT_LOAD)
5339         {
5340           map->includes_phdrs =
5341             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
5342              && (segment->p_offset + segment->p_filesz
5343                  >= ((bfd_vma) iehdr->e_phoff
5344                      + iehdr->e_phnum * iehdr->e_phentsize)));
5345
5346           if (segment->p_type == PT_LOAD && map->includes_phdrs)
5347             phdr_included = TRUE;
5348         }
5349
5350       if (section_count == 0)
5351         {
5352           /* Special segments, such as the PT_PHDR segment, may contain
5353              no sections, but ordinary, loadable segments should contain
5354              something.  They are allowed by the ELF spec however, so only
5355              a warning is produced.  */
5356           if (segment->p_type == PT_LOAD)
5357             (*_bfd_error_handler) (_("%B: warning: Empty loadable segment"
5358                                      " detected, is this intentional ?\n"),
5359                                    ibfd);
5360
5361           map->count = 0;
5362           *pointer_to_map = map;
5363           pointer_to_map = &map->next;
5364
5365           continue;
5366         }
5367
5368       /* Now scan the sections in the input BFD again and attempt
5369          to add their corresponding output sections to the segment map.
5370          The problem here is how to handle an output section which has
5371          been moved (ie had its LMA changed).  There are four possibilities:
5372
5373          1. None of the sections have been moved.
5374             In this case we can continue to use the segment LMA from the
5375             input BFD.
5376
5377          2. All of the sections have been moved by the same amount.
5378             In this case we can change the segment's LMA to match the LMA
5379             of the first section.
5380
5381          3. Some of the sections have been moved, others have not.
5382             In this case those sections which have not been moved can be
5383             placed in the current segment which will have to have its size,
5384             and possibly its LMA changed, and a new segment or segments will
5385             have to be created to contain the other sections.
5386
5387          4. The sections have been moved, but not by the same amount.
5388             In this case we can change the segment's LMA to match the LMA
5389             of the first section and we will have to create a new segment
5390             or segments to contain the other sections.
5391
5392          In order to save time, we allocate an array to hold the section
5393          pointers that we are interested in.  As these sections get assigned
5394          to a segment, they are removed from this array.  */
5395
5396       /* Gcc 2.96 miscompiles this code on mips. Don't do casting here
5397          to work around this long long bug.  */
5398       sections = bfd_malloc2 (section_count, sizeof (asection *));
5399       if (sections == NULL)
5400         return FALSE;
5401
5402       /* Step One: Scan for segment vs section LMA conflicts.
5403          Also add the sections to the section array allocated above.
5404          Also add the sections to the current segment.  In the common
5405          case, where the sections have not been moved, this means that
5406          we have completely filled the segment, and there is nothing
5407          more to do.  */
5408       isec = 0;
5409       matching_lma = 0;
5410       suggested_lma = 0;
5411       first_matching_lma = TRUE;
5412       first_suggested_lma = TRUE;
5413
5414       for (section = ibfd->sections;
5415            section != NULL;
5416            section = section->next)
5417         if (section == first_section)
5418           break;
5419
5420       for (j = 0; section != NULL; section = section->next)
5421         {
5422           if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
5423             {
5424               output_section = section->output_section;
5425
5426               sections[j++] = section;
5427
5428               /* The Solaris native linker always sets p_paddr to 0.
5429                  We try to catch that case here, and set it to the
5430                  correct value.  Note - some backends require that
5431                  p_paddr be left as zero.  */
5432               if (segment->p_paddr == 0
5433                   && segment->p_vaddr != 0
5434                   && !bed->want_p_paddr_set_to_zero
5435                   && isec == 0
5436                   && output_section->lma != 0
5437                   && output_section->vma == (segment->p_vaddr
5438                                              + (map->includes_filehdr
5439                                                 ? iehdr->e_ehsize
5440                                                 : 0)
5441                                              + (map->includes_phdrs
5442                                                 ? (iehdr->e_phnum
5443                                                    * iehdr->e_phentsize)
5444                                                 : 0)))
5445                 map->p_paddr = segment->p_vaddr;
5446
5447               /* Match up the physical address of the segment with the
5448                  LMA address of the output section.  */
5449               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
5450                   || IS_COREFILE_NOTE (segment, section)
5451                   || (bed->want_p_paddr_set_to_zero
5452                       && IS_CONTAINED_BY_VMA (output_section, segment)))
5453                 {
5454                   if (first_matching_lma || output_section->lma < matching_lma)
5455                     {
5456                       matching_lma = output_section->lma;
5457                       first_matching_lma = FALSE;
5458                     }
5459
5460                   /* We assume that if the section fits within the segment
5461                      then it does not overlap any other section within that
5462                      segment.  */
5463                   map->sections[isec++] = output_section;
5464                 }
5465               else if (first_suggested_lma)
5466                 {
5467                   suggested_lma = output_section->lma;
5468                   first_suggested_lma = FALSE;
5469                 }
5470
5471               if (j == section_count)
5472                 break;
5473             }
5474         }
5475
5476       BFD_ASSERT (j == section_count);
5477
5478       /* Step Two: Adjust the physical address of the current segment,
5479          if necessary.  */
5480       if (isec == section_count)
5481         {
5482           /* All of the sections fitted within the segment as currently
5483              specified.  This is the default case.  Add the segment to
5484              the list of built segments and carry on to process the next
5485              program header in the input BFD.  */
5486           map->count = section_count;
5487           *pointer_to_map = map;
5488           pointer_to_map = &map->next;
5489
5490           if (!bed->want_p_paddr_set_to_zero
5491               && matching_lma != map->p_paddr
5492               && !map->includes_filehdr && !map->includes_phdrs)
5493             /* There is some padding before the first section in the
5494                segment.  So, we must account for that in the output
5495                segment's vma.  */
5496             map->p_vaddr_offset = matching_lma - map->p_paddr;
5497
5498           free (sections);
5499           continue;
5500         }
5501       else
5502         {
5503           if (!first_matching_lma)
5504             {
5505               /* At least one section fits inside the current segment.
5506                  Keep it, but modify its physical address to match the
5507                  LMA of the first section that fitted.  */
5508               map->p_paddr = matching_lma;
5509             }
5510           else
5511             {
5512               /* None of the sections fitted inside the current segment.
5513                  Change the current segment's physical address to match
5514                  the LMA of the first section.  */
5515               map->p_paddr = suggested_lma;
5516             }
5517
5518           /* Offset the segment physical address from the lma
5519              to allow for space taken up by elf headers.  */
5520           if (map->includes_filehdr)
5521             map->p_paddr -= iehdr->e_ehsize;
5522
5523           if (map->includes_phdrs)
5524             {
5525               map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
5526
5527               /* iehdr->e_phnum is just an estimate of the number
5528                  of program headers that we will need.  Make a note
5529                  here of the number we used and the segment we chose
5530                  to hold these headers, so that we can adjust the
5531                  offset when we know the correct value.  */
5532               phdr_adjust_num = iehdr->e_phnum;
5533               phdr_adjust_seg = map;
5534             }
5535         }
5536
5537       /* Step Three: Loop over the sections again, this time assigning
5538          those that fit to the current segment and removing them from the
5539          sections array; but making sure not to leave large gaps.  Once all
5540          possible sections have been assigned to the current segment it is
5541          added to the list of built segments and if sections still remain
5542          to be assigned, a new segment is constructed before repeating
5543          the loop.  */
5544       isec = 0;
5545       do
5546         {
5547           map->count = 0;
5548           suggested_lma = 0;
5549           first_suggested_lma = TRUE;
5550
5551           /* Fill the current segment with sections that fit.  */
5552           for (j = 0; j < section_count; j++)
5553             {
5554               section = sections[j];
5555
5556               if (section == NULL)
5557                 continue;
5558
5559               output_section = section->output_section;
5560
5561               BFD_ASSERT (output_section != NULL);
5562
5563               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
5564                   || IS_COREFILE_NOTE (segment, section))
5565                 {
5566                   if (map->count == 0)
5567                     {
5568                       /* If the first section in a segment does not start at
5569                          the beginning of the segment, then something is
5570                          wrong.  */
5571                       if (output_section->lma
5572                           != (map->p_paddr
5573                               + (map->includes_filehdr ? iehdr->e_ehsize : 0)
5574                               + (map->includes_phdrs
5575                                  ? iehdr->e_phnum * iehdr->e_phentsize
5576                                  : 0)))
5577                         abort ();
5578                     }
5579                   else
5580                     {
5581                       asection *prev_sec;
5582
5583                       prev_sec = map->sections[map->count - 1];
5584
5585                       /* If the gap between the end of the previous section
5586                          and the start of this section is more than
5587                          maxpagesize then we need to start a new segment.  */
5588                       if ((BFD_ALIGN (prev_sec->lma + prev_sec->size,
5589                                       maxpagesize)
5590                            < BFD_ALIGN (output_section->lma, maxpagesize))
5591                           || (prev_sec->lma + prev_sec->size
5592                               > output_section->lma))
5593                         {
5594                           if (first_suggested_lma)
5595                             {
5596                               suggested_lma = output_section->lma;
5597                               first_suggested_lma = FALSE;
5598                             }
5599
5600                           continue;
5601                         }
5602                     }
5603
5604                   map->sections[map->count++] = output_section;
5605                   ++isec;
5606                   sections[j] = NULL;
5607                   section->segment_mark = TRUE;
5608                 }
5609               else if (first_suggested_lma)
5610                 {
5611                   suggested_lma = output_section->lma;
5612                   first_suggested_lma = FALSE;
5613                 }
5614             }
5615
5616           BFD_ASSERT (map->count > 0);
5617
5618           /* Add the current segment to the list of built segments.  */
5619           *pointer_to_map = map;
5620           pointer_to_map = &map->next;
5621
5622           if (isec < section_count)
5623             {
5624               /* We still have not allocated all of the sections to
5625                  segments.  Create a new segment here, initialise it
5626                  and carry on looping.  */
5627               amt = sizeof (struct elf_segment_map);
5628               amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
5629               map = bfd_alloc (obfd, amt);
5630               if (map == NULL)
5631                 {
5632                   free (sections);
5633                   return FALSE;
5634                 }
5635
5636               /* Initialise the fields of the segment map.  Set the physical
5637                  physical address to the LMA of the first section that has
5638                  not yet been assigned.  */
5639               map->next = NULL;
5640               map->p_type = segment->p_type;
5641               map->p_flags = segment->p_flags;
5642               map->p_flags_valid = 1;
5643               map->p_paddr = suggested_lma;
5644               map->p_paddr_valid = 1;
5645               map->includes_filehdr = 0;
5646               map->includes_phdrs = 0;
5647             }
5648         }
5649       while (isec < section_count);
5650
5651       free (sections);
5652     }
5653
5654   /* The Solaris linker creates program headers in which all the
5655      p_paddr fields are zero.  When we try to objcopy or strip such a
5656      file, we get confused.  Check for this case, and if we find it
5657      reset the p_paddr_valid fields.  */
5658   for (map = map_first; map != NULL; map = map->next)
5659     if (map->p_paddr != 0)
5660       break;
5661   if (map == NULL)
5662     for (map = map_first; map != NULL; map = map->next)
5663       map->p_paddr_valid = 0;
5664
5665   elf_tdata (obfd)->segment_map = map_first;
5666
5667   /* If we had to estimate the number of program headers that were
5668      going to be needed, then check our estimate now and adjust
5669      the offset if necessary.  */
5670   if (phdr_adjust_seg != NULL)
5671     {
5672       unsigned int count;
5673
5674       for (count = 0, map = map_first; map != NULL; map = map->next)
5675         count++;
5676
5677       if (count > phdr_adjust_num)
5678         phdr_adjust_seg->p_paddr
5679           -= (count - phdr_adjust_num) * iehdr->e_phentsize;
5680     }
5681
5682 #undef SEGMENT_END
5683 #undef SECTION_SIZE
5684 #undef IS_CONTAINED_BY_VMA
5685 #undef IS_CONTAINED_BY_LMA
5686 #undef IS_NOTE
5687 #undef IS_COREFILE_NOTE
5688 #undef IS_SOLARIS_PT_INTERP
5689 #undef IS_SECTION_IN_INPUT_SEGMENT
5690 #undef INCLUDE_SECTION_IN_SEGMENT
5691 #undef SEGMENT_AFTER_SEGMENT
5692 #undef SEGMENT_OVERLAPS
5693   return TRUE;
5694 }
5695
5696 /* Copy ELF program header information.  */
5697
5698 static bfd_boolean
5699 copy_elf_program_header (bfd *ibfd, bfd *obfd)
5700 {
5701   Elf_Internal_Ehdr *iehdr;
5702   struct elf_segment_map *map;
5703   struct elf_segment_map *map_first;
5704   struct elf_segment_map **pointer_to_map;
5705   Elf_Internal_Phdr *segment;
5706   unsigned int i;
5707   unsigned int num_segments;
5708   bfd_boolean phdr_included = FALSE;
5709
5710   iehdr = elf_elfheader (ibfd);
5711
5712   map_first = NULL;
5713   pointer_to_map = &map_first;
5714
5715   num_segments = elf_elfheader (ibfd)->e_phnum;
5716   for (i = 0, segment = elf_tdata (ibfd)->phdr;
5717        i < num_segments;
5718        i++, segment++)
5719     {
5720       asection *section;
5721       unsigned int section_count;
5722       bfd_size_type amt;
5723       Elf_Internal_Shdr *this_hdr;
5724       asection *first_section = NULL;
5725       asection *lowest_section = NULL;
5726
5727       /* Compute how many sections are in this segment.  */
5728       for (section = ibfd->sections, section_count = 0;
5729            section != NULL;
5730            section = section->next)
5731         {
5732           this_hdr = &(elf_section_data(section)->this_hdr);
5733           if (ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, segment))
5734             {
5735               if (!first_section)
5736                 first_section = lowest_section = section;
5737               if (section->lma < lowest_section->lma)
5738                 lowest_section = section;
5739               section_count++;
5740             }
5741         }
5742
5743       /* Allocate a segment map big enough to contain
5744          all of the sections we have selected.  */
5745       amt = sizeof (struct elf_segment_map);
5746       if (section_count != 0)
5747         amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
5748       map = bfd_zalloc (obfd, amt);
5749       if (map == NULL)
5750         return FALSE;
5751
5752       /* Initialize the fields of the output segment map with the
5753          input segment.  */
5754       map->next = NULL;
5755       map->p_type = segment->p_type;
5756       map->p_flags = segment->p_flags;
5757       map->p_flags_valid = 1;
5758       map->p_paddr = segment->p_paddr;
5759       map->p_paddr_valid = 1;
5760       map->p_align = segment->p_align;
5761       map->p_align_valid = 1;
5762       map->p_vaddr_offset = 0;
5763
5764       if (map->p_type == PT_GNU_RELRO
5765           && segment->p_filesz == segment->p_memsz)
5766         {
5767           /* The PT_GNU_RELRO segment may contain the first a few
5768              bytes in the .got.plt section even if the whole .got.plt
5769              section isn't in the PT_GNU_RELRO segment.  We won't
5770              change the size of the PT_GNU_RELRO segment.  */
5771           map->p_size = segment->p_filesz;
5772           map->p_size_valid = 1;
5773         }
5774
5775       /* Determine if this segment contains the ELF file header
5776          and if it contains the program headers themselves.  */
5777       map->includes_filehdr = (segment->p_offset == 0
5778                                && segment->p_filesz >= iehdr->e_ehsize);
5779
5780       map->includes_phdrs = 0;
5781       if (! phdr_included || segment->p_type != PT_LOAD)
5782         {
5783           map->includes_phdrs =
5784             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
5785              && (segment->p_offset + segment->p_filesz
5786                  >= ((bfd_vma) iehdr->e_phoff
5787                      + iehdr->e_phnum * iehdr->e_phentsize)));
5788
5789           if (segment->p_type == PT_LOAD && map->includes_phdrs)
5790             phdr_included = TRUE;
5791         }
5792
5793       if (!map->includes_phdrs && !map->includes_filehdr)
5794         /* There is some other padding before the first section.  */
5795         map->p_vaddr_offset = ((lowest_section ? lowest_section->lma : 0)
5796                                - segment->p_paddr);
5797
5798       if (section_count != 0)
5799         {
5800           unsigned int isec = 0;
5801
5802           for (section = first_section;
5803                section != NULL;
5804                section = section->next)
5805             {
5806               this_hdr = &(elf_section_data(section)->this_hdr);
5807               if (ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, segment))
5808                 {
5809                   map->sections[isec++] = section->output_section;
5810                   if (isec == section_count)
5811                     break;
5812                 }
5813             }
5814         }
5815
5816       map->count = section_count;
5817       *pointer_to_map = map;
5818       pointer_to_map = &map->next;
5819     }
5820
5821   elf_tdata (obfd)->segment_map = map_first;
5822   return TRUE;
5823 }
5824
5825 /* Copy private BFD data.  This copies or rewrites ELF program header
5826    information.  */
5827
5828 static bfd_boolean
5829 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
5830 {
5831   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
5832       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
5833     return TRUE;
5834
5835   if (elf_tdata (ibfd)->phdr == NULL)
5836     return TRUE;
5837
5838   if (ibfd->xvec == obfd->xvec)
5839     {
5840       /* Check to see if any sections in the input BFD
5841          covered by ELF program header have changed.  */
5842       Elf_Internal_Phdr *segment;
5843       asection *section, *osec;
5844       unsigned int i, num_segments;
5845       Elf_Internal_Shdr *this_hdr;
5846       const struct elf_backend_data *bed;
5847
5848       bed = get_elf_backend_data (ibfd);
5849
5850       /* Regenerate the segment map if p_paddr is set to 0.  */
5851       if (bed->want_p_paddr_set_to_zero)
5852         goto rewrite;
5853
5854       /* Initialize the segment mark field.  */
5855       for (section = obfd->sections; section != NULL;
5856            section = section->next)
5857         section->segment_mark = FALSE;
5858
5859       num_segments = elf_elfheader (ibfd)->e_phnum;
5860       for (i = 0, segment = elf_tdata (ibfd)->phdr;
5861            i < num_segments;
5862            i++, segment++)
5863         {
5864           /* PR binutils/3535.  The Solaris linker always sets the p_paddr
5865              and p_memsz fields of special segments (DYNAMIC, INTERP) to 0
5866              which severly confuses things, so always regenerate the segment
5867              map in this case.  */
5868           if (segment->p_paddr == 0
5869               && segment->p_memsz == 0
5870               && (segment->p_type == PT_INTERP || segment->p_type == PT_DYNAMIC))
5871             goto rewrite;
5872
5873           for (section = ibfd->sections;
5874                section != NULL; section = section->next)
5875             {
5876               /* We mark the output section so that we know it comes
5877                  from the input BFD.  */
5878               osec = section->output_section;
5879               if (osec)
5880                 osec->segment_mark = TRUE;
5881
5882               /* Check if this section is covered by the segment.  */
5883               this_hdr = &(elf_section_data(section)->this_hdr);
5884               if (ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, segment))
5885                 {
5886                   /* FIXME: Check if its output section is changed or
5887                      removed.  What else do we need to check?  */
5888                   if (osec == NULL
5889                       || section->flags != osec->flags
5890                       || section->lma != osec->lma
5891                       || section->vma != osec->vma
5892                       || section->size != osec->size
5893                       || section->rawsize != osec->rawsize
5894                       || section->alignment_power != osec->alignment_power)
5895                     goto rewrite;
5896                 }
5897             }
5898         }
5899
5900       /* Check to see if any output section do not come from the
5901          input BFD.  */
5902       for (section = obfd->sections; section != NULL;
5903            section = section->next)
5904         {
5905           if (section->segment_mark == FALSE)
5906             goto rewrite;
5907           else
5908             section->segment_mark = FALSE;
5909         }
5910
5911       return copy_elf_program_header (ibfd, obfd);
5912     }
5913
5914 rewrite:
5915   return rewrite_elf_program_header (ibfd, obfd);
5916 }
5917
5918 /* Initialize private output section information from input section.  */
5919
5920 bfd_boolean
5921 _bfd_elf_init_private_section_data (bfd *ibfd,
5922                                     asection *isec,
5923                                     bfd *obfd,
5924                                     asection *osec,
5925                                     struct bfd_link_info *link_info)
5926
5927 {
5928   Elf_Internal_Shdr *ihdr, *ohdr;
5929   bfd_boolean need_group = link_info == NULL || link_info->relocatable;
5930
5931   if (ibfd->xvec->flavour != bfd_target_elf_flavour
5932       || obfd->xvec->flavour != bfd_target_elf_flavour)
5933     return TRUE;
5934
5935   /* Don't copy the output ELF section type from input if the
5936      output BFD section flags have been set to something different.
5937      elf_fake_sections will set ELF section type based on BFD
5938      section flags.  */
5939   if (elf_section_type (osec) == SHT_NULL
5940       && (osec->flags == isec->flags || !osec->flags))
5941     elf_section_type (osec) = elf_section_type (isec);
5942
5943   /* FIXME: Is this correct for all OS/PROC specific flags?  */
5944   elf_section_flags (osec) |= (elf_section_flags (isec)
5945                                & (SHF_MASKOS | SHF_MASKPROC));
5946
5947   /* Set things up for objcopy and relocatable link.  The output
5948      SHT_GROUP section will have its elf_next_in_group pointing back
5949      to the input group members.  Ignore linker created group section.
5950      See elfNN_ia64_object_p in elfxx-ia64.c.  */
5951   if (need_group)
5952     {
5953       if (elf_sec_group (isec) == NULL
5954           || (elf_sec_group (isec)->flags & SEC_LINKER_CREATED) == 0)
5955         {
5956           if (elf_section_flags (isec) & SHF_GROUP)
5957             elf_section_flags (osec) |= SHF_GROUP;
5958           elf_next_in_group (osec) = elf_next_in_group (isec);
5959           elf_group_name (osec) = elf_group_name (isec);
5960         }
5961     }
5962
5963   ihdr = &elf_section_data (isec)->this_hdr;
5964
5965   /* We need to handle elf_linked_to_section for SHF_LINK_ORDER. We
5966      don't use the output section of the linked-to section since it
5967      may be NULL at this point.  */
5968   if ((ihdr->sh_flags & SHF_LINK_ORDER) != 0)
5969     {
5970       ohdr = &elf_section_data (osec)->this_hdr;
5971       ohdr->sh_flags |= SHF_LINK_ORDER;
5972       elf_linked_to_section (osec) = elf_linked_to_section (isec);
5973     }
5974
5975   osec->use_rela_p = isec->use_rela_p;
5976
5977   return TRUE;
5978 }
5979
5980 /* Copy private section information.  This copies over the entsize
5981    field, and sometimes the info field.  */
5982
5983 bfd_boolean
5984 _bfd_elf_copy_private_section_data (bfd *ibfd,
5985                                     asection *isec,
5986                                     bfd *obfd,
5987                                     asection *osec)
5988 {
5989   Elf_Internal_Shdr *ihdr, *ohdr;
5990
5991   if (ibfd->xvec->flavour != bfd_target_elf_flavour
5992       || obfd->xvec->flavour != bfd_target_elf_flavour)
5993     return TRUE;
5994
5995   ihdr = &elf_section_data (isec)->this_hdr;
5996   ohdr = &elf_section_data (osec)->this_hdr;
5997
5998   ohdr->sh_entsize = ihdr->sh_entsize;
5999
6000   if (ihdr->sh_type == SHT_SYMTAB
6001       || ihdr->sh_type == SHT_DYNSYM
6002       || ihdr->sh_type == SHT_GNU_verneed
6003       || ihdr->sh_type == SHT_GNU_verdef)
6004     ohdr->sh_info = ihdr->sh_info;
6005
6006   return _bfd_elf_init_private_section_data (ibfd, isec, obfd, osec,
6007                                              NULL);
6008 }
6009
6010 /* Copy private header information.  */
6011
6012 bfd_boolean
6013 _bfd_elf_copy_private_header_data (bfd *ibfd, bfd *obfd)
6014 {
6015   asection *isec;
6016
6017   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
6018       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
6019     return TRUE;
6020
6021   /* Copy over private BFD data if it has not already been copied.
6022      This must be done here, rather than in the copy_private_bfd_data
6023      entry point, because the latter is called after the section
6024      contents have been set, which means that the program headers have
6025      already been worked out.  */
6026   if (elf_tdata (obfd)->segment_map == NULL && elf_tdata (ibfd)->phdr != NULL)
6027     {
6028       if (! copy_private_bfd_data (ibfd, obfd))
6029         return FALSE;
6030     }
6031
6032   /* _bfd_elf_copy_private_section_data copied over the SHF_GROUP flag
6033      but this might be wrong if we deleted the group section.  */
6034   for (isec = ibfd->sections; isec != NULL; isec = isec->next)
6035     if (elf_section_type (isec) == SHT_GROUP
6036         && isec->output_section == NULL)
6037       {
6038         asection *first = elf_next_in_group (isec);
6039         asection *s = first;
6040         while (s != NULL)
6041           {
6042             if (s->output_section != NULL)
6043               {
6044                 elf_section_flags (s->output_section) &= ~SHF_GROUP;
6045                 elf_group_name (s->output_section) = NULL;
6046               }
6047             s = elf_next_in_group (s);
6048             if (s == first)
6049               break;
6050           }
6051       }
6052
6053   return TRUE;
6054 }
6055
6056 /* Copy private symbol information.  If this symbol is in a section
6057    which we did not map into a BFD section, try to map the section
6058    index correctly.  We use special macro definitions for the mapped
6059    section indices; these definitions are interpreted by the
6060    swap_out_syms function.  */
6061
6062 #define MAP_ONESYMTAB (SHN_HIOS + 1)
6063 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
6064 #define MAP_STRTAB    (SHN_HIOS + 3)
6065 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
6066 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
6067
6068 bfd_boolean
6069 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
6070                                    asymbol *isymarg,
6071                                    bfd *obfd,
6072                                    asymbol *osymarg)
6073 {
6074   elf_symbol_type *isym, *osym;
6075
6076   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
6077       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
6078     return TRUE;
6079
6080   isym = elf_symbol_from (ibfd, isymarg);
6081   osym = elf_symbol_from (obfd, osymarg);
6082
6083   if (isym != NULL
6084       && isym->internal_elf_sym.st_shndx != 0
6085       && osym != NULL
6086       && bfd_is_abs_section (isym->symbol.section))
6087     {
6088       unsigned int shndx;
6089
6090       shndx = isym->internal_elf_sym.st_shndx;
6091       if (shndx == elf_onesymtab (ibfd))
6092         shndx = MAP_ONESYMTAB;
6093       else if (shndx == elf_dynsymtab (ibfd))
6094         shndx = MAP_DYNSYMTAB;
6095       else if (shndx == elf_tdata (ibfd)->strtab_section)
6096         shndx = MAP_STRTAB;
6097       else if (shndx == elf_tdata (ibfd)->shstrtab_section)
6098         shndx = MAP_SHSTRTAB;
6099       else if (shndx == elf_tdata (ibfd)->symtab_shndx_section)
6100         shndx = MAP_SYM_SHNDX;
6101       osym->internal_elf_sym.st_shndx = shndx;
6102     }
6103
6104   return TRUE;
6105 }
6106
6107 /* Swap out the symbols.  */
6108
6109 static bfd_boolean
6110 swap_out_syms (bfd *abfd,
6111                struct bfd_strtab_hash **sttp,
6112                int relocatable_p)
6113 {
6114   const struct elf_backend_data *bed;
6115   int symcount;
6116   asymbol **syms;
6117   struct bfd_strtab_hash *stt;
6118   Elf_Internal_Shdr *symtab_hdr;
6119   Elf_Internal_Shdr *symtab_shndx_hdr;
6120   Elf_Internal_Shdr *symstrtab_hdr;
6121   bfd_byte *outbound_syms;
6122   bfd_byte *outbound_shndx;
6123   int idx;
6124   bfd_size_type amt;
6125   bfd_boolean name_local_sections;
6126
6127   if (!elf_map_symbols (abfd))
6128     return FALSE;
6129
6130   /* Dump out the symtabs.  */
6131   stt = _bfd_elf_stringtab_init ();
6132   if (stt == NULL)
6133     return FALSE;
6134
6135   bed = get_elf_backend_data (abfd);
6136   symcount = bfd_get_symcount (abfd);
6137   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
6138   symtab_hdr->sh_type = SHT_SYMTAB;
6139   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
6140   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
6141   symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
6142   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
6143
6144   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
6145   symstrtab_hdr->sh_type = SHT_STRTAB;
6146
6147   outbound_syms = bfd_alloc2 (abfd, 1 + symcount, bed->s->sizeof_sym);
6148   if (outbound_syms == NULL)
6149     {
6150       _bfd_stringtab_free (stt);
6151       return FALSE;
6152     }
6153   symtab_hdr->contents = outbound_syms;
6154
6155   outbound_shndx = NULL;
6156   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
6157   if (symtab_shndx_hdr->sh_name != 0)
6158     {
6159       amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
6160       outbound_shndx = bfd_zalloc2 (abfd, 1 + symcount,
6161                                     sizeof (Elf_External_Sym_Shndx));
6162       if (outbound_shndx == NULL)
6163         {
6164           _bfd_stringtab_free (stt);
6165           return FALSE;
6166         }
6167
6168       symtab_shndx_hdr->contents = outbound_shndx;
6169       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
6170       symtab_shndx_hdr->sh_size = amt;
6171       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
6172       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
6173     }
6174
6175   /* Now generate the data (for "contents").  */
6176   {
6177     /* Fill in zeroth symbol and swap it out.  */
6178     Elf_Internal_Sym sym;
6179     sym.st_name = 0;
6180     sym.st_value = 0;
6181     sym.st_size = 0;
6182     sym.st_info = 0;
6183     sym.st_other = 0;
6184     sym.st_shndx = SHN_UNDEF;
6185     bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
6186     outbound_syms += bed->s->sizeof_sym;
6187     if (outbound_shndx != NULL)
6188       outbound_shndx += sizeof (Elf_External_Sym_Shndx);
6189   }
6190
6191   name_local_sections
6192     = (bed->elf_backend_name_local_section_symbols
6193        && bed->elf_backend_name_local_section_symbols (abfd));
6194
6195   syms = bfd_get_outsymbols (abfd);
6196   for (idx = 0; idx < symcount; idx++)
6197     {
6198       Elf_Internal_Sym sym;
6199       bfd_vma value = syms[idx]->value;
6200       elf_symbol_type *type_ptr;
6201       flagword flags = syms[idx]->flags;
6202       int type;
6203
6204       if (!name_local_sections
6205           && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
6206         {
6207           /* Local section symbols have no name.  */
6208           sym.st_name = 0;
6209         }
6210       else
6211         {
6212           sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
6213                                                             syms[idx]->name,
6214                                                             TRUE, FALSE);
6215           if (sym.st_name == (unsigned long) -1)
6216             {
6217               _bfd_stringtab_free (stt);
6218               return FALSE;
6219             }
6220         }
6221
6222       type_ptr = elf_symbol_from (abfd, syms[idx]);
6223
6224       if ((flags & BSF_SECTION_SYM) == 0
6225           && bfd_is_com_section (syms[idx]->section))
6226         {
6227           /* ELF common symbols put the alignment into the `value' field,
6228              and the size into the `size' field.  This is backwards from
6229              how BFD handles it, so reverse it here.  */
6230           sym.st_size = value;
6231           if (type_ptr == NULL
6232               || type_ptr->internal_elf_sym.st_value == 0)
6233             sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
6234           else
6235             sym.st_value = type_ptr->internal_elf_sym.st_value;
6236           sym.st_shndx = _bfd_elf_section_from_bfd_section
6237             (abfd, syms[idx]->section);
6238         }
6239       else
6240         {
6241           asection *sec = syms[idx]->section;
6242           unsigned int shndx;
6243
6244           if (sec->output_section)
6245             {
6246               value += sec->output_offset;
6247               sec = sec->output_section;
6248             }
6249
6250           /* Don't add in the section vma for relocatable output.  */
6251           if (! relocatable_p)
6252             value += sec->vma;
6253           sym.st_value = value;
6254           sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
6255
6256           if (bfd_is_abs_section (sec)
6257               && type_ptr != NULL
6258               && type_ptr->internal_elf_sym.st_shndx != 0)
6259             {
6260               /* This symbol is in a real ELF section which we did
6261                  not create as a BFD section.  Undo the mapping done
6262                  by copy_private_symbol_data.  */
6263               shndx = type_ptr->internal_elf_sym.st_shndx;
6264               switch (shndx)
6265                 {
6266                 case MAP_ONESYMTAB:
6267                   shndx = elf_onesymtab (abfd);
6268                   break;
6269                 case MAP_DYNSYMTAB:
6270                   shndx = elf_dynsymtab (abfd);
6271                   break;
6272                 case MAP_STRTAB:
6273                   shndx = elf_tdata (abfd)->strtab_section;
6274                   break;
6275                 case MAP_SHSTRTAB:
6276                   shndx = elf_tdata (abfd)->shstrtab_section;
6277                   break;
6278                 case MAP_SYM_SHNDX:
6279                   shndx = elf_tdata (abfd)->symtab_shndx_section;
6280                   break;
6281                 default:
6282                   break;
6283                 }
6284             }
6285           else
6286             {
6287               shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
6288
6289               if (shndx == SHN_BAD)
6290                 {
6291                   asection *sec2;
6292
6293                   /* Writing this would be a hell of a lot easier if
6294                      we had some decent documentation on bfd, and
6295                      knew what to expect of the library, and what to
6296                      demand of applications.  For example, it
6297                      appears that `objcopy' might not set the
6298                      section of a symbol to be a section that is
6299                      actually in the output file.  */
6300                   sec2 = bfd_get_section_by_name (abfd, sec->name);
6301                   if (sec2 == NULL)
6302                     {
6303                       _bfd_error_handler (_("\
6304 Unable to find equivalent output section for symbol '%s' from section '%s'"),
6305                                           syms[idx]->name ? syms[idx]->name : "<Local sym>",
6306                                           sec->name);
6307                       bfd_set_error (bfd_error_invalid_operation);
6308                       _bfd_stringtab_free (stt);
6309                       return FALSE;
6310                     }
6311
6312                   shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
6313                   BFD_ASSERT (shndx != SHN_BAD);
6314                 }
6315             }
6316
6317           sym.st_shndx = shndx;
6318         }
6319
6320       if ((flags & BSF_THREAD_LOCAL) != 0)
6321         type = STT_TLS;
6322       else if ((flags & BSF_FUNCTION) != 0)
6323         type = STT_FUNC;
6324       else if ((flags & BSF_OBJECT) != 0)
6325         type = STT_OBJECT;
6326       else if ((flags & BSF_RELC) != 0)
6327         type = STT_RELC;
6328       else if ((flags & BSF_SRELC) != 0)
6329         type = STT_SRELC;
6330       else
6331         type = STT_NOTYPE;
6332
6333       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
6334         type = STT_TLS;
6335
6336       /* Processor-specific types.  */
6337       if (type_ptr != NULL
6338           && bed->elf_backend_get_symbol_type)
6339         type = ((*bed->elf_backend_get_symbol_type)
6340                 (&type_ptr->internal_elf_sym, type));
6341
6342       if (flags & BSF_SECTION_SYM)
6343         {
6344           if (flags & BSF_GLOBAL)
6345             sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
6346           else
6347             sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
6348         }
6349       else if (bfd_is_com_section (syms[idx]->section))
6350         {
6351 #ifdef USE_STT_COMMON
6352           if (type == STT_OBJECT)
6353             sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_COMMON);
6354           else
6355 #else
6356             sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
6357 #endif
6358         }
6359       else if (bfd_is_und_section (syms[idx]->section))
6360         sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
6361                                     ? STB_WEAK
6362                                     : STB_GLOBAL),
6363                                    type);
6364       else if (flags & BSF_FILE)
6365         sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
6366       else
6367         {
6368           int bind = STB_LOCAL;
6369
6370           if (flags & BSF_LOCAL)
6371             bind = STB_LOCAL;
6372           else if (flags & BSF_WEAK)
6373             bind = STB_WEAK;
6374           else if (flags & BSF_GLOBAL)
6375             bind = STB_GLOBAL;
6376
6377           sym.st_info = ELF_ST_INFO (bind, type);
6378         }
6379
6380       if (type_ptr != NULL)
6381         sym.st_other = type_ptr->internal_elf_sym.st_other;
6382       else
6383         sym.st_other = 0;
6384
6385       bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
6386       outbound_syms += bed->s->sizeof_sym;
6387       if (outbound_shndx != NULL)
6388         outbound_shndx += sizeof (Elf_External_Sym_Shndx);
6389     }
6390
6391   *sttp = stt;
6392   symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
6393   symstrtab_hdr->sh_type = SHT_STRTAB;
6394
6395   symstrtab_hdr->sh_flags = 0;
6396   symstrtab_hdr->sh_addr = 0;
6397   symstrtab_hdr->sh_entsize = 0;
6398   symstrtab_hdr->sh_link = 0;
6399   symstrtab_hdr->sh_info = 0;
6400   symstrtab_hdr->sh_addralign = 1;
6401
6402   return TRUE;
6403 }
6404
6405 /* Return the number of bytes required to hold the symtab vector.
6406
6407    Note that we base it on the count plus 1, since we will null terminate
6408    the vector allocated based on this size.  However, the ELF symbol table
6409    always has a dummy entry as symbol #0, so it ends up even.  */
6410
6411 long
6412 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
6413 {
6414   long symcount;
6415   long symtab_size;
6416   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
6417
6418   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
6419   symtab_size = (symcount + 1) * (sizeof (asymbol *));
6420   if (symcount > 0)
6421     symtab_size -= sizeof (asymbol *);
6422
6423   return symtab_size;
6424 }
6425
6426 long
6427 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
6428 {
6429   long symcount;
6430   long symtab_size;
6431   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
6432
6433   if (elf_dynsymtab (abfd) == 0)
6434     {
6435       bfd_set_error (bfd_error_invalid_operation);
6436       return -1;
6437     }
6438
6439   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
6440   symtab_size = (symcount + 1) * (sizeof (asymbol *));
6441   if (symcount > 0)
6442     symtab_size -= sizeof (asymbol *);
6443
6444   return symtab_size;
6445 }
6446
6447 long
6448 _bfd_elf_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
6449                                 sec_ptr asect)
6450 {
6451   return (asect->reloc_count + 1) * sizeof (arelent *);
6452 }
6453
6454 /* Canonicalize the relocs.  */
6455
6456 long
6457 _bfd_elf_canonicalize_reloc (bfd *abfd,
6458                              sec_ptr section,
6459                              arelent **relptr,
6460                              asymbol **symbols)
6461 {
6462   arelent *tblptr;
6463   unsigned int i;
6464   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6465
6466   if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
6467     return -1;
6468
6469   tblptr = section->relocation;
6470   for (i = 0; i < section->reloc_count; i++)
6471     *relptr++ = tblptr++;
6472
6473   *relptr = NULL;
6474
6475   return section->reloc_count;
6476 }
6477
6478 long
6479 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
6480 {
6481   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6482   long symcount = bed->s->slurp_symbol_table (abfd, allocation, FALSE);
6483
6484   if (symcount >= 0)
6485     bfd_get_symcount (abfd) = symcount;
6486   return symcount;
6487 }
6488
6489 long
6490 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
6491                                       asymbol **allocation)
6492 {
6493   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6494   long symcount = bed->s->slurp_symbol_table (abfd, allocation, TRUE);
6495
6496   if (symcount >= 0)
6497     bfd_get_dynamic_symcount (abfd) = symcount;
6498   return symcount;
6499 }
6500
6501 /* Return the size required for the dynamic reloc entries.  Any loadable
6502    section that was actually installed in the BFD, and has type SHT_REL
6503    or SHT_RELA, and uses the dynamic symbol table, is considered to be a
6504    dynamic reloc section.  */
6505
6506 long
6507 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
6508 {
6509   long ret;
6510   asection *s;
6511
6512   if (elf_dynsymtab (abfd) == 0)
6513     {
6514       bfd_set_error (bfd_error_invalid_operation);
6515       return -1;
6516     }
6517
6518   ret = sizeof (arelent *);
6519   for (s = abfd->sections; s != NULL; s = s->next)
6520     if ((s->flags & SEC_LOAD) != 0
6521         && elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
6522         && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
6523             || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
6524       ret += ((s->size / elf_section_data (s)->this_hdr.sh_entsize)
6525               * sizeof (arelent *));
6526
6527   return ret;
6528 }
6529
6530 /* Canonicalize the dynamic relocation entries.  Note that we return the
6531    dynamic relocations as a single block, although they are actually
6532    associated with particular sections; the interface, which was
6533    designed for SunOS style shared libraries, expects that there is only
6534    one set of dynamic relocs.  Any loadable section that was actually
6535    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses the
6536    dynamic symbol table, is considered to be a dynamic reloc section.  */
6537
6538 long
6539 _bfd_elf_canonicalize_dynamic_reloc (bfd *abfd,
6540                                      arelent **storage,
6541                                      asymbol **syms)
6542 {
6543   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
6544   asection *s;
6545   long ret;
6546
6547   if (elf_dynsymtab (abfd) == 0)
6548     {
6549       bfd_set_error (bfd_error_invalid_operation);
6550       return -1;
6551     }
6552
6553   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
6554   ret = 0;
6555   for (s = abfd->sections; s != NULL; s = s->next)
6556     {
6557       if ((s->flags & SEC_LOAD) != 0
6558           && elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
6559           && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
6560               || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
6561         {
6562           arelent *p;
6563           long count, i;
6564
6565           if (! (*slurp_relocs) (abfd, s, syms, TRUE))
6566             return -1;
6567           count = s->size / elf_section_data (s)->this_hdr.sh_entsize;
6568           p = s->relocation;
6569           for (i = 0; i < count; i++)
6570             *storage++ = p++;
6571           ret += count;
6572         }
6573     }
6574
6575   *storage = NULL;
6576
6577   return ret;
6578 }
6579 \f
6580 /* Read in the version information.  */
6581
6582 bfd_boolean
6583 _bfd_elf_slurp_version_tables (bfd *abfd, bfd_boolean default_imported_symver)
6584 {
6585   bfd_byte *contents = NULL;
6586   unsigned int freeidx = 0;
6587
6588   if (elf_dynverref (abfd) != 0)
6589     {
6590       Elf_Internal_Shdr *hdr;
6591       Elf_External_Verneed *everneed;
6592       Elf_Internal_Verneed *iverneed;
6593       unsigned int i;
6594       bfd_byte *contents_end;
6595
6596       hdr = &elf_tdata (abfd)->dynverref_hdr;
6597
6598       elf_tdata (abfd)->verref = bfd_zalloc2 (abfd, hdr->sh_info,
6599                                               sizeof (Elf_Internal_Verneed));
6600       if (elf_tdata (abfd)->verref == NULL)
6601         goto error_return;
6602
6603       elf_tdata (abfd)->cverrefs = hdr->sh_info;
6604
6605       contents = bfd_malloc (hdr->sh_size);
6606       if (contents == NULL)
6607         {
6608 error_return_verref:
6609           elf_tdata (abfd)->verref = NULL;
6610           elf_tdata (abfd)->cverrefs = 0;
6611           goto error_return;
6612         }
6613       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
6614           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
6615         goto error_return_verref;
6616
6617       if (hdr->sh_info && hdr->sh_size < sizeof (Elf_External_Verneed))
6618         goto error_return_verref;
6619
6620       BFD_ASSERT (sizeof (Elf_External_Verneed)
6621                   == sizeof (Elf_External_Vernaux));
6622       contents_end = contents + hdr->sh_size - sizeof (Elf_External_Verneed);
6623       everneed = (Elf_External_Verneed *) contents;
6624       iverneed = elf_tdata (abfd)->verref;
6625       for (i = 0; i < hdr->sh_info; i++, iverneed++)
6626         {
6627           Elf_External_Vernaux *evernaux;
6628           Elf_Internal_Vernaux *ivernaux;
6629           unsigned int j;
6630
6631           _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
6632
6633           iverneed->vn_bfd = abfd;
6634
6635           iverneed->vn_filename =
6636             bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
6637                                              iverneed->vn_file);
6638           if (iverneed->vn_filename == NULL)
6639             goto error_return_verref;
6640
6641           if (iverneed->vn_cnt == 0)
6642             iverneed->vn_auxptr = NULL;
6643           else
6644             {
6645               iverneed->vn_auxptr = bfd_alloc2 (abfd, iverneed->vn_cnt,
6646                                                 sizeof (Elf_Internal_Vernaux));
6647               if (iverneed->vn_auxptr == NULL)
6648                 goto error_return_verref;
6649             }
6650
6651           if (iverneed->vn_aux
6652               > (size_t) (contents_end - (bfd_byte *) everneed))
6653             goto error_return_verref;
6654
6655           evernaux = ((Elf_External_Vernaux *)
6656                       ((bfd_byte *) everneed + iverneed->vn_aux));
6657           ivernaux = iverneed->vn_auxptr;
6658           for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
6659             {
6660               _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
6661
6662               ivernaux->vna_nodename =
6663                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
6664                                                  ivernaux->vna_name);
6665               if (ivernaux->vna_nodename == NULL)
6666                 goto error_return_verref;
6667
6668               if (j + 1 < iverneed->vn_cnt)
6669                 ivernaux->vna_nextptr = ivernaux + 1;
6670               else
6671                 ivernaux->vna_nextptr = NULL;
6672
6673               if (ivernaux->vna_next
6674                   > (size_t) (contents_end - (bfd_byte *) evernaux))
6675                 goto error_return_verref;
6676
6677               evernaux = ((Elf_External_Vernaux *)
6678                           ((bfd_byte *) evernaux + ivernaux->vna_next));
6679
6680               if (ivernaux->vna_other > freeidx)
6681                 freeidx = ivernaux->vna_other;
6682             }
6683
6684           if (i + 1 < hdr->sh_info)
6685             iverneed->vn_nextref = iverneed + 1;
6686           else
6687             iverneed->vn_nextref = NULL;
6688
6689           if (iverneed->vn_next
6690               > (size_t) (contents_end - (bfd_byte *) everneed))
6691             goto error_return_verref;
6692
6693           everneed = ((Elf_External_Verneed *)
6694                       ((bfd_byte *) everneed + iverneed->vn_next));
6695         }
6696
6697       free (contents);
6698       contents = NULL;
6699     }
6700
6701   if (elf_dynverdef (abfd) != 0)
6702     {
6703       Elf_Internal_Shdr *hdr;
6704       Elf_External_Verdef *everdef;
6705       Elf_Internal_Verdef *iverdef;
6706       Elf_Internal_Verdef *iverdefarr;
6707       Elf_Internal_Verdef iverdefmem;
6708       unsigned int i;
6709       unsigned int maxidx;
6710       bfd_byte *contents_end_def, *contents_end_aux;
6711
6712       hdr = &elf_tdata (abfd)->dynverdef_hdr;
6713
6714       contents = bfd_malloc (hdr->sh_size);
6715       if (contents == NULL)
6716         goto error_return;
6717       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
6718           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
6719         goto error_return;
6720
6721       if (hdr->sh_info && hdr->sh_size < sizeof (Elf_External_Verdef))
6722         goto error_return;
6723
6724       BFD_ASSERT (sizeof (Elf_External_Verdef)
6725                   >= sizeof (Elf_External_Verdaux));
6726       contents_end_def = contents + hdr->sh_size
6727                          - sizeof (Elf_External_Verdef);
6728       contents_end_aux = contents + hdr->sh_size
6729                          - sizeof (Elf_External_Verdaux);
6730
6731       /* We know the number of entries in the section but not the maximum
6732          index.  Therefore we have to run through all entries and find
6733          the maximum.  */
6734       everdef = (Elf_External_Verdef *) contents;
6735       maxidx = 0;
6736       for (i = 0; i < hdr->sh_info; ++i)
6737         {
6738           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
6739
6740           if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
6741             maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
6742
6743           if (iverdefmem.vd_next
6744               > (size_t) (contents_end_def - (bfd_byte *) everdef))
6745             goto error_return;
6746
6747           everdef = ((Elf_External_Verdef *)
6748                      ((bfd_byte *) everdef + iverdefmem.vd_next));
6749         }
6750
6751       if (default_imported_symver)
6752         {
6753           if (freeidx > maxidx)
6754             maxidx = ++freeidx;
6755           else
6756             freeidx = ++maxidx;
6757         }
6758       elf_tdata (abfd)->verdef = bfd_zalloc2 (abfd, maxidx,
6759                                               sizeof (Elf_Internal_Verdef));
6760       if (elf_tdata (abfd)->verdef == NULL)
6761         goto error_return;
6762
6763       elf_tdata (abfd)->cverdefs = maxidx;
6764
6765       everdef = (Elf_External_Verdef *) contents;
6766       iverdefarr = elf_tdata (abfd)->verdef;
6767       for (i = 0; i < hdr->sh_info; i++)
6768         {
6769           Elf_External_Verdaux *everdaux;
6770           Elf_Internal_Verdaux *iverdaux;
6771           unsigned int j;
6772
6773           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
6774
6775           if ((iverdefmem.vd_ndx & VERSYM_VERSION) == 0)
6776             {
6777 error_return_verdef:
6778               elf_tdata (abfd)->verdef = NULL;
6779               elf_tdata (abfd)->cverdefs = 0;
6780               goto error_return;
6781             }
6782
6783           iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
6784           memcpy (iverdef, &iverdefmem, sizeof (Elf_Internal_Verdef));
6785
6786           iverdef->vd_bfd = abfd;
6787
6788           if (iverdef->vd_cnt == 0)
6789             iverdef->vd_auxptr = NULL;
6790           else
6791             {
6792               iverdef->vd_auxptr = bfd_alloc2 (abfd, iverdef->vd_cnt,
6793                                                sizeof (Elf_Internal_Verdaux));
6794               if (iverdef->vd_auxptr == NULL)
6795                 goto error_return_verdef;
6796             }
6797
6798           if (iverdef->vd_aux
6799               > (size_t) (contents_end_aux - (bfd_byte *) everdef))
6800             goto error_return_verdef;
6801
6802           everdaux = ((Elf_External_Verdaux *)
6803                       ((bfd_byte *) everdef + iverdef->vd_aux));
6804           iverdaux = iverdef->vd_auxptr;
6805           for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
6806             {
6807               _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
6808
6809               iverdaux->vda_nodename =
6810                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
6811                                                  iverdaux->vda_name);
6812               if (iverdaux->vda_nodename == NULL)
6813                 goto error_return_verdef;
6814
6815               if (j + 1 < iverdef->vd_cnt)
6816                 iverdaux->vda_nextptr = iverdaux + 1;
6817               else
6818                 iverdaux->vda_nextptr = NULL;
6819
6820               if (iverdaux->vda_next
6821                   > (size_t) (contents_end_aux - (bfd_byte *) everdaux))
6822                 goto error_return_verdef;
6823
6824               everdaux = ((Elf_External_Verdaux *)
6825                           ((bfd_byte *) everdaux + iverdaux->vda_next));
6826             }
6827
6828           if (iverdef->vd_cnt)
6829             iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
6830
6831           if ((size_t) (iverdef - iverdefarr) + 1 < maxidx)
6832             iverdef->vd_nextdef = iverdef + 1;
6833           else
6834             iverdef->vd_nextdef = NULL;
6835
6836           everdef = ((Elf_External_Verdef *)
6837                      ((bfd_byte *) everdef + iverdef->vd_next));
6838         }
6839
6840       free (contents);
6841       contents = NULL;
6842     }
6843   else if (default_imported_symver)
6844     {
6845       if (freeidx < 3)
6846         freeidx = 3;
6847       else
6848         freeidx++;
6849
6850       elf_tdata (abfd)->verdef = bfd_zalloc2 (abfd, freeidx,
6851                                               sizeof (Elf_Internal_Verdef));
6852       if (elf_tdata (abfd)->verdef == NULL)
6853         goto error_return;
6854
6855       elf_tdata (abfd)->cverdefs = freeidx;
6856     }
6857
6858   /* Create a default version based on the soname.  */
6859   if (default_imported_symver)
6860     {
6861       Elf_Internal_Verdef *iverdef;
6862       Elf_Internal_Verdaux *iverdaux;
6863
6864       iverdef = &elf_tdata (abfd)->verdef[freeidx - 1];;
6865
6866       iverdef->vd_version = VER_DEF_CURRENT;
6867       iverdef->vd_flags = 0;
6868       iverdef->vd_ndx = freeidx;
6869       iverdef->vd_cnt = 1;
6870
6871       iverdef->vd_bfd = abfd;
6872
6873       iverdef->vd_nodename = bfd_elf_get_dt_soname (abfd);
6874       if (iverdef->vd_nodename == NULL)
6875         goto error_return_verdef;
6876       iverdef->vd_nextdef = NULL;
6877       iverdef->vd_auxptr = bfd_alloc (abfd, sizeof (Elf_Internal_Verdaux));
6878       if (iverdef->vd_auxptr == NULL)
6879         goto error_return_verdef;
6880
6881       iverdaux = iverdef->vd_auxptr;
6882       iverdaux->vda_nodename = iverdef->vd_nodename;
6883       iverdaux->vda_nextptr = NULL;
6884     }
6885
6886   return TRUE;
6887
6888  error_return:
6889   if (contents != NULL)
6890     free (contents);
6891   return FALSE;
6892 }
6893 \f
6894 asymbol *
6895 _bfd_elf_make_empty_symbol (bfd *abfd)
6896 {
6897   elf_symbol_type *newsym;
6898   bfd_size_type amt = sizeof (elf_symbol_type);
6899
6900   newsym = bfd_zalloc (abfd, amt);
6901   if (!newsym)
6902     return NULL;
6903   else
6904     {
6905       newsym->symbol.the_bfd = abfd;
6906       return &newsym->symbol;
6907     }
6908 }
6909
6910 void
6911 _bfd_elf_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
6912                           asymbol *symbol,
6913                           symbol_info *ret)
6914 {
6915   bfd_symbol_info (symbol, ret);
6916 }
6917
6918 /* Return whether a symbol name implies a local symbol.  Most targets
6919    use this function for the is_local_label_name entry point, but some
6920    override it.  */
6921
6922 bfd_boolean
6923 _bfd_elf_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
6924                               const char *name)
6925 {
6926   /* Normal local symbols start with ``.L''.  */
6927   if (name[0] == '.' && name[1] == 'L')
6928     return TRUE;
6929
6930   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
6931      DWARF debugging symbols starting with ``..''.  */
6932   if (name[0] == '.' && name[1] == '.')
6933     return TRUE;
6934
6935   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
6936      emitting DWARF debugging output.  I suspect this is actually a
6937      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
6938      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
6939      underscore to be emitted on some ELF targets).  For ease of use,
6940      we treat such symbols as local.  */
6941   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
6942     return TRUE;
6943
6944   return FALSE;
6945 }
6946
6947 alent *
6948 _bfd_elf_get_lineno (bfd *abfd ATTRIBUTE_UNUSED,
6949                      asymbol *symbol ATTRIBUTE_UNUSED)
6950 {
6951   abort ();
6952   return NULL;
6953 }
6954
6955 bfd_boolean
6956 _bfd_elf_set_arch_mach (bfd *abfd,
6957                         enum bfd_architecture arch,
6958                         unsigned long machine)
6959 {
6960   /* If this isn't the right architecture for this backend, and this
6961      isn't the generic backend, fail.  */
6962   if (arch != get_elf_backend_data (abfd)->arch
6963       && arch != bfd_arch_unknown
6964       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
6965     return FALSE;
6966
6967   return bfd_default_set_arch_mach (abfd, arch, machine);
6968 }
6969
6970 /* Find the function to a particular section and offset,
6971    for error reporting.  */
6972
6973 static bfd_boolean
6974 elf_find_function (bfd *abfd ATTRIBUTE_UNUSED,
6975                    asection *section,
6976                    asymbol **symbols,
6977                    bfd_vma offset,
6978                    const char **filename_ptr,
6979                    const char **functionname_ptr)
6980 {
6981   const char *filename;
6982   asymbol *func, *file;
6983   bfd_vma low_func;
6984   asymbol **p;
6985   /* ??? Given multiple file symbols, it is impossible to reliably
6986      choose the right file name for global symbols.  File symbols are
6987      local symbols, and thus all file symbols must sort before any
6988      global symbols.  The ELF spec may be interpreted to say that a
6989      file symbol must sort before other local symbols, but currently
6990      ld -r doesn't do this.  So, for ld -r output, it is possible to
6991      make a better choice of file name for local symbols by ignoring
6992      file symbols appearing after a given local symbol.  */
6993   enum { nothing_seen, symbol_seen, file_after_symbol_seen } state;
6994
6995   filename = NULL;
6996   func = NULL;
6997   file = NULL;
6998   low_func = 0;
6999   state = nothing_seen;
7000
7001   for (p = symbols; *p != NULL; p++)
7002     {
7003       elf_symbol_type *q;
7004
7005       q = (elf_symbol_type *) *p;
7006
7007       switch (ELF_ST_TYPE (q->internal_elf_sym.st_info))
7008         {
7009         default:
7010           break;
7011         case STT_FILE:
7012           file = &q->symbol;
7013           if (state == symbol_seen)
7014             state = file_after_symbol_seen;
7015           continue;
7016         case STT_NOTYPE:
7017         case STT_FUNC:
7018           if (bfd_get_section (&q->symbol) == section
7019               && q->symbol.value >= low_func
7020               && q->symbol.value <= offset)
7021             {
7022               func = (asymbol *) q;
7023               low_func = q->symbol.value;
7024               filename = NULL;
7025               if (file != NULL
7026                   && (ELF_ST_BIND (q->internal_elf_sym.st_info) == STB_LOCAL
7027                       || state != file_after_symbol_seen))
7028                 filename = bfd_asymbol_name (file);
7029             }
7030           break;
7031         }
7032       if (state == nothing_seen)
7033         state = symbol_seen;
7034     }
7035
7036   if (func == NULL)
7037     return FALSE;
7038
7039   if (filename_ptr)
7040     *filename_ptr = filename;
7041   if (functionname_ptr)
7042     *functionname_ptr = bfd_asymbol_name (func);
7043
7044   return TRUE;
7045 }
7046
7047 /* Find the nearest line to a particular section and offset,
7048    for error reporting.  */
7049
7050 bfd_boolean
7051 _bfd_elf_find_nearest_line (bfd *abfd,
7052                             asection *section,
7053                             asymbol **symbols,
7054                             bfd_vma offset,
7055                             const char **filename_ptr,
7056                             const char **functionname_ptr,
7057                             unsigned int *line_ptr)
7058 {
7059   bfd_boolean found;
7060
7061   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
7062                                      filename_ptr, functionname_ptr,
7063                                      line_ptr))
7064     {
7065       if (!*functionname_ptr)
7066         elf_find_function (abfd, section, symbols, offset,
7067                            *filename_ptr ? NULL : filename_ptr,
7068                            functionname_ptr);
7069
7070       return TRUE;
7071     }
7072
7073   if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
7074                                      filename_ptr, functionname_ptr,
7075                                      line_ptr, 0,
7076                                      &elf_tdata (abfd)->dwarf2_find_line_info))
7077     {
7078       if (!*functionname_ptr)
7079         elf_find_function (abfd, section, symbols, offset,
7080                            *filename_ptr ? NULL : filename_ptr,
7081                            functionname_ptr);
7082
7083       return TRUE;
7084     }
7085
7086   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
7087                                              &found, filename_ptr,
7088                                              functionname_ptr, line_ptr,
7089                                              &elf_tdata (abfd)->line_info))
7090     return FALSE;
7091   if (found && (*functionname_ptr || *line_ptr))
7092     return TRUE;
7093
7094   if (symbols == NULL)
7095     return FALSE;
7096
7097   if (! elf_find_function (abfd, section, symbols, offset,
7098                            filename_ptr, functionname_ptr))
7099     return FALSE;
7100
7101   *line_ptr = 0;
7102   return TRUE;
7103 }
7104
7105 /* Find the line for a symbol.  */
7106
7107 bfd_boolean
7108 _bfd_elf_find_line (bfd *abfd, asymbol **symbols, asymbol *symbol,
7109                     const char **filename_ptr, unsigned int *line_ptr)
7110 {
7111   return _bfd_dwarf2_find_line (abfd, symbols, symbol,
7112                                 filename_ptr, line_ptr, 0,
7113                                 &elf_tdata (abfd)->dwarf2_find_line_info);
7114 }
7115
7116 /* After a call to bfd_find_nearest_line, successive calls to
7117    bfd_find_inliner_info can be used to get source information about
7118    each level of function inlining that terminated at the address
7119    passed to bfd_find_nearest_line.  Currently this is only supported
7120    for DWARF2 with appropriate DWARF3 extensions. */
7121
7122 bfd_boolean
7123 _bfd_elf_find_inliner_info (bfd *abfd,
7124                             const char **filename_ptr,
7125                             const char **functionname_ptr,
7126                             unsigned int *line_ptr)
7127 {
7128   bfd_boolean found;
7129   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
7130                                          functionname_ptr, line_ptr,
7131                                          & elf_tdata (abfd)->dwarf2_find_line_info);
7132   return found;
7133 }
7134
7135 int
7136 _bfd_elf_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
7137 {
7138   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7139   int ret = bed->s->sizeof_ehdr;
7140
7141   if (!info->relocatable)
7142     {
7143       bfd_size_type phdr_size = elf_tdata (abfd)->program_header_size;
7144
7145       if (phdr_size == (bfd_size_type) -1)
7146         {
7147           struct elf_segment_map *m;
7148
7149           phdr_size = 0;
7150           for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
7151             phdr_size += bed->s->sizeof_phdr;
7152
7153           if (phdr_size == 0)
7154             phdr_size = get_program_header_size (abfd, info);
7155         }
7156
7157       elf_tdata (abfd)->program_header_size = phdr_size;
7158       ret += phdr_size;
7159     }
7160
7161   return ret;
7162 }
7163
7164 bfd_boolean
7165 _bfd_elf_set_section_contents (bfd *abfd,
7166                                sec_ptr section,
7167                                const void *location,
7168                                file_ptr offset,
7169                                bfd_size_type count)
7170 {
7171   Elf_Internal_Shdr *hdr;
7172   bfd_signed_vma pos;
7173
7174   if (! abfd->output_has_begun
7175       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
7176     return FALSE;
7177
7178   hdr = &elf_section_data (section)->this_hdr;
7179   pos = hdr->sh_offset + offset;
7180   if (bfd_seek (abfd, pos, SEEK_SET) != 0
7181       || bfd_bwrite (location, count, abfd) != count)
7182     return FALSE;
7183
7184   return TRUE;
7185 }
7186
7187 void
7188 _bfd_elf_no_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
7189                            arelent *cache_ptr ATTRIBUTE_UNUSED,
7190                            Elf_Internal_Rela *dst ATTRIBUTE_UNUSED)
7191 {
7192   abort ();
7193 }
7194
7195 /* Try to convert a non-ELF reloc into an ELF one.  */
7196
7197 bfd_boolean
7198 _bfd_elf_validate_reloc (bfd *abfd, arelent *areloc)
7199 {
7200   /* Check whether we really have an ELF howto.  */
7201
7202   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
7203     {
7204       bfd_reloc_code_real_type code;
7205       reloc_howto_type *howto;
7206
7207       /* Alien reloc: Try to determine its type to replace it with an
7208          equivalent ELF reloc.  */
7209
7210       if (areloc->howto->pc_relative)
7211         {
7212           switch (areloc->howto->bitsize)
7213             {
7214             case 8:
7215               code = BFD_RELOC_8_PCREL;
7216               break;
7217             case 12:
7218               code = BFD_RELOC_12_PCREL;
7219               break;
7220             case 16:
7221               code = BFD_RELOC_16_PCREL;
7222               break;
7223             case 24:
7224               code = BFD_RELOC_24_PCREL;
7225               break;
7226             case 32:
7227               code = BFD_RELOC_32_PCREL;
7228               break;
7229             case 64:
7230               code = BFD_RELOC_64_PCREL;
7231               break;
7232             default:
7233               goto fail;
7234             }
7235
7236           howto = bfd_reloc_type_lookup (abfd, code);
7237
7238           if (areloc->howto->pcrel_offset != howto->pcrel_offset)
7239             {
7240               if (howto->pcrel_offset)
7241                 areloc->addend += areloc->address;
7242               else
7243                 areloc->addend -= areloc->address; /* addend is unsigned!! */
7244             }
7245         }
7246       else
7247         {
7248           switch (areloc->howto->bitsize)
7249             {
7250             case 8:
7251               code = BFD_RELOC_8;
7252               break;
7253             case 14:
7254               code = BFD_RELOC_14;
7255               break;
7256             case 16:
7257               code = BFD_RELOC_16;
7258               break;
7259             case 26:
7260               code = BFD_RELOC_26;
7261               break;
7262             case 32:
7263               code = BFD_RELOC_32;
7264               break;
7265             case 64:
7266               code = BFD_RELOC_64;
7267               break;
7268             default:
7269               goto fail;
7270             }
7271
7272           howto = bfd_reloc_type_lookup (abfd, code);
7273         }
7274
7275       if (howto)
7276         areloc->howto = howto;
7277       else
7278         goto fail;
7279     }
7280
7281   return TRUE;
7282
7283  fail:
7284   (*_bfd_error_handler)
7285     (_("%B: unsupported relocation type %s"),
7286      abfd, areloc->howto->name);
7287   bfd_set_error (bfd_error_bad_value);
7288   return FALSE;
7289 }
7290
7291 bfd_boolean
7292 _bfd_elf_close_and_cleanup (bfd *abfd)
7293 {
7294   if (bfd_get_format (abfd) == bfd_object)
7295     {
7296       if (elf_tdata (abfd) != NULL && elf_shstrtab (abfd) != NULL)
7297         _bfd_elf_strtab_free (elf_shstrtab (abfd));
7298       _bfd_dwarf2_cleanup_debug_info (abfd);
7299     }
7300
7301   return _bfd_generic_close_and_cleanup (abfd);
7302 }
7303
7304 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
7305    in the relocation's offset.  Thus we cannot allow any sort of sanity
7306    range-checking to interfere.  There is nothing else to do in processing
7307    this reloc.  */
7308
7309 bfd_reloc_status_type
7310 _bfd_elf_rel_vtable_reloc_fn
7311   (bfd *abfd ATTRIBUTE_UNUSED, arelent *re ATTRIBUTE_UNUSED,
7312    struct bfd_symbol *symbol ATTRIBUTE_UNUSED,
7313    void *data ATTRIBUTE_UNUSED, asection *is ATTRIBUTE_UNUSED,
7314    bfd *obfd ATTRIBUTE_UNUSED, char **errmsg ATTRIBUTE_UNUSED)
7315 {
7316   return bfd_reloc_ok;
7317 }
7318 \f
7319 /* Elf core file support.  Much of this only works on native
7320    toolchains, since we rely on knowing the
7321    machine-dependent procfs structure in order to pick
7322    out details about the corefile.  */
7323
7324 #ifdef HAVE_SYS_PROCFS_H
7325 # include <sys/procfs.h>
7326 #endif
7327
7328 /* FIXME: this is kinda wrong, but it's what gdb wants.  */
7329
7330 static int
7331 elfcore_make_pid (bfd *abfd)
7332 {
7333   return ((elf_tdata (abfd)->core_lwpid << 16)
7334           + (elf_tdata (abfd)->core_pid));
7335 }
7336
7337 /* If there isn't a section called NAME, make one, using
7338    data from SECT.  Note, this function will generate a
7339    reference to NAME, so you shouldn't deallocate or
7340    overwrite it.  */
7341
7342 static bfd_boolean
7343 elfcore_maybe_make_sect (bfd *abfd, char *name, asection *sect)
7344 {
7345   asection *sect2;
7346
7347   if (bfd_get_section_by_name (abfd, name) != NULL)
7348     return TRUE;
7349
7350   sect2 = bfd_make_section_with_flags (abfd, name, sect->flags);
7351   if (sect2 == NULL)
7352     return FALSE;
7353
7354   sect2->size = sect->size;
7355   sect2->filepos = sect->filepos;
7356   sect2->alignment_power = sect->alignment_power;
7357   return TRUE;
7358 }
7359
7360 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
7361    actually creates up to two pseudosections:
7362    - For the single-threaded case, a section named NAME, unless
7363      such a section already exists.
7364    - For the multi-threaded case, a section named "NAME/PID", where
7365      PID is elfcore_make_pid (abfd).
7366    Both pseudosections have identical contents. */
7367 bfd_boolean
7368 _bfd_elfcore_make_pseudosection (bfd *abfd,
7369                                  char *name,
7370                                  size_t size,
7371                                  ufile_ptr filepos)
7372 {
7373   char buf[100];
7374   char *threaded_name;
7375   size_t len;
7376   asection *sect;
7377
7378   /* Build the section name.  */
7379
7380   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
7381   len = strlen (buf) + 1;
7382   threaded_name = bfd_alloc (abfd, len);
7383   if (threaded_name == NULL)
7384     return FALSE;
7385   memcpy (threaded_name, buf, len);
7386
7387   sect = bfd_make_section_anyway_with_flags (abfd, threaded_name,
7388                                              SEC_HAS_CONTENTS);
7389   if (sect == NULL)
7390     return FALSE;
7391   sect->size = size;
7392   sect->filepos = filepos;
7393   sect->alignment_power = 2;
7394
7395   return elfcore_maybe_make_sect (abfd, name, sect);
7396 }
7397
7398 /* prstatus_t exists on:
7399      solaris 2.5+
7400      linux 2.[01] + glibc
7401      unixware 4.2
7402 */
7403
7404 #if defined (HAVE_PRSTATUS_T)
7405
7406 static bfd_boolean
7407 elfcore_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
7408 {
7409   size_t size;
7410   int offset;
7411
7412   if (note->descsz == sizeof (prstatus_t))
7413     {
7414       prstatus_t prstat;
7415
7416       size = sizeof (prstat.pr_reg);
7417       offset   = offsetof (prstatus_t, pr_reg);
7418       memcpy (&prstat, note->descdata, sizeof (prstat));
7419
7420       /* Do not overwrite the core signal if it
7421          has already been set by another thread.  */
7422       if (elf_tdata (abfd)->core_signal == 0)
7423         elf_tdata (abfd)->core_signal = prstat.pr_cursig;
7424       elf_tdata (abfd)->core_pid = prstat.pr_pid;
7425
7426       /* pr_who exists on:
7427          solaris 2.5+
7428          unixware 4.2
7429          pr_who doesn't exist on:
7430          linux 2.[01]
7431          */
7432 #if defined (HAVE_PRSTATUS_T_PR_WHO)
7433       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
7434 #endif
7435     }
7436 #if defined (HAVE_PRSTATUS32_T)
7437   else if (note->descsz == sizeof (prstatus32_t))
7438     {
7439       /* 64-bit host, 32-bit corefile */
7440       prstatus32_t prstat;
7441
7442       size = sizeof (prstat.pr_reg);
7443       offset   = offsetof (prstatus32_t, pr_reg);
7444       memcpy (&prstat, note->descdata, sizeof (prstat));
7445
7446       /* Do not overwrite the core signal if it
7447          has already been set by another thread.  */
7448       if (elf_tdata (abfd)->core_signal == 0)
7449         elf_tdata (abfd)->core_signal = prstat.pr_cursig;
7450       elf_tdata (abfd)->core_pid = prstat.pr_pid;
7451
7452       /* pr_who exists on:
7453          solaris 2.5+
7454          unixware 4.2
7455          pr_who doesn't exist on:
7456          linux 2.[01]
7457          */
7458 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
7459       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
7460 #endif
7461     }
7462 #endif /* HAVE_PRSTATUS32_T */
7463   else
7464     {
7465       /* Fail - we don't know how to handle any other
7466          note size (ie. data object type).  */
7467       return TRUE;
7468     }
7469
7470   /* Make a ".reg/999" section and a ".reg" section.  */
7471   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
7472                                           size, note->descpos + offset);
7473 }
7474 #endif /* defined (HAVE_PRSTATUS_T) */
7475
7476 /* Create a pseudosection containing the exact contents of NOTE.  */
7477 static bfd_boolean
7478 elfcore_make_note_pseudosection (bfd *abfd,
7479                                  char *name,
7480                                  Elf_Internal_Note *note)
7481 {
7482   return _bfd_elfcore_make_pseudosection (abfd, name,
7483                                           note->descsz, note->descpos);
7484 }
7485
7486 /* There isn't a consistent prfpregset_t across platforms,
7487    but it doesn't matter, because we don't have to pick this
7488    data structure apart.  */
7489
7490 static bfd_boolean
7491 elfcore_grok_prfpreg (bfd *abfd, Elf_Internal_Note *note)
7492 {
7493   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
7494 }
7495
7496 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
7497    type of NT_PRXFPREG.  Just include the whole note's contents
7498    literally.  */
7499
7500 static bfd_boolean
7501 elfcore_grok_prxfpreg (bfd *abfd, Elf_Internal_Note *note)
7502 {
7503   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
7504 }
7505
7506 static bfd_boolean
7507 elfcore_grok_ppc_vmx (bfd *abfd, Elf_Internal_Note *note)
7508 {
7509   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vmx", note);
7510 }
7511
7512
7513 #if defined (HAVE_PRPSINFO_T)
7514 typedef prpsinfo_t   elfcore_psinfo_t;
7515 #if defined (HAVE_PRPSINFO32_T)         /* Sparc64 cross Sparc32 */
7516 typedef prpsinfo32_t elfcore_psinfo32_t;
7517 #endif
7518 #endif
7519
7520 #if defined (HAVE_PSINFO_T)
7521 typedef psinfo_t   elfcore_psinfo_t;
7522 #if defined (HAVE_PSINFO32_T)           /* Sparc64 cross Sparc32 */
7523 typedef psinfo32_t elfcore_psinfo32_t;
7524 #endif
7525 #endif
7526
7527 /* return a malloc'ed copy of a string at START which is at
7528    most MAX bytes long, possibly without a terminating '\0'.
7529    the copy will always have a terminating '\0'.  */
7530
7531 char *
7532 _bfd_elfcore_strndup (bfd *abfd, char *start, size_t max)
7533 {
7534   char *dups;
7535   char *end = memchr (start, '\0', max);
7536   size_t len;
7537
7538   if (end == NULL)
7539     len = max;
7540   else
7541     len = end - start;
7542
7543   dups = bfd_alloc (abfd, len + 1);
7544   if (dups == NULL)
7545     return NULL;
7546
7547   memcpy (dups, start, len);
7548   dups[len] = '\0';
7549
7550   return dups;
7551 }
7552
7553 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
7554 static bfd_boolean
7555 elfcore_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
7556 {
7557   if (note->descsz == sizeof (elfcore_psinfo_t))
7558     {
7559       elfcore_psinfo_t psinfo;
7560
7561       memcpy (&psinfo, note->descdata, sizeof (psinfo));
7562
7563       elf_tdata (abfd)->core_program
7564         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
7565                                 sizeof (psinfo.pr_fname));
7566
7567       elf_tdata (abfd)->core_command
7568         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
7569                                 sizeof (psinfo.pr_psargs));
7570     }
7571 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
7572   else if (note->descsz == sizeof (elfcore_psinfo32_t))
7573     {
7574       /* 64-bit host, 32-bit corefile */
7575       elfcore_psinfo32_t psinfo;
7576
7577       memcpy (&psinfo, note->descdata, sizeof (psinfo));
7578
7579       elf_tdata (abfd)->core_program
7580         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
7581                                 sizeof (psinfo.pr_fname));
7582
7583       elf_tdata (abfd)->core_command
7584         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
7585                                 sizeof (psinfo.pr_psargs));
7586     }
7587 #endif
7588
7589   else
7590     {
7591       /* Fail - we don't know how to handle any other
7592          note size (ie. data object type).  */
7593       return TRUE;
7594     }
7595
7596   /* Note that for some reason, a spurious space is tacked
7597      onto the end of the args in some (at least one anyway)
7598      implementations, so strip it off if it exists.  */
7599
7600   {
7601     char *command = elf_tdata (abfd)->core_command;
7602     int n = strlen (command);
7603
7604     if (0 < n && command[n - 1] == ' ')
7605       command[n - 1] = '\0';
7606   }
7607
7608   return TRUE;
7609 }
7610 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
7611
7612 #if defined (HAVE_PSTATUS_T)
7613 static bfd_boolean
7614 elfcore_grok_pstatus (bfd *abfd, Elf_Internal_Note *note)
7615 {
7616   if (note->descsz == sizeof (pstatus_t)
7617 #if defined (HAVE_PXSTATUS_T)
7618       || note->descsz == sizeof (pxstatus_t)
7619 #endif
7620       )
7621     {
7622       pstatus_t pstat;
7623
7624       memcpy (&pstat, note->descdata, sizeof (pstat));
7625
7626       elf_tdata (abfd)->core_pid = pstat.pr_pid;
7627     }
7628 #if defined (HAVE_PSTATUS32_T)
7629   else if (note->descsz == sizeof (pstatus32_t))
7630     {
7631       /* 64-bit host, 32-bit corefile */
7632       pstatus32_t pstat;
7633
7634       memcpy (&pstat, note->descdata, sizeof (pstat));
7635
7636       elf_tdata (abfd)->core_pid = pstat.pr_pid;
7637     }
7638 #endif
7639   /* Could grab some more details from the "representative"
7640      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
7641      NT_LWPSTATUS note, presumably.  */
7642
7643   return TRUE;
7644 }
7645 #endif /* defined (HAVE_PSTATUS_T) */
7646
7647 #if defined (HAVE_LWPSTATUS_T)
7648 static bfd_boolean
7649 elfcore_grok_lwpstatus (bfd *abfd, Elf_Internal_Note *note)
7650 {
7651   lwpstatus_t lwpstat;
7652   char buf[100];
7653   char *name;
7654   size_t len;
7655   asection *sect;
7656
7657   if (note->descsz != sizeof (lwpstat)
7658 #if defined (HAVE_LWPXSTATUS_T)
7659       && note->descsz != sizeof (lwpxstatus_t)
7660 #endif
7661       )
7662     return TRUE;
7663
7664   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
7665
7666   elf_tdata (abfd)->core_lwpid = lwpstat.pr_lwpid;
7667   elf_tdata (abfd)->core_signal = lwpstat.pr_cursig;
7668
7669   /* Make a ".reg/999" section.  */
7670
7671   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
7672   len = strlen (buf) + 1;
7673   name = bfd_alloc (abfd, len);
7674   if (name == NULL)
7675     return FALSE;
7676   memcpy (name, buf, len);
7677
7678   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
7679   if (sect == NULL)
7680     return FALSE;
7681
7682 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
7683   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
7684   sect->filepos = note->descpos
7685     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
7686 #endif
7687
7688 #if defined (HAVE_LWPSTATUS_T_PR_REG)
7689   sect->size = sizeof (lwpstat.pr_reg);
7690   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
7691 #endif
7692
7693   sect->alignment_power = 2;
7694
7695   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
7696     return FALSE;
7697
7698   /* Make a ".reg2/999" section */
7699
7700   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
7701   len = strlen (buf) + 1;
7702   name = bfd_alloc (abfd, len);
7703   if (name == NULL)
7704     return FALSE;
7705   memcpy (name, buf, len);
7706
7707   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
7708   if (sect == NULL)
7709     return FALSE;
7710
7711 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
7712   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
7713   sect->filepos = note->descpos
7714     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
7715 #endif
7716
7717 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
7718   sect->size = sizeof (lwpstat.pr_fpreg);
7719   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
7720 #endif
7721
7722   sect->alignment_power = 2;
7723
7724   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
7725 }
7726 #endif /* defined (HAVE_LWPSTATUS_T) */
7727
7728 static bfd_boolean
7729 elfcore_grok_win32pstatus (bfd *abfd, Elf_Internal_Note *note)
7730 {
7731   char buf[30];
7732   char *name;
7733   size_t len;
7734   asection *sect;
7735   int type;
7736   int is_active_thread;
7737   bfd_vma base_addr;
7738
7739   if (note->descsz < 728)
7740     return TRUE;
7741
7742   if (! CONST_STRNEQ (note->namedata, "win32"))
7743     return TRUE;
7744
7745   type = bfd_get_32 (abfd, note->descdata);
7746
7747   switch (type)
7748     {
7749     case 1 /* NOTE_INFO_PROCESS */:
7750       /* FIXME: need to add ->core_command.  */
7751       /* process_info.pid */
7752       elf_tdata (abfd)->core_pid = bfd_get_32 (abfd, note->descdata + 8);
7753       /* process_info.signal */
7754       elf_tdata (abfd)->core_signal = bfd_get_32 (abfd, note->descdata + 12);
7755       break;
7756
7757     case 2 /* NOTE_INFO_THREAD */:
7758       /* Make a ".reg/999" section.  */
7759       /* thread_info.tid */
7760       sprintf (buf, ".reg/%ld", (long) bfd_get_32 (abfd, note->descdata + 8));
7761
7762       len = strlen (buf) + 1;
7763       name = bfd_alloc (abfd, len);
7764       if (name == NULL)
7765         return FALSE;
7766
7767       memcpy (name, buf, len);
7768
7769       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
7770       if (sect == NULL)
7771         return FALSE;
7772
7773       /* sizeof (thread_info.thread_context) */
7774       sect->size = 716;
7775       /* offsetof (thread_info.thread_context) */
7776       sect->filepos = note->descpos + 12;
7777       sect->alignment_power = 2;
7778
7779       /* thread_info.is_active_thread */
7780       is_active_thread = bfd_get_32 (abfd, note->descdata + 8);
7781
7782       if (is_active_thread)
7783         if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
7784           return FALSE;
7785       break;
7786
7787     case 3 /* NOTE_INFO_MODULE */:
7788       /* Make a ".module/xxxxxxxx" section.  */
7789       /* module_info.base_address */
7790       base_addr = bfd_get_32 (abfd, note->descdata + 4);
7791       sprintf (buf, ".module/%08lx", (long) base_addr);
7792
7793       len = strlen (buf) + 1;
7794       name = bfd_alloc (abfd, len);
7795       if (name == NULL)
7796         return FALSE;
7797
7798       memcpy (name, buf, len);
7799
7800       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
7801
7802       if (sect == NULL)
7803         return FALSE;
7804
7805       sect->size = note->descsz;
7806       sect->filepos = note->descpos;
7807       sect->alignment_power = 2;
7808       break;
7809
7810     default:
7811       return TRUE;
7812     }
7813
7814   return TRUE;
7815 }
7816
7817 static bfd_boolean
7818 elfcore_grok_note (bfd *abfd, Elf_Internal_Note *note)
7819 {
7820   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7821
7822   switch (note->type)
7823     {
7824     default:
7825       return TRUE;
7826
7827     case NT_PRSTATUS:
7828       if (bed->elf_backend_grok_prstatus)
7829         if ((*bed->elf_backend_grok_prstatus) (abfd, note))
7830           return TRUE;
7831 #if defined (HAVE_PRSTATUS_T)
7832       return elfcore_grok_prstatus (abfd, note);
7833 #else
7834       return TRUE;
7835 #endif
7836
7837 #if defined (HAVE_PSTATUS_T)
7838     case NT_PSTATUS:
7839       return elfcore_grok_pstatus (abfd, note);
7840 #endif
7841
7842 #if defined (HAVE_LWPSTATUS_T)
7843     case NT_LWPSTATUS:
7844       return elfcore_grok_lwpstatus (abfd, note);
7845 #endif
7846
7847     case NT_FPREGSET:           /* FIXME: rename to NT_PRFPREG */
7848       return elfcore_grok_prfpreg (abfd, note);
7849
7850     case NT_WIN32PSTATUS:
7851       return elfcore_grok_win32pstatus (abfd, note);
7852
7853     case NT_PRXFPREG:           /* Linux SSE extension */
7854       if (note->namesz == 6
7855           && strcmp (note->namedata, "LINUX") == 0)
7856         return elfcore_grok_prxfpreg (abfd, note);
7857       else
7858         return TRUE;
7859
7860     case NT_PPC_VMX:
7861       if (note->namesz == 6
7862           && strcmp (note->namedata, "LINUX") == 0)
7863         return elfcore_grok_ppc_vmx (abfd, note);
7864       else
7865         return TRUE;
7866
7867     case NT_PRPSINFO:
7868     case NT_PSINFO:
7869       if (bed->elf_backend_grok_psinfo)
7870         if ((*bed->elf_backend_grok_psinfo) (abfd, note))
7871           return TRUE;
7872 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
7873       return elfcore_grok_psinfo (abfd, note);
7874 #else
7875       return TRUE;
7876 #endif
7877
7878     case NT_AUXV:
7879       {
7880         asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
7881                                                              SEC_HAS_CONTENTS);
7882
7883         if (sect == NULL)
7884           return FALSE;
7885         sect->size = note->descsz;
7886         sect->filepos = note->descpos;
7887         sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
7888
7889         return TRUE;
7890       }
7891     }
7892 }
7893
7894 static bfd_boolean
7895 elfobj_grok_gnu_build_id (bfd *abfd, Elf_Internal_Note *note)
7896 {
7897   elf_tdata (abfd)->build_id_size = note->descsz;
7898   elf_tdata (abfd)->build_id = bfd_alloc (abfd, note->descsz);
7899   if (elf_tdata (abfd)->build_id == NULL)
7900     return FALSE;
7901
7902   memcpy (elf_tdata (abfd)->build_id, note->descdata, note->descsz);
7903
7904   return TRUE;
7905 }
7906
7907 static bfd_boolean
7908 elfobj_grok_gnu_note (bfd *abfd, Elf_Internal_Note *note)
7909 {
7910   switch (note->type)
7911     {
7912     default:
7913       return TRUE;
7914
7915     case NT_GNU_BUILD_ID:
7916       return elfobj_grok_gnu_build_id (abfd, note);
7917     }
7918 }
7919
7920 static bfd_boolean
7921 elfcore_netbsd_get_lwpid (Elf_Internal_Note *note, int *lwpidp)
7922 {
7923   char *cp;
7924
7925   cp = strchr (note->namedata, '@');
7926   if (cp != NULL)
7927     {
7928       *lwpidp = atoi(cp + 1);
7929       return TRUE;
7930     }
7931   return FALSE;
7932 }
7933
7934 static bfd_boolean
7935 elfcore_grok_netbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
7936 {
7937   /* Signal number at offset 0x08. */
7938   elf_tdata (abfd)->core_signal
7939     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
7940
7941   /* Process ID at offset 0x50. */
7942   elf_tdata (abfd)->core_pid
7943     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
7944
7945   /* Command name at 0x7c (max 32 bytes, including nul). */
7946   elf_tdata (abfd)->core_command
7947     = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
7948
7949   return elfcore_make_note_pseudosection (abfd, ".note.netbsdcore.procinfo",
7950                                           note);
7951 }
7952
7953 static bfd_boolean
7954 elfcore_grok_netbsd_note (bfd *abfd, Elf_Internal_Note *note)
7955 {
7956   int lwp;
7957
7958   if (elfcore_netbsd_get_lwpid (note, &lwp))
7959     elf_tdata (abfd)->core_lwpid = lwp;
7960
7961   if (note->type == NT_NETBSDCORE_PROCINFO)
7962     {
7963       /* NetBSD-specific core "procinfo".  Note that we expect to
7964          find this note before any of the others, which is fine,
7965          since the kernel writes this note out first when it
7966          creates a core file.  */
7967
7968       return elfcore_grok_netbsd_procinfo (abfd, note);
7969     }
7970
7971   /* As of Jan 2002 there are no other machine-independent notes
7972      defined for NetBSD core files.  If the note type is less
7973      than the start of the machine-dependent note types, we don't
7974      understand it.  */
7975
7976   if (note->type < NT_NETBSDCORE_FIRSTMACH)
7977     return TRUE;
7978
7979
7980   switch (bfd_get_arch (abfd))
7981     {
7982       /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
7983          PT_GETFPREGS == mach+2.  */
7984
7985     case bfd_arch_alpha:
7986     case bfd_arch_sparc:
7987       switch (note->type)
7988         {
7989         case NT_NETBSDCORE_FIRSTMACH+0:
7990           return elfcore_make_note_pseudosection (abfd, ".reg", note);
7991
7992         case NT_NETBSDCORE_FIRSTMACH+2:
7993           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
7994
7995         default:
7996           return TRUE;
7997         }
7998
7999       /* On all other arch's, PT_GETREGS == mach+1 and
8000          PT_GETFPREGS == mach+3.  */
8001
8002     default:
8003       switch (note->type)
8004         {
8005         case NT_NETBSDCORE_FIRSTMACH+1:
8006           return elfcore_make_note_pseudosection (abfd, ".reg", note);
8007
8008         case NT_NETBSDCORE_FIRSTMACH+3:
8009           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
8010
8011         default:
8012           return TRUE;
8013         }
8014     }
8015     /* NOTREACHED */
8016 }
8017
8018 static bfd_boolean
8019 elfcore_grok_nto_status (bfd *abfd, Elf_Internal_Note *note, long *tid)
8020 {
8021   void *ddata = note->descdata;
8022   char buf[100];
8023   char *name;
8024   asection *sect;
8025   short sig;
8026   unsigned flags;
8027
8028   /* nto_procfs_status 'pid' field is at offset 0.  */
8029   elf_tdata (abfd)->core_pid = bfd_get_32 (abfd, (bfd_byte *) ddata);
8030
8031   /* nto_procfs_status 'tid' field is at offset 4.  Pass it back.  */
8032   *tid = bfd_get_32 (abfd, (bfd_byte *) ddata + 4);
8033
8034   /* nto_procfs_status 'flags' field is at offset 8.  */
8035   flags = bfd_get_32 (abfd, (bfd_byte *) ddata + 8);
8036
8037   /* nto_procfs_status 'what' field is at offset 14.  */
8038   if ((sig = bfd_get_16 (abfd, (bfd_byte *) ddata + 14)) > 0)
8039     {
8040       elf_tdata (abfd)->core_signal = sig;
8041       elf_tdata (abfd)->core_lwpid = *tid;
8042     }
8043
8044   /* _DEBUG_FLAG_CURTID (current thread) is 0x80.  Some cores
8045      do not come from signals so we make sure we set the current
8046      thread just in case.  */
8047   if (flags & 0x00000080)
8048     elf_tdata (abfd)->core_lwpid = *tid;
8049
8050   /* Make a ".qnx_core_status/%d" section.  */
8051   sprintf (buf, ".qnx_core_status/%ld", *tid);
8052
8053   name = bfd_alloc (abfd, strlen (buf) + 1);
8054   if (name == NULL)
8055     return FALSE;
8056   strcpy (name, buf);
8057
8058   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8059   if (sect == NULL)
8060     return FALSE;
8061
8062   sect->size            = note->descsz;
8063   sect->filepos         = note->descpos;
8064   sect->alignment_power = 2;
8065
8066   return (elfcore_maybe_make_sect (abfd, ".qnx_core_status", sect));
8067 }
8068
8069 static bfd_boolean
8070 elfcore_grok_nto_regs (bfd *abfd,
8071                        Elf_Internal_Note *note,
8072                        long tid,
8073                        char *base)
8074 {
8075   char buf[100];
8076   char *name;
8077   asection *sect;
8078
8079   /* Make a "(base)/%d" section.  */
8080   sprintf (buf, "%s/%ld", base, tid);
8081
8082   name = bfd_alloc (abfd, strlen (buf) + 1);
8083   if (name == NULL)
8084     return FALSE;
8085   strcpy (name, buf);
8086
8087   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8088   if (sect == NULL)
8089     return FALSE;
8090
8091   sect->size            = note->descsz;
8092   sect->filepos         = note->descpos;
8093   sect->alignment_power = 2;
8094
8095   /* This is the current thread.  */
8096   if (elf_tdata (abfd)->core_lwpid == tid)
8097     return elfcore_maybe_make_sect (abfd, base, sect);
8098
8099   return TRUE;
8100 }
8101
8102 #define BFD_QNT_CORE_INFO       7
8103 #define BFD_QNT_CORE_STATUS     8
8104 #define BFD_QNT_CORE_GREG       9
8105 #define BFD_QNT_CORE_FPREG      10
8106
8107 static bfd_boolean
8108 elfcore_grok_nto_note (bfd *abfd, Elf_Internal_Note *note)
8109 {
8110   /* Every GREG section has a STATUS section before it.  Store the
8111      tid from the previous call to pass down to the next gregs
8112      function.  */
8113   static long tid = 1;
8114
8115   switch (note->type)
8116     {
8117     case BFD_QNT_CORE_INFO:
8118       return elfcore_make_note_pseudosection (abfd, ".qnx_core_info", note);
8119     case BFD_QNT_CORE_STATUS:
8120       return elfcore_grok_nto_status (abfd, note, &tid);
8121     case BFD_QNT_CORE_GREG:
8122       return elfcore_grok_nto_regs (abfd, note, tid, ".reg");
8123     case BFD_QNT_CORE_FPREG:
8124       return elfcore_grok_nto_regs (abfd, note, tid, ".reg2");
8125     default:
8126       return TRUE;
8127     }
8128 }
8129
8130 static bfd_boolean
8131 elfcore_grok_spu_note (bfd *abfd, Elf_Internal_Note *note)
8132 {
8133   char *name;
8134   asection *sect;
8135   size_t len;
8136
8137   /* Use note name as section name.  */
8138   len = note->namesz;
8139   name = bfd_alloc (abfd, len);
8140   if (name == NULL)
8141     return FALSE;
8142   memcpy (name, note->namedata, len);
8143   name[len - 1] = '\0';
8144
8145   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8146   if (sect == NULL)
8147     return FALSE;
8148
8149   sect->size            = note->descsz;
8150   sect->filepos         = note->descpos;
8151   sect->alignment_power = 1;
8152
8153   return TRUE;
8154 }
8155
8156 /* Function: elfcore_write_note
8157
8158    Inputs:
8159      buffer to hold note, and current size of buffer
8160      name of note
8161      type of note
8162      data for note
8163      size of data for note
8164
8165    Writes note to end of buffer.  ELF64 notes are written exactly as
8166    for ELF32, despite the current (as of 2006) ELF gabi specifying
8167    that they ought to have 8-byte namesz and descsz field, and have
8168    8-byte alignment.  Other writers, eg. Linux kernel, do the same.
8169
8170    Return:
8171    Pointer to realloc'd buffer, *BUFSIZ updated.  */
8172
8173 char *
8174 elfcore_write_note (bfd *abfd,
8175                     char *buf,
8176                     int *bufsiz,
8177                     const char *name,
8178                     int type,
8179                     const void *input,
8180                     int size)
8181 {
8182   Elf_External_Note *xnp;
8183   size_t namesz;
8184   size_t newspace;
8185   char *dest;
8186
8187   namesz = 0;
8188   if (name != NULL)
8189     namesz = strlen (name) + 1;
8190
8191   newspace = 12 + ((namesz + 3) & -4) + ((size + 3) & -4);
8192
8193   buf = realloc (buf, *bufsiz + newspace);
8194   if (buf == NULL)
8195     return buf;
8196   dest = buf + *bufsiz;
8197   *bufsiz += newspace;
8198   xnp = (Elf_External_Note *) dest;
8199   H_PUT_32 (abfd, namesz, xnp->namesz);
8200   H_PUT_32 (abfd, size, xnp->descsz);
8201   H_PUT_32 (abfd, type, xnp->type);
8202   dest = xnp->name;
8203   if (name != NULL)
8204     {
8205       memcpy (dest, name, namesz);
8206       dest += namesz;
8207       while (namesz & 3)
8208         {
8209           *dest++ = '\0';
8210           ++namesz;
8211         }
8212     }
8213   memcpy (dest, input, size);
8214   dest += size;
8215   while (size & 3)
8216     {
8217       *dest++ = '\0';
8218       ++size;
8219     }
8220   return buf;
8221 }
8222
8223 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
8224 char *
8225 elfcore_write_prpsinfo (bfd  *abfd,
8226                         char *buf,
8227                         int  *bufsiz,
8228                         const char *fname,
8229                         const char *psargs)
8230 {
8231   const char *note_name = "CORE";
8232   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8233
8234   if (bed->elf_backend_write_core_note != NULL)
8235     {
8236       char *ret;
8237       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
8238                                                  NT_PRPSINFO, fname, psargs);
8239       if (ret != NULL)
8240         return ret;
8241     }
8242
8243 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
8244   if (bed->s->elfclass == ELFCLASS32)
8245     {
8246 #if defined (HAVE_PSINFO32_T)
8247       psinfo32_t data;
8248       int note_type = NT_PSINFO;
8249 #else
8250       prpsinfo32_t data;
8251       int note_type = NT_PRPSINFO;
8252 #endif
8253
8254       memset (&data, 0, sizeof (data));
8255       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
8256       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
8257       return elfcore_write_note (abfd, buf, bufsiz,
8258                                  note_name, note_type, &data, sizeof (data));
8259     }
8260   else
8261 #endif
8262     {
8263 #if defined (HAVE_PSINFO_T)
8264       psinfo_t data;
8265       int note_type = NT_PSINFO;
8266 #else
8267       prpsinfo_t data;
8268       int note_type = NT_PRPSINFO;
8269 #endif
8270
8271       memset (&data, 0, sizeof (data));
8272       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
8273       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
8274       return elfcore_write_note (abfd, buf, bufsiz,
8275                                  note_name, note_type, &data, sizeof (data));
8276     }
8277 }
8278 #endif  /* PSINFO_T or PRPSINFO_T */
8279
8280 #if defined (HAVE_PRSTATUS_T)
8281 char *
8282 elfcore_write_prstatus (bfd *abfd,
8283                         char *buf,
8284                         int *bufsiz,
8285                         long pid,
8286                         int cursig,
8287                         const void *gregs)
8288 {
8289   const char *note_name = "CORE";
8290   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8291
8292   if (bed->elf_backend_write_core_note != NULL)
8293     {
8294       char *ret;
8295       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
8296                                                  NT_PRSTATUS,
8297                                                  pid, cursig, gregs);
8298       if (ret != NULL)
8299         return ret;
8300     }
8301
8302 #if defined (HAVE_PRSTATUS32_T)
8303   if (bed->s->elfclass == ELFCLASS32)
8304     {
8305       prstatus32_t prstat;
8306
8307       memset (&prstat, 0, sizeof (prstat));
8308       prstat.pr_pid = pid;
8309       prstat.pr_cursig = cursig;
8310       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
8311       return elfcore_write_note (abfd, buf, bufsiz, note_name,
8312                                  NT_PRSTATUS, &prstat, sizeof (prstat));
8313     }
8314   else
8315 #endif
8316     {
8317       prstatus_t prstat;
8318
8319       memset (&prstat, 0, sizeof (prstat));
8320       prstat.pr_pid = pid;
8321       prstat.pr_cursig = cursig;
8322       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
8323       return elfcore_write_note (abfd, buf, bufsiz, note_name,
8324                                  NT_PRSTATUS, &prstat, sizeof (prstat));
8325     }
8326 }
8327 #endif /* HAVE_PRSTATUS_T */
8328
8329 #if defined (HAVE_LWPSTATUS_T)
8330 char *
8331 elfcore_write_lwpstatus (bfd *abfd,
8332                          char *buf,
8333                          int *bufsiz,
8334                          long pid,
8335                          int cursig,
8336                          const void *gregs)
8337 {
8338   lwpstatus_t lwpstat;
8339   const char *note_name = "CORE";
8340
8341   memset (&lwpstat, 0, sizeof (lwpstat));
8342   lwpstat.pr_lwpid  = pid >> 16;
8343   lwpstat.pr_cursig = cursig;
8344 #if defined (HAVE_LWPSTATUS_T_PR_REG)
8345   memcpy (lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
8346 #elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
8347 #if !defined(gregs)
8348   memcpy (lwpstat.pr_context.uc_mcontext.gregs,
8349           gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
8350 #else
8351   memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
8352           gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
8353 #endif
8354 #endif
8355   return elfcore_write_note (abfd, buf, bufsiz, note_name,
8356                              NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
8357 }
8358 #endif /* HAVE_LWPSTATUS_T */
8359
8360 #if defined (HAVE_PSTATUS_T)
8361 char *
8362 elfcore_write_pstatus (bfd *abfd,
8363                        char *buf,
8364                        int *bufsiz,
8365                        long pid,
8366                        int cursig ATTRIBUTE_UNUSED,
8367                        const void *gregs ATTRIBUTE_UNUSED)
8368 {
8369   const char *note_name = "CORE";
8370 #if defined (HAVE_PSTATUS32_T)
8371   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8372
8373   if (bed->s->elfclass == ELFCLASS32)
8374     {
8375       pstatus32_t pstat;
8376
8377       memset (&pstat, 0, sizeof (pstat));
8378       pstat.pr_pid = pid & 0xffff;
8379       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
8380                                 NT_PSTATUS, &pstat, sizeof (pstat));
8381       return buf;
8382     }
8383   else
8384 #endif
8385     {
8386       pstatus_t pstat;
8387
8388       memset (&pstat, 0, sizeof (pstat));
8389       pstat.pr_pid = pid & 0xffff;
8390       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
8391                                 NT_PSTATUS, &pstat, sizeof (pstat));
8392       return buf;
8393     }
8394 }
8395 #endif /* HAVE_PSTATUS_T */
8396
8397 char *
8398 elfcore_write_prfpreg (bfd *abfd,
8399                        char *buf,
8400                        int *bufsiz,
8401                        const void *fpregs,
8402                        int size)
8403 {
8404   const char *note_name = "CORE";
8405   return elfcore_write_note (abfd, buf, bufsiz,
8406                              note_name, NT_FPREGSET, fpregs, size);
8407 }
8408
8409 char *
8410 elfcore_write_prxfpreg (bfd *abfd,
8411                         char *buf,
8412                         int *bufsiz,
8413                         const void *xfpregs,
8414                         int size)
8415 {
8416   char *note_name = "LINUX";
8417   return elfcore_write_note (abfd, buf, bufsiz,
8418                              note_name, NT_PRXFPREG, xfpregs, size);
8419 }
8420
8421 char *
8422 elfcore_write_ppc_vmx (bfd *abfd,
8423                        char *buf,
8424                        int *bufsiz,
8425                        const void *ppc_vmx,
8426                        int size)
8427 {
8428   char *note_name = "LINUX";
8429   return elfcore_write_note (abfd, buf, bufsiz,
8430                              note_name, NT_PPC_VMX, ppc_vmx, size);
8431 }
8432
8433 static bfd_boolean
8434 elf_parse_notes (bfd *abfd, char *buf, size_t size, file_ptr offset)
8435 {
8436   char *p;
8437
8438   p = buf;
8439   while (p < buf + size)
8440     {
8441       /* FIXME: bad alignment assumption.  */
8442       Elf_External_Note *xnp = (Elf_External_Note *) p;
8443       Elf_Internal_Note in;
8444
8445       in.type = H_GET_32 (abfd, xnp->type);
8446
8447       in.namesz = H_GET_32 (abfd, xnp->namesz);
8448       in.namedata = xnp->name;
8449
8450       in.descsz = H_GET_32 (abfd, xnp->descsz);
8451       in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
8452       in.descpos = offset + (in.descdata - buf);
8453
8454       switch (bfd_get_format (abfd))
8455         {
8456         default:
8457           return TRUE;
8458
8459         case bfd_core:
8460           if (CONST_STRNEQ (in.namedata, "NetBSD-CORE"))
8461             {
8462               if (! elfcore_grok_netbsd_note (abfd, &in))
8463                 return FALSE;
8464             }
8465           else if (CONST_STRNEQ (in.namedata, "QNX"))
8466             {
8467               if (! elfcore_grok_nto_note (abfd, &in))
8468                 return FALSE;
8469             }
8470           else if (CONST_STRNEQ (in.namedata, "SPU/"))
8471             {
8472               if (! elfcore_grok_spu_note (abfd, &in))
8473                 return FALSE;
8474             }
8475           else
8476             {
8477               if (! elfcore_grok_note (abfd, &in))
8478                 return FALSE;
8479             }
8480           break;
8481
8482         case bfd_object:
8483           if (in.namesz == sizeof "GNU" && strcmp (in.namedata, "GNU") == 0)
8484             {
8485               if (! elfobj_grok_gnu_note (abfd, &in))
8486                 return FALSE;
8487             }
8488           break;
8489         }
8490
8491       p = in.descdata + BFD_ALIGN (in.descsz, 4);
8492     }
8493
8494   return TRUE;
8495 }
8496
8497 static bfd_boolean
8498 elf_read_notes (bfd *abfd, file_ptr offset, bfd_size_type size)
8499 {
8500   char *buf;
8501
8502   if (size <= 0)
8503     return TRUE;
8504
8505   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
8506     return FALSE;
8507
8508   buf = bfd_malloc (size);
8509   if (buf == NULL)
8510     return FALSE;
8511
8512   if (bfd_bread (buf, size, abfd) != size
8513       || !elf_parse_notes (abfd, buf, size, offset))
8514     {
8515       free (buf);
8516       return FALSE;
8517     }
8518
8519   free (buf);
8520   return TRUE;
8521 }
8522 \f
8523 /* Providing external access to the ELF program header table.  */
8524
8525 /* Return an upper bound on the number of bytes required to store a
8526    copy of ABFD's program header table entries.  Return -1 if an error
8527    occurs; bfd_get_error will return an appropriate code.  */
8528
8529 long
8530 bfd_get_elf_phdr_upper_bound (bfd *abfd)
8531 {
8532   if (abfd->xvec->flavour != bfd_target_elf_flavour)
8533     {
8534       bfd_set_error (bfd_error_wrong_format);
8535       return -1;
8536     }
8537
8538   return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
8539 }
8540
8541 /* Copy ABFD's program header table entries to *PHDRS.  The entries
8542    will be stored as an array of Elf_Internal_Phdr structures, as
8543    defined in include/elf/internal.h.  To find out how large the
8544    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
8545
8546    Return the number of program header table entries read, or -1 if an
8547    error occurs; bfd_get_error will return an appropriate code.  */
8548
8549 int
8550 bfd_get_elf_phdrs (bfd *abfd, void *phdrs)
8551 {
8552   int num_phdrs;
8553
8554   if (abfd->xvec->flavour != bfd_target_elf_flavour)
8555     {
8556       bfd_set_error (bfd_error_wrong_format);
8557       return -1;
8558     }
8559
8560   num_phdrs = elf_elfheader (abfd)->e_phnum;
8561   memcpy (phdrs, elf_tdata (abfd)->phdr,
8562           num_phdrs * sizeof (Elf_Internal_Phdr));
8563
8564   return num_phdrs;
8565 }
8566
8567 enum elf_reloc_type_class
8568 _bfd_elf_reloc_type_class (const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED)
8569 {
8570   return reloc_class_normal;
8571 }
8572
8573 /* For RELA architectures, return the relocation value for a
8574    relocation against a local symbol.  */
8575
8576 bfd_vma
8577 _bfd_elf_rela_local_sym (bfd *abfd,
8578                          Elf_Internal_Sym *sym,
8579                          asection **psec,
8580                          Elf_Internal_Rela *rel)
8581 {
8582   asection *sec = *psec;
8583   bfd_vma relocation;
8584
8585   relocation = (sec->output_section->vma
8586                 + sec->output_offset
8587                 + sym->st_value);
8588   if ((sec->flags & SEC_MERGE)
8589       && ELF_ST_TYPE (sym->st_info) == STT_SECTION
8590       && sec->sec_info_type == ELF_INFO_TYPE_MERGE)
8591     {
8592       rel->r_addend =
8593         _bfd_merged_section_offset (abfd, psec,
8594                                     elf_section_data (sec)->sec_info,
8595                                     sym->st_value + rel->r_addend);
8596       if (sec != *psec)
8597         {
8598           /* If we have changed the section, and our original section is
8599              marked with SEC_EXCLUDE, it means that the original
8600              SEC_MERGE section has been completely subsumed in some
8601              other SEC_MERGE section.  In this case, we need to leave
8602              some info around for --emit-relocs.  */
8603           if ((sec->flags & SEC_EXCLUDE) != 0)
8604             sec->kept_section = *psec;
8605           sec = *psec;
8606         }
8607       rel->r_addend -= relocation;
8608       rel->r_addend += sec->output_section->vma + sec->output_offset;
8609     }
8610   return relocation;
8611 }
8612
8613 bfd_vma
8614 _bfd_elf_rel_local_sym (bfd *abfd,
8615                         Elf_Internal_Sym *sym,
8616                         asection **psec,
8617                         bfd_vma addend)
8618 {
8619   asection *sec = *psec;
8620
8621   if (sec->sec_info_type != ELF_INFO_TYPE_MERGE)
8622     return sym->st_value + addend;
8623
8624   return _bfd_merged_section_offset (abfd, psec,
8625                                      elf_section_data (sec)->sec_info,
8626                                      sym->st_value + addend);
8627 }
8628
8629 bfd_vma
8630 _bfd_elf_section_offset (bfd *abfd,
8631                          struct bfd_link_info *info,
8632                          asection *sec,
8633                          bfd_vma offset)
8634 {
8635   switch (sec->sec_info_type)
8636     {
8637     case ELF_INFO_TYPE_STABS:
8638       return _bfd_stab_section_offset (sec, elf_section_data (sec)->sec_info,
8639                                        offset);
8640     case ELF_INFO_TYPE_EH_FRAME:
8641       return _bfd_elf_eh_frame_section_offset (abfd, info, sec, offset);
8642     default:
8643       return offset;
8644     }
8645 }
8646 \f
8647 /* Create a new BFD as if by bfd_openr.  Rather than opening a file,
8648    reconstruct an ELF file by reading the segments out of remote memory
8649    based on the ELF file header at EHDR_VMA and the ELF program headers it
8650    points to.  If not null, *LOADBASEP is filled in with the difference
8651    between the VMAs from which the segments were read, and the VMAs the
8652    file headers (and hence BFD's idea of each section's VMA) put them at.
8653
8654    The function TARGET_READ_MEMORY is called to copy LEN bytes from the
8655    remote memory at target address VMA into the local buffer at MYADDR; it
8656    should return zero on success or an `errno' code on failure.  TEMPL must
8657    be a BFD for an ELF target with the word size and byte order found in
8658    the remote memory.  */
8659
8660 bfd *
8661 bfd_elf_bfd_from_remote_memory
8662   (bfd *templ,
8663    bfd_vma ehdr_vma,
8664    bfd_vma *loadbasep,
8665    int (*target_read_memory) (bfd_vma, bfd_byte *, int))
8666 {
8667   return (*get_elf_backend_data (templ)->elf_backend_bfd_from_remote_memory)
8668     (templ, ehdr_vma, loadbasep, target_read_memory);
8669 }
8670 \f
8671 long
8672 _bfd_elf_get_synthetic_symtab (bfd *abfd,
8673                                long symcount ATTRIBUTE_UNUSED,
8674                                asymbol **syms ATTRIBUTE_UNUSED,
8675                                long dynsymcount,
8676                                asymbol **dynsyms,
8677                                asymbol **ret)
8678 {
8679   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8680   asection *relplt;
8681   asymbol *s;
8682   const char *relplt_name;
8683   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
8684   arelent *p;
8685   long count, i, n;
8686   size_t size;
8687   Elf_Internal_Shdr *hdr;
8688   char *names;
8689   asection *plt;
8690
8691   *ret = NULL;
8692
8693   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0)
8694     return 0;
8695
8696   if (dynsymcount <= 0)
8697     return 0;
8698
8699   if (!bed->plt_sym_val)
8700     return 0;
8701
8702   relplt_name = bed->relplt_name;
8703   if (relplt_name == NULL)
8704     relplt_name = bed->default_use_rela_p ? ".rela.plt" : ".rel.plt";
8705   relplt = bfd_get_section_by_name (abfd, relplt_name);
8706   if (relplt == NULL)
8707     return 0;
8708
8709   hdr = &elf_section_data (relplt)->this_hdr;
8710   if (hdr->sh_link != elf_dynsymtab (abfd)
8711       || (hdr->sh_type != SHT_REL && hdr->sh_type != SHT_RELA))
8712     return 0;
8713
8714   plt = bfd_get_section_by_name (abfd, ".plt");
8715   if (plt == NULL)
8716     return 0;
8717
8718   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
8719   if (! (*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
8720     return -1;
8721
8722   count = relplt->size / hdr->sh_entsize;
8723   size = count * sizeof (asymbol);
8724   p = relplt->relocation;
8725   for (i = 0; i < count; i++, p++)
8726     size += strlen ((*p->sym_ptr_ptr)->name) + sizeof ("@plt");
8727
8728   s = *ret = bfd_malloc (size);
8729   if (s == NULL)
8730     return -1;
8731
8732   names = (char *) (s + count);
8733   p = relplt->relocation;
8734   n = 0;
8735   for (i = 0; i < count; i++, p++)
8736     {
8737       size_t len;
8738       bfd_vma addr;
8739
8740       addr = bed->plt_sym_val (i, plt, p);
8741       if (addr == (bfd_vma) -1)
8742         continue;
8743
8744       *s = **p->sym_ptr_ptr;
8745       /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
8746          we are defining a symbol, ensure one of them is set.  */
8747       if ((s->flags & BSF_LOCAL) == 0)
8748         s->flags |= BSF_GLOBAL;
8749       s->section = plt;
8750       s->value = addr - plt->vma;
8751       s->name = names;
8752       s->udata.p = NULL;
8753       len = strlen ((*p->sym_ptr_ptr)->name);
8754       memcpy (names, (*p->sym_ptr_ptr)->name, len);
8755       names += len;
8756       memcpy (names, "@plt", sizeof ("@plt"));
8757       names += sizeof ("@plt");
8758       ++s, ++n;
8759     }
8760
8761   return n;
8762 }
8763
8764 /* It is only used by x86-64 so far.  */
8765 asection _bfd_elf_large_com_section
8766   = BFD_FAKE_SECTION (_bfd_elf_large_com_section,
8767                       SEC_IS_COMMON, NULL, "LARGE_COMMON", 0);
8768
8769 void
8770 _bfd_elf_set_osabi (bfd * abfd,
8771                     struct bfd_link_info * link_info ATTRIBUTE_UNUSED)
8772 {
8773   Elf_Internal_Ehdr * i_ehdrp;  /* ELF file header, internal form.  */
8774
8775   i_ehdrp = elf_elfheader (abfd);
8776
8777   i_ehdrp->e_ident[EI_OSABI] = get_elf_backend_data (abfd)->elf_osabi;
8778 }
8779
8780
8781 /* Return TRUE for ELF symbol types that represent functions.
8782    This is the default version of this function, which is sufficient for
8783    most targets.  It returns true if TYPE is STT_FUNC.  */
8784
8785 bfd_boolean
8786 _bfd_elf_is_function_type (unsigned int type)
8787 {
8788   return (type == STT_FUNC);
8789 }