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