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