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