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