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