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