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