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