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