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