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