Re-apply "elf: Properly compute offsets of note descriptor and next note"
[external/binutils.git] / bfd / elf.c
1 /* ELF executable support for BFD.
2
3    Copyright (C) 1993-2017 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       int tls_count = 0;
4570       asection *first_tls = NULL;
4571       asection *first_mbind = NULL;
4572       asection *dynsec, *eh_frame_hdr;
4573       bfd_size_type amt;
4574       bfd_vma addr_mask, wrap_to = 0;
4575       bfd_boolean linker_created_pt_phdr_segment = FALSE;
4576
4577       /* Select the allocated sections, and sort them.  */
4578
4579       sections = (asection **) bfd_malloc2 (bfd_count_sections (abfd),
4580                                             sizeof (asection *));
4581       if (sections == NULL)
4582         goto error_return;
4583
4584       /* Calculate top address, avoiding undefined behaviour of shift
4585          left operator when shift count is equal to size of type
4586          being shifted.  */
4587       addr_mask = ((bfd_vma) 1 << (bfd_arch_bits_per_address (abfd) - 1)) - 1;
4588       addr_mask = (addr_mask << 1) + 1;
4589
4590       i = 0;
4591       for (s = abfd->sections; s != NULL; s = s->next)
4592         {
4593           if ((s->flags & SEC_ALLOC) != 0)
4594             {
4595               sections[i] = s;
4596               ++i;
4597               /* A wrapping section potentially clashes with header.  */
4598               if (((s->lma + s->size) & addr_mask) < (s->lma & addr_mask))
4599                 wrap_to = (s->lma + s->size) & addr_mask;
4600             }
4601         }
4602       BFD_ASSERT (i <= bfd_count_sections (abfd));
4603       count = i;
4604
4605       qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
4606
4607       /* Build the mapping.  */
4608
4609       mfirst = NULL;
4610       pm = &mfirst;
4611
4612       /* If we have a .interp section, then create a PT_PHDR segment for
4613          the program headers and a PT_INTERP segment for the .interp
4614          section.  */
4615       s = bfd_get_section_by_name (abfd, ".interp");
4616       if (s != NULL && (s->flags & SEC_LOAD) != 0)
4617         {
4618           amt = sizeof (struct elf_segment_map);
4619           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4620           if (m == NULL)
4621             goto error_return;
4622           m->next = NULL;
4623           m->p_type = PT_PHDR;
4624           m->p_flags = PF_R;
4625           m->p_flags_valid = 1;
4626           m->includes_phdrs = 1;
4627           linker_created_pt_phdr_segment = TRUE;
4628           *pm = m;
4629           pm = &m->next;
4630
4631           amt = sizeof (struct elf_segment_map);
4632           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4633           if (m == NULL)
4634             goto error_return;
4635           m->next = NULL;
4636           m->p_type = PT_INTERP;
4637           m->count = 1;
4638           m->sections[0] = s;
4639
4640           *pm = m;
4641           pm = &m->next;
4642         }
4643
4644       /* Look through the sections.  We put sections in the same program
4645          segment when the start of the second section can be placed within
4646          a few bytes of the end of the first section.  */
4647       last_hdr = NULL;
4648       last_size = 0;
4649       phdr_index = 0;
4650       maxpagesize = bed->maxpagesize;
4651       /* PR 17512: file: c8455299.
4652          Avoid divide-by-zero errors later on.
4653          FIXME: Should we abort if the maxpagesize is zero ?  */
4654       if (maxpagesize == 0)
4655         maxpagesize = 1;
4656       writable = FALSE;
4657       dynsec = bfd_get_section_by_name (abfd, ".dynamic");
4658       if (dynsec != NULL
4659           && (dynsec->flags & SEC_LOAD) == 0)
4660         dynsec = NULL;
4661
4662       /* Deal with -Ttext or something similar such that the first section
4663          is not adjacent to the program headers.  This is an
4664          approximation, since at this point we don't know exactly how many
4665          program headers we will need.  */
4666       if (count > 0)
4667         {
4668           bfd_size_type phdr_size = elf_program_header_size (abfd);
4669
4670           if (phdr_size == (bfd_size_type) -1)
4671             phdr_size = get_program_header_size (abfd, info);
4672           phdr_size += bed->s->sizeof_ehdr;
4673           if ((abfd->flags & D_PAGED) == 0
4674               || (sections[0]->lma & addr_mask) < phdr_size
4675               || ((sections[0]->lma & addr_mask) % maxpagesize
4676                   < phdr_size % maxpagesize)
4677               || (sections[0]->lma & addr_mask & -maxpagesize) < wrap_to)
4678             {
4679               /* PR 20815: The ELF standard says that a PT_PHDR segment, if
4680                  present, must be included as part of the memory image of the
4681                  program.  Ie it must be part of a PT_LOAD segment as well.
4682                  If we have had to create our own PT_PHDR segment, but it is
4683                  not going to be covered by the first PT_LOAD segment, then
4684                  force the inclusion if we can...  */
4685               if ((abfd->flags & D_PAGED) != 0
4686                   && linker_created_pt_phdr_segment)
4687                 phdr_in_segment = TRUE;
4688               else
4689                 phdr_in_segment = FALSE;
4690             }
4691         }
4692
4693       for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
4694         {
4695           asection *hdr;
4696           bfd_boolean new_segment;
4697
4698           hdr = *hdrpp;
4699
4700           /* See if this section and the last one will fit in the same
4701              segment.  */
4702
4703           if (last_hdr == NULL)
4704             {
4705               /* If we don't have a segment yet, then we don't need a new
4706                  one (we build the last one after this loop).  */
4707               new_segment = FALSE;
4708             }
4709           else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
4710             {
4711               /* If this section has a different relation between the
4712                  virtual address and the load address, then we need a new
4713                  segment.  */
4714               new_segment = TRUE;
4715             }
4716           else if (hdr->lma < last_hdr->lma + last_size
4717                    || last_hdr->lma + last_size < last_hdr->lma)
4718             {
4719               /* If this section has a load address that makes it overlap
4720                  the previous section, then we need a new segment.  */
4721               new_segment = TRUE;
4722             }
4723           /* In the next test we have to be careful when last_hdr->lma is close
4724              to the end of the address space.  If the aligned address wraps
4725              around to the start of the address space, then there are no more
4726              pages left in memory and it is OK to assume that the current
4727              section can be included in the current segment.  */
4728           else if ((BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
4729                     > last_hdr->lma)
4730                    && (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
4731                        <= hdr->lma))
4732             {
4733               /* If putting this section in this segment would force us to
4734                  skip a page in the segment, then we need a new segment.  */
4735               new_segment = TRUE;
4736             }
4737           else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
4738                    && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0
4739                    && ((abfd->flags & D_PAGED) == 0
4740                        || (((last_hdr->lma + last_size - 1) & -maxpagesize)
4741                            != (hdr->lma & -maxpagesize))))
4742             {
4743               /* We don't want to put a loaded section after a
4744                  nonloaded (ie. bss style) section in the same segment
4745                  as that will force the non-loaded section to be loaded.
4746                  Consider .tbss sections as loaded for this purpose.
4747                  However, like the writable/non-writable case below,
4748                  if they are on the same page then they must be put
4749                  in the same segment.  */
4750               new_segment = TRUE;
4751             }
4752           else if ((abfd->flags & D_PAGED) == 0)
4753             {
4754               /* If the file is not demand paged, which means that we
4755                  don't require the sections to be correctly aligned in the
4756                  file, then there is no other reason for a new segment.  */
4757               new_segment = FALSE;
4758             }
4759           else if (! writable
4760                    && (hdr->flags & SEC_READONLY) == 0
4761                    && (((last_hdr->lma + last_size - 1) & -maxpagesize)
4762                        != (hdr->lma & -maxpagesize)))
4763             {
4764               /* We don't want to put a writable section in a read only
4765                  segment, unless they are on the same page in memory
4766                  anyhow.  We already know that the last section does not
4767                  bring us past the current section on the page, so the
4768                  only case in which the new section is not on the same
4769                  page as the previous section is when the previous section
4770                  ends precisely on a page boundary.  */
4771               new_segment = TRUE;
4772             }
4773           else
4774             {
4775               /* Otherwise, we can use the same segment.  */
4776               new_segment = FALSE;
4777             }
4778
4779           /* Allow interested parties a chance to override our decision.  */
4780           if (last_hdr != NULL
4781               && info != NULL
4782               && info->callbacks->override_segment_assignment != NULL)
4783             new_segment
4784               = info->callbacks->override_segment_assignment (info, abfd, hdr,
4785                                                               last_hdr,
4786                                                               new_segment);
4787
4788           if (! new_segment)
4789             {
4790               if ((hdr->flags & SEC_READONLY) == 0)
4791                 writable = TRUE;
4792               last_hdr = hdr;
4793               /* .tbss sections effectively have zero size.  */
4794               if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
4795                   != SEC_THREAD_LOCAL)
4796                 last_size = hdr->size;
4797               else
4798                 last_size = 0;
4799               continue;
4800             }
4801
4802           /* We need a new program segment.  We must create a new program
4803              header holding all the sections from phdr_index until hdr.  */
4804
4805           m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
4806           if (m == NULL)
4807             goto error_return;
4808
4809           *pm = m;
4810           pm = &m->next;
4811
4812           if ((hdr->flags & SEC_READONLY) == 0)
4813             writable = TRUE;
4814           else
4815             writable = FALSE;
4816
4817           last_hdr = hdr;
4818           /* .tbss sections effectively have zero size.  */
4819           if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
4820             last_size = hdr->size;
4821           else
4822             last_size = 0;
4823           phdr_index = i;
4824           phdr_in_segment = FALSE;
4825         }
4826
4827       /* Create a final PT_LOAD program segment, but not if it's just
4828          for .tbss.  */
4829       if (last_hdr != NULL
4830           && (i - phdr_index != 1
4831               || ((last_hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
4832                   != SEC_THREAD_LOCAL)))
4833         {
4834           m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
4835           if (m == NULL)
4836             goto error_return;
4837
4838           *pm = m;
4839           pm = &m->next;
4840         }
4841
4842       /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
4843       if (dynsec != NULL)
4844         {
4845           m = _bfd_elf_make_dynamic_segment (abfd, dynsec);
4846           if (m == NULL)
4847             goto error_return;
4848           *pm = m;
4849           pm = &m->next;
4850         }
4851
4852       /* For each batch of consecutive loadable .note sections,
4853          add a PT_NOTE segment.  We don't use bfd_get_section_by_name,
4854          because if we link together nonloadable .note sections and
4855          loadable .note sections, we will generate two .note sections
4856          in the output file.  FIXME: Using names for section types is
4857          bogus anyhow.  */
4858       for (s = abfd->sections; s != NULL; s = s->next)
4859         {
4860           if ((s->flags & SEC_LOAD) != 0
4861               && CONST_STRNEQ (s->name, ".note"))
4862             {
4863               asection *s2;
4864
4865               count = 1;
4866               amt = sizeof (struct elf_segment_map);
4867               if (s->alignment_power == 2)
4868                 for (s2 = s; s2->next != NULL; s2 = s2->next)
4869                   {
4870                     if (s2->next->alignment_power == 2
4871                         && (s2->next->flags & SEC_LOAD) != 0
4872                         && CONST_STRNEQ (s2->next->name, ".note")
4873                         && align_power (s2->lma + s2->size, 2)
4874                            == s2->next->lma)
4875                       count++;
4876                     else
4877                       break;
4878                   }
4879               amt += (count - 1) * sizeof (asection *);
4880               m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4881               if (m == NULL)
4882                 goto error_return;
4883               m->next = NULL;
4884               m->p_type = PT_NOTE;
4885               m->count = count;
4886               while (count > 1)
4887                 {
4888                   m->sections[m->count - count--] = s;
4889                   BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
4890                   s = s->next;
4891                 }
4892               m->sections[m->count - 1] = s;
4893               BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
4894               *pm = m;
4895               pm = &m->next;
4896             }
4897           if (s->flags & SEC_THREAD_LOCAL)
4898             {
4899               if (! tls_count)
4900                 first_tls = s;
4901               tls_count++;
4902             }
4903           if (first_mbind == NULL
4904               && (elf_section_flags (s) & SHF_GNU_MBIND) != 0)
4905             first_mbind = s;
4906         }
4907
4908       /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
4909       if (tls_count > 0)
4910         {
4911           amt = sizeof (struct elf_segment_map);
4912           amt += (tls_count - 1) * sizeof (asection *);
4913           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4914           if (m == NULL)
4915             goto error_return;
4916           m->next = NULL;
4917           m->p_type = PT_TLS;
4918           m->count = tls_count;
4919           /* Mandated PF_R.  */
4920           m->p_flags = PF_R;
4921           m->p_flags_valid = 1;
4922           s = first_tls;
4923           for (i = 0; i < (unsigned int) tls_count; ++i)
4924             {
4925               if ((s->flags & SEC_THREAD_LOCAL) == 0)
4926                 {
4927                   _bfd_error_handler
4928                     (_("%B: TLS sections are not adjacent:"), abfd);
4929                   s = first_tls;
4930                   i = 0;
4931                   while (i < (unsigned int) tls_count)
4932                     {
4933                       if ((s->flags & SEC_THREAD_LOCAL) != 0)
4934                         {
4935                           _bfd_error_handler (_("           TLS: %A"), s);
4936                           i++;
4937                         }
4938                       else
4939                         _bfd_error_handler (_(" non-TLS: %A"), s);
4940                       s = s->next;
4941                     }
4942                   bfd_set_error (bfd_error_bad_value);
4943                   goto error_return;
4944                 }
4945               m->sections[i] = s;
4946               s = s->next;
4947             }
4948
4949           *pm = m;
4950           pm = &m->next;
4951         }
4952
4953       if (first_mbind && (abfd->flags & D_PAGED) != 0)
4954         for (s = first_mbind; s != NULL; s = s->next)
4955           if ((elf_section_flags (s) & SHF_GNU_MBIND) != 0
4956               && (elf_section_data (s)->this_hdr.sh_info
4957                   <= PT_GNU_MBIND_NUM))
4958             {
4959               /* Mandated PF_R.  */
4960               unsigned long p_flags = PF_R;
4961               if ((s->flags & SEC_READONLY) == 0)
4962                 p_flags |= PF_W;
4963               if ((s->flags & SEC_CODE) != 0)
4964                 p_flags |= PF_X;
4965
4966               amt = sizeof (struct elf_segment_map) + sizeof (asection *);
4967               m = bfd_zalloc (abfd, amt);
4968               if (m == NULL)
4969                 goto error_return;
4970               m->next = NULL;
4971               m->p_type = (PT_GNU_MBIND_LO
4972                            + elf_section_data (s)->this_hdr.sh_info);
4973               m->count = 1;
4974               m->p_flags_valid = 1;
4975               m->sections[0] = s;
4976               m->p_flags = p_flags;
4977
4978               *pm = m;
4979               pm = &m->next;
4980             }
4981
4982       /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
4983          segment.  */
4984       eh_frame_hdr = elf_eh_frame_hdr (abfd);
4985       if (eh_frame_hdr != NULL
4986           && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
4987         {
4988           amt = sizeof (struct elf_segment_map);
4989           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4990           if (m == NULL)
4991             goto error_return;
4992           m->next = NULL;
4993           m->p_type = PT_GNU_EH_FRAME;
4994           m->count = 1;
4995           m->sections[0] = eh_frame_hdr->output_section;
4996
4997           *pm = m;
4998           pm = &m->next;
4999         }
5000
5001       if (elf_stack_flags (abfd))
5002         {
5003           amt = sizeof (struct elf_segment_map);
5004           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5005           if (m == NULL)
5006             goto error_return;
5007           m->next = NULL;
5008           m->p_type = PT_GNU_STACK;
5009           m->p_flags = elf_stack_flags (abfd);
5010           m->p_align = bed->stack_align;
5011           m->p_flags_valid = 1;
5012           m->p_align_valid = m->p_align != 0;
5013           if (info->stacksize > 0)
5014             {
5015               m->p_size = info->stacksize;
5016               m->p_size_valid = 1;
5017             }
5018
5019           *pm = m;
5020           pm = &m->next;
5021         }
5022
5023       if (info != NULL && info->relro)
5024         {
5025           for (m = mfirst; m != NULL; m = m->next)
5026             {
5027               if (m->p_type == PT_LOAD
5028                   && m->count != 0
5029                   && m->sections[0]->vma >= info->relro_start
5030                   && m->sections[0]->vma < info->relro_end)
5031                 {
5032                   i = m->count;
5033                   while (--i != (unsigned) -1)
5034                     if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS))
5035                         == (SEC_LOAD | SEC_HAS_CONTENTS))
5036                       break;
5037
5038                   if (i != (unsigned) -1)
5039                     break;
5040                 }
5041             }
5042
5043           /* Make a PT_GNU_RELRO segment only when it isn't empty.  */
5044           if (m != NULL)
5045             {
5046               amt = sizeof (struct elf_segment_map);
5047               m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
5048               if (m == NULL)
5049                 goto error_return;
5050               m->next = NULL;
5051               m->p_type = PT_GNU_RELRO;
5052               *pm = m;
5053               pm = &m->next;
5054             }
5055         }
5056
5057       free (sections);
5058       elf_seg_map (abfd) = mfirst;
5059     }
5060
5061   if (!elf_modify_segment_map (abfd, info, no_user_phdrs))
5062     return FALSE;
5063
5064   for (count = 0, m = elf_seg_map (abfd); m != NULL; m = m->next)
5065     ++count;
5066   elf_program_header_size (abfd) = count * bed->s->sizeof_phdr;
5067
5068   return TRUE;
5069
5070  error_return:
5071   if (sections != NULL)
5072     free (sections);
5073   return FALSE;
5074 }
5075
5076 /* Sort sections by address.  */
5077
5078 static int
5079 elf_sort_sections (const void *arg1, const void *arg2)
5080 {
5081   const asection *sec1 = *(const asection **) arg1;
5082   const asection *sec2 = *(const asection **) arg2;
5083   bfd_size_type size1, size2;
5084
5085   /* Sort by LMA first, since this is the address used to
5086      place the section into a segment.  */
5087   if (sec1->lma < sec2->lma)
5088     return -1;
5089   else if (sec1->lma > sec2->lma)
5090     return 1;
5091
5092   /* Then sort by VMA.  Normally the LMA and the VMA will be
5093      the same, and this will do nothing.  */
5094   if (sec1->vma < sec2->vma)
5095     return -1;
5096   else if (sec1->vma > sec2->vma)
5097     return 1;
5098
5099   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
5100
5101 #define TOEND(x) (((x)->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0)
5102
5103   if (TOEND (sec1))
5104     {
5105       if (TOEND (sec2))
5106         {
5107           /* If the indicies are the same, do not return 0
5108              here, but continue to try the next comparison.  */
5109           if (sec1->target_index - sec2->target_index != 0)
5110             return sec1->target_index - sec2->target_index;
5111         }
5112       else
5113         return 1;
5114     }
5115   else if (TOEND (sec2))
5116     return -1;
5117
5118 #undef TOEND
5119
5120   /* Sort by size, to put zero sized sections
5121      before others at the same address.  */
5122
5123   size1 = (sec1->flags & SEC_LOAD) ? sec1->size : 0;
5124   size2 = (sec2->flags & SEC_LOAD) ? sec2->size : 0;
5125
5126   if (size1 < size2)
5127     return -1;
5128   if (size1 > size2)
5129     return 1;
5130
5131   return sec1->target_index - sec2->target_index;
5132 }
5133
5134 /* Ian Lance Taylor writes:
5135
5136    We shouldn't be using % with a negative signed number.  That's just
5137    not good.  We have to make sure either that the number is not
5138    negative, or that the number has an unsigned type.  When the types
5139    are all the same size they wind up as unsigned.  When file_ptr is a
5140    larger signed type, the arithmetic winds up as signed long long,
5141    which is wrong.
5142
5143    What we're trying to say here is something like ``increase OFF by
5144    the least amount that will cause it to be equal to the VMA modulo
5145    the page size.''  */
5146 /* In other words, something like:
5147
5148    vma_offset = m->sections[0]->vma % bed->maxpagesize;
5149    off_offset = off % bed->maxpagesize;
5150    if (vma_offset < off_offset)
5151      adjustment = vma_offset + bed->maxpagesize - off_offset;
5152    else
5153      adjustment = vma_offset - off_offset;
5154
5155    which can be collapsed into the expression below.  */
5156
5157 static file_ptr
5158 vma_page_aligned_bias (bfd_vma vma, ufile_ptr off, bfd_vma maxpagesize)
5159 {
5160   /* PR binutils/16199: Handle an alignment of zero.  */
5161   if (maxpagesize == 0)
5162     maxpagesize = 1;
5163   return ((vma - off) % maxpagesize);
5164 }
5165
5166 static void
5167 print_segment_map (const struct elf_segment_map *m)
5168 {
5169   unsigned int j;
5170   const char *pt = get_segment_type (m->p_type);
5171   char buf[32];
5172
5173   if (pt == NULL)
5174     {
5175       if (m->p_type >= PT_LOPROC && m->p_type <= PT_HIPROC)
5176         sprintf (buf, "LOPROC+%7.7x",
5177                  (unsigned int) (m->p_type - PT_LOPROC));
5178       else if (m->p_type >= PT_LOOS && m->p_type <= PT_HIOS)
5179         sprintf (buf, "LOOS+%7.7x",
5180                  (unsigned int) (m->p_type - PT_LOOS));
5181       else
5182         snprintf (buf, sizeof (buf), "%8.8x",
5183                   (unsigned int) m->p_type);
5184       pt = buf;
5185     }
5186   fflush (stdout);
5187   fprintf (stderr, "%s:", pt);
5188   for (j = 0; j < m->count; j++)
5189     fprintf (stderr, " %s", m->sections [j]->name);
5190   putc ('\n',stderr);
5191   fflush (stderr);
5192 }
5193
5194 static bfd_boolean
5195 write_zeros (bfd *abfd, file_ptr pos, bfd_size_type len)
5196 {
5197   void *buf;
5198   bfd_boolean ret;
5199
5200   if (bfd_seek (abfd, pos, SEEK_SET) != 0)
5201     return FALSE;
5202   buf = bfd_zmalloc (len);
5203   if (buf == NULL)
5204     return FALSE;
5205   ret = bfd_bwrite (buf, len, abfd) == len;
5206   free (buf);
5207   return ret;
5208 }
5209
5210 /* Assign file positions to the sections based on the mapping from
5211    sections to segments.  This function also sets up some fields in
5212    the file header.  */
5213
5214 static bfd_boolean
5215 assign_file_positions_for_load_sections (bfd *abfd,
5216                                          struct bfd_link_info *link_info)
5217 {
5218   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5219   struct elf_segment_map *m;
5220   Elf_Internal_Phdr *phdrs;
5221   Elf_Internal_Phdr *p;
5222   file_ptr off;
5223   bfd_size_type maxpagesize;
5224   unsigned int pt_load_count = 0;
5225   unsigned int alloc;
5226   unsigned int i, j;
5227   bfd_vma header_pad = 0;
5228
5229   if (link_info == NULL
5230       && !_bfd_elf_map_sections_to_segments (abfd, link_info))
5231     return FALSE;
5232
5233   alloc = 0;
5234   for (m = elf_seg_map (abfd); m != NULL; m = m->next)
5235     {
5236       ++alloc;
5237       if (m->header_size)
5238         header_pad = m->header_size;
5239     }
5240
5241   if (alloc)
5242     {
5243       elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
5244       elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
5245     }
5246   else
5247     {
5248       /* PR binutils/12467.  */
5249       elf_elfheader (abfd)->e_phoff = 0;
5250       elf_elfheader (abfd)->e_phentsize = 0;
5251     }
5252
5253   elf_elfheader (abfd)->e_phnum = alloc;
5254
5255   if (elf_program_header_size (abfd) == (bfd_size_type) -1)
5256     elf_program_header_size (abfd) = alloc * bed->s->sizeof_phdr;
5257   else
5258     BFD_ASSERT (elf_program_header_size (abfd)
5259                 >= alloc * bed->s->sizeof_phdr);
5260
5261   if (alloc == 0)
5262     {
5263       elf_next_file_pos (abfd) = bed->s->sizeof_ehdr;
5264       return TRUE;
5265     }
5266
5267   /* We're writing the size in elf_program_header_size (abfd),
5268      see assign_file_positions_except_relocs, so make sure we have
5269      that amount allocated, with trailing space cleared.
5270      The variable alloc contains the computed need, while
5271      elf_program_header_size (abfd) contains the size used for the
5272      layout.
5273      See ld/emultempl/elf-generic.em:gld${EMULATION_NAME}_map_segments
5274      where the layout is forced to according to a larger size in the
5275      last iterations for the testcase ld-elf/header.  */
5276   BFD_ASSERT (elf_program_header_size (abfd) % bed->s->sizeof_phdr
5277               == 0);
5278   phdrs = (Elf_Internal_Phdr *)
5279      bfd_zalloc2 (abfd,
5280                   (elf_program_header_size (abfd) / bed->s->sizeof_phdr),
5281                   sizeof (Elf_Internal_Phdr));
5282   elf_tdata (abfd)->phdr = phdrs;
5283   if (phdrs == NULL)
5284     return FALSE;
5285
5286   maxpagesize = 1;
5287   if ((abfd->flags & D_PAGED) != 0)
5288     maxpagesize = bed->maxpagesize;
5289
5290   off = bed->s->sizeof_ehdr;
5291   off += alloc * bed->s->sizeof_phdr;
5292   if (header_pad < (bfd_vma) off)
5293     header_pad = 0;
5294   else
5295     header_pad -= off;
5296   off += header_pad;
5297
5298   for (m = elf_seg_map (abfd), p = phdrs, j = 0;
5299        m != NULL;
5300        m = m->next, p++, j++)
5301     {
5302       asection **secpp;
5303       bfd_vma off_adjust;
5304       bfd_boolean no_contents;
5305
5306       /* If elf_segment_map is not from map_sections_to_segments, the
5307          sections may not be correctly ordered.  NOTE: sorting should
5308          not be done to the PT_NOTE section of a corefile, which may
5309          contain several pseudo-sections artificially created by bfd.
5310          Sorting these pseudo-sections breaks things badly.  */
5311       if (m->count > 1
5312           && !(elf_elfheader (abfd)->e_type == ET_CORE
5313                && m->p_type == PT_NOTE))
5314         qsort (m->sections, (size_t) m->count, sizeof (asection *),
5315                elf_sort_sections);
5316
5317       /* An ELF segment (described by Elf_Internal_Phdr) may contain a
5318          number of sections with contents contributing to both p_filesz
5319          and p_memsz, followed by a number of sections with no contents
5320          that just contribute to p_memsz.  In this loop, OFF tracks next
5321          available file offset for PT_LOAD and PT_NOTE segments.  */
5322       p->p_type = m->p_type;
5323       p->p_flags = m->p_flags;
5324
5325       if (m->count == 0)
5326         p->p_vaddr = 0;
5327       else
5328         p->p_vaddr = m->sections[0]->vma - m->p_vaddr_offset;
5329
5330       if (m->p_paddr_valid)
5331         p->p_paddr = m->p_paddr;
5332       else if (m->count == 0)
5333         p->p_paddr = 0;
5334       else
5335         p->p_paddr = m->sections[0]->lma - m->p_vaddr_offset;
5336
5337       if (p->p_type == PT_LOAD
5338           && (abfd->flags & D_PAGED) != 0)
5339         {
5340           /* p_align in demand paged PT_LOAD segments effectively stores
5341              the maximum page size.  When copying an executable with
5342              objcopy, we set m->p_align from the input file.  Use this
5343              value for maxpagesize rather than bed->maxpagesize, which
5344              may be different.  Note that we use maxpagesize for PT_TLS
5345              segment alignment later in this function, so we are relying
5346              on at least one PT_LOAD segment appearing before a PT_TLS
5347              segment.  */
5348           if (m->p_align_valid)
5349             maxpagesize = m->p_align;
5350
5351           p->p_align = maxpagesize;
5352           pt_load_count += 1;
5353         }
5354       else if (m->p_align_valid)
5355         p->p_align = m->p_align;
5356       else if (m->count == 0)
5357         p->p_align = 1 << bed->s->log_file_align;
5358       else
5359         p->p_align = 0;
5360
5361       no_contents = FALSE;
5362       off_adjust = 0;
5363       if (p->p_type == PT_LOAD
5364           && m->count > 0)
5365         {
5366           bfd_size_type align;
5367           unsigned int align_power = 0;
5368
5369           if (m->p_align_valid)
5370             align = p->p_align;
5371           else
5372             {
5373               for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
5374                 {
5375                   unsigned int secalign;
5376
5377                   secalign = bfd_get_section_alignment (abfd, *secpp);
5378                   if (secalign > align_power)
5379                     align_power = secalign;
5380                 }
5381               align = (bfd_size_type) 1 << align_power;
5382               if (align < maxpagesize)
5383                 align = maxpagesize;
5384             }
5385
5386           for (i = 0; i < m->count; i++)
5387             if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
5388               /* If we aren't making room for this section, then
5389                  it must be SHT_NOBITS regardless of what we've
5390                  set via struct bfd_elf_special_section.  */
5391               elf_section_type (m->sections[i]) = SHT_NOBITS;
5392
5393           /* Find out whether this segment contains any loadable
5394              sections.  */
5395           no_contents = TRUE;
5396           for (i = 0; i < m->count; i++)
5397             if (elf_section_type (m->sections[i]) != SHT_NOBITS)
5398               {
5399                 no_contents = FALSE;
5400                 break;
5401               }
5402
5403           off_adjust = vma_page_aligned_bias (p->p_vaddr, off, align);
5404
5405           /* Broken hardware and/or kernel require that files do not
5406              map the same page with different permissions on some hppa
5407              processors.  */
5408           if (pt_load_count > 1
5409               && bed->no_page_alias
5410               && (off & (maxpagesize - 1)) != 0
5411               && (off & -maxpagesize) == ((off + off_adjust) & -maxpagesize))
5412             off_adjust += maxpagesize;
5413           off += off_adjust;
5414           if (no_contents)
5415             {
5416               /* We shouldn't need to align the segment on disk since
5417                  the segment doesn't need file space, but the gABI
5418                  arguably requires the alignment and glibc ld.so
5419                  checks it.  So to comply with the alignment
5420                  requirement but not waste file space, we adjust
5421                  p_offset for just this segment.  (OFF_ADJUST is
5422                  subtracted from OFF later.)  This may put p_offset
5423                  past the end of file, but that shouldn't matter.  */
5424             }
5425           else
5426             off_adjust = 0;
5427         }
5428       /* Make sure the .dynamic section is the first section in the
5429          PT_DYNAMIC segment.  */
5430       else if (p->p_type == PT_DYNAMIC
5431                && m->count > 1
5432                && strcmp (m->sections[0]->name, ".dynamic") != 0)
5433         {
5434           _bfd_error_handler
5435             (_("%B: The first section in the PT_DYNAMIC segment"
5436                " is not the .dynamic section"),
5437              abfd);
5438           bfd_set_error (bfd_error_bad_value);
5439           return FALSE;
5440         }
5441       /* Set the note section type to SHT_NOTE.  */
5442       else if (p->p_type == PT_NOTE)
5443         for (i = 0; i < m->count; i++)
5444           elf_section_type (m->sections[i]) = SHT_NOTE;
5445
5446       p->p_offset = 0;
5447       p->p_filesz = 0;
5448       p->p_memsz = 0;
5449
5450       if (m->includes_filehdr)
5451         {
5452           if (!m->p_flags_valid)
5453             p->p_flags |= PF_R;
5454           p->p_filesz = bed->s->sizeof_ehdr;
5455           p->p_memsz = bed->s->sizeof_ehdr;
5456           if (m->count > 0)
5457             {
5458               if (p->p_vaddr < (bfd_vma) off
5459                   || (!m->p_paddr_valid
5460                       && p->p_paddr < (bfd_vma) off))
5461                 {
5462                   _bfd_error_handler
5463                     (_("%B: Not enough room for program headers,"
5464                        " try linking with -N"),
5465                      abfd);
5466                   bfd_set_error (bfd_error_bad_value);
5467                   return FALSE;
5468                 }
5469
5470               p->p_vaddr -= off;
5471               if (!m->p_paddr_valid)
5472                 p->p_paddr -= off;
5473             }
5474         }
5475
5476       if (m->includes_phdrs)
5477         {
5478           if (!m->p_flags_valid)
5479             p->p_flags |= PF_R;
5480
5481           if (!m->includes_filehdr)
5482             {
5483               p->p_offset = bed->s->sizeof_ehdr;
5484
5485               if (m->count > 0)
5486                 {
5487                   p->p_vaddr -= off - p->p_offset;
5488                   if (!m->p_paddr_valid)
5489                     p->p_paddr -= off - p->p_offset;
5490                 }
5491             }
5492
5493           p->p_filesz += alloc * bed->s->sizeof_phdr;
5494           p->p_memsz += alloc * bed->s->sizeof_phdr;
5495           if (m->count)
5496             {
5497               p->p_filesz += header_pad;
5498               p->p_memsz += header_pad;
5499             }
5500         }
5501
5502       if (p->p_type == PT_LOAD
5503           || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
5504         {
5505           if (!m->includes_filehdr && !m->includes_phdrs)
5506             p->p_offset = off;
5507           else
5508             {
5509               file_ptr adjust;
5510
5511               adjust = off - (p->p_offset + p->p_filesz);
5512               if (!no_contents)
5513                 p->p_filesz += adjust;
5514               p->p_memsz += adjust;
5515             }
5516         }
5517
5518       /* Set up p_filesz, p_memsz, p_align and p_flags from the section
5519          maps.  Set filepos for sections in PT_LOAD segments, and in
5520          core files, for sections in PT_NOTE segments.
5521          assign_file_positions_for_non_load_sections will set filepos
5522          for other sections and update p_filesz for other segments.  */
5523       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
5524         {
5525           asection *sec;
5526           bfd_size_type align;
5527           Elf_Internal_Shdr *this_hdr;
5528
5529           sec = *secpp;
5530           this_hdr = &elf_section_data (sec)->this_hdr;
5531           align = (bfd_size_type) 1 << bfd_get_section_alignment (abfd, sec);
5532
5533           if ((p->p_type == PT_LOAD
5534                || p->p_type == PT_TLS)
5535               && (this_hdr->sh_type != SHT_NOBITS
5536                   || ((this_hdr->sh_flags & SHF_ALLOC) != 0
5537                       && ((this_hdr->sh_flags & SHF_TLS) == 0
5538                           || p->p_type == PT_TLS))))
5539             {
5540               bfd_vma p_start = p->p_paddr;
5541               bfd_vma p_end = p_start + p->p_memsz;
5542               bfd_vma s_start = sec->lma;
5543               bfd_vma adjust = s_start - p_end;
5544
5545               if (adjust != 0
5546                   && (s_start < p_end
5547                       || p_end < p_start))
5548                 {
5549                   _bfd_error_handler
5550                     /* xgettext:c-format */
5551                     (_("%B: section %A lma %#Lx adjusted to %#Lx"),
5552                      abfd, sec, s_start, p_end);
5553                   adjust = 0;
5554                   sec->lma = p_end;
5555                 }
5556               p->p_memsz += adjust;
5557
5558               if (this_hdr->sh_type != SHT_NOBITS)
5559                 {
5560                   if (p->p_filesz + adjust < p->p_memsz)
5561                     {
5562                       /* We have a PROGBITS section following NOBITS ones.
5563                          Allocate file space for the NOBITS section(s) and
5564                          zero it.  */
5565                       adjust = p->p_memsz - p->p_filesz;
5566                       if (!write_zeros (abfd, off, adjust))
5567                         return FALSE;
5568                     }
5569                   off += adjust;
5570                   p->p_filesz += adjust;
5571                 }
5572             }
5573
5574           if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
5575             {
5576               /* The section at i == 0 is the one that actually contains
5577                  everything.  */
5578               if (i == 0)
5579                 {
5580                   this_hdr->sh_offset = sec->filepos = off;
5581                   off += this_hdr->sh_size;
5582                   p->p_filesz = this_hdr->sh_size;
5583                   p->p_memsz = 0;
5584                   p->p_align = 1;
5585                 }
5586               else
5587                 {
5588                   /* The rest are fake sections that shouldn't be written.  */
5589                   sec->filepos = 0;
5590                   sec->size = 0;
5591                   sec->flags = 0;
5592                   continue;
5593                 }
5594             }
5595           else
5596             {
5597               if (p->p_type == PT_LOAD)
5598                 {
5599                   this_hdr->sh_offset = sec->filepos = off;
5600                   if (this_hdr->sh_type != SHT_NOBITS)
5601                     off += this_hdr->sh_size;
5602                 }
5603               else if (this_hdr->sh_type == SHT_NOBITS
5604                        && (this_hdr->sh_flags & SHF_TLS) != 0
5605                        && this_hdr->sh_offset == 0)
5606                 {
5607                   /* This is a .tbss section that didn't get a PT_LOAD.
5608                      (See _bfd_elf_map_sections_to_segments "Create a
5609                      final PT_LOAD".)  Set sh_offset to the value it
5610                      would have if we had created a zero p_filesz and
5611                      p_memsz PT_LOAD header for the section.  This
5612                      also makes the PT_TLS header have the same
5613                      p_offset value.  */
5614                   bfd_vma adjust = vma_page_aligned_bias (this_hdr->sh_addr,
5615                                                           off, align);
5616                   this_hdr->sh_offset = sec->filepos = off + adjust;
5617                 }
5618
5619               if (this_hdr->sh_type != SHT_NOBITS)
5620                 {
5621                   p->p_filesz += this_hdr->sh_size;
5622                   /* A load section without SHF_ALLOC is something like
5623                      a note section in a PT_NOTE segment.  These take
5624                      file space but are not loaded into memory.  */
5625                   if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
5626                     p->p_memsz += this_hdr->sh_size;
5627                 }
5628               else if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
5629                 {
5630                   if (p->p_type == PT_TLS)
5631                     p->p_memsz += this_hdr->sh_size;
5632
5633                   /* .tbss is special.  It doesn't contribute to p_memsz of
5634                      normal segments.  */
5635                   else if ((this_hdr->sh_flags & SHF_TLS) == 0)
5636                     p->p_memsz += this_hdr->sh_size;
5637                 }
5638
5639               if (align > p->p_align
5640                   && !m->p_align_valid
5641                   && (p->p_type != PT_LOAD
5642                       || (abfd->flags & D_PAGED) == 0))
5643                 p->p_align = align;
5644             }
5645
5646           if (!m->p_flags_valid)
5647             {
5648               p->p_flags |= PF_R;
5649               if ((this_hdr->sh_flags & SHF_EXECINSTR) != 0)
5650                 p->p_flags |= PF_X;
5651               if ((this_hdr->sh_flags & SHF_WRITE) != 0)
5652                 p->p_flags |= PF_W;
5653             }
5654         }
5655
5656       off -= off_adjust;
5657
5658       /* Check that all sections are in a PT_LOAD segment.
5659          Don't check funky gdb generated core files.  */
5660       if (p->p_type == PT_LOAD && bfd_get_format (abfd) != bfd_core)
5661         {
5662           bfd_boolean check_vma = TRUE;
5663
5664           for (i = 1; i < m->count; i++)
5665             if (m->sections[i]->vma == m->sections[i - 1]->vma
5666                 && ELF_SECTION_SIZE (&(elf_section_data (m->sections[i])
5667                                        ->this_hdr), p) != 0
5668                 && ELF_SECTION_SIZE (&(elf_section_data (m->sections[i - 1])
5669                                        ->this_hdr), p) != 0)
5670               {
5671                 /* Looks like we have overlays packed into the segment.  */
5672                 check_vma = FALSE;
5673                 break;
5674               }
5675
5676           for (i = 0; i < m->count; i++)
5677             {
5678               Elf_Internal_Shdr *this_hdr;
5679               asection *sec;
5680
5681               sec = m->sections[i];
5682               this_hdr = &(elf_section_data(sec)->this_hdr);
5683               if (!ELF_SECTION_IN_SEGMENT_1 (this_hdr, p, check_vma, 0)
5684                   && !ELF_TBSS_SPECIAL (this_hdr, p))
5685                 {
5686                   _bfd_error_handler
5687                     /* xgettext:c-format */
5688                     (_("%B: section `%A' can't be allocated in segment %d"),
5689                      abfd, sec, j);
5690                   print_segment_map (m);
5691                 }
5692             }
5693         }
5694     }
5695
5696   elf_next_file_pos (abfd) = off;
5697   return TRUE;
5698 }
5699
5700 /* Assign file positions for the other sections.  */
5701
5702 static bfd_boolean
5703 assign_file_positions_for_non_load_sections (bfd *abfd,
5704                                              struct bfd_link_info *link_info)
5705 {
5706   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5707   Elf_Internal_Shdr **i_shdrpp;
5708   Elf_Internal_Shdr **hdrpp, **end_hdrpp;
5709   Elf_Internal_Phdr *phdrs;
5710   Elf_Internal_Phdr *p;
5711   struct elf_segment_map *m;
5712   struct elf_segment_map *hdrs_segment;
5713   bfd_vma filehdr_vaddr, filehdr_paddr;
5714   bfd_vma phdrs_vaddr, phdrs_paddr;
5715   file_ptr off;
5716   unsigned int count;
5717
5718   i_shdrpp = elf_elfsections (abfd);
5719   end_hdrpp = i_shdrpp + elf_numsections (abfd);
5720   off = elf_next_file_pos (abfd);
5721   for (hdrpp = i_shdrpp + 1; hdrpp < end_hdrpp; hdrpp++)
5722     {
5723       Elf_Internal_Shdr *hdr;
5724
5725       hdr = *hdrpp;
5726       if (hdr->bfd_section != NULL
5727           && (hdr->bfd_section->filepos != 0
5728               || (hdr->sh_type == SHT_NOBITS
5729                   && hdr->contents == NULL)))
5730         BFD_ASSERT (hdr->sh_offset == hdr->bfd_section->filepos);
5731       else if ((hdr->sh_flags & SHF_ALLOC) != 0)
5732         {
5733           if (hdr->sh_size != 0)
5734             _bfd_error_handler
5735               /* xgettext:c-format */
5736               (_("%B: warning: allocated section `%s' not in segment"),
5737                abfd,
5738                (hdr->bfd_section == NULL
5739                 ? "*unknown*"
5740                 : hdr->bfd_section->name));
5741           /* We don't need to page align empty sections.  */
5742           if ((abfd->flags & D_PAGED) != 0 && hdr->sh_size != 0)
5743             off += vma_page_aligned_bias (hdr->sh_addr, off,
5744                                           bed->maxpagesize);
5745           else
5746             off += vma_page_aligned_bias (hdr->sh_addr, off,
5747                                           hdr->sh_addralign);
5748           off = _bfd_elf_assign_file_position_for_section (hdr, off,
5749                                                            FALSE);
5750         }
5751       else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
5752                 && hdr->bfd_section == NULL)
5753                || (hdr->bfd_section != NULL
5754                    && (hdr->bfd_section->flags & SEC_ELF_COMPRESS))
5755                    /* Compress DWARF debug sections.  */
5756                || hdr == i_shdrpp[elf_onesymtab (abfd)]
5757                || (elf_symtab_shndx_list (abfd) != NULL
5758                    && hdr == i_shdrpp[elf_symtab_shndx_list (abfd)->ndx])
5759                || hdr == i_shdrpp[elf_strtab_sec (abfd)]
5760                || hdr == i_shdrpp[elf_shstrtab_sec (abfd)])
5761         hdr->sh_offset = -1;
5762       else
5763         off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
5764     }
5765
5766   /* Now that we have set the section file positions, we can set up
5767      the file positions for the non PT_LOAD segments.  */
5768   count = 0;
5769   filehdr_vaddr = 0;
5770   filehdr_paddr = 0;
5771   phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
5772   phdrs_paddr = 0;
5773   hdrs_segment = NULL;
5774   phdrs = elf_tdata (abfd)->phdr;
5775   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
5776     {
5777       ++count;
5778       if (p->p_type != PT_LOAD)
5779         continue;
5780
5781       if (m->includes_filehdr)
5782         {
5783           filehdr_vaddr = p->p_vaddr;
5784           filehdr_paddr = p->p_paddr;
5785         }
5786       if (m->includes_phdrs)
5787         {
5788           phdrs_vaddr = p->p_vaddr;
5789           phdrs_paddr = p->p_paddr;
5790           if (m->includes_filehdr)
5791             {
5792               hdrs_segment = m;
5793               phdrs_vaddr += bed->s->sizeof_ehdr;
5794               phdrs_paddr += bed->s->sizeof_ehdr;
5795             }
5796         }
5797     }
5798
5799   if (hdrs_segment != NULL && link_info != NULL)
5800     {
5801       /* There is a segment that contains both the file headers and the
5802          program headers, so provide a symbol __ehdr_start pointing there.
5803          A program can use this to examine itself robustly.  */
5804
5805       struct elf_link_hash_entry *hash
5806         = elf_link_hash_lookup (elf_hash_table (link_info), "__ehdr_start",
5807                                 FALSE, FALSE, TRUE);
5808       /* If the symbol was referenced and not defined, define it.  */
5809       if (hash != NULL
5810           && (hash->root.type == bfd_link_hash_new
5811               || hash->root.type == bfd_link_hash_undefined
5812               || hash->root.type == bfd_link_hash_undefweak
5813               || hash->root.type == bfd_link_hash_common))
5814         {
5815           asection *s = NULL;
5816           if (hdrs_segment->count != 0)
5817             /* The segment contains sections, so use the first one.  */
5818             s = hdrs_segment->sections[0];
5819           else
5820             /* Use the first (i.e. lowest-addressed) section in any segment.  */
5821             for (m = elf_seg_map (abfd); m != NULL; m = m->next)
5822               if (m->count != 0)
5823                 {
5824                   s = m->sections[0];
5825                   break;
5826                 }
5827
5828           if (s != NULL)
5829             {
5830               hash->root.u.def.value = filehdr_vaddr - s->vma;
5831               hash->root.u.def.section = s;
5832             }
5833           else
5834             {
5835               hash->root.u.def.value = filehdr_vaddr;
5836               hash->root.u.def.section = bfd_abs_section_ptr;
5837             }
5838
5839           hash->root.type = bfd_link_hash_defined;
5840           hash->def_regular = 1;
5841           hash->non_elf = 0;
5842         }
5843     }
5844
5845   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
5846     {
5847       if (p->p_type == PT_GNU_RELRO)
5848         {
5849           const Elf_Internal_Phdr *lp;
5850           struct elf_segment_map *lm;
5851
5852           if (link_info != NULL)
5853             {
5854               /* During linking the range of the RELRO segment is passed
5855                  in link_info.  */
5856               for (lm = elf_seg_map (abfd), lp = phdrs;
5857                    lm != NULL;
5858                    lm = lm->next, lp++)
5859                 {
5860                   if (lp->p_type == PT_LOAD
5861                       && lp->p_vaddr < link_info->relro_end
5862                       && lm->count != 0
5863                       && lm->sections[0]->vma >= link_info->relro_start)
5864                     break;
5865                 }
5866
5867               BFD_ASSERT (lm != NULL);
5868             }
5869           else
5870             {
5871               /* Otherwise we are copying an executable or shared
5872                  library, but we need to use the same linker logic.  */
5873               for (lp = phdrs; lp < phdrs + count; ++lp)
5874                 {
5875                   if (lp->p_type == PT_LOAD
5876                       && lp->p_paddr == p->p_paddr)
5877                     break;
5878                 }
5879             }
5880
5881           if (lp < phdrs + count)
5882             {
5883               p->p_vaddr = lp->p_vaddr;
5884               p->p_paddr = lp->p_paddr;
5885               p->p_offset = lp->p_offset;
5886               if (link_info != NULL)
5887                 p->p_filesz = link_info->relro_end - lp->p_vaddr;
5888               else if (m->p_size_valid)
5889                 p->p_filesz = m->p_size;
5890               else
5891                 abort ();
5892               p->p_memsz = p->p_filesz;
5893               /* Preserve the alignment and flags if they are valid. The
5894                  gold linker generates RW/4 for the PT_GNU_RELRO section.
5895                  It is better for objcopy/strip to honor these attributes
5896                  otherwise gdb will choke when using separate debug files.
5897                */
5898               if (!m->p_align_valid)
5899                 p->p_align = 1;
5900               if (!m->p_flags_valid)
5901                 p->p_flags = PF_R;
5902             }
5903           else
5904             {
5905               memset (p, 0, sizeof *p);
5906               p->p_type = PT_NULL;
5907             }
5908         }
5909       else if (p->p_type == PT_GNU_STACK)
5910         {
5911           if (m->p_size_valid)
5912             p->p_memsz = m->p_size;
5913         }
5914       else if (m->count != 0)
5915         {
5916           unsigned int i;
5917
5918           if (p->p_type != PT_LOAD
5919               && (p->p_type != PT_NOTE
5920                   || bfd_get_format (abfd) != bfd_core))
5921             {
5922               /* A user specified segment layout may include a PHDR
5923                  segment that overlaps with a LOAD segment...  */
5924               if (p->p_type == PT_PHDR)
5925                 {
5926                   m->count = 0;
5927                   continue;
5928                 }
5929
5930               if (m->includes_filehdr || m->includes_phdrs)
5931                 {
5932                   /* PR 17512: file: 2195325e.  */
5933                   _bfd_error_handler
5934                     (_("%B: error: non-load segment %d includes file header "
5935                        "and/or program header"),
5936                      abfd, (int) (p - phdrs));
5937                   return FALSE;
5938                 }
5939
5940               p->p_filesz = 0;
5941               p->p_offset = m->sections[0]->filepos;
5942               for (i = m->count; i-- != 0;)
5943                 {
5944                   asection *sect = m->sections[i];
5945                   Elf_Internal_Shdr *hdr = &elf_section_data (sect)->this_hdr;
5946                   if (hdr->sh_type != SHT_NOBITS)
5947                     {
5948                       p->p_filesz = (sect->filepos - m->sections[0]->filepos
5949                                      + hdr->sh_size);
5950                       break;
5951                     }
5952                 }
5953             }
5954         }
5955       else if (m->includes_filehdr)
5956         {
5957           p->p_vaddr = filehdr_vaddr;
5958           if (! m->p_paddr_valid)
5959             p->p_paddr = filehdr_paddr;
5960         }
5961       else if (m->includes_phdrs)
5962         {
5963           p->p_vaddr = phdrs_vaddr;
5964           if (! m->p_paddr_valid)
5965             p->p_paddr = phdrs_paddr;
5966         }
5967     }
5968
5969   elf_next_file_pos (abfd) = off;
5970
5971   return TRUE;
5972 }
5973
5974 static elf_section_list *
5975 find_section_in_list (unsigned int i, elf_section_list * list)
5976 {
5977   for (;list != NULL; list = list->next)
5978     if (list->ndx == i)
5979       break;
5980   return list;
5981 }
5982
5983 /* Work out the file positions of all the sections.  This is called by
5984    _bfd_elf_compute_section_file_positions.  All the section sizes and
5985    VMAs must be known before this is called.
5986
5987    Reloc sections come in two flavours: Those processed specially as
5988    "side-channel" data attached to a section to which they apply, and
5989    those that bfd doesn't process as relocations.  The latter sort are
5990    stored in a normal bfd section by bfd_section_from_shdr.   We don't
5991    consider the former sort here, unless they form part of the loadable
5992    image.  Reloc sections not assigned here will be handled later by
5993    assign_file_positions_for_relocs.
5994
5995    We also don't set the positions of the .symtab and .strtab here.  */
5996
5997 static bfd_boolean
5998 assign_file_positions_except_relocs (bfd *abfd,
5999                                      struct bfd_link_info *link_info)
6000 {
6001   struct elf_obj_tdata *tdata = elf_tdata (abfd);
6002   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
6003   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6004
6005   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
6006       && bfd_get_format (abfd) != bfd_core)
6007     {
6008       Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
6009       unsigned int num_sec = elf_numsections (abfd);
6010       Elf_Internal_Shdr **hdrpp;
6011       unsigned int i;
6012       file_ptr off;
6013
6014       /* Start after the ELF header.  */
6015       off = i_ehdrp->e_ehsize;
6016
6017       /* We are not creating an executable, which means that we are
6018          not creating a program header, and that the actual order of
6019          the sections in the file is unimportant.  */
6020       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
6021         {
6022           Elf_Internal_Shdr *hdr;
6023
6024           hdr = *hdrpp;
6025           if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
6026                && hdr->bfd_section == NULL)
6027               || (hdr->bfd_section != NULL
6028                   && (hdr->bfd_section->flags & SEC_ELF_COMPRESS))
6029                   /* Compress DWARF debug sections.  */
6030               || i == elf_onesymtab (abfd)
6031               || (elf_symtab_shndx_list (abfd) != NULL
6032                   && hdr == i_shdrpp[elf_symtab_shndx_list (abfd)->ndx])
6033               || i == elf_strtab_sec (abfd)
6034               || i == elf_shstrtab_sec (abfd))
6035             {
6036               hdr->sh_offset = -1;
6037             }
6038           else
6039             off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
6040         }
6041
6042       elf_next_file_pos (abfd) = off;
6043     }
6044   else
6045     {
6046       unsigned int alloc;
6047
6048       /* Assign file positions for the loaded sections based on the
6049          assignment of sections to segments.  */
6050       if (!assign_file_positions_for_load_sections (abfd, link_info))
6051         return FALSE;
6052
6053       /* And for non-load sections.  */
6054       if (!assign_file_positions_for_non_load_sections (abfd, link_info))
6055         return FALSE;
6056
6057       if (bed->elf_backend_modify_program_headers != NULL)
6058         {
6059           if (!(*bed->elf_backend_modify_program_headers) (abfd, link_info))
6060             return FALSE;
6061         }
6062
6063       /* Set e_type in ELF header to ET_EXEC for -pie -Ttext-segment=.  */
6064       if (link_info != NULL && bfd_link_pie (link_info))
6065         {
6066           unsigned int num_segments = elf_elfheader (abfd)->e_phnum;
6067           Elf_Internal_Phdr *segment = elf_tdata (abfd)->phdr;
6068           Elf_Internal_Phdr *end_segment = &segment[num_segments];
6069
6070           /* Find the lowest p_vaddr in PT_LOAD segments.  */
6071           bfd_vma p_vaddr = (bfd_vma) -1;
6072           for (; segment < end_segment; segment++)
6073             if (segment->p_type == PT_LOAD && p_vaddr > segment->p_vaddr)
6074               p_vaddr = segment->p_vaddr;
6075
6076           /* Set e_type to ET_EXEC if the lowest p_vaddr in PT_LOAD
6077              segments is non-zero.  */
6078           if (p_vaddr)
6079             i_ehdrp->e_type = ET_EXEC;
6080         }
6081
6082       /* Write out the program headers.  */
6083       alloc = elf_program_header_size (abfd) / bed->s->sizeof_phdr;
6084
6085       /* Sort the program headers into the ordering required by the ELF standard.  */
6086       if (alloc == 0)
6087         return TRUE;
6088
6089       /* PR ld/20815 - Check that the program header segment, if present, will
6090          be loaded into memory.  FIXME: The check below is not sufficient as
6091          really all PT_LOAD segments should be checked before issuing an error
6092          message.  Plus the PHDR segment does not have to be the first segment
6093          in the program header table.  But this version of the check should
6094          catch all real world use cases.
6095
6096          FIXME: We used to have code here to sort the PT_LOAD segments into
6097          ascending order, as per the ELF spec.  But this breaks some programs,
6098          including the Linux kernel.  But really either the spec should be
6099          changed or the programs updated.  */
6100       if (alloc > 1
6101           && tdata->phdr[0].p_type == PT_PHDR
6102           && ! bed->elf_backend_allow_non_load_phdr (abfd, tdata->phdr, alloc)
6103           && tdata->phdr[1].p_type == PT_LOAD
6104           && (tdata->phdr[1].p_vaddr > tdata->phdr[0].p_vaddr
6105               || (tdata->phdr[1].p_vaddr + tdata->phdr[1].p_memsz)
6106               <  (tdata->phdr[0].p_vaddr + tdata->phdr[0].p_memsz)))
6107         {
6108           /* The fix for this error is usually to edit the linker script being
6109              used and set up the program headers manually.  Either that or
6110              leave room for the headers at the start of the SECTIONS.  */
6111           _bfd_error_handler (_("\
6112 %B: error: PHDR segment not covered by LOAD segment"),
6113                               abfd);
6114           return FALSE;
6115         }
6116
6117       if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
6118           || bed->s->write_out_phdrs (abfd, tdata->phdr, alloc) != 0)
6119         return FALSE;
6120     }
6121
6122   return TRUE;
6123 }
6124
6125 static bfd_boolean
6126 prep_headers (bfd *abfd)
6127 {
6128   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form.  */
6129   struct elf_strtab_hash *shstrtab;
6130   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6131
6132   i_ehdrp = elf_elfheader (abfd);
6133
6134   shstrtab = _bfd_elf_strtab_init ();
6135   if (shstrtab == NULL)
6136     return FALSE;
6137
6138   elf_shstrtab (abfd) = shstrtab;
6139
6140   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
6141   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
6142   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
6143   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
6144
6145   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
6146   i_ehdrp->e_ident[EI_DATA] =
6147     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
6148   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
6149
6150   if ((abfd->flags & DYNAMIC) != 0)
6151     i_ehdrp->e_type = ET_DYN;
6152   else if ((abfd->flags & EXEC_P) != 0)
6153     i_ehdrp->e_type = ET_EXEC;
6154   else if (bfd_get_format (abfd) == bfd_core)
6155     i_ehdrp->e_type = ET_CORE;
6156   else
6157     i_ehdrp->e_type = ET_REL;
6158
6159   switch (bfd_get_arch (abfd))
6160     {
6161     case bfd_arch_unknown:
6162       i_ehdrp->e_machine = EM_NONE;
6163       break;
6164
6165       /* There used to be a long list of cases here, each one setting
6166          e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
6167          in the corresponding bfd definition.  To avoid duplication,
6168          the switch was removed.  Machines that need special handling
6169          can generally do it in elf_backend_final_write_processing(),
6170          unless they need the information earlier than the final write.
6171          Such need can generally be supplied by replacing the tests for
6172          e_machine with the conditions used to determine it.  */
6173     default:
6174       i_ehdrp->e_machine = bed->elf_machine_code;
6175     }
6176
6177   i_ehdrp->e_version = bed->s->ev_current;
6178   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
6179
6180   /* No program header, for now.  */
6181   i_ehdrp->e_phoff = 0;
6182   i_ehdrp->e_phentsize = 0;
6183   i_ehdrp->e_phnum = 0;
6184
6185   /* Each bfd section is section header entry.  */
6186   i_ehdrp->e_entry = bfd_get_start_address (abfd);
6187   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
6188
6189   /* If we're building an executable, we'll need a program header table.  */
6190   if (abfd->flags & EXEC_P)
6191     /* It all happens later.  */
6192     ;
6193   else
6194     {
6195       i_ehdrp->e_phentsize = 0;
6196       i_ehdrp->e_phoff = 0;
6197     }
6198
6199   elf_tdata (abfd)->symtab_hdr.sh_name =
6200     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", FALSE);
6201   elf_tdata (abfd)->strtab_hdr.sh_name =
6202     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", FALSE);
6203   elf_tdata (abfd)->shstrtab_hdr.sh_name =
6204     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", FALSE);
6205   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
6206       || elf_tdata (abfd)->strtab_hdr.sh_name == (unsigned int) -1
6207       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
6208     return FALSE;
6209
6210   return TRUE;
6211 }
6212
6213 /* Assign file positions for all the reloc sections which are not part
6214    of the loadable file image, and the file position of section headers.  */
6215
6216 static bfd_boolean
6217 _bfd_elf_assign_file_positions_for_non_load (bfd *abfd)
6218 {
6219   file_ptr off;
6220   Elf_Internal_Shdr **shdrpp, **end_shdrpp;
6221   Elf_Internal_Shdr *shdrp;
6222   Elf_Internal_Ehdr *i_ehdrp;
6223   const struct elf_backend_data *bed;
6224
6225   off = elf_next_file_pos (abfd);
6226
6227   shdrpp = elf_elfsections (abfd);
6228   end_shdrpp = shdrpp + elf_numsections (abfd);
6229   for (shdrpp++; shdrpp < end_shdrpp; shdrpp++)
6230     {
6231       shdrp = *shdrpp;
6232       if (shdrp->sh_offset == -1)
6233         {
6234           asection *sec = shdrp->bfd_section;
6235           bfd_boolean is_rel = (shdrp->sh_type == SHT_REL
6236                                 || shdrp->sh_type == SHT_RELA);
6237           if (is_rel
6238               || (sec != NULL && (sec->flags & SEC_ELF_COMPRESS)))
6239             {
6240               if (!is_rel)
6241                 {
6242                   const char *name = sec->name;
6243                   struct bfd_elf_section_data *d;
6244
6245                   /* Compress DWARF debug sections.  */
6246                   if (!bfd_compress_section (abfd, sec,
6247                                              shdrp->contents))
6248                     return FALSE;
6249
6250                   if (sec->compress_status == COMPRESS_SECTION_DONE
6251                       && (abfd->flags & BFD_COMPRESS_GABI) == 0)
6252                     {
6253                       /* If section is compressed with zlib-gnu, convert
6254                          section name from .debug_* to .zdebug_*.  */
6255                       char *new_name
6256                         = convert_debug_to_zdebug (abfd, name);
6257                       if (new_name == NULL)
6258                         return FALSE;
6259                       name = new_name;
6260                     }
6261                   /* Add section name to section name section.  */
6262                   if (shdrp->sh_name != (unsigned int) -1)
6263                     abort ();
6264                   shdrp->sh_name
6265                     = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
6266                                                           name, FALSE);
6267                   d = elf_section_data (sec);
6268
6269                   /* Add reloc section name to section name section.  */
6270                   if (d->rel.hdr
6271                       && !_bfd_elf_set_reloc_sh_name (abfd,
6272                                                       d->rel.hdr,
6273                                                       name, FALSE))
6274                     return FALSE;
6275                   if (d->rela.hdr
6276                       && !_bfd_elf_set_reloc_sh_name (abfd,
6277                                                       d->rela.hdr,
6278                                                       name, TRUE))
6279                     return FALSE;
6280
6281                   /* Update section size and contents.  */
6282                   shdrp->sh_size = sec->size;
6283                   shdrp->contents = sec->contents;
6284                   shdrp->bfd_section->contents = NULL;
6285                 }
6286               off = _bfd_elf_assign_file_position_for_section (shdrp,
6287                                                                off,
6288                                                                TRUE);
6289             }
6290         }
6291     }
6292
6293   /* Place section name section after DWARF debug sections have been
6294      compressed.  */
6295   _bfd_elf_strtab_finalize (elf_shstrtab (abfd));
6296   shdrp = &elf_tdata (abfd)->shstrtab_hdr;
6297   shdrp->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
6298   off = _bfd_elf_assign_file_position_for_section (shdrp, off, TRUE);
6299
6300   /* Place the section headers.  */
6301   i_ehdrp = elf_elfheader (abfd);
6302   bed = get_elf_backend_data (abfd);
6303   off = align_file_position (off, 1 << bed->s->log_file_align);
6304   i_ehdrp->e_shoff = off;
6305   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
6306   elf_next_file_pos (abfd) = off;
6307
6308   return TRUE;
6309 }
6310
6311 bfd_boolean
6312 _bfd_elf_write_object_contents (bfd *abfd)
6313 {
6314   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
6315   Elf_Internal_Shdr **i_shdrp;
6316   bfd_boolean failed;
6317   unsigned int count, num_sec;
6318   struct elf_obj_tdata *t;
6319
6320   if (! abfd->output_has_begun
6321       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
6322     return FALSE;
6323
6324   i_shdrp = elf_elfsections (abfd);
6325
6326   failed = FALSE;
6327   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
6328   if (failed)
6329     return FALSE;
6330
6331   if (!_bfd_elf_assign_file_positions_for_non_load (abfd))
6332     return FALSE;
6333
6334   /* After writing the headers, we need to write the sections too...  */
6335   num_sec = elf_numsections (abfd);
6336   for (count = 1; count < num_sec; count++)
6337     {
6338       i_shdrp[count]->sh_name
6339         = _bfd_elf_strtab_offset (elf_shstrtab (abfd),
6340                                   i_shdrp[count]->sh_name);
6341       if (bed->elf_backend_section_processing)
6342         (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
6343       if (i_shdrp[count]->contents)
6344         {
6345           bfd_size_type amt = i_shdrp[count]->sh_size;
6346
6347           if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
6348               || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
6349             return FALSE;
6350         }
6351     }
6352
6353   /* Write out the section header names.  */
6354   t = elf_tdata (abfd);
6355   if (elf_shstrtab (abfd) != NULL
6356       && (bfd_seek (abfd, t->shstrtab_hdr.sh_offset, SEEK_SET) != 0
6357           || !_bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd))))
6358     return FALSE;
6359
6360   if (bed->elf_backend_final_write_processing)
6361     (*bed->elf_backend_final_write_processing) (abfd, elf_linker (abfd));
6362
6363   if (!bed->s->write_shdrs_and_ehdr (abfd))
6364     return FALSE;
6365
6366   /* This is last since write_shdrs_and_ehdr can touch i_shdrp[0].  */
6367   if (t->o->build_id.after_write_object_contents != NULL)
6368     return (*t->o->build_id.after_write_object_contents) (abfd);
6369
6370   return TRUE;
6371 }
6372
6373 bfd_boolean
6374 _bfd_elf_write_corefile_contents (bfd *abfd)
6375 {
6376   /* Hopefully this can be done just like an object file.  */
6377   return _bfd_elf_write_object_contents (abfd);
6378 }
6379
6380 /* Given a section, search the header to find them.  */
6381
6382 unsigned int
6383 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
6384 {
6385   const struct elf_backend_data *bed;
6386   unsigned int sec_index;
6387
6388   if (elf_section_data (asect) != NULL
6389       && elf_section_data (asect)->this_idx != 0)
6390     return elf_section_data (asect)->this_idx;
6391
6392   if (bfd_is_abs_section (asect))
6393     sec_index = SHN_ABS;
6394   else if (bfd_is_com_section (asect))
6395     sec_index = SHN_COMMON;
6396   else if (bfd_is_und_section (asect))
6397     sec_index = SHN_UNDEF;
6398   else
6399     sec_index = SHN_BAD;
6400
6401   bed = get_elf_backend_data (abfd);
6402   if (bed->elf_backend_section_from_bfd_section)
6403     {
6404       int retval = sec_index;
6405
6406       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
6407         return retval;
6408     }
6409
6410   if (sec_index == SHN_BAD)
6411     bfd_set_error (bfd_error_nonrepresentable_section);
6412
6413   return sec_index;
6414 }
6415
6416 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
6417    on error.  */
6418
6419 int
6420 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
6421 {
6422   asymbol *asym_ptr = *asym_ptr_ptr;
6423   int idx;
6424   flagword flags = asym_ptr->flags;
6425
6426   /* When gas creates relocations against local labels, it creates its
6427      own symbol for the section, but does put the symbol into the
6428      symbol chain, so udata is 0.  When the linker is generating
6429      relocatable output, this section symbol may be for one of the
6430      input sections rather than the output section.  */
6431   if (asym_ptr->udata.i == 0
6432       && (flags & BSF_SECTION_SYM)
6433       && asym_ptr->section)
6434     {
6435       asection *sec;
6436       int indx;
6437
6438       sec = asym_ptr->section;
6439       if (sec->owner != abfd && sec->output_section != NULL)
6440         sec = sec->output_section;
6441       if (sec->owner == abfd
6442           && (indx = sec->index) < elf_num_section_syms (abfd)
6443           && elf_section_syms (abfd)[indx] != NULL)
6444         asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
6445     }
6446
6447   idx = asym_ptr->udata.i;
6448
6449   if (idx == 0)
6450     {
6451       /* This case can occur when using --strip-symbol on a symbol
6452          which is used in a relocation entry.  */
6453       _bfd_error_handler
6454         /* xgettext:c-format */
6455         (_("%B: symbol `%s' required but not present"),
6456          abfd, bfd_asymbol_name (asym_ptr));
6457       bfd_set_error (bfd_error_no_symbols);
6458       return -1;
6459     }
6460
6461 #if DEBUG & 4
6462   {
6463     fprintf (stderr,
6464              "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8x\n",
6465              (long) asym_ptr, asym_ptr->name, idx, flags);
6466     fflush (stderr);
6467   }
6468 #endif
6469
6470   return idx;
6471 }
6472
6473 /* Rewrite program header information.  */
6474
6475 static bfd_boolean
6476 rewrite_elf_program_header (bfd *ibfd, bfd *obfd)
6477 {
6478   Elf_Internal_Ehdr *iehdr;
6479   struct elf_segment_map *map;
6480   struct elf_segment_map *map_first;
6481   struct elf_segment_map **pointer_to_map;
6482   Elf_Internal_Phdr *segment;
6483   asection *section;
6484   unsigned int i;
6485   unsigned int num_segments;
6486   bfd_boolean phdr_included = FALSE;
6487   bfd_boolean p_paddr_valid;
6488   bfd_vma maxpagesize;
6489   struct elf_segment_map *phdr_adjust_seg = NULL;
6490   unsigned int phdr_adjust_num = 0;
6491   const struct elf_backend_data *bed;
6492
6493   bed = get_elf_backend_data (ibfd);
6494   iehdr = elf_elfheader (ibfd);
6495
6496   map_first = NULL;
6497   pointer_to_map = &map_first;
6498
6499   num_segments = elf_elfheader (ibfd)->e_phnum;
6500   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
6501
6502   /* Returns the end address of the segment + 1.  */
6503 #define SEGMENT_END(segment, start)                                     \
6504   (start + (segment->p_memsz > segment->p_filesz                        \
6505             ? segment->p_memsz : segment->p_filesz))
6506
6507 #define SECTION_SIZE(section, segment)                                  \
6508   (((section->flags & (SEC_HAS_CONTENTS | SEC_THREAD_LOCAL))            \
6509     != SEC_THREAD_LOCAL || segment->p_type == PT_TLS)                   \
6510    ? section->size : 0)
6511
6512   /* Returns TRUE if the given section is contained within
6513      the given segment.  VMA addresses are compared.  */
6514 #define IS_CONTAINED_BY_VMA(section, segment)                           \
6515   (section->vma >= segment->p_vaddr                                     \
6516    && (section->vma + SECTION_SIZE (section, segment)                   \
6517        <= (SEGMENT_END (segment, segment->p_vaddr))))
6518
6519   /* Returns TRUE if the given section is contained within
6520      the given segment.  LMA addresses are compared.  */
6521 #define IS_CONTAINED_BY_LMA(section, segment, base)                     \
6522   (section->lma >= base                                                 \
6523    && (section->lma + SECTION_SIZE (section, segment)                   \
6524        <= SEGMENT_END (segment, base)))
6525
6526   /* Handle PT_NOTE segment.  */
6527 #define IS_NOTE(p, s)                                                   \
6528   (p->p_type == PT_NOTE                                                 \
6529    && elf_section_type (s) == SHT_NOTE                                  \
6530    && (bfd_vma) s->filepos >= p->p_offset                               \
6531    && ((bfd_vma) s->filepos + s->size                                   \
6532        <= p->p_offset + p->p_filesz))
6533
6534   /* Special case: corefile "NOTE" section containing regs, prpsinfo
6535      etc.  */
6536 #define IS_COREFILE_NOTE(p, s)                                          \
6537   (IS_NOTE (p, s)                                                       \
6538    && bfd_get_format (ibfd) == bfd_core                                 \
6539    && s->vma == 0                                                       \
6540    && s->lma == 0)
6541
6542   /* The complicated case when p_vaddr is 0 is to handle the Solaris
6543      linker, which generates a PT_INTERP section with p_vaddr and
6544      p_memsz set to 0.  */
6545 #define IS_SOLARIS_PT_INTERP(p, s)                                      \
6546   (p->p_vaddr == 0                                                      \
6547    && p->p_paddr == 0                                                   \
6548    && p->p_memsz == 0                                                   \
6549    && p->p_filesz > 0                                                   \
6550    && (s->flags & SEC_HAS_CONTENTS) != 0                                \
6551    && s->size > 0                                                       \
6552    && (bfd_vma) s->filepos >= p->p_offset                               \
6553    && ((bfd_vma) s->filepos + s->size                                   \
6554        <= p->p_offset + p->p_filesz))
6555
6556   /* Decide if the given section should be included in the given segment.
6557      A section will be included if:
6558        1. It is within the address space of the segment -- we use the LMA
6559           if that is set for the segment and the VMA otherwise,
6560        2. It is an allocated section or a NOTE section in a PT_NOTE
6561           segment.
6562        3. There is an output section associated with it,
6563        4. The section has not already been allocated to a previous segment.
6564        5. PT_GNU_STACK segments do not include any sections.
6565        6. PT_TLS segment includes only SHF_TLS sections.
6566        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.
6567        8. PT_DYNAMIC should not contain empty sections at the beginning
6568           (with the possible exception of .dynamic).  */
6569 #define IS_SECTION_IN_INPUT_SEGMENT(section, segment, bed)              \
6570   ((((segment->p_paddr                                                  \
6571       ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)        \
6572       : IS_CONTAINED_BY_VMA (section, segment))                         \
6573      && (section->flags & SEC_ALLOC) != 0)                              \
6574     || IS_NOTE (segment, section))                                      \
6575    && segment->p_type != PT_GNU_STACK                                   \
6576    && (segment->p_type != PT_TLS                                        \
6577        || (section->flags & SEC_THREAD_LOCAL))                          \
6578    && (segment->p_type == PT_LOAD                                       \
6579        || segment->p_type == PT_TLS                                     \
6580        || (section->flags & SEC_THREAD_LOCAL) == 0)                     \
6581    && (segment->p_type != PT_DYNAMIC                                    \
6582        || SECTION_SIZE (section, segment) > 0                           \
6583        || (segment->p_paddr                                             \
6584            ? segment->p_paddr != section->lma                           \
6585            : segment->p_vaddr != section->vma)                          \
6586        || (strcmp (bfd_get_section_name (ibfd, section), ".dynamic")    \
6587            == 0))                                                       \
6588    && !section->segment_mark)
6589
6590 /* If the output section of a section in the input segment is NULL,
6591    it is removed from the corresponding output segment.   */
6592 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)               \
6593   (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed)          \
6594    && section->output_section != NULL)
6595
6596   /* Returns TRUE iff seg1 starts after the end of seg2.  */
6597 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)                        \
6598   (seg1->field >= SEGMENT_END (seg2, seg2->field))
6599
6600   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
6601      their VMA address ranges and their LMA address ranges overlap.
6602      It is possible to have overlapping VMA ranges without overlapping LMA
6603      ranges.  RedBoot images for example can have both .data and .bss mapped
6604      to the same VMA range, but with the .data section mapped to a different
6605      LMA.  */
6606 #define SEGMENT_OVERLAPS(seg1, seg2)                                    \
6607   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)                     \
6608         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))                 \
6609    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)                     \
6610         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
6611
6612   /* Initialise the segment mark field.  */
6613   for (section = ibfd->sections; section != NULL; section = section->next)
6614     section->segment_mark = FALSE;
6615
6616   /* The Solaris linker creates program headers in which all the
6617      p_paddr fields are zero.  When we try to objcopy or strip such a
6618      file, we get confused.  Check for this case, and if we find it
6619      don't set the p_paddr_valid fields.  */
6620   p_paddr_valid = FALSE;
6621   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6622        i < num_segments;
6623        i++, segment++)
6624     if (segment->p_paddr != 0)
6625       {
6626         p_paddr_valid = TRUE;
6627         break;
6628       }
6629
6630   /* Scan through the segments specified in the program header
6631      of the input BFD.  For this first scan we look for overlaps
6632      in the loadable segments.  These can be created by weird
6633      parameters to objcopy.  Also, fix some solaris weirdness.  */
6634   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6635        i < num_segments;
6636        i++, segment++)
6637     {
6638       unsigned int j;
6639       Elf_Internal_Phdr *segment2;
6640
6641       if (segment->p_type == PT_INTERP)
6642         for (section = ibfd->sections; section; section = section->next)
6643           if (IS_SOLARIS_PT_INTERP (segment, section))
6644             {
6645               /* Mininal change so that the normal section to segment
6646                  assignment code will work.  */
6647               segment->p_vaddr = section->vma;
6648               break;
6649             }
6650
6651       if (segment->p_type != PT_LOAD)
6652         {
6653           /* Remove PT_GNU_RELRO segment.  */
6654           if (segment->p_type == PT_GNU_RELRO)
6655             segment->p_type = PT_NULL;
6656           continue;
6657         }
6658
6659       /* Determine if this segment overlaps any previous segments.  */
6660       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2++)
6661         {
6662           bfd_signed_vma extra_length;
6663
6664           if (segment2->p_type != PT_LOAD
6665               || !SEGMENT_OVERLAPS (segment, segment2))
6666             continue;
6667
6668           /* Merge the two segments together.  */
6669           if (segment2->p_vaddr < segment->p_vaddr)
6670             {
6671               /* Extend SEGMENT2 to include SEGMENT and then delete
6672                  SEGMENT.  */
6673               extra_length = (SEGMENT_END (segment, segment->p_vaddr)
6674                               - SEGMENT_END (segment2, segment2->p_vaddr));
6675
6676               if (extra_length > 0)
6677                 {
6678                   segment2->p_memsz += extra_length;
6679                   segment2->p_filesz += extra_length;
6680                 }
6681
6682               segment->p_type = PT_NULL;
6683
6684               /* Since we have deleted P we must restart the outer loop.  */
6685               i = 0;
6686               segment = elf_tdata (ibfd)->phdr;
6687               break;
6688             }
6689           else
6690             {
6691               /* Extend SEGMENT to include SEGMENT2 and then delete
6692                  SEGMENT2.  */
6693               extra_length = (SEGMENT_END (segment2, segment2->p_vaddr)
6694                               - SEGMENT_END (segment, segment->p_vaddr));
6695
6696               if (extra_length > 0)
6697                 {
6698                   segment->p_memsz += extra_length;
6699                   segment->p_filesz += extra_length;
6700                 }
6701
6702               segment2->p_type = PT_NULL;
6703             }
6704         }
6705     }
6706
6707   /* The second scan attempts to assign sections to segments.  */
6708   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6709        i < num_segments;
6710        i++, segment++)
6711     {
6712       unsigned int section_count;
6713       asection **sections;
6714       asection *output_section;
6715       unsigned int isec;
6716       bfd_vma matching_lma;
6717       bfd_vma suggested_lma;
6718       unsigned int j;
6719       bfd_size_type amt;
6720       asection *first_section;
6721       bfd_boolean first_matching_lma;
6722       bfd_boolean first_suggested_lma;
6723
6724       if (segment->p_type == PT_NULL)
6725         continue;
6726
6727       first_section = NULL;
6728       /* Compute how many sections might be placed into this segment.  */
6729       for (section = ibfd->sections, section_count = 0;
6730            section != NULL;
6731            section = section->next)
6732         {
6733           /* Find the first section in the input segment, which may be
6734              removed from the corresponding output segment.   */
6735           if (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed))
6736             {
6737               if (first_section == NULL)
6738                 first_section = section;
6739               if (section->output_section != NULL)
6740                 ++section_count;
6741             }
6742         }
6743
6744       /* Allocate a segment map big enough to contain
6745          all of the sections we have selected.  */
6746       amt = sizeof (struct elf_segment_map);
6747       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
6748       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
6749       if (map == NULL)
6750         return FALSE;
6751
6752       /* Initialise the fields of the segment map.  Default to
6753          using the physical address of the segment in the input BFD.  */
6754       map->next = NULL;
6755       map->p_type = segment->p_type;
6756       map->p_flags = segment->p_flags;
6757       map->p_flags_valid = 1;
6758
6759       /* If the first section in the input segment is removed, there is
6760          no need to preserve segment physical address in the corresponding
6761          output segment.  */
6762       if (!first_section || first_section->output_section != NULL)
6763         {
6764           map->p_paddr = segment->p_paddr;
6765           map->p_paddr_valid = p_paddr_valid;
6766         }
6767
6768       /* Determine if this segment contains the ELF file header
6769          and if it contains the program headers themselves.  */
6770       map->includes_filehdr = (segment->p_offset == 0
6771                                && segment->p_filesz >= iehdr->e_ehsize);
6772       map->includes_phdrs = 0;
6773
6774       if (!phdr_included || segment->p_type != PT_LOAD)
6775         {
6776           map->includes_phdrs =
6777             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
6778              && (segment->p_offset + segment->p_filesz
6779                  >= ((bfd_vma) iehdr->e_phoff
6780                      + iehdr->e_phnum * iehdr->e_phentsize)));
6781
6782           if (segment->p_type == PT_LOAD && map->includes_phdrs)
6783             phdr_included = TRUE;
6784         }
6785
6786       if (section_count == 0)
6787         {
6788           /* Special segments, such as the PT_PHDR segment, may contain
6789              no sections, but ordinary, loadable segments should contain
6790              something.  They are allowed by the ELF spec however, so only
6791              a warning is produced.  
6792              There is however the valid use case of embedded systems which
6793              have segments with p_filesz of 0 and a p_memsz > 0 to initialize
6794              flash memory with zeros.  No warning is shown for that case.  */
6795           if (segment->p_type == PT_LOAD
6796               && (segment->p_filesz > 0 || segment->p_memsz == 0))
6797             /* xgettext:c-format */
6798             _bfd_error_handler (_("%B: warning: Empty loadable segment detected"
6799                                   " at vaddr=%#Lx, is this intentional?"),
6800                                 ibfd, segment->p_vaddr);
6801
6802           map->count = 0;
6803           *pointer_to_map = map;
6804           pointer_to_map = &map->next;
6805
6806           continue;
6807         }
6808
6809       /* Now scan the sections in the input BFD again and attempt
6810          to add their corresponding output sections to the segment map.
6811          The problem here is how to handle an output section which has
6812          been moved (ie had its LMA changed).  There are four possibilities:
6813
6814          1. None of the sections have been moved.
6815             In this case we can continue to use the segment LMA from the
6816             input BFD.
6817
6818          2. All of the sections have been moved by the same amount.
6819             In this case we can change the segment's LMA to match the LMA
6820             of the first section.
6821
6822          3. Some of the sections have been moved, others have not.
6823             In this case those sections which have not been moved can be
6824             placed in the current segment which will have to have its size,
6825             and possibly its LMA changed, and a new segment or segments will
6826             have to be created to contain the other sections.
6827
6828          4. The sections have been moved, but not by the same amount.
6829             In this case we can change the segment's LMA to match the LMA
6830             of the first section and we will have to create a new segment
6831             or segments to contain the other sections.
6832
6833          In order to save time, we allocate an array to hold the section
6834          pointers that we are interested in.  As these sections get assigned
6835          to a segment, they are removed from this array.  */
6836
6837       sections = (asection **) bfd_malloc2 (section_count, sizeof (asection *));
6838       if (sections == NULL)
6839         return FALSE;
6840
6841       /* Step One: Scan for segment vs section LMA conflicts.
6842          Also add the sections to the section array allocated above.
6843          Also add the sections to the current segment.  In the common
6844          case, where the sections have not been moved, this means that
6845          we have completely filled the segment, and there is nothing
6846          more to do.  */
6847       isec = 0;
6848       matching_lma = 0;
6849       suggested_lma = 0;
6850       first_matching_lma = TRUE;
6851       first_suggested_lma = TRUE;
6852
6853       for (section = first_section, j = 0;
6854            section != NULL;
6855            section = section->next)
6856         {
6857           if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
6858             {
6859               output_section = section->output_section;
6860
6861               sections[j++] = section;
6862
6863               /* The Solaris native linker always sets p_paddr to 0.
6864                  We try to catch that case here, and set it to the
6865                  correct value.  Note - some backends require that
6866                  p_paddr be left as zero.  */
6867               if (!p_paddr_valid
6868                   && segment->p_vaddr != 0
6869                   && !bed->want_p_paddr_set_to_zero
6870                   && isec == 0
6871                   && output_section->lma != 0
6872                   && output_section->vma == (segment->p_vaddr
6873                                              + (map->includes_filehdr
6874                                                 ? iehdr->e_ehsize
6875                                                 : 0)
6876                                              + (map->includes_phdrs
6877                                                 ? (iehdr->e_phnum
6878                                                    * iehdr->e_phentsize)
6879                                                 : 0)))
6880                 map->p_paddr = segment->p_vaddr;
6881
6882               /* Match up the physical address of the segment with the
6883                  LMA address of the output section.  */
6884               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
6885                   || IS_COREFILE_NOTE (segment, section)
6886                   || (bed->want_p_paddr_set_to_zero
6887                       && IS_CONTAINED_BY_VMA (output_section, segment)))
6888                 {
6889                   if (first_matching_lma || output_section->lma < matching_lma)
6890                     {
6891                       matching_lma = output_section->lma;
6892                       first_matching_lma = FALSE;
6893                     }
6894
6895                   /* We assume that if the section fits within the segment
6896                      then it does not overlap any other section within that
6897                      segment.  */
6898                   map->sections[isec++] = output_section;
6899                 }
6900               else if (first_suggested_lma)
6901                 {
6902                   suggested_lma = output_section->lma;
6903                   first_suggested_lma = FALSE;
6904                 }
6905
6906               if (j == section_count)
6907                 break;
6908             }
6909         }
6910
6911       BFD_ASSERT (j == section_count);
6912
6913       /* Step Two: Adjust the physical address of the current segment,
6914          if necessary.  */
6915       if (isec == section_count)
6916         {
6917           /* All of the sections fitted within the segment as currently
6918              specified.  This is the default case.  Add the segment to
6919              the list of built segments and carry on to process the next
6920              program header in the input BFD.  */
6921           map->count = section_count;
6922           *pointer_to_map = map;
6923           pointer_to_map = &map->next;
6924
6925           if (p_paddr_valid
6926               && !bed->want_p_paddr_set_to_zero
6927               && matching_lma != map->p_paddr
6928               && !map->includes_filehdr
6929               && !map->includes_phdrs)
6930             /* There is some padding before the first section in the
6931                segment.  So, we must account for that in the output
6932                segment's vma.  */
6933             map->p_vaddr_offset = matching_lma - map->p_paddr;
6934
6935           free (sections);
6936           continue;
6937         }
6938       else
6939         {
6940           if (!first_matching_lma)
6941             {
6942               /* At least one section fits inside the current segment.
6943                  Keep it, but modify its physical address to match the
6944                  LMA of the first section that fitted.  */
6945               map->p_paddr = matching_lma;
6946             }
6947           else
6948             {
6949               /* None of the sections fitted inside the current segment.
6950                  Change the current segment's physical address to match
6951                  the LMA of the first section.  */
6952               map->p_paddr = suggested_lma;
6953             }
6954
6955           /* Offset the segment physical address from the lma
6956              to allow for space taken up by elf headers.  */
6957           if (map->includes_filehdr)
6958             {
6959               if (map->p_paddr >= iehdr->e_ehsize)
6960                 map->p_paddr -= iehdr->e_ehsize;
6961               else
6962                 {
6963                   map->includes_filehdr = FALSE;
6964                   map->includes_phdrs = FALSE;
6965                 }
6966             }
6967
6968           if (map->includes_phdrs)
6969             {
6970               if (map->p_paddr >= iehdr->e_phnum * iehdr->e_phentsize)
6971                 {
6972                   map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
6973
6974                   /* iehdr->e_phnum is just an estimate of the number
6975                      of program headers that we will need.  Make a note
6976                      here of the number we used and the segment we chose
6977                      to hold these headers, so that we can adjust the
6978                      offset when we know the correct value.  */
6979                   phdr_adjust_num = iehdr->e_phnum;
6980                   phdr_adjust_seg = map;
6981                 }
6982               else
6983                 map->includes_phdrs = FALSE;
6984             }
6985         }
6986
6987       /* Step Three: Loop over the sections again, this time assigning
6988          those that fit to the current segment and removing them from the
6989          sections array; but making sure not to leave large gaps.  Once all
6990          possible sections have been assigned to the current segment it is
6991          added to the list of built segments and if sections still remain
6992          to be assigned, a new segment is constructed before repeating
6993          the loop.  */
6994       isec = 0;
6995       do
6996         {
6997           map->count = 0;
6998           suggested_lma = 0;
6999           first_suggested_lma = TRUE;
7000
7001           /* Fill the current segment with sections that fit.  */
7002           for (j = 0; j < section_count; j++)
7003             {
7004               section = sections[j];
7005
7006               if (section == NULL)
7007                 continue;
7008
7009               output_section = section->output_section;
7010
7011               BFD_ASSERT (output_section != NULL);
7012
7013               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
7014                   || IS_COREFILE_NOTE (segment, section))
7015                 {
7016                   if (map->count == 0)
7017                     {
7018                       /* If the first section in a segment does not start at
7019                          the beginning of the segment, then something is
7020                          wrong.  */
7021                       if (output_section->lma
7022                           != (map->p_paddr
7023                               + (map->includes_filehdr ? iehdr->e_ehsize : 0)
7024                               + (map->includes_phdrs
7025                                  ? iehdr->e_phnum * iehdr->e_phentsize
7026                                  : 0)))
7027                         abort ();
7028                     }
7029                   else
7030                     {
7031                       asection *prev_sec;
7032
7033                       prev_sec = map->sections[map->count - 1];
7034
7035                       /* If the gap between the end of the previous section
7036                          and the start of this section is more than
7037                          maxpagesize then we need to start a new segment.  */
7038                       if ((BFD_ALIGN (prev_sec->lma + prev_sec->size,
7039                                       maxpagesize)
7040                            < BFD_ALIGN (output_section->lma, maxpagesize))
7041                           || (prev_sec->lma + prev_sec->size
7042                               > output_section->lma))
7043                         {
7044                           if (first_suggested_lma)
7045                             {
7046                               suggested_lma = output_section->lma;
7047                               first_suggested_lma = FALSE;
7048                             }
7049
7050                           continue;
7051                         }
7052                     }
7053
7054                   map->sections[map->count++] = output_section;
7055                   ++isec;
7056                   sections[j] = NULL;
7057                   section->segment_mark = TRUE;
7058                 }
7059               else if (first_suggested_lma)
7060                 {
7061                   suggested_lma = output_section->lma;
7062                   first_suggested_lma = FALSE;
7063                 }
7064             }
7065
7066           BFD_ASSERT (map->count > 0);
7067
7068           /* Add the current segment to the list of built segments.  */
7069           *pointer_to_map = map;
7070           pointer_to_map = &map->next;
7071
7072           if (isec < section_count)
7073             {
7074               /* We still have not allocated all of the sections to
7075                  segments.  Create a new segment here, initialise it
7076                  and carry on looping.  */
7077               amt = sizeof (struct elf_segment_map);
7078               amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
7079               map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
7080               if (map == NULL)
7081                 {
7082                   free (sections);
7083                   return FALSE;
7084                 }
7085
7086               /* Initialise the fields of the segment map.  Set the physical
7087                  physical address to the LMA of the first section that has
7088                  not yet been assigned.  */
7089               map->next = NULL;
7090               map->p_type = segment->p_type;
7091               map->p_flags = segment->p_flags;
7092               map->p_flags_valid = 1;
7093               map->p_paddr = suggested_lma;
7094               map->p_paddr_valid = p_paddr_valid;
7095               map->includes_filehdr = 0;
7096               map->includes_phdrs = 0;
7097             }
7098         }
7099       while (isec < section_count);
7100
7101       free (sections);
7102     }
7103
7104   elf_seg_map (obfd) = map_first;
7105
7106   /* If we had to estimate the number of program headers that were
7107      going to be needed, then check our estimate now and adjust
7108      the offset if necessary.  */
7109   if (phdr_adjust_seg != NULL)
7110     {
7111       unsigned int count;
7112
7113       for (count = 0, map = map_first; map != NULL; map = map->next)
7114         count++;
7115
7116       if (count > phdr_adjust_num)
7117         phdr_adjust_seg->p_paddr
7118           -= (count - phdr_adjust_num) * iehdr->e_phentsize;
7119     }
7120
7121 #undef SEGMENT_END
7122 #undef SECTION_SIZE
7123 #undef IS_CONTAINED_BY_VMA
7124 #undef IS_CONTAINED_BY_LMA
7125 #undef IS_NOTE
7126 #undef IS_COREFILE_NOTE
7127 #undef IS_SOLARIS_PT_INTERP
7128 #undef IS_SECTION_IN_INPUT_SEGMENT
7129 #undef INCLUDE_SECTION_IN_SEGMENT
7130 #undef SEGMENT_AFTER_SEGMENT
7131 #undef SEGMENT_OVERLAPS
7132   return TRUE;
7133 }
7134
7135 /* Copy ELF program header information.  */
7136
7137 static bfd_boolean
7138 copy_elf_program_header (bfd *ibfd, bfd *obfd)
7139 {
7140   Elf_Internal_Ehdr *iehdr;
7141   struct elf_segment_map *map;
7142   struct elf_segment_map *map_first;
7143   struct elf_segment_map **pointer_to_map;
7144   Elf_Internal_Phdr *segment;
7145   unsigned int i;
7146   unsigned int num_segments;
7147   bfd_boolean phdr_included = FALSE;
7148   bfd_boolean p_paddr_valid;
7149
7150   iehdr = elf_elfheader (ibfd);
7151
7152   map_first = NULL;
7153   pointer_to_map = &map_first;
7154
7155   /* If all the segment p_paddr fields are zero, don't set
7156      map->p_paddr_valid.  */
7157   p_paddr_valid = FALSE;
7158   num_segments = elf_elfheader (ibfd)->e_phnum;
7159   for (i = 0, segment = elf_tdata (ibfd)->phdr;
7160        i < num_segments;
7161        i++, segment++)
7162     if (segment->p_paddr != 0)
7163       {
7164         p_paddr_valid = TRUE;
7165         break;
7166       }
7167
7168   for (i = 0, segment = elf_tdata (ibfd)->phdr;
7169        i < num_segments;
7170        i++, segment++)
7171     {
7172       asection *section;
7173       unsigned int section_count;
7174       bfd_size_type amt;
7175       Elf_Internal_Shdr *this_hdr;
7176       asection *first_section = NULL;
7177       asection *lowest_section;
7178
7179       /* Compute how many sections are in this segment.  */
7180       for (section = ibfd->sections, section_count = 0;
7181            section != NULL;
7182            section = section->next)
7183         {
7184           this_hdr = &(elf_section_data(section)->this_hdr);
7185           if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
7186             {
7187               if (first_section == NULL)
7188                 first_section = section;
7189               section_count++;
7190             }
7191         }
7192
7193       /* Allocate a segment map big enough to contain
7194          all of the sections we have selected.  */
7195       amt = sizeof (struct elf_segment_map);
7196       if (section_count != 0)
7197         amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
7198       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
7199       if (map == NULL)
7200         return FALSE;
7201
7202       /* Initialize the fields of the output segment map with the
7203          input segment.  */
7204       map->next = NULL;
7205       map->p_type = segment->p_type;
7206       map->p_flags = segment->p_flags;
7207       map->p_flags_valid = 1;
7208       map->p_paddr = segment->p_paddr;
7209       map->p_paddr_valid = p_paddr_valid;
7210       map->p_align = segment->p_align;
7211       map->p_align_valid = 1;
7212       map->p_vaddr_offset = 0;
7213
7214       if (map->p_type == PT_GNU_RELRO
7215           || map->p_type == PT_GNU_STACK)
7216         {
7217           /* The PT_GNU_RELRO segment may contain the first a few
7218              bytes in the .got.plt section even if the whole .got.plt
7219              section isn't in the PT_GNU_RELRO segment.  We won't
7220              change the size of the PT_GNU_RELRO segment.
7221              Similarly, PT_GNU_STACK size is significant on uclinux
7222              systems.    */
7223           map->p_size = segment->p_memsz;
7224           map->p_size_valid = 1;
7225         }
7226
7227       /* Determine if this segment contains the ELF file header
7228          and if it contains the program headers themselves.  */
7229       map->includes_filehdr = (segment->p_offset == 0
7230                                && segment->p_filesz >= iehdr->e_ehsize);
7231
7232       map->includes_phdrs = 0;
7233       if (! phdr_included || segment->p_type != PT_LOAD)
7234         {
7235           map->includes_phdrs =
7236             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
7237              && (segment->p_offset + segment->p_filesz
7238                  >= ((bfd_vma) iehdr->e_phoff
7239                      + iehdr->e_phnum * iehdr->e_phentsize)));
7240
7241           if (segment->p_type == PT_LOAD && map->includes_phdrs)
7242             phdr_included = TRUE;
7243         }
7244
7245       lowest_section = NULL;
7246       if (section_count != 0)
7247         {
7248           unsigned int isec = 0;
7249
7250           for (section = first_section;
7251                section != NULL;
7252                section = section->next)
7253             {
7254               this_hdr = &(elf_section_data(section)->this_hdr);
7255               if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
7256                 {
7257                   map->sections[isec++] = section->output_section;
7258                   if ((section->flags & SEC_ALLOC) != 0)
7259                     {
7260                       bfd_vma seg_off;
7261
7262                       if (lowest_section == NULL
7263                           || section->lma < lowest_section->lma)
7264                         lowest_section = section;
7265
7266                       /* Section lmas are set up from PT_LOAD header
7267                          p_paddr in _bfd_elf_make_section_from_shdr.
7268                          If this header has a p_paddr that disagrees
7269                          with the section lma, flag the p_paddr as
7270                          invalid.  */
7271                       if ((section->flags & SEC_LOAD) != 0)
7272                         seg_off = this_hdr->sh_offset - segment->p_offset;
7273                       else
7274                         seg_off = this_hdr->sh_addr - segment->p_vaddr;
7275                       if (section->lma - segment->p_paddr != seg_off)
7276                         map->p_paddr_valid = FALSE;
7277                     }
7278                   if (isec == section_count)
7279                     break;
7280                 }
7281             }
7282         }
7283
7284       if (map->includes_filehdr && lowest_section != NULL)
7285         /* We need to keep the space used by the headers fixed.  */
7286         map->header_size = lowest_section->vma - segment->p_vaddr;
7287
7288       if (!map->includes_phdrs
7289           && !map->includes_filehdr
7290           && map->p_paddr_valid)
7291         /* There is some other padding before the first section.  */
7292         map->p_vaddr_offset = ((lowest_section ? lowest_section->lma : 0)
7293                                - segment->p_paddr);
7294
7295       map->count = section_count;
7296       *pointer_to_map = map;
7297       pointer_to_map = &map->next;
7298     }
7299
7300   elf_seg_map (obfd) = map_first;
7301   return TRUE;
7302 }
7303
7304 /* Copy private BFD data.  This copies or rewrites ELF program header
7305    information.  */
7306
7307 static bfd_boolean
7308 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
7309 {
7310   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
7311       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
7312     return TRUE;
7313
7314   if (elf_tdata (ibfd)->phdr == NULL)
7315     return TRUE;
7316
7317   if (ibfd->xvec == obfd->xvec)
7318     {
7319       /* Check to see if any sections in the input BFD
7320          covered by ELF program header have changed.  */
7321       Elf_Internal_Phdr *segment;
7322       asection *section, *osec;
7323       unsigned int i, num_segments;
7324       Elf_Internal_Shdr *this_hdr;
7325       const struct elf_backend_data *bed;
7326
7327       bed = get_elf_backend_data (ibfd);
7328
7329       /* Regenerate the segment map if p_paddr is set to 0.  */
7330       if (bed->want_p_paddr_set_to_zero)
7331         goto rewrite;
7332
7333       /* Initialize the segment mark field.  */
7334       for (section = obfd->sections; section != NULL;
7335            section = section->next)
7336         section->segment_mark = FALSE;
7337
7338       num_segments = elf_elfheader (ibfd)->e_phnum;
7339       for (i = 0, segment = elf_tdata (ibfd)->phdr;
7340            i < num_segments;
7341            i++, segment++)
7342         {
7343           /* PR binutils/3535.  The Solaris linker always sets the p_paddr
7344              and p_memsz fields of special segments (DYNAMIC, INTERP) to 0
7345              which severly confuses things, so always regenerate the segment
7346              map in this case.  */
7347           if (segment->p_paddr == 0
7348               && segment->p_memsz == 0
7349               && (segment->p_type == PT_INTERP || segment->p_type == PT_DYNAMIC))
7350             goto rewrite;
7351
7352           for (section = ibfd->sections;
7353                section != NULL; section = section->next)
7354             {
7355               /* We mark the output section so that we know it comes
7356                  from the input BFD.  */
7357               osec = section->output_section;
7358               if (osec)
7359                 osec->segment_mark = TRUE;
7360
7361               /* Check if this section is covered by the segment.  */
7362               this_hdr = &(elf_section_data(section)->this_hdr);
7363               if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
7364                 {
7365                   /* FIXME: Check if its output section is changed or
7366                      removed.  What else do we need to check?  */
7367                   if (osec == NULL
7368                       || section->flags != osec->flags
7369                       || section->lma != osec->lma
7370                       || section->vma != osec->vma
7371                       || section->size != osec->size
7372                       || section->rawsize != osec->rawsize
7373                       || section->alignment_power != osec->alignment_power)
7374                     goto rewrite;
7375                 }
7376             }
7377         }
7378
7379       /* Check to see if any output section do not come from the
7380          input BFD.  */
7381       for (section = obfd->sections; section != NULL;
7382            section = section->next)
7383         {
7384           if (!section->segment_mark)
7385             goto rewrite;
7386           else
7387             section->segment_mark = FALSE;
7388         }
7389
7390       return copy_elf_program_header (ibfd, obfd);
7391     }
7392
7393 rewrite:
7394   if (ibfd->xvec == obfd->xvec)
7395     {
7396       /* When rewriting program header, set the output maxpagesize to
7397          the maximum alignment of input PT_LOAD segments.  */
7398       Elf_Internal_Phdr *segment;
7399       unsigned int i;
7400       unsigned int num_segments = elf_elfheader (ibfd)->e_phnum;
7401       bfd_vma maxpagesize = 0;
7402
7403       for (i = 0, segment = elf_tdata (ibfd)->phdr;
7404            i < num_segments;
7405            i++, segment++)
7406         if (segment->p_type == PT_LOAD
7407             && maxpagesize < segment->p_align)
7408           {
7409             /* PR 17512: file: f17299af.  */
7410             if (segment->p_align > (bfd_vma) 1 << ((sizeof (bfd_vma) * 8) - 2))
7411               /* xgettext:c-format */
7412               _bfd_error_handler (_("%B: warning: segment alignment of %#Lx"
7413                                     " is too large"),
7414                                   ibfd, segment->p_align);
7415             else
7416               maxpagesize = segment->p_align;
7417           }
7418
7419       if (maxpagesize != get_elf_backend_data (obfd)->maxpagesize)
7420         bfd_emul_set_maxpagesize (bfd_get_target (obfd), maxpagesize);
7421     }
7422
7423   return rewrite_elf_program_header (ibfd, obfd);
7424 }
7425
7426 /* Initialize private output section information from input section.  */
7427
7428 bfd_boolean
7429 _bfd_elf_init_private_section_data (bfd *ibfd,
7430                                     asection *isec,
7431                                     bfd *obfd,
7432                                     asection *osec,
7433                                     struct bfd_link_info *link_info)
7434
7435 {
7436   Elf_Internal_Shdr *ihdr, *ohdr;
7437   bfd_boolean final_link = (link_info != NULL
7438                             && !bfd_link_relocatable (link_info));
7439
7440   if (ibfd->xvec->flavour != bfd_target_elf_flavour
7441       || obfd->xvec->flavour != bfd_target_elf_flavour)
7442     return TRUE;
7443
7444   BFD_ASSERT (elf_section_data (osec) != NULL);
7445
7446   /* For objcopy and relocatable link, don't copy the output ELF
7447      section type from input if the output BFD section flags have been
7448      set to something different.  For a final link allow some flags
7449      that the linker clears to differ.  */
7450   if (elf_section_type (osec) == SHT_NULL
7451       && (osec->flags == isec->flags
7452           || (final_link
7453               && ((osec->flags ^ isec->flags)
7454                   & ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC)) == 0)))
7455     elf_section_type (osec) = elf_section_type (isec);
7456
7457   /* FIXME: Is this correct for all OS/PROC specific flags?  */
7458   elf_section_flags (osec) |= (elf_section_flags (isec)
7459                                & (SHF_MASKOS | SHF_MASKPROC));
7460
7461   /* Copy sh_info from input for mbind section.  */
7462   if (elf_section_flags (isec) & SHF_GNU_MBIND)
7463     elf_section_data (osec)->this_hdr.sh_info
7464       = elf_section_data (isec)->this_hdr.sh_info;
7465
7466   /* Set things up for objcopy and relocatable link.  The output
7467      SHT_GROUP section will have its elf_next_in_group pointing back
7468      to the input group members.  Ignore linker created group section.
7469      See elfNN_ia64_object_p in elfxx-ia64.c.  */
7470   if ((link_info == NULL
7471        || !link_info->resolve_section_groups)
7472       && (elf_sec_group (isec) == NULL
7473           || (elf_sec_group (isec)->flags & SEC_LINKER_CREATED) == 0))
7474     {
7475       if (elf_section_flags (isec) & SHF_GROUP)
7476         elf_section_flags (osec) |= SHF_GROUP;
7477       elf_next_in_group (osec) = elf_next_in_group (isec);
7478       elf_section_data (osec)->group = elf_section_data (isec)->group;
7479     }
7480
7481   /* If not decompress, preserve SHF_COMPRESSED.  */
7482   if (!final_link && (ibfd->flags & BFD_DECOMPRESS) == 0)
7483     elf_section_flags (osec) |= (elf_section_flags (isec)
7484                                  & SHF_COMPRESSED);
7485
7486   ihdr = &elf_section_data (isec)->this_hdr;
7487
7488   /* We need to handle elf_linked_to_section for SHF_LINK_ORDER. We
7489      don't use the output section of the linked-to section since it
7490      may be NULL at this point.  */
7491   if ((ihdr->sh_flags & SHF_LINK_ORDER) != 0)
7492     {
7493       ohdr = &elf_section_data (osec)->this_hdr;
7494       ohdr->sh_flags |= SHF_LINK_ORDER;
7495       elf_linked_to_section (osec) = elf_linked_to_section (isec);
7496     }
7497
7498   osec->use_rela_p = isec->use_rela_p;
7499
7500   return TRUE;
7501 }
7502
7503 /* Copy private section information.  This copies over the entsize
7504    field, and sometimes the info field.  */
7505
7506 bfd_boolean
7507 _bfd_elf_copy_private_section_data (bfd *ibfd,
7508                                     asection *isec,
7509                                     bfd *obfd,
7510                                     asection *osec)
7511 {
7512   Elf_Internal_Shdr *ihdr, *ohdr;
7513
7514   if (ibfd->xvec->flavour != bfd_target_elf_flavour
7515       || obfd->xvec->flavour != bfd_target_elf_flavour)
7516     return TRUE;
7517
7518   ihdr = &elf_section_data (isec)->this_hdr;
7519   ohdr = &elf_section_data (osec)->this_hdr;
7520
7521   ohdr->sh_entsize = ihdr->sh_entsize;
7522
7523   if (ihdr->sh_type == SHT_SYMTAB
7524       || ihdr->sh_type == SHT_DYNSYM
7525       || ihdr->sh_type == SHT_GNU_verneed
7526       || ihdr->sh_type == SHT_GNU_verdef)
7527     ohdr->sh_info = ihdr->sh_info;
7528
7529   return _bfd_elf_init_private_section_data (ibfd, isec, obfd, osec,
7530                                              NULL);
7531 }
7532
7533 /* Look at all the SHT_GROUP sections in IBFD, making any adjustments
7534    necessary if we are removing either the SHT_GROUP section or any of
7535    the group member sections.  DISCARDED is the value that a section's
7536    output_section has if the section will be discarded, NULL when this
7537    function is called from objcopy, bfd_abs_section_ptr when called
7538    from the linker.  */
7539
7540 bfd_boolean
7541 _bfd_elf_fixup_group_sections (bfd *ibfd, asection *discarded)
7542 {
7543   asection *isec;
7544
7545   for (isec = ibfd->sections; isec != NULL; isec = isec->next)
7546     if (elf_section_type (isec) == SHT_GROUP)
7547       {
7548         asection *first = elf_next_in_group (isec);
7549         asection *s = first;
7550         bfd_size_type removed = 0;
7551
7552         while (s != NULL)
7553           {
7554             /* If this member section is being output but the
7555                SHT_GROUP section is not, then clear the group info
7556                set up by _bfd_elf_copy_private_section_data.  */
7557             if (s->output_section != discarded
7558                 && isec->output_section == discarded)
7559               {
7560                 elf_section_flags (s->output_section) &= ~SHF_GROUP;
7561                 elf_group_name (s->output_section) = NULL;
7562               }
7563             /* Conversely, if the member section is not being output
7564                but the SHT_GROUP section is, then adjust its size.  */
7565             else if (s->output_section == discarded
7566                      && isec->output_section != discarded)
7567               removed += 4;
7568             s = elf_next_in_group (s);
7569             if (s == first)
7570               break;
7571           }
7572         if (removed != 0)
7573           {
7574             if (discarded != NULL)
7575               {
7576                 /* If we've been called for ld -r, then we need to
7577                    adjust the input section size.  This function may
7578                    be called multiple times, so save the original
7579                    size.  */
7580                 if (isec->rawsize == 0)
7581                   isec->rawsize = isec->size;
7582                 isec->size = isec->rawsize - removed;
7583               }
7584             else
7585               {
7586                 /* Adjust the output section size when called from
7587                    objcopy. */
7588                 isec->output_section->size -= removed;
7589               }
7590           }
7591       }
7592
7593   return TRUE;
7594 }
7595
7596 /* Copy private header information.  */
7597
7598 bfd_boolean
7599 _bfd_elf_copy_private_header_data (bfd *ibfd, bfd *obfd)
7600 {
7601   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
7602       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
7603     return TRUE;
7604
7605   /* Copy over private BFD data if it has not already been copied.
7606      This must be done here, rather than in the copy_private_bfd_data
7607      entry point, because the latter is called after the section
7608      contents have been set, which means that the program headers have
7609      already been worked out.  */
7610   if (elf_seg_map (obfd) == NULL && elf_tdata (ibfd)->phdr != NULL)
7611     {
7612       if (! copy_private_bfd_data (ibfd, obfd))
7613         return FALSE;
7614     }
7615
7616   return _bfd_elf_fixup_group_sections (ibfd, NULL);
7617 }
7618
7619 /* Copy private symbol information.  If this symbol is in a section
7620    which we did not map into a BFD section, try to map the section
7621    index correctly.  We use special macro definitions for the mapped
7622    section indices; these definitions are interpreted by the
7623    swap_out_syms function.  */
7624
7625 #define MAP_ONESYMTAB (SHN_HIOS + 1)
7626 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
7627 #define MAP_STRTAB    (SHN_HIOS + 3)
7628 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
7629 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
7630
7631 bfd_boolean
7632 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
7633                                    asymbol *isymarg,
7634                                    bfd *obfd,
7635                                    asymbol *osymarg)
7636 {
7637   elf_symbol_type *isym, *osym;
7638
7639   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
7640       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
7641     return TRUE;
7642
7643   isym = elf_symbol_from (ibfd, isymarg);
7644   osym = elf_symbol_from (obfd, osymarg);
7645
7646   if (isym != NULL
7647       && isym->internal_elf_sym.st_shndx != 0
7648       && osym != NULL
7649       && bfd_is_abs_section (isym->symbol.section))
7650     {
7651       unsigned int shndx;
7652
7653       shndx = isym->internal_elf_sym.st_shndx;
7654       if (shndx == elf_onesymtab (ibfd))
7655         shndx = MAP_ONESYMTAB;
7656       else if (shndx == elf_dynsymtab (ibfd))
7657         shndx = MAP_DYNSYMTAB;
7658       else if (shndx == elf_strtab_sec (ibfd))
7659         shndx = MAP_STRTAB;
7660       else if (shndx == elf_shstrtab_sec (ibfd))
7661         shndx = MAP_SHSTRTAB;
7662       else if (find_section_in_list (shndx, elf_symtab_shndx_list (ibfd)))
7663         shndx = MAP_SYM_SHNDX;
7664       osym->internal_elf_sym.st_shndx = shndx;
7665     }
7666
7667   return TRUE;
7668 }
7669
7670 /* Swap out the symbols.  */
7671
7672 static bfd_boolean
7673 swap_out_syms (bfd *abfd,
7674                struct elf_strtab_hash **sttp,
7675                int relocatable_p)
7676 {
7677   const struct elf_backend_data *bed;
7678   int symcount;
7679   asymbol **syms;
7680   struct elf_strtab_hash *stt;
7681   Elf_Internal_Shdr *symtab_hdr;
7682   Elf_Internal_Shdr *symtab_shndx_hdr;
7683   Elf_Internal_Shdr *symstrtab_hdr;
7684   struct elf_sym_strtab *symstrtab;
7685   bfd_byte *outbound_syms;
7686   bfd_byte *outbound_shndx;
7687   unsigned long outbound_syms_index;
7688   unsigned long outbound_shndx_index;
7689   int idx;
7690   unsigned int num_locals;
7691   bfd_size_type amt;
7692   bfd_boolean name_local_sections;
7693
7694   if (!elf_map_symbols (abfd, &num_locals))
7695     return FALSE;
7696
7697   /* Dump out the symtabs.  */
7698   stt = _bfd_elf_strtab_init ();
7699   if (stt == NULL)
7700     return FALSE;
7701
7702   bed = get_elf_backend_data (abfd);
7703   symcount = bfd_get_symcount (abfd);
7704   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
7705   symtab_hdr->sh_type = SHT_SYMTAB;
7706   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
7707   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
7708   symtab_hdr->sh_info = num_locals + 1;
7709   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
7710
7711   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
7712   symstrtab_hdr->sh_type = SHT_STRTAB;
7713
7714   /* Allocate buffer to swap out the .strtab section.  */
7715   symstrtab = (struct elf_sym_strtab *) bfd_malloc ((symcount + 1)
7716                                                     * sizeof (*symstrtab));
7717   if (symstrtab == NULL)
7718     {
7719       _bfd_elf_strtab_free (stt);
7720       return FALSE;
7721     }
7722
7723   outbound_syms = (bfd_byte *) bfd_alloc2 (abfd, 1 + symcount,
7724                                            bed->s->sizeof_sym);
7725   if (outbound_syms == NULL)
7726     {
7727 error_return:
7728       _bfd_elf_strtab_free (stt);
7729       free (symstrtab);
7730       return FALSE;
7731     }
7732   symtab_hdr->contents = outbound_syms;
7733   outbound_syms_index = 0;
7734
7735   outbound_shndx = NULL;
7736   outbound_shndx_index = 0;
7737
7738   if (elf_symtab_shndx_list (abfd))
7739     {
7740       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
7741       if (symtab_shndx_hdr->sh_name != 0)
7742         {
7743           amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
7744           outbound_shndx =  (bfd_byte *)
7745             bfd_zalloc2 (abfd, 1 + symcount, sizeof (Elf_External_Sym_Shndx));
7746           if (outbound_shndx == NULL)
7747             goto error_return;
7748
7749           symtab_shndx_hdr->contents = outbound_shndx;
7750           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
7751           symtab_shndx_hdr->sh_size = amt;
7752           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
7753           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
7754         }
7755       /* FIXME: What about any other headers in the list ?  */
7756     }
7757
7758   /* Now generate the data (for "contents").  */
7759   {
7760     /* Fill in zeroth symbol and swap it out.  */
7761     Elf_Internal_Sym sym;
7762     sym.st_name = 0;
7763     sym.st_value = 0;
7764     sym.st_size = 0;
7765     sym.st_info = 0;
7766     sym.st_other = 0;
7767     sym.st_shndx = SHN_UNDEF;
7768     sym.st_target_internal = 0;
7769     symstrtab[0].sym = sym;
7770     symstrtab[0].dest_index = outbound_syms_index;
7771     symstrtab[0].destshndx_index = outbound_shndx_index;
7772     outbound_syms_index++;
7773     if (outbound_shndx != NULL)
7774       outbound_shndx_index++;
7775   }
7776
7777   name_local_sections
7778     = (bed->elf_backend_name_local_section_symbols
7779        && bed->elf_backend_name_local_section_symbols (abfd));
7780
7781   syms = bfd_get_outsymbols (abfd);
7782   for (idx = 0; idx < symcount;)
7783     {
7784       Elf_Internal_Sym sym;
7785       bfd_vma value = syms[idx]->value;
7786       elf_symbol_type *type_ptr;
7787       flagword flags = syms[idx]->flags;
7788       int type;
7789
7790       if (!name_local_sections
7791           && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
7792         {
7793           /* Local section symbols have no name.  */
7794           sym.st_name = (unsigned long) -1;
7795         }
7796       else
7797         {
7798           /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
7799              to get the final offset for st_name.  */
7800           sym.st_name
7801             = (unsigned long) _bfd_elf_strtab_add (stt, syms[idx]->name,
7802                                                    FALSE);
7803           if (sym.st_name == (unsigned long) -1)
7804             goto error_return;
7805         }
7806
7807       type_ptr = elf_symbol_from (abfd, syms[idx]);
7808
7809       if ((flags & BSF_SECTION_SYM) == 0
7810           && bfd_is_com_section (syms[idx]->section))
7811         {
7812           /* ELF common symbols put the alignment into the `value' field,
7813              and the size into the `size' field.  This is backwards from
7814              how BFD handles it, so reverse it here.  */
7815           sym.st_size = value;
7816           if (type_ptr == NULL
7817               || type_ptr->internal_elf_sym.st_value == 0)
7818             sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
7819           else
7820             sym.st_value = type_ptr->internal_elf_sym.st_value;
7821           sym.st_shndx = _bfd_elf_section_from_bfd_section
7822             (abfd, syms[idx]->section);
7823         }
7824       else
7825         {
7826           asection *sec = syms[idx]->section;
7827           unsigned int shndx;
7828
7829           if (sec->output_section)
7830             {
7831               value += sec->output_offset;
7832               sec = sec->output_section;
7833             }
7834
7835           /* Don't add in the section vma for relocatable output.  */
7836           if (! relocatable_p)
7837             value += sec->vma;
7838           sym.st_value = value;
7839           sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
7840
7841           if (bfd_is_abs_section (sec)
7842               && type_ptr != NULL
7843               && type_ptr->internal_elf_sym.st_shndx != 0)
7844             {
7845               /* This symbol is in a real ELF section which we did
7846                  not create as a BFD section.  Undo the mapping done
7847                  by copy_private_symbol_data.  */
7848               shndx = type_ptr->internal_elf_sym.st_shndx;
7849               switch (shndx)
7850                 {
7851                 case MAP_ONESYMTAB:
7852                   shndx = elf_onesymtab (abfd);
7853                   break;
7854                 case MAP_DYNSYMTAB:
7855                   shndx = elf_dynsymtab (abfd);
7856                   break;
7857                 case MAP_STRTAB:
7858                   shndx = elf_strtab_sec (abfd);
7859                   break;
7860                 case MAP_SHSTRTAB:
7861                   shndx = elf_shstrtab_sec (abfd);
7862                   break;
7863                 case MAP_SYM_SHNDX:
7864                   if (elf_symtab_shndx_list (abfd))
7865                     shndx = elf_symtab_shndx_list (abfd)->ndx;
7866                   break;
7867                 default:
7868                   shndx = SHN_ABS;
7869                   break;
7870                 }
7871             }
7872           else
7873             {
7874               shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
7875
7876               if (shndx == SHN_BAD)
7877                 {
7878                   asection *sec2;
7879
7880                   /* Writing this would be a hell of a lot easier if
7881                      we had some decent documentation on bfd, and
7882                      knew what to expect of the library, and what to
7883                      demand of applications.  For example, it
7884                      appears that `objcopy' might not set the
7885                      section of a symbol to be a section that is
7886                      actually in the output file.  */
7887                   sec2 = bfd_get_section_by_name (abfd, sec->name);
7888                   if (sec2 != NULL)
7889                     shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
7890                   if (shndx == SHN_BAD)
7891                     {
7892                       /* xgettext:c-format */
7893                       _bfd_error_handler (_("\
7894 Unable to find equivalent output section for symbol '%s' from section '%s'"),
7895                                           syms[idx]->name ? syms[idx]->name : "<Local sym>",
7896                                           sec->name);
7897                       bfd_set_error (bfd_error_invalid_operation);
7898                       goto error_return;
7899                     }
7900                 }
7901             }
7902
7903           sym.st_shndx = shndx;
7904         }
7905
7906       if ((flags & BSF_THREAD_LOCAL) != 0)
7907         type = STT_TLS;
7908       else if ((flags & BSF_GNU_INDIRECT_FUNCTION) != 0)
7909         type = STT_GNU_IFUNC;
7910       else if ((flags & BSF_FUNCTION) != 0)
7911         type = STT_FUNC;
7912       else if ((flags & BSF_OBJECT) != 0)
7913         type = STT_OBJECT;
7914       else if ((flags & BSF_RELC) != 0)
7915         type = STT_RELC;
7916       else if ((flags & BSF_SRELC) != 0)
7917         type = STT_SRELC;
7918       else
7919         type = STT_NOTYPE;
7920
7921       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
7922         type = STT_TLS;
7923
7924       /* Processor-specific types.  */
7925       if (type_ptr != NULL
7926           && bed->elf_backend_get_symbol_type)
7927         type = ((*bed->elf_backend_get_symbol_type)
7928                 (&type_ptr->internal_elf_sym, type));
7929
7930       if (flags & BSF_SECTION_SYM)
7931         {
7932           if (flags & BSF_GLOBAL)
7933             sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
7934           else
7935             sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
7936         }
7937       else if (bfd_is_com_section (syms[idx]->section))
7938         {
7939           if (type != STT_TLS)
7940             {
7941               if ((abfd->flags & BFD_CONVERT_ELF_COMMON))
7942                 type = ((abfd->flags & BFD_USE_ELF_STT_COMMON)
7943                         ? STT_COMMON : STT_OBJECT);
7944               else
7945                 type = ((flags & BSF_ELF_COMMON) != 0
7946                         ? STT_COMMON : STT_OBJECT);
7947             }
7948           sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
7949         }
7950       else if (bfd_is_und_section (syms[idx]->section))
7951         sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
7952                                     ? STB_WEAK
7953                                     : STB_GLOBAL),
7954                                    type);
7955       else if (flags & BSF_FILE)
7956         sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
7957       else
7958         {
7959           int bind = STB_LOCAL;
7960
7961           if (flags & BSF_LOCAL)
7962             bind = STB_LOCAL;
7963           else if (flags & BSF_GNU_UNIQUE)
7964             bind = STB_GNU_UNIQUE;
7965           else if (flags & BSF_WEAK)
7966             bind = STB_WEAK;
7967           else if (flags & BSF_GLOBAL)
7968             bind = STB_GLOBAL;
7969
7970           sym.st_info = ELF_ST_INFO (bind, type);
7971         }
7972
7973       if (type_ptr != NULL)
7974         {
7975           sym.st_other = type_ptr->internal_elf_sym.st_other;
7976           sym.st_target_internal
7977             = type_ptr->internal_elf_sym.st_target_internal;
7978         }
7979       else
7980         {
7981           sym.st_other = 0;
7982           sym.st_target_internal = 0;
7983         }
7984
7985       idx++;
7986       symstrtab[idx].sym = sym;
7987       symstrtab[idx].dest_index = outbound_syms_index;
7988       symstrtab[idx].destshndx_index = outbound_shndx_index;
7989
7990       outbound_syms_index++;
7991       if (outbound_shndx != NULL)
7992         outbound_shndx_index++;
7993     }
7994
7995   /* Finalize the .strtab section.  */
7996   _bfd_elf_strtab_finalize (stt);
7997
7998   /* Swap out the .strtab section.  */
7999   for (idx = 0; idx <= symcount; idx++)
8000     {
8001       struct elf_sym_strtab *elfsym = &symstrtab[idx];
8002       if (elfsym->sym.st_name == (unsigned long) -1)
8003         elfsym->sym.st_name = 0;
8004       else
8005         elfsym->sym.st_name = _bfd_elf_strtab_offset (stt,
8006                                                       elfsym->sym.st_name);
8007       bed->s->swap_symbol_out (abfd, &elfsym->sym,
8008                                (outbound_syms
8009                                 + (elfsym->dest_index
8010                                    * bed->s->sizeof_sym)),
8011                                (outbound_shndx
8012                                 + (elfsym->destshndx_index
8013                                    * sizeof (Elf_External_Sym_Shndx))));
8014     }
8015   free (symstrtab);
8016
8017   *sttp = stt;
8018   symstrtab_hdr->sh_size = _bfd_elf_strtab_size (stt);
8019   symstrtab_hdr->sh_type = SHT_STRTAB;
8020   symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
8021   symstrtab_hdr->sh_addr = 0;
8022   symstrtab_hdr->sh_entsize = 0;
8023   symstrtab_hdr->sh_link = 0;
8024   symstrtab_hdr->sh_info = 0;
8025   symstrtab_hdr->sh_addralign = 1;
8026
8027   return TRUE;
8028 }
8029
8030 /* Return the number of bytes required to hold the symtab vector.
8031
8032    Note that we base it on the count plus 1, since we will null terminate
8033    the vector allocated based on this size.  However, the ELF symbol table
8034    always has a dummy entry as symbol #0, so it ends up even.  */
8035
8036 long
8037 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
8038 {
8039   long symcount;
8040   long symtab_size;
8041   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
8042
8043   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
8044   symtab_size = (symcount + 1) * (sizeof (asymbol *));
8045   if (symcount > 0)
8046     symtab_size -= sizeof (asymbol *);
8047
8048   return symtab_size;
8049 }
8050
8051 long
8052 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
8053 {
8054   long symcount;
8055   long symtab_size;
8056   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
8057
8058   if (elf_dynsymtab (abfd) == 0)
8059     {
8060       bfd_set_error (bfd_error_invalid_operation);
8061       return -1;
8062     }
8063
8064   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
8065   symtab_size = (symcount + 1) * (sizeof (asymbol *));
8066   if (symcount > 0)
8067     symtab_size -= sizeof (asymbol *);
8068
8069   return symtab_size;
8070 }
8071
8072 long
8073 _bfd_elf_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
8074                                 sec_ptr asect)
8075 {
8076   return (asect->reloc_count + 1) * sizeof (arelent *);
8077 }
8078
8079 /* Canonicalize the relocs.  */
8080
8081 long
8082 _bfd_elf_canonicalize_reloc (bfd *abfd,
8083                              sec_ptr section,
8084                              arelent **relptr,
8085                              asymbol **symbols)
8086 {
8087   arelent *tblptr;
8088   unsigned int i;
8089   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8090
8091   if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
8092     return -1;
8093
8094   tblptr = section->relocation;
8095   for (i = 0; i < section->reloc_count; i++)
8096     *relptr++ = tblptr++;
8097
8098   *relptr = NULL;
8099
8100   return section->reloc_count;
8101 }
8102
8103 long
8104 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
8105 {
8106   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8107   long symcount = bed->s->slurp_symbol_table (abfd, allocation, FALSE);
8108
8109   if (symcount >= 0)
8110     bfd_get_symcount (abfd) = symcount;
8111   return symcount;
8112 }
8113
8114 long
8115 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
8116                                       asymbol **allocation)
8117 {
8118   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8119   long symcount = bed->s->slurp_symbol_table (abfd, allocation, TRUE);
8120
8121   if (symcount >= 0)
8122     bfd_get_dynamic_symcount (abfd) = symcount;
8123   return symcount;
8124 }
8125
8126 /* Return the size required for the dynamic reloc entries.  Any loadable
8127    section that was actually installed in the BFD, and has type SHT_REL
8128    or SHT_RELA, and uses the dynamic symbol table, is considered to be a
8129    dynamic reloc section.  */
8130
8131 long
8132 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
8133 {
8134   long ret;
8135   asection *s;
8136
8137   if (elf_dynsymtab (abfd) == 0)
8138     {
8139       bfd_set_error (bfd_error_invalid_operation);
8140       return -1;
8141     }
8142
8143   ret = sizeof (arelent *);
8144   for (s = abfd->sections; s != NULL; s = s->next)
8145     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
8146         && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
8147             || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
8148       ret += ((s->size / elf_section_data (s)->this_hdr.sh_entsize)
8149               * sizeof (arelent *));
8150
8151   return ret;
8152 }
8153
8154 /* Canonicalize the dynamic relocation entries.  Note that we return the
8155    dynamic relocations as a single block, although they are actually
8156    associated with particular sections; the interface, which was
8157    designed for SunOS style shared libraries, expects that there is only
8158    one set of dynamic relocs.  Any loadable section that was actually
8159    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses the
8160    dynamic symbol table, is considered to be a dynamic reloc section.  */
8161
8162 long
8163 _bfd_elf_canonicalize_dynamic_reloc (bfd *abfd,
8164                                      arelent **storage,
8165                                      asymbol **syms)
8166 {
8167   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
8168   asection *s;
8169   long ret;
8170
8171   if (elf_dynsymtab (abfd) == 0)
8172     {
8173       bfd_set_error (bfd_error_invalid_operation);
8174       return -1;
8175     }
8176
8177   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
8178   ret = 0;
8179   for (s = abfd->sections; s != NULL; s = s->next)
8180     {
8181       if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
8182           && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
8183               || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
8184         {
8185           arelent *p;
8186           long count, i;
8187
8188           if (! (*slurp_relocs) (abfd, s, syms, TRUE))
8189             return -1;
8190           count = s->size / elf_section_data (s)->this_hdr.sh_entsize;
8191           p = s->relocation;
8192           for (i = 0; i < count; i++)
8193             *storage++ = p++;
8194           ret += count;
8195         }
8196     }
8197
8198   *storage = NULL;
8199
8200   return ret;
8201 }
8202 \f
8203 /* Read in the version information.  */
8204
8205 bfd_boolean
8206 _bfd_elf_slurp_version_tables (bfd *abfd, bfd_boolean default_imported_symver)
8207 {
8208   bfd_byte *contents = NULL;
8209   unsigned int freeidx = 0;
8210
8211   if (elf_dynverref (abfd) != 0)
8212     {
8213       Elf_Internal_Shdr *hdr;
8214       Elf_External_Verneed *everneed;
8215       Elf_Internal_Verneed *iverneed;
8216       unsigned int i;
8217       bfd_byte *contents_end;
8218
8219       hdr = &elf_tdata (abfd)->dynverref_hdr;
8220
8221       if (hdr->sh_info == 0
8222           || hdr->sh_info > hdr->sh_size / sizeof (Elf_External_Verneed))
8223         {
8224 error_return_bad_verref:
8225           _bfd_error_handler
8226             (_("%B: .gnu.version_r invalid entry"), abfd);
8227           bfd_set_error (bfd_error_bad_value);
8228 error_return_verref:
8229           elf_tdata (abfd)->verref = NULL;
8230           elf_tdata (abfd)->cverrefs = 0;
8231           goto error_return;
8232         }
8233
8234       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
8235       if (contents == NULL)
8236         goto error_return_verref;
8237
8238       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
8239           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
8240         goto error_return_verref;
8241
8242       elf_tdata (abfd)->verref = (Elf_Internal_Verneed *)
8243         bfd_alloc2 (abfd, hdr->sh_info, sizeof (Elf_Internal_Verneed));
8244
8245       if (elf_tdata (abfd)->verref == NULL)
8246         goto error_return_verref;
8247
8248       BFD_ASSERT (sizeof (Elf_External_Verneed)
8249                   == sizeof (Elf_External_Vernaux));
8250       contents_end = contents + hdr->sh_size - sizeof (Elf_External_Verneed);
8251       everneed = (Elf_External_Verneed *) contents;
8252       iverneed = elf_tdata (abfd)->verref;
8253       for (i = 0; i < hdr->sh_info; i++, iverneed++)
8254         {
8255           Elf_External_Vernaux *evernaux;
8256           Elf_Internal_Vernaux *ivernaux;
8257           unsigned int j;
8258
8259           _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
8260
8261           iverneed->vn_bfd = abfd;
8262
8263           iverneed->vn_filename =
8264             bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
8265                                              iverneed->vn_file);
8266           if (iverneed->vn_filename == NULL)
8267             goto error_return_bad_verref;
8268
8269           if (iverneed->vn_cnt == 0)
8270             iverneed->vn_auxptr = NULL;
8271           else
8272             {
8273               iverneed->vn_auxptr = (struct elf_internal_vernaux *)
8274                   bfd_alloc2 (abfd, iverneed->vn_cnt,
8275                               sizeof (Elf_Internal_Vernaux));
8276               if (iverneed->vn_auxptr == NULL)
8277                 goto error_return_verref;
8278             }
8279
8280           if (iverneed->vn_aux
8281               > (size_t) (contents_end - (bfd_byte *) everneed))
8282             goto error_return_bad_verref;
8283
8284           evernaux = ((Elf_External_Vernaux *)
8285                       ((bfd_byte *) everneed + iverneed->vn_aux));
8286           ivernaux = iverneed->vn_auxptr;
8287           for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
8288             {
8289               _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
8290
8291               ivernaux->vna_nodename =
8292                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
8293                                                  ivernaux->vna_name);
8294               if (ivernaux->vna_nodename == NULL)
8295                 goto error_return_bad_verref;
8296
8297               if (ivernaux->vna_other > freeidx)
8298                 freeidx = ivernaux->vna_other;
8299
8300               ivernaux->vna_nextptr = NULL;
8301               if (ivernaux->vna_next == 0)
8302                 {
8303                   iverneed->vn_cnt = j + 1;
8304                   break;
8305                 }
8306               if (j + 1 < iverneed->vn_cnt)
8307                 ivernaux->vna_nextptr = ivernaux + 1;
8308
8309               if (ivernaux->vna_next
8310                   > (size_t) (contents_end - (bfd_byte *) evernaux))
8311                 goto error_return_bad_verref;
8312
8313               evernaux = ((Elf_External_Vernaux *)
8314                           ((bfd_byte *) evernaux + ivernaux->vna_next));
8315             }
8316
8317           iverneed->vn_nextref = NULL;
8318           if (iverneed->vn_next == 0)
8319             break;
8320           if (i + 1 < hdr->sh_info)
8321             iverneed->vn_nextref = iverneed + 1;
8322
8323           if (iverneed->vn_next
8324               > (size_t) (contents_end - (bfd_byte *) everneed))
8325             goto error_return_bad_verref;
8326
8327           everneed = ((Elf_External_Verneed *)
8328                       ((bfd_byte *) everneed + iverneed->vn_next));
8329         }
8330       elf_tdata (abfd)->cverrefs = i;
8331
8332       free (contents);
8333       contents = NULL;
8334     }
8335
8336   if (elf_dynverdef (abfd) != 0)
8337     {
8338       Elf_Internal_Shdr *hdr;
8339       Elf_External_Verdef *everdef;
8340       Elf_Internal_Verdef *iverdef;
8341       Elf_Internal_Verdef *iverdefarr;
8342       Elf_Internal_Verdef iverdefmem;
8343       unsigned int i;
8344       unsigned int maxidx;
8345       bfd_byte *contents_end_def, *contents_end_aux;
8346
8347       hdr = &elf_tdata (abfd)->dynverdef_hdr;
8348
8349       if (hdr->sh_info == 0 || hdr->sh_size < sizeof (Elf_External_Verdef))
8350         {
8351         error_return_bad_verdef:
8352           _bfd_error_handler
8353             (_("%B: .gnu.version_d invalid entry"), abfd);
8354           bfd_set_error (bfd_error_bad_value);
8355         error_return_verdef:
8356           elf_tdata (abfd)->verdef = NULL;
8357           elf_tdata (abfd)->cverdefs = 0;
8358           goto error_return;
8359         }
8360
8361       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
8362       if (contents == NULL)
8363         goto error_return_verdef;
8364       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
8365           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
8366         goto error_return_verdef;
8367
8368       BFD_ASSERT (sizeof (Elf_External_Verdef)
8369                   >= sizeof (Elf_External_Verdaux));
8370       contents_end_def = contents + hdr->sh_size
8371                          - sizeof (Elf_External_Verdef);
8372       contents_end_aux = contents + hdr->sh_size
8373                          - sizeof (Elf_External_Verdaux);
8374
8375       /* We know the number of entries in the section but not the maximum
8376          index.  Therefore we have to run through all entries and find
8377          the maximum.  */
8378       everdef = (Elf_External_Verdef *) contents;
8379       maxidx = 0;
8380       for (i = 0; i < hdr->sh_info; ++i)
8381         {
8382           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
8383
8384           if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) == 0)
8385             goto error_return_bad_verdef;
8386           if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
8387             maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
8388
8389           if (iverdefmem.vd_next == 0)
8390             break;
8391
8392           if (iverdefmem.vd_next
8393               > (size_t) (contents_end_def - (bfd_byte *) everdef))
8394             goto error_return_bad_verdef;
8395
8396           everdef = ((Elf_External_Verdef *)
8397                      ((bfd_byte *) everdef + iverdefmem.vd_next));
8398         }
8399
8400       if (default_imported_symver)
8401         {
8402           if (freeidx > maxidx)
8403             maxidx = ++freeidx;
8404           else
8405             freeidx = ++maxidx;
8406         }
8407
8408       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *)
8409         bfd_zalloc2 (abfd, maxidx, sizeof (Elf_Internal_Verdef));
8410       if (elf_tdata (abfd)->verdef == NULL)
8411         goto error_return_verdef;
8412
8413       elf_tdata (abfd)->cverdefs = maxidx;
8414
8415       everdef = (Elf_External_Verdef *) contents;
8416       iverdefarr = elf_tdata (abfd)->verdef;
8417       for (i = 0; i < hdr->sh_info; i++)
8418         {
8419           Elf_External_Verdaux *everdaux;
8420           Elf_Internal_Verdaux *iverdaux;
8421           unsigned int j;
8422
8423           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
8424
8425           if ((iverdefmem.vd_ndx & VERSYM_VERSION) == 0)
8426             goto error_return_bad_verdef;
8427
8428           iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
8429           memcpy (iverdef, &iverdefmem, offsetof (Elf_Internal_Verdef, vd_bfd));
8430
8431           iverdef->vd_bfd = abfd;
8432
8433           if (iverdef->vd_cnt == 0)
8434             iverdef->vd_auxptr = NULL;
8435           else
8436             {
8437               iverdef->vd_auxptr = (struct elf_internal_verdaux *)
8438                   bfd_alloc2 (abfd, iverdef->vd_cnt,
8439                               sizeof (Elf_Internal_Verdaux));
8440               if (iverdef->vd_auxptr == NULL)
8441                 goto error_return_verdef;
8442             }
8443
8444           if (iverdef->vd_aux
8445               > (size_t) (contents_end_aux - (bfd_byte *) everdef))
8446             goto error_return_bad_verdef;
8447
8448           everdaux = ((Elf_External_Verdaux *)
8449                       ((bfd_byte *) everdef + iverdef->vd_aux));
8450           iverdaux = iverdef->vd_auxptr;
8451           for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
8452             {
8453               _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
8454
8455               iverdaux->vda_nodename =
8456                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
8457                                                  iverdaux->vda_name);
8458               if (iverdaux->vda_nodename == NULL)
8459                 goto error_return_bad_verdef;
8460
8461               iverdaux->vda_nextptr = NULL;
8462               if (iverdaux->vda_next == 0)
8463                 {
8464                   iverdef->vd_cnt = j + 1;
8465                   break;
8466                 }
8467               if (j + 1 < iverdef->vd_cnt)
8468                 iverdaux->vda_nextptr = iverdaux + 1;
8469
8470               if (iverdaux->vda_next
8471                   > (size_t) (contents_end_aux - (bfd_byte *) everdaux))
8472                 goto error_return_bad_verdef;
8473
8474               everdaux = ((Elf_External_Verdaux *)
8475                           ((bfd_byte *) everdaux + iverdaux->vda_next));
8476             }
8477
8478           iverdef->vd_nodename = NULL;
8479           if (iverdef->vd_cnt)
8480             iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
8481
8482           iverdef->vd_nextdef = NULL;
8483           if (iverdef->vd_next == 0)
8484             break;
8485           if ((size_t) (iverdef - iverdefarr) + 1 < maxidx)
8486             iverdef->vd_nextdef = iverdef + 1;
8487
8488           everdef = ((Elf_External_Verdef *)
8489                      ((bfd_byte *) everdef + iverdef->vd_next));
8490         }
8491
8492       free (contents);
8493       contents = NULL;
8494     }
8495   else if (default_imported_symver)
8496     {
8497       if (freeidx < 3)
8498         freeidx = 3;
8499       else
8500         freeidx++;
8501
8502       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *)
8503           bfd_zalloc2 (abfd, freeidx, sizeof (Elf_Internal_Verdef));
8504       if (elf_tdata (abfd)->verdef == NULL)
8505         goto error_return;
8506
8507       elf_tdata (abfd)->cverdefs = freeidx;
8508     }
8509
8510   /* Create a default version based on the soname.  */
8511   if (default_imported_symver)
8512     {
8513       Elf_Internal_Verdef *iverdef;
8514       Elf_Internal_Verdaux *iverdaux;
8515
8516       iverdef = &elf_tdata (abfd)->verdef[freeidx - 1];
8517
8518       iverdef->vd_version = VER_DEF_CURRENT;
8519       iverdef->vd_flags = 0;
8520       iverdef->vd_ndx = freeidx;
8521       iverdef->vd_cnt = 1;
8522
8523       iverdef->vd_bfd = abfd;
8524
8525       iverdef->vd_nodename = bfd_elf_get_dt_soname (abfd);
8526       if (iverdef->vd_nodename == NULL)
8527         goto error_return_verdef;
8528       iverdef->vd_nextdef = NULL;
8529       iverdef->vd_auxptr = ((struct elf_internal_verdaux *)
8530                             bfd_zalloc (abfd, sizeof (Elf_Internal_Verdaux)));
8531       if (iverdef->vd_auxptr == NULL)
8532         goto error_return_verdef;
8533
8534       iverdaux = iverdef->vd_auxptr;
8535       iverdaux->vda_nodename = iverdef->vd_nodename;
8536     }
8537
8538   return TRUE;
8539
8540  error_return:
8541   if (contents != NULL)
8542     free (contents);
8543   return FALSE;
8544 }
8545 \f
8546 asymbol *
8547 _bfd_elf_make_empty_symbol (bfd *abfd)
8548 {
8549   elf_symbol_type *newsym;
8550
8551   newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof * newsym);
8552   if (!newsym)
8553     return NULL;
8554   newsym->symbol.the_bfd = abfd;
8555   return &newsym->symbol;
8556 }
8557
8558 void
8559 _bfd_elf_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
8560                           asymbol *symbol,
8561                           symbol_info *ret)
8562 {
8563   bfd_symbol_info (symbol, ret);
8564 }
8565
8566 /* Return whether a symbol name implies a local symbol.  Most targets
8567    use this function for the is_local_label_name entry point, but some
8568    override it.  */
8569
8570 bfd_boolean
8571 _bfd_elf_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
8572                               const char *name)
8573 {
8574   /* Normal local symbols start with ``.L''.  */
8575   if (name[0] == '.' && name[1] == 'L')
8576     return TRUE;
8577
8578   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
8579      DWARF debugging symbols starting with ``..''.  */
8580   if (name[0] == '.' && name[1] == '.')
8581     return TRUE;
8582
8583   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
8584      emitting DWARF debugging output.  I suspect this is actually a
8585      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
8586      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
8587      underscore to be emitted on some ELF targets).  For ease of use,
8588      we treat such symbols as local.  */
8589   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
8590     return TRUE;
8591
8592   /* Treat assembler generated fake symbols, dollar local labels and
8593      forward-backward labels (aka local labels) as locals.
8594      These labels have the form:
8595
8596        L0^A.*                                  (fake symbols)
8597
8598        [.]?L[0123456789]+{^A|^B}[0123456789]*  (local labels)
8599
8600      Versions which start with .L will have already been matched above,
8601      so we only need to match the rest.  */
8602   if (name[0] == 'L' && ISDIGIT (name[1]))
8603     {
8604       bfd_boolean ret = FALSE;
8605       const char * p;
8606       char c;
8607
8608       for (p = name + 2; (c = *p); p++)
8609         {
8610           if (c == 1 || c == 2)
8611             {
8612               if (c == 1 && p == name + 2)
8613                 /* A fake symbol.  */
8614                 return TRUE;
8615
8616               /* FIXME: We are being paranoid here and treating symbols like
8617                  L0^Bfoo as if there were non-local, on the grounds that the
8618                  assembler will never generate them.  But can any symbol
8619                  containing an ASCII value in the range 1-31 ever be anything
8620                  other than some kind of local ?  */
8621               ret = TRUE;
8622             }
8623
8624           if (! ISDIGIT (c))
8625             {
8626               ret = FALSE;
8627               break;
8628             }
8629         }
8630       return ret;
8631     }
8632
8633   return FALSE;
8634 }
8635
8636 alent *
8637 _bfd_elf_get_lineno (bfd *abfd ATTRIBUTE_UNUSED,
8638                      asymbol *symbol ATTRIBUTE_UNUSED)
8639 {
8640   abort ();
8641   return NULL;
8642 }
8643
8644 bfd_boolean
8645 _bfd_elf_set_arch_mach (bfd *abfd,
8646                         enum bfd_architecture arch,
8647                         unsigned long machine)
8648 {
8649   /* If this isn't the right architecture for this backend, and this
8650      isn't the generic backend, fail.  */
8651   if (arch != get_elf_backend_data (abfd)->arch
8652       && arch != bfd_arch_unknown
8653       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
8654     return FALSE;
8655
8656   return bfd_default_set_arch_mach (abfd, arch, machine);
8657 }
8658
8659 /* Find the nearest line to a particular section and offset,
8660    for error reporting.  */
8661
8662 bfd_boolean
8663 _bfd_elf_find_nearest_line (bfd *abfd,
8664                             asymbol **symbols,
8665                             asection *section,
8666                             bfd_vma offset,
8667                             const char **filename_ptr,
8668                             const char **functionname_ptr,
8669                             unsigned int *line_ptr,
8670                             unsigned int *discriminator_ptr)
8671 {
8672   bfd_boolean found;
8673
8674   if (_bfd_dwarf2_find_nearest_line (abfd, symbols, NULL, section, offset,
8675                                      filename_ptr, functionname_ptr,
8676                                      line_ptr, discriminator_ptr,
8677                                      dwarf_debug_sections, 0,
8678                                      &elf_tdata (abfd)->dwarf2_find_line_info)
8679       || _bfd_dwarf1_find_nearest_line (abfd, symbols, section, offset,
8680                                         filename_ptr, functionname_ptr,
8681                                         line_ptr))
8682     {
8683       if (!*functionname_ptr)
8684         _bfd_elf_find_function (abfd, symbols, section, offset,
8685                                 *filename_ptr ? NULL : filename_ptr,
8686                                 functionname_ptr);
8687       return TRUE;
8688     }
8689
8690   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
8691                                              &found, filename_ptr,
8692                                              functionname_ptr, line_ptr,
8693                                              &elf_tdata (abfd)->line_info))
8694     return FALSE;
8695   if (found && (*functionname_ptr || *line_ptr))
8696     return TRUE;
8697
8698   if (symbols == NULL)
8699     return FALSE;
8700
8701   if (! _bfd_elf_find_function (abfd, symbols, section, offset,
8702                                 filename_ptr, functionname_ptr))
8703     return FALSE;
8704
8705   *line_ptr = 0;
8706   return TRUE;
8707 }
8708
8709 /* Find the line for a symbol.  */
8710
8711 bfd_boolean
8712 _bfd_elf_find_line (bfd *abfd, asymbol **symbols, asymbol *symbol,
8713                     const char **filename_ptr, unsigned int *line_ptr)
8714 {
8715   return _bfd_dwarf2_find_nearest_line (abfd, symbols, symbol, NULL, 0,
8716                                         filename_ptr, NULL, line_ptr, NULL,
8717                                         dwarf_debug_sections, 0,
8718                                         &elf_tdata (abfd)->dwarf2_find_line_info);
8719 }
8720
8721 /* After a call to bfd_find_nearest_line, successive calls to
8722    bfd_find_inliner_info can be used to get source information about
8723    each level of function inlining that terminated at the address
8724    passed to bfd_find_nearest_line.  Currently this is only supported
8725    for DWARF2 with appropriate DWARF3 extensions. */
8726
8727 bfd_boolean
8728 _bfd_elf_find_inliner_info (bfd *abfd,
8729                             const char **filename_ptr,
8730                             const char **functionname_ptr,
8731                             unsigned int *line_ptr)
8732 {
8733   bfd_boolean found;
8734   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
8735                                          functionname_ptr, line_ptr,
8736                                          & elf_tdata (abfd)->dwarf2_find_line_info);
8737   return found;
8738 }
8739
8740 int
8741 _bfd_elf_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
8742 {
8743   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8744   int ret = bed->s->sizeof_ehdr;
8745
8746   if (!bfd_link_relocatable (info))
8747     {
8748       bfd_size_type phdr_size = elf_program_header_size (abfd);
8749
8750       if (phdr_size == (bfd_size_type) -1)
8751         {
8752           struct elf_segment_map *m;
8753
8754           phdr_size = 0;
8755           for (m = elf_seg_map (abfd); m != NULL; m = m->next)
8756             phdr_size += bed->s->sizeof_phdr;
8757
8758           if (phdr_size == 0)
8759             phdr_size = get_program_header_size (abfd, info);
8760         }
8761
8762       elf_program_header_size (abfd) = phdr_size;
8763       ret += phdr_size;
8764     }
8765
8766   return ret;
8767 }
8768
8769 bfd_boolean
8770 _bfd_elf_set_section_contents (bfd *abfd,
8771                                sec_ptr section,
8772                                const void *location,
8773                                file_ptr offset,
8774                                bfd_size_type count)
8775 {
8776   Elf_Internal_Shdr *hdr;
8777   file_ptr pos;
8778
8779   if (! abfd->output_has_begun
8780       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
8781     return FALSE;
8782
8783   if (!count)
8784     return TRUE;
8785
8786   hdr = &elf_section_data (section)->this_hdr;
8787   if (hdr->sh_offset == (file_ptr) -1)
8788     {
8789       /* We must compress this section.  Write output to the buffer.  */
8790       unsigned char *contents = hdr->contents;
8791       if ((offset + count) > hdr->sh_size
8792           || (section->flags & SEC_ELF_COMPRESS) == 0
8793           || contents == NULL)
8794         abort ();
8795       memcpy (contents + offset, location, count);
8796       return TRUE;
8797     }
8798   pos = hdr->sh_offset + offset;
8799   if (bfd_seek (abfd, pos, SEEK_SET) != 0
8800       || bfd_bwrite (location, count, abfd) != count)
8801     return FALSE;
8802
8803   return TRUE;
8804 }
8805
8806 void
8807 _bfd_elf_no_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
8808                            arelent *cache_ptr ATTRIBUTE_UNUSED,
8809                            Elf_Internal_Rela *dst ATTRIBUTE_UNUSED)
8810 {
8811   abort ();
8812 }
8813
8814 /* Try to convert a non-ELF reloc into an ELF one.  */
8815
8816 bfd_boolean
8817 _bfd_elf_validate_reloc (bfd *abfd, arelent *areloc)
8818 {
8819   /* Check whether we really have an ELF howto.  */
8820
8821   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
8822     {
8823       bfd_reloc_code_real_type code;
8824       reloc_howto_type *howto;
8825
8826       /* Alien reloc: Try to determine its type to replace it with an
8827          equivalent ELF reloc.  */
8828
8829       if (areloc->howto->pc_relative)
8830         {
8831           switch (areloc->howto->bitsize)
8832             {
8833             case 8:
8834               code = BFD_RELOC_8_PCREL;
8835               break;
8836             case 12:
8837               code = BFD_RELOC_12_PCREL;
8838               break;
8839             case 16:
8840               code = BFD_RELOC_16_PCREL;
8841               break;
8842             case 24:
8843               code = BFD_RELOC_24_PCREL;
8844               break;
8845             case 32:
8846               code = BFD_RELOC_32_PCREL;
8847               break;
8848             case 64:
8849               code = BFD_RELOC_64_PCREL;
8850               break;
8851             default:
8852               goto fail;
8853             }
8854
8855           howto = bfd_reloc_type_lookup (abfd, code);
8856
8857           if (areloc->howto->pcrel_offset != howto->pcrel_offset)
8858             {
8859               if (howto->pcrel_offset)
8860                 areloc->addend += areloc->address;
8861               else
8862                 areloc->addend -= areloc->address; /* addend is unsigned!! */
8863             }
8864         }
8865       else
8866         {
8867           switch (areloc->howto->bitsize)
8868             {
8869             case 8:
8870               code = BFD_RELOC_8;
8871               break;
8872             case 14:
8873               code = BFD_RELOC_14;
8874               break;
8875             case 16:
8876               code = BFD_RELOC_16;
8877               break;
8878             case 26:
8879               code = BFD_RELOC_26;
8880               break;
8881             case 32:
8882               code = BFD_RELOC_32;
8883               break;
8884             case 64:
8885               code = BFD_RELOC_64;
8886               break;
8887             default:
8888               goto fail;
8889             }
8890
8891           howto = bfd_reloc_type_lookup (abfd, code);
8892         }
8893
8894       if (howto)
8895         areloc->howto = howto;
8896       else
8897         goto fail;
8898     }
8899
8900   return TRUE;
8901
8902  fail:
8903   _bfd_error_handler
8904     /* xgettext:c-format */
8905     (_("%B: unsupported relocation type %s"),
8906      abfd, areloc->howto->name);
8907   bfd_set_error (bfd_error_bad_value);
8908   return FALSE;
8909 }
8910
8911 bfd_boolean
8912 _bfd_elf_close_and_cleanup (bfd *abfd)
8913 {
8914   struct elf_obj_tdata *tdata = elf_tdata (abfd);
8915   if (bfd_get_format (abfd) == bfd_object && tdata != NULL)
8916     {
8917       if (elf_tdata (abfd)->o != NULL && elf_shstrtab (abfd) != NULL)
8918         _bfd_elf_strtab_free (elf_shstrtab (abfd));
8919       _bfd_dwarf2_cleanup_debug_info (abfd, &tdata->dwarf2_find_line_info);
8920     }
8921
8922   return _bfd_generic_close_and_cleanup (abfd);
8923 }
8924
8925 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
8926    in the relocation's offset.  Thus we cannot allow any sort of sanity
8927    range-checking to interfere.  There is nothing else to do in processing
8928    this reloc.  */
8929
8930 bfd_reloc_status_type
8931 _bfd_elf_rel_vtable_reloc_fn
8932   (bfd *abfd ATTRIBUTE_UNUSED, arelent *re ATTRIBUTE_UNUSED,
8933    struct bfd_symbol *symbol ATTRIBUTE_UNUSED,
8934    void *data ATTRIBUTE_UNUSED, asection *is ATTRIBUTE_UNUSED,
8935    bfd *obfd ATTRIBUTE_UNUSED, char **errmsg ATTRIBUTE_UNUSED)
8936 {
8937   return bfd_reloc_ok;
8938 }
8939 \f
8940 /* Elf core file support.  Much of this only works on native
8941    toolchains, since we rely on knowing the
8942    machine-dependent procfs structure in order to pick
8943    out details about the corefile.  */
8944
8945 #ifdef HAVE_SYS_PROCFS_H
8946 /* Needed for new procfs interface on sparc-solaris.  */
8947 # define _STRUCTURED_PROC 1
8948 # include <sys/procfs.h>
8949 #endif
8950
8951 /* Return a PID that identifies a "thread" for threaded cores, or the
8952    PID of the main process for non-threaded cores.  */
8953
8954 static int
8955 elfcore_make_pid (bfd *abfd)
8956 {
8957   int pid;
8958
8959   pid = elf_tdata (abfd)->core->lwpid;
8960   if (pid == 0)
8961     pid = elf_tdata (abfd)->core->pid;
8962
8963   return pid;
8964 }
8965
8966 /* If there isn't a section called NAME, make one, using
8967    data from SECT.  Note, this function will generate a
8968    reference to NAME, so you shouldn't deallocate or
8969    overwrite it.  */
8970
8971 static bfd_boolean
8972 elfcore_maybe_make_sect (bfd *abfd, char *name, asection *sect)
8973 {
8974   asection *sect2;
8975
8976   if (bfd_get_section_by_name (abfd, name) != NULL)
8977     return TRUE;
8978
8979   sect2 = bfd_make_section_with_flags (abfd, name, sect->flags);
8980   if (sect2 == NULL)
8981     return FALSE;
8982
8983   sect2->size = sect->size;
8984   sect2->filepos = sect->filepos;
8985   sect2->alignment_power = sect->alignment_power;
8986   return TRUE;
8987 }
8988
8989 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
8990    actually creates up to two pseudosections:
8991    - For the single-threaded case, a section named NAME, unless
8992      such a section already exists.
8993    - For the multi-threaded case, a section named "NAME/PID", where
8994      PID is elfcore_make_pid (abfd).
8995    Both pseudosections have identical contents.  */
8996 bfd_boolean
8997 _bfd_elfcore_make_pseudosection (bfd *abfd,
8998                                  char *name,
8999                                  size_t size,
9000                                  ufile_ptr filepos)
9001 {
9002   char buf[100];
9003   char *threaded_name;
9004   size_t len;
9005   asection *sect;
9006
9007   /* Build the section name.  */
9008
9009   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
9010   len = strlen (buf) + 1;
9011   threaded_name = (char *) bfd_alloc (abfd, len);
9012   if (threaded_name == NULL)
9013     return FALSE;
9014   memcpy (threaded_name, buf, len);
9015
9016   sect = bfd_make_section_anyway_with_flags (abfd, threaded_name,
9017                                              SEC_HAS_CONTENTS);
9018   if (sect == NULL)
9019     return FALSE;
9020   sect->size = size;
9021   sect->filepos = filepos;
9022   sect->alignment_power = 2;
9023
9024   return elfcore_maybe_make_sect (abfd, name, sect);
9025 }
9026
9027 /* prstatus_t exists on:
9028      solaris 2.5+
9029      linux 2.[01] + glibc
9030      unixware 4.2
9031 */
9032
9033 #if defined (HAVE_PRSTATUS_T)
9034
9035 static bfd_boolean
9036 elfcore_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
9037 {
9038   size_t size;
9039   int offset;
9040
9041   if (note->descsz == sizeof (prstatus_t))
9042     {
9043       prstatus_t prstat;
9044
9045       size = sizeof (prstat.pr_reg);
9046       offset   = offsetof (prstatus_t, pr_reg);
9047       memcpy (&prstat, note->descdata, sizeof (prstat));
9048
9049       /* Do not overwrite the core signal if it
9050          has already been set by another thread.  */
9051       if (elf_tdata (abfd)->core->signal == 0)
9052         elf_tdata (abfd)->core->signal = prstat.pr_cursig;
9053       if (elf_tdata (abfd)->core->pid == 0)
9054         elf_tdata (abfd)->core->pid = prstat.pr_pid;
9055
9056       /* pr_who exists on:
9057          solaris 2.5+
9058          unixware 4.2
9059          pr_who doesn't exist on:
9060          linux 2.[01]
9061          */
9062 #if defined (HAVE_PRSTATUS_T_PR_WHO)
9063       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
9064 #else
9065       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
9066 #endif
9067     }
9068 #if defined (HAVE_PRSTATUS32_T)
9069   else if (note->descsz == sizeof (prstatus32_t))
9070     {
9071       /* 64-bit host, 32-bit corefile */
9072       prstatus32_t prstat;
9073
9074       size = sizeof (prstat.pr_reg);
9075       offset   = offsetof (prstatus32_t, pr_reg);
9076       memcpy (&prstat, note->descdata, sizeof (prstat));
9077
9078       /* Do not overwrite the core signal if it
9079          has already been set by another thread.  */
9080       if (elf_tdata (abfd)->core->signal == 0)
9081         elf_tdata (abfd)->core->signal = prstat.pr_cursig;
9082       if (elf_tdata (abfd)->core->pid == 0)
9083         elf_tdata (abfd)->core->pid = prstat.pr_pid;
9084
9085       /* pr_who exists on:
9086          solaris 2.5+
9087          unixware 4.2
9088          pr_who doesn't exist on:
9089          linux 2.[01]
9090          */
9091 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
9092       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
9093 #else
9094       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
9095 #endif
9096     }
9097 #endif /* HAVE_PRSTATUS32_T */
9098   else
9099     {
9100       /* Fail - we don't know how to handle any other
9101          note size (ie. data object type).  */
9102       return TRUE;
9103     }
9104
9105   /* Make a ".reg/999" section and a ".reg" section.  */
9106   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
9107                                           size, note->descpos + offset);
9108 }
9109 #endif /* defined (HAVE_PRSTATUS_T) */
9110
9111 /* Create a pseudosection containing the exact contents of NOTE.  */
9112 static bfd_boolean
9113 elfcore_make_note_pseudosection (bfd *abfd,
9114                                  char *name,
9115                                  Elf_Internal_Note *note)
9116 {
9117   return _bfd_elfcore_make_pseudosection (abfd, name,
9118                                           note->descsz, note->descpos);
9119 }
9120
9121 /* There isn't a consistent prfpregset_t across platforms,
9122    but it doesn't matter, because we don't have to pick this
9123    data structure apart.  */
9124
9125 static bfd_boolean
9126 elfcore_grok_prfpreg (bfd *abfd, Elf_Internal_Note *note)
9127 {
9128   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
9129 }
9130
9131 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
9132    type of NT_PRXFPREG.  Just include the whole note's contents
9133    literally.  */
9134
9135 static bfd_boolean
9136 elfcore_grok_prxfpreg (bfd *abfd, Elf_Internal_Note *note)
9137 {
9138   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
9139 }
9140
9141 /* Linux dumps the Intel XSAVE extended state in a note named "LINUX"
9142    with a note type of NT_X86_XSTATE.  Just include the whole note's
9143    contents literally.  */
9144
9145 static bfd_boolean
9146 elfcore_grok_xstatereg (bfd *abfd, Elf_Internal_Note *note)
9147 {
9148   return elfcore_make_note_pseudosection (abfd, ".reg-xstate", note);
9149 }
9150
9151 static bfd_boolean
9152 elfcore_grok_ppc_vmx (bfd *abfd, Elf_Internal_Note *note)
9153 {
9154   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vmx", note);
9155 }
9156
9157 static bfd_boolean
9158 elfcore_grok_ppc_vsx (bfd *abfd, Elf_Internal_Note *note)
9159 {
9160   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vsx", note);
9161 }
9162
9163 static bfd_boolean
9164 elfcore_grok_s390_high_gprs (bfd *abfd, Elf_Internal_Note *note)
9165 {
9166   return elfcore_make_note_pseudosection (abfd, ".reg-s390-high-gprs", note);
9167 }
9168
9169 static bfd_boolean
9170 elfcore_grok_s390_timer (bfd *abfd, Elf_Internal_Note *note)
9171 {
9172   return elfcore_make_note_pseudosection (abfd, ".reg-s390-timer", note);
9173 }
9174
9175 static bfd_boolean
9176 elfcore_grok_s390_todcmp (bfd *abfd, Elf_Internal_Note *note)
9177 {
9178   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todcmp", note);
9179 }
9180
9181 static bfd_boolean
9182 elfcore_grok_s390_todpreg (bfd *abfd, Elf_Internal_Note *note)
9183 {
9184   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todpreg", note);
9185 }
9186
9187 static bfd_boolean
9188 elfcore_grok_s390_ctrs (bfd *abfd, Elf_Internal_Note *note)
9189 {
9190   return elfcore_make_note_pseudosection (abfd, ".reg-s390-ctrs", note);
9191 }
9192
9193 static bfd_boolean
9194 elfcore_grok_s390_prefix (bfd *abfd, Elf_Internal_Note *note)
9195 {
9196   return elfcore_make_note_pseudosection (abfd, ".reg-s390-prefix", note);
9197 }
9198
9199 static bfd_boolean
9200 elfcore_grok_s390_last_break (bfd *abfd, Elf_Internal_Note *note)
9201 {
9202   return elfcore_make_note_pseudosection (abfd, ".reg-s390-last-break", note);
9203 }
9204
9205 static bfd_boolean
9206 elfcore_grok_s390_system_call (bfd *abfd, Elf_Internal_Note *note)
9207 {
9208   return elfcore_make_note_pseudosection (abfd, ".reg-s390-system-call", note);
9209 }
9210
9211 static bfd_boolean
9212 elfcore_grok_s390_tdb (bfd *abfd, Elf_Internal_Note *note)
9213 {
9214   return elfcore_make_note_pseudosection (abfd, ".reg-s390-tdb", note);
9215 }
9216
9217 static bfd_boolean
9218 elfcore_grok_s390_vxrs_low (bfd *abfd, Elf_Internal_Note *note)
9219 {
9220   return elfcore_make_note_pseudosection (abfd, ".reg-s390-vxrs-low", note);
9221 }
9222
9223 static bfd_boolean
9224 elfcore_grok_s390_vxrs_high (bfd *abfd, Elf_Internal_Note *note)
9225 {
9226   return elfcore_make_note_pseudosection (abfd, ".reg-s390-vxrs-high", note);
9227 }
9228
9229 static bfd_boolean
9230 elfcore_grok_s390_gs_cb (bfd *abfd, Elf_Internal_Note *note)
9231 {
9232   return elfcore_make_note_pseudosection (abfd, ".reg-s390-gs-cb", note);
9233 }
9234
9235 static bfd_boolean
9236 elfcore_grok_s390_gs_bc (bfd *abfd, Elf_Internal_Note *note)
9237 {
9238   return elfcore_make_note_pseudosection (abfd, ".reg-s390-gs-bc", note);
9239 }
9240
9241 static bfd_boolean
9242 elfcore_grok_arm_vfp (bfd *abfd, Elf_Internal_Note *note)
9243 {
9244   return elfcore_make_note_pseudosection (abfd, ".reg-arm-vfp", note);
9245 }
9246
9247 static bfd_boolean
9248 elfcore_grok_aarch_tls (bfd *abfd, Elf_Internal_Note *note)
9249 {
9250   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-tls", note);
9251 }
9252
9253 static bfd_boolean
9254 elfcore_grok_aarch_hw_break (bfd *abfd, Elf_Internal_Note *note)
9255 {
9256   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-break", note);
9257 }
9258
9259 static bfd_boolean
9260 elfcore_grok_aarch_hw_watch (bfd *abfd, Elf_Internal_Note *note)
9261 {
9262   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-watch", note);
9263 }
9264
9265 #if defined (HAVE_PRPSINFO_T)
9266 typedef prpsinfo_t   elfcore_psinfo_t;
9267 #if defined (HAVE_PRPSINFO32_T)         /* Sparc64 cross Sparc32 */
9268 typedef prpsinfo32_t elfcore_psinfo32_t;
9269 #endif
9270 #endif
9271
9272 #if defined (HAVE_PSINFO_T)
9273 typedef psinfo_t   elfcore_psinfo_t;
9274 #if defined (HAVE_PSINFO32_T)           /* Sparc64 cross Sparc32 */
9275 typedef psinfo32_t elfcore_psinfo32_t;
9276 #endif
9277 #endif
9278
9279 /* return a malloc'ed copy of a string at START which is at
9280    most MAX bytes long, possibly without a terminating '\0'.
9281    the copy will always have a terminating '\0'.  */
9282
9283 char *
9284 _bfd_elfcore_strndup (bfd *abfd, char *start, size_t max)
9285 {
9286   char *dups;
9287   char *end = (char *) memchr (start, '\0', max);
9288   size_t len;
9289
9290   if (end == NULL)
9291     len = max;
9292   else
9293     len = end - start;
9294
9295   dups = (char *) bfd_alloc (abfd, len + 1);
9296   if (dups == NULL)
9297     return NULL;
9298
9299   memcpy (dups, start, len);
9300   dups[len] = '\0';
9301
9302   return dups;
9303 }
9304
9305 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
9306 static bfd_boolean
9307 elfcore_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
9308 {
9309   if (note->descsz == sizeof (elfcore_psinfo_t))
9310     {
9311       elfcore_psinfo_t psinfo;
9312
9313       memcpy (&psinfo, note->descdata, sizeof (psinfo));
9314
9315 #if defined (HAVE_PSINFO_T_PR_PID) || defined (HAVE_PRPSINFO_T_PR_PID)
9316       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
9317 #endif
9318       elf_tdata (abfd)->core->program
9319         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
9320                                 sizeof (psinfo.pr_fname));
9321
9322       elf_tdata (abfd)->core->command
9323         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
9324                                 sizeof (psinfo.pr_psargs));
9325     }
9326 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
9327   else if (note->descsz == sizeof (elfcore_psinfo32_t))
9328     {
9329       /* 64-bit host, 32-bit corefile */
9330       elfcore_psinfo32_t psinfo;
9331
9332       memcpy (&psinfo, note->descdata, sizeof (psinfo));
9333
9334 #if defined (HAVE_PSINFO32_T_PR_PID) || defined (HAVE_PRPSINFO32_T_PR_PID)
9335       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
9336 #endif
9337       elf_tdata (abfd)->core->program
9338         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
9339                                 sizeof (psinfo.pr_fname));
9340
9341       elf_tdata (abfd)->core->command
9342         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
9343                                 sizeof (psinfo.pr_psargs));
9344     }
9345 #endif
9346
9347   else
9348     {
9349       /* Fail - we don't know how to handle any other
9350          note size (ie. data object type).  */
9351       return TRUE;
9352     }
9353
9354   /* Note that for some reason, a spurious space is tacked
9355      onto the end of the args in some (at least one anyway)
9356      implementations, so strip it off if it exists.  */
9357
9358   {
9359     char *command = elf_tdata (abfd)->core->command;
9360     int n = strlen (command);
9361
9362     if (0 < n && command[n - 1] == ' ')
9363       command[n - 1] = '\0';
9364   }
9365
9366   return TRUE;
9367 }
9368 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
9369
9370 #if defined (HAVE_PSTATUS_T)
9371 static bfd_boolean
9372 elfcore_grok_pstatus (bfd *abfd, Elf_Internal_Note *note)
9373 {
9374   if (note->descsz == sizeof (pstatus_t)
9375 #if defined (HAVE_PXSTATUS_T)
9376       || note->descsz == sizeof (pxstatus_t)
9377 #endif
9378       )
9379     {
9380       pstatus_t pstat;
9381
9382       memcpy (&pstat, note->descdata, sizeof (pstat));
9383
9384       elf_tdata (abfd)->core->pid = pstat.pr_pid;
9385     }
9386 #if defined (HAVE_PSTATUS32_T)
9387   else if (note->descsz == sizeof (pstatus32_t))
9388     {
9389       /* 64-bit host, 32-bit corefile */
9390       pstatus32_t pstat;
9391
9392       memcpy (&pstat, note->descdata, sizeof (pstat));
9393
9394       elf_tdata (abfd)->core->pid = pstat.pr_pid;
9395     }
9396 #endif
9397   /* Could grab some more details from the "representative"
9398      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
9399      NT_LWPSTATUS note, presumably.  */
9400
9401   return TRUE;
9402 }
9403 #endif /* defined (HAVE_PSTATUS_T) */
9404
9405 #if defined (HAVE_LWPSTATUS_T)
9406 static bfd_boolean
9407 elfcore_grok_lwpstatus (bfd *abfd, Elf_Internal_Note *note)
9408 {
9409   lwpstatus_t lwpstat;
9410   char buf[100];
9411   char *name;
9412   size_t len;
9413   asection *sect;
9414
9415   if (note->descsz != sizeof (lwpstat)
9416 #if defined (HAVE_LWPXSTATUS_T)
9417       && note->descsz != sizeof (lwpxstatus_t)
9418 #endif
9419       )
9420     return TRUE;
9421
9422   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
9423
9424   elf_tdata (abfd)->core->lwpid = lwpstat.pr_lwpid;
9425   /* Do not overwrite the core signal if it has already been set by
9426      another thread.  */
9427   if (elf_tdata (abfd)->core->signal == 0)
9428     elf_tdata (abfd)->core->signal = lwpstat.pr_cursig;
9429
9430   /* Make a ".reg/999" section.  */
9431
9432   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
9433   len = strlen (buf) + 1;
9434   name = bfd_alloc (abfd, len);
9435   if (name == NULL)
9436     return FALSE;
9437   memcpy (name, buf, len);
9438
9439   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9440   if (sect == NULL)
9441     return FALSE;
9442
9443 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
9444   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
9445   sect->filepos = note->descpos
9446     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
9447 #endif
9448
9449 #if defined (HAVE_LWPSTATUS_T_PR_REG)
9450   sect->size = sizeof (lwpstat.pr_reg);
9451   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
9452 #endif
9453
9454   sect->alignment_power = 2;
9455
9456   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
9457     return FALSE;
9458
9459   /* Make a ".reg2/999" section */
9460
9461   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
9462   len = strlen (buf) + 1;
9463   name = bfd_alloc (abfd, len);
9464   if (name == NULL)
9465     return FALSE;
9466   memcpy (name, buf, len);
9467
9468   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9469   if (sect == NULL)
9470     return FALSE;
9471
9472 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
9473   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
9474   sect->filepos = note->descpos
9475     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
9476 #endif
9477
9478 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
9479   sect->size = sizeof (lwpstat.pr_fpreg);
9480   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
9481 #endif
9482
9483   sect->alignment_power = 2;
9484
9485   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
9486 }
9487 #endif /* defined (HAVE_LWPSTATUS_T) */
9488
9489 static bfd_boolean
9490 elfcore_grok_win32pstatus (bfd *abfd, Elf_Internal_Note *note)
9491 {
9492   char buf[30];
9493   char *name;
9494   size_t len;
9495   asection *sect;
9496   int type;
9497   int is_active_thread;
9498   bfd_vma base_addr;
9499
9500   if (note->descsz < 728)
9501     return TRUE;
9502
9503   if (! CONST_STRNEQ (note->namedata, "win32"))
9504     return TRUE;
9505
9506   type = bfd_get_32 (abfd, note->descdata);
9507
9508   switch (type)
9509     {
9510     case 1 /* NOTE_INFO_PROCESS */:
9511       /* FIXME: need to add ->core->command.  */
9512       /* process_info.pid */
9513       elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, note->descdata + 8);
9514       /* process_info.signal */
9515       elf_tdata (abfd)->core->signal = bfd_get_32 (abfd, note->descdata + 12);
9516       break;
9517
9518     case 2 /* NOTE_INFO_THREAD */:
9519       /* Make a ".reg/999" section.  */
9520       /* thread_info.tid */
9521       sprintf (buf, ".reg/%ld", (long) bfd_get_32 (abfd, note->descdata + 8));
9522
9523       len = strlen (buf) + 1;
9524       name = (char *) bfd_alloc (abfd, len);
9525       if (name == NULL)
9526         return FALSE;
9527
9528       memcpy (name, buf, len);
9529
9530       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9531       if (sect == NULL)
9532         return FALSE;
9533
9534       /* sizeof (thread_info.thread_context) */
9535       sect->size = 716;
9536       /* offsetof (thread_info.thread_context) */
9537       sect->filepos = note->descpos + 12;
9538       sect->alignment_power = 2;
9539
9540       /* thread_info.is_active_thread */
9541       is_active_thread = bfd_get_32 (abfd, note->descdata + 8);
9542
9543       if (is_active_thread)
9544         if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
9545           return FALSE;
9546       break;
9547
9548     case 3 /* NOTE_INFO_MODULE */:
9549       /* Make a ".module/xxxxxxxx" section.  */
9550       /* module_info.base_address */
9551       base_addr = bfd_get_32 (abfd, note->descdata + 4);
9552       sprintf (buf, ".module/%08lx", (unsigned long) base_addr);
9553
9554       len = strlen (buf) + 1;
9555       name = (char *) bfd_alloc (abfd, len);
9556       if (name == NULL)
9557         return FALSE;
9558
9559       memcpy (name, buf, len);
9560
9561       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9562
9563       if (sect == NULL)
9564         return FALSE;
9565
9566       sect->size = note->descsz;
9567       sect->filepos = note->descpos;
9568       sect->alignment_power = 2;
9569       break;
9570
9571     default:
9572       return TRUE;
9573     }
9574
9575   return TRUE;
9576 }
9577
9578 static bfd_boolean
9579 elfcore_grok_note (bfd *abfd, Elf_Internal_Note *note)
9580 {
9581   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9582
9583   switch (note->type)
9584     {
9585     default:
9586       return TRUE;
9587
9588     case NT_PRSTATUS:
9589       if (bed->elf_backend_grok_prstatus)
9590         if ((*bed->elf_backend_grok_prstatus) (abfd, note))
9591           return TRUE;
9592 #if defined (HAVE_PRSTATUS_T)
9593       return elfcore_grok_prstatus (abfd, note);
9594 #else
9595       return TRUE;
9596 #endif
9597
9598 #if defined (HAVE_PSTATUS_T)
9599     case NT_PSTATUS:
9600       return elfcore_grok_pstatus (abfd, note);
9601 #endif
9602
9603 #if defined (HAVE_LWPSTATUS_T)
9604     case NT_LWPSTATUS:
9605       return elfcore_grok_lwpstatus (abfd, note);
9606 #endif
9607
9608     case NT_FPREGSET:           /* FIXME: rename to NT_PRFPREG */
9609       return elfcore_grok_prfpreg (abfd, note);
9610
9611     case NT_WIN32PSTATUS:
9612       return elfcore_grok_win32pstatus (abfd, note);
9613
9614     case NT_PRXFPREG:           /* Linux SSE extension */
9615       if (note->namesz == 6
9616           && strcmp (note->namedata, "LINUX") == 0)
9617         return elfcore_grok_prxfpreg (abfd, note);
9618       else
9619         return TRUE;
9620
9621     case NT_X86_XSTATE:         /* Linux XSAVE extension */
9622       if (note->namesz == 6
9623           && strcmp (note->namedata, "LINUX") == 0)
9624         return elfcore_grok_xstatereg (abfd, note);
9625       else
9626         return TRUE;
9627
9628     case NT_PPC_VMX:
9629       if (note->namesz == 6
9630           && strcmp (note->namedata, "LINUX") == 0)
9631         return elfcore_grok_ppc_vmx (abfd, note);
9632       else
9633         return TRUE;
9634
9635     case NT_PPC_VSX:
9636       if (note->namesz == 6
9637           && strcmp (note->namedata, "LINUX") == 0)
9638         return elfcore_grok_ppc_vsx (abfd, note);
9639       else
9640         return TRUE;
9641
9642     case NT_S390_HIGH_GPRS:
9643       if (note->namesz == 6
9644           && strcmp (note->namedata, "LINUX") == 0)
9645         return elfcore_grok_s390_high_gprs (abfd, note);
9646       else
9647         return TRUE;
9648
9649     case NT_S390_TIMER:
9650       if (note->namesz == 6
9651           && strcmp (note->namedata, "LINUX") == 0)
9652         return elfcore_grok_s390_timer (abfd, note);
9653       else
9654         return TRUE;
9655
9656     case NT_S390_TODCMP:
9657       if (note->namesz == 6
9658           && strcmp (note->namedata, "LINUX") == 0)
9659         return elfcore_grok_s390_todcmp (abfd, note);
9660       else
9661         return TRUE;
9662
9663     case NT_S390_TODPREG:
9664       if (note->namesz == 6
9665           && strcmp (note->namedata, "LINUX") == 0)
9666         return elfcore_grok_s390_todpreg (abfd, note);
9667       else
9668         return TRUE;
9669
9670     case NT_S390_CTRS:
9671       if (note->namesz == 6
9672           && strcmp (note->namedata, "LINUX") == 0)
9673         return elfcore_grok_s390_ctrs (abfd, note);
9674       else
9675         return TRUE;
9676
9677     case NT_S390_PREFIX:
9678       if (note->namesz == 6
9679           && strcmp (note->namedata, "LINUX") == 0)
9680         return elfcore_grok_s390_prefix (abfd, note);
9681       else
9682         return TRUE;
9683
9684     case NT_S390_LAST_BREAK:
9685       if (note->namesz == 6
9686           && strcmp (note->namedata, "LINUX") == 0)
9687         return elfcore_grok_s390_last_break (abfd, note);
9688       else
9689         return TRUE;
9690
9691     case NT_S390_SYSTEM_CALL:
9692       if (note->namesz == 6
9693           && strcmp (note->namedata, "LINUX") == 0)
9694         return elfcore_grok_s390_system_call (abfd, note);
9695       else
9696         return TRUE;
9697
9698     case NT_S390_TDB:
9699       if (note->namesz == 6
9700           && strcmp (note->namedata, "LINUX") == 0)
9701         return elfcore_grok_s390_tdb (abfd, note);
9702       else
9703         return TRUE;
9704
9705     case NT_S390_VXRS_LOW:
9706       if (note->namesz == 6
9707           && strcmp (note->namedata, "LINUX") == 0)
9708         return elfcore_grok_s390_vxrs_low (abfd, note);
9709       else
9710         return TRUE;
9711
9712     case NT_S390_VXRS_HIGH:
9713       if (note->namesz == 6
9714           && strcmp (note->namedata, "LINUX") == 0)
9715         return elfcore_grok_s390_vxrs_high (abfd, note);
9716       else
9717         return TRUE;
9718
9719     case NT_S390_GS_CB:
9720       if (note->namesz == 6
9721           && strcmp (note->namedata, "LINUX") == 0)
9722         return elfcore_grok_s390_gs_cb (abfd, note);
9723       else
9724         return TRUE;
9725
9726     case NT_S390_GS_BC:
9727       if (note->namesz == 6
9728           && strcmp (note->namedata, "LINUX") == 0)
9729         return elfcore_grok_s390_gs_bc (abfd, note);
9730       else
9731         return TRUE;
9732
9733     case NT_ARM_VFP:
9734       if (note->namesz == 6
9735           && strcmp (note->namedata, "LINUX") == 0)
9736         return elfcore_grok_arm_vfp (abfd, note);
9737       else
9738         return TRUE;
9739
9740     case NT_ARM_TLS:
9741       if (note->namesz == 6
9742           && strcmp (note->namedata, "LINUX") == 0)
9743         return elfcore_grok_aarch_tls (abfd, note);
9744       else
9745         return TRUE;
9746
9747     case NT_ARM_HW_BREAK:
9748       if (note->namesz == 6
9749           && strcmp (note->namedata, "LINUX") == 0)
9750         return elfcore_grok_aarch_hw_break (abfd, note);
9751       else
9752         return TRUE;
9753
9754     case NT_ARM_HW_WATCH:
9755       if (note->namesz == 6
9756           && strcmp (note->namedata, "LINUX") == 0)
9757         return elfcore_grok_aarch_hw_watch (abfd, note);
9758       else
9759         return TRUE;
9760
9761     case NT_PRPSINFO:
9762     case NT_PSINFO:
9763       if (bed->elf_backend_grok_psinfo)
9764         if ((*bed->elf_backend_grok_psinfo) (abfd, note))
9765           return TRUE;
9766 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
9767       return elfcore_grok_psinfo (abfd, note);
9768 #else
9769       return TRUE;
9770 #endif
9771
9772     case NT_AUXV:
9773       {
9774         asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
9775                                                              SEC_HAS_CONTENTS);
9776
9777         if (sect == NULL)
9778           return FALSE;
9779         sect->size = note->descsz;
9780         sect->filepos = note->descpos;
9781         sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
9782
9783         return TRUE;
9784       }
9785
9786     case NT_FILE:
9787       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.file",
9788                                               note);
9789
9790     case NT_SIGINFO:
9791       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.siginfo",
9792                                               note);
9793
9794     }
9795 }
9796
9797 static bfd_boolean
9798 elfobj_grok_gnu_build_id (bfd *abfd, Elf_Internal_Note *note)
9799 {
9800   struct bfd_build_id* build_id;
9801
9802   if (note->descsz == 0)
9803     return FALSE;
9804
9805   build_id = bfd_alloc (abfd, sizeof (struct bfd_build_id) - 1 + note->descsz);
9806   if (build_id == NULL)
9807     return FALSE;
9808
9809   build_id->size = note->descsz;
9810   memcpy (build_id->data, note->descdata, note->descsz);
9811   abfd->build_id = build_id;
9812
9813   return TRUE;
9814 }
9815
9816 static bfd_boolean
9817 elfobj_grok_gnu_note (bfd *abfd, Elf_Internal_Note *note)
9818 {
9819   switch (note->type)
9820     {
9821     default:
9822       return TRUE;
9823
9824     case NT_GNU_PROPERTY_TYPE_0:
9825       return _bfd_elf_parse_gnu_properties (abfd, note);
9826
9827     case NT_GNU_BUILD_ID:
9828       return elfobj_grok_gnu_build_id (abfd, note);
9829     }
9830 }
9831
9832 static bfd_boolean
9833 elfobj_grok_stapsdt_note_1 (bfd *abfd, Elf_Internal_Note *note)
9834 {
9835   struct sdt_note *cur =
9836     (struct sdt_note *) bfd_alloc (abfd, sizeof (struct sdt_note)
9837                                    + note->descsz);
9838
9839   cur->next = (struct sdt_note *) (elf_tdata (abfd))->sdt_note_head;
9840   cur->size = (bfd_size_type) note->descsz;
9841   memcpy (cur->data, note->descdata, note->descsz);
9842
9843   elf_tdata (abfd)->sdt_note_head = cur;
9844
9845   return TRUE;
9846 }
9847
9848 static bfd_boolean
9849 elfobj_grok_stapsdt_note (bfd *abfd, Elf_Internal_Note *note)
9850 {
9851   switch (note->type)
9852     {
9853     case NT_STAPSDT:
9854       return elfobj_grok_stapsdt_note_1 (abfd, note);
9855
9856     default:
9857       return TRUE;
9858     }
9859 }
9860
9861 static bfd_boolean
9862 elfcore_grok_freebsd_psinfo (bfd *abfd, Elf_Internal_Note *note)
9863 {
9864   size_t offset;
9865
9866   switch (elf_elfheader (abfd)->e_ident[EI_CLASS])
9867     {
9868     case ELFCLASS32:
9869       if (note->descsz < 108)
9870         return FALSE;
9871       break;
9872
9873     case ELFCLASS64:
9874       if (note->descsz < 120)
9875         return FALSE;
9876       break;
9877
9878     default:
9879       return FALSE;
9880     }
9881
9882   /* Check for version 1 in pr_version.  */
9883   if (bfd_h_get_32 (abfd, (bfd_byte *) note->descdata) != 1)
9884     return FALSE;
9885
9886   offset = 4;
9887
9888   /* Skip over pr_psinfosz. */
9889   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS32)
9890     offset += 4;
9891   else
9892     {
9893       offset += 4;      /* Padding before pr_psinfosz. */
9894       offset += 8;
9895     }
9896
9897   /* pr_fname is PRFNAMESZ (16) + 1 bytes in size.  */
9898   elf_tdata (abfd)->core->program
9899     = _bfd_elfcore_strndup (abfd, note->descdata + offset, 17);
9900   offset += 17;
9901
9902   /* pr_psargs is PRARGSZ (80) + 1 bytes in size.  */
9903   elf_tdata (abfd)->core->command
9904     = _bfd_elfcore_strndup (abfd, note->descdata + offset, 81);
9905   offset += 81;
9906
9907   /* Padding before pr_pid.  */
9908   offset += 2;
9909
9910   /* The pr_pid field was added in version "1a".  */
9911   if (note->descsz < offset + 4)
9912     return TRUE;
9913
9914   elf_tdata (abfd)->core->pid
9915     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
9916
9917   return TRUE;
9918 }
9919
9920 static bfd_boolean
9921 elfcore_grok_freebsd_prstatus (bfd *abfd, Elf_Internal_Note *note)
9922 {
9923   size_t offset;
9924   size_t size;
9925   size_t min_size;
9926
9927   /* Compute offset of pr_getregsz, skipping over pr_statussz.
9928      Also compute minimum size of this note.  */
9929   switch (elf_elfheader (abfd)->e_ident[EI_CLASS])
9930     {
9931     case ELFCLASS32:
9932       offset = 4 + 4;
9933       min_size = offset + (4 * 2) + 4 + 4 + 4;
9934       break;
9935
9936     case ELFCLASS64:
9937       offset = 4 + 4 + 8;       /* Includes padding before pr_statussz.  */
9938       min_size = offset + (8 * 2) + 4 + 4 + 4 + 4;
9939       break;
9940
9941     default:
9942       return FALSE;
9943     }
9944
9945   if (note->descsz < min_size)
9946     return FALSE;
9947
9948   /* Check for version 1 in pr_version.  */
9949   if (bfd_h_get_32 (abfd, (bfd_byte *) note->descdata) != 1)
9950     return FALSE;
9951
9952   /* Extract size of pr_reg from pr_gregsetsz.  */
9953   /* Skip over pr_gregsetsz and pr_fpregsetsz.  */
9954   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS32)
9955     {
9956       size = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
9957       offset += 4 * 2;
9958     }
9959   else
9960     {
9961       size = bfd_h_get_64 (abfd, (bfd_byte *) note->descdata + offset);
9962       offset += 8 * 2;
9963     }
9964
9965   /* Skip over pr_osreldate.  */
9966   offset += 4;
9967
9968   /* Read signal from pr_cursig.  */
9969   if (elf_tdata (abfd)->core->signal == 0)
9970     elf_tdata (abfd)->core->signal
9971       = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
9972   offset += 4;
9973
9974   /* Read TID from pr_pid.  */
9975   elf_tdata (abfd)->core->lwpid
9976       = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + offset);
9977   offset += 4;
9978
9979   /* Padding before pr_reg.  */
9980   if (elf_elfheader (abfd)->e_ident[EI_CLASS] == ELFCLASS64)
9981     offset += 4;
9982
9983   /* Make sure that there is enough data remaining in the note.  */
9984   if ((note->descsz - offset) < size)
9985     return FALSE;
9986
9987   /* Make a ".reg/999" section and a ".reg" section.  */
9988   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
9989                                           size, note->descpos + offset);
9990 }
9991
9992 static bfd_boolean
9993 elfcore_grok_freebsd_note (bfd *abfd, Elf_Internal_Note *note)
9994 {
9995   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9996
9997   switch (note->type)
9998     {
9999     case NT_PRSTATUS:
10000       if (bed->elf_backend_grok_freebsd_prstatus)
10001         if ((*bed->elf_backend_grok_freebsd_prstatus) (abfd, note))
10002           return TRUE;
10003       return elfcore_grok_freebsd_prstatus (abfd, note);
10004
10005     case NT_FPREGSET:
10006       return elfcore_grok_prfpreg (abfd, note);
10007
10008     case NT_PRPSINFO:
10009       return elfcore_grok_freebsd_psinfo (abfd, note);
10010
10011     case NT_FREEBSD_THRMISC:
10012       if (note->namesz == 8)
10013         return elfcore_make_note_pseudosection (abfd, ".thrmisc", note);
10014       else
10015         return TRUE;
10016
10017     case NT_FREEBSD_PROCSTAT_AUXV:
10018       {
10019         asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
10020                                                              SEC_HAS_CONTENTS);
10021
10022         if (sect == NULL)
10023           return FALSE;
10024         sect->size = note->descsz - 4;
10025         sect->filepos = note->descpos + 4;
10026         sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
10027
10028         return TRUE;
10029       }
10030
10031     case NT_X86_XSTATE:
10032       if (note->namesz == 8)
10033         return elfcore_grok_xstatereg (abfd, note);
10034       else
10035         return TRUE;
10036
10037     case NT_FREEBSD_PTLWPINFO:
10038       return elfcore_make_note_pseudosection (abfd, ".note.freebsdcore.lwpinfo",
10039                                               note);
10040
10041     case NT_ARM_VFP:
10042       return elfcore_grok_arm_vfp (abfd, note);
10043
10044     default:
10045       return TRUE;
10046     }
10047 }
10048
10049 static bfd_boolean
10050 elfcore_netbsd_get_lwpid (Elf_Internal_Note *note, int *lwpidp)
10051 {
10052   char *cp;
10053
10054   cp = strchr (note->namedata, '@');
10055   if (cp != NULL)
10056     {
10057       *lwpidp = atoi(cp + 1);
10058       return TRUE;
10059     }
10060   return FALSE;
10061 }
10062
10063 static bfd_boolean
10064 elfcore_grok_netbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
10065 {
10066   if (note->descsz <= 0x7c + 31)
10067     return FALSE;
10068
10069   /* Signal number at offset 0x08. */
10070   elf_tdata (abfd)->core->signal
10071     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
10072
10073   /* Process ID at offset 0x50. */
10074   elf_tdata (abfd)->core->pid
10075     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
10076
10077   /* Command name at 0x7c (max 32 bytes, including nul). */
10078   elf_tdata (abfd)->core->command
10079     = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
10080
10081   return elfcore_make_note_pseudosection (abfd, ".note.netbsdcore.procinfo",
10082                                           note);
10083 }
10084
10085 static bfd_boolean
10086 elfcore_grok_netbsd_note (bfd *abfd, Elf_Internal_Note *note)
10087 {
10088   int lwp;
10089
10090   if (elfcore_netbsd_get_lwpid (note, &lwp))
10091     elf_tdata (abfd)->core->lwpid = lwp;
10092
10093   if (note->type == NT_NETBSDCORE_PROCINFO)
10094     {
10095       /* NetBSD-specific core "procinfo".  Note that we expect to
10096          find this note before any of the others, which is fine,
10097          since the kernel writes this note out first when it
10098          creates a core file.  */
10099
10100       return elfcore_grok_netbsd_procinfo (abfd, note);
10101     }
10102
10103   /* As of Jan 2002 there are no other machine-independent notes
10104      defined for NetBSD core files.  If the note type is less
10105      than the start of the machine-dependent note types, we don't
10106      understand it.  */
10107
10108   if (note->type < NT_NETBSDCORE_FIRSTMACH)
10109     return TRUE;
10110
10111
10112   switch (bfd_get_arch (abfd))
10113     {
10114       /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
10115          PT_GETFPREGS == mach+2.  */
10116
10117     case bfd_arch_alpha:
10118     case bfd_arch_sparc:
10119       switch (note->type)
10120         {
10121         case NT_NETBSDCORE_FIRSTMACH+0:
10122           return elfcore_make_note_pseudosection (abfd, ".reg", note);
10123
10124         case NT_NETBSDCORE_FIRSTMACH+2:
10125           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
10126
10127         default:
10128           return TRUE;
10129         }
10130
10131       /* On all other arch's, PT_GETREGS == mach+1 and
10132          PT_GETFPREGS == mach+3.  */
10133
10134     default:
10135       switch (note->type)
10136         {
10137         case NT_NETBSDCORE_FIRSTMACH+1:
10138           return elfcore_make_note_pseudosection (abfd, ".reg", note);
10139
10140         case NT_NETBSDCORE_FIRSTMACH+3:
10141           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
10142
10143         default:
10144           return TRUE;
10145         }
10146     }
10147     /* NOTREACHED */
10148 }
10149
10150 static bfd_boolean
10151 elfcore_grok_openbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
10152 {
10153   if (note->descsz <= 0x48 + 31)
10154     return FALSE;
10155
10156   /* Signal number at offset 0x08. */
10157   elf_tdata (abfd)->core->signal
10158     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
10159
10160   /* Process ID at offset 0x20. */
10161   elf_tdata (abfd)->core->pid
10162     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x20);
10163
10164   /* Command name at 0x48 (max 32 bytes, including nul). */
10165   elf_tdata (abfd)->core->command
10166     = _bfd_elfcore_strndup (abfd, note->descdata + 0x48, 31);
10167
10168   return TRUE;
10169 }
10170
10171 static bfd_boolean
10172 elfcore_grok_openbsd_note (bfd *abfd, Elf_Internal_Note *note)
10173 {
10174   if (note->type == NT_OPENBSD_PROCINFO)
10175     return elfcore_grok_openbsd_procinfo (abfd, note);
10176
10177   if (note->type == NT_OPENBSD_REGS)
10178     return elfcore_make_note_pseudosection (abfd, ".reg", note);
10179
10180   if (note->type == NT_OPENBSD_FPREGS)
10181     return elfcore_make_note_pseudosection (abfd, ".reg2", note);
10182
10183   if (note->type == NT_OPENBSD_XFPREGS)
10184     return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
10185
10186   if (note->type == NT_OPENBSD_AUXV)
10187     {
10188       asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
10189                                                            SEC_HAS_CONTENTS);
10190
10191       if (sect == NULL)
10192         return FALSE;
10193       sect->size = note->descsz;
10194       sect->filepos = note->descpos;
10195       sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
10196
10197       return TRUE;
10198     }
10199
10200   if (note->type == NT_OPENBSD_WCOOKIE)
10201     {
10202       asection *sect = bfd_make_section_anyway_with_flags (abfd, ".wcookie",
10203                                                            SEC_HAS_CONTENTS);
10204
10205       if (sect == NULL)
10206         return FALSE;
10207       sect->size = note->descsz;
10208       sect->filepos = note->descpos;
10209       sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
10210
10211       return TRUE;
10212     }
10213
10214   return TRUE;
10215 }
10216
10217 static bfd_boolean
10218 elfcore_grok_nto_status (bfd *abfd, Elf_Internal_Note *note, long *tid)
10219 {
10220   void *ddata = note->descdata;
10221   char buf[100];
10222   char *name;
10223   asection *sect;
10224   short sig;
10225   unsigned flags;
10226
10227   if (note->descsz < 16)
10228     return FALSE;
10229
10230   /* nto_procfs_status 'pid' field is at offset 0.  */
10231   elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, (bfd_byte *) ddata);
10232
10233   /* nto_procfs_status 'tid' field is at offset 4.  Pass it back.  */
10234   *tid = bfd_get_32 (abfd, (bfd_byte *) ddata + 4);
10235
10236   /* nto_procfs_status 'flags' field is at offset 8.  */
10237   flags = bfd_get_32 (abfd, (bfd_byte *) ddata + 8);
10238
10239   /* nto_procfs_status 'what' field is at offset 14.  */
10240   if ((sig = bfd_get_16 (abfd, (bfd_byte *) ddata + 14)) > 0)
10241     {
10242       elf_tdata (abfd)->core->signal = sig;
10243       elf_tdata (abfd)->core->lwpid = *tid;
10244     }
10245
10246   /* _DEBUG_FLAG_CURTID (current thread) is 0x80.  Some cores
10247      do not come from signals so we make sure we set the current
10248      thread just in case.  */
10249   if (flags & 0x00000080)
10250     elf_tdata (abfd)->core->lwpid = *tid;
10251
10252   /* Make a ".qnx_core_status/%d" section.  */
10253   sprintf (buf, ".qnx_core_status/%ld", *tid);
10254
10255   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
10256   if (name == NULL)
10257     return FALSE;
10258   strcpy (name, buf);
10259
10260   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
10261   if (sect == NULL)
10262     return FALSE;
10263
10264   sect->size            = note->descsz;
10265   sect->filepos         = note->descpos;
10266   sect->alignment_power = 2;
10267
10268   return (elfcore_maybe_make_sect (abfd, ".qnx_core_status", sect));
10269 }
10270
10271 static bfd_boolean
10272 elfcore_grok_nto_regs (bfd *abfd,
10273                        Elf_Internal_Note *note,
10274                        long tid,
10275                        char *base)
10276 {
10277   char buf[100];
10278   char *name;
10279   asection *sect;
10280
10281   /* Make a "(base)/%d" section.  */
10282   sprintf (buf, "%s/%ld", base, tid);
10283
10284   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
10285   if (name == NULL)
10286     return FALSE;
10287   strcpy (name, buf);
10288
10289   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
10290   if (sect == NULL)
10291     return FALSE;
10292
10293   sect->size            = note->descsz;
10294   sect->filepos         = note->descpos;
10295   sect->alignment_power = 2;
10296
10297   /* This is the current thread.  */
10298   if (elf_tdata (abfd)->core->lwpid == tid)
10299     return elfcore_maybe_make_sect (abfd, base, sect);
10300
10301   return TRUE;
10302 }
10303
10304 #define BFD_QNT_CORE_INFO       7
10305 #define BFD_QNT_CORE_STATUS     8
10306 #define BFD_QNT_CORE_GREG       9
10307 #define BFD_QNT_CORE_FPREG      10
10308
10309 static bfd_boolean
10310 elfcore_grok_nto_note (bfd *abfd, Elf_Internal_Note *note)
10311 {
10312   /* Every GREG section has a STATUS section before it.  Store the
10313      tid from the previous call to pass down to the next gregs
10314      function.  */
10315   static long tid = 1;
10316
10317   switch (note->type)
10318     {
10319     case BFD_QNT_CORE_INFO:
10320       return elfcore_make_note_pseudosection (abfd, ".qnx_core_info", note);
10321     case BFD_QNT_CORE_STATUS:
10322       return elfcore_grok_nto_status (abfd, note, &tid);
10323     case BFD_QNT_CORE_GREG:
10324       return elfcore_grok_nto_regs (abfd, note, tid, ".reg");
10325     case BFD_QNT_CORE_FPREG:
10326       return elfcore_grok_nto_regs (abfd, note, tid, ".reg2");
10327     default:
10328       return TRUE;
10329     }
10330 }
10331
10332 static bfd_boolean
10333 elfcore_grok_spu_note (bfd *abfd, Elf_Internal_Note *note)
10334 {
10335   char *name;
10336   asection *sect;
10337   size_t len;
10338
10339   /* Use note name as section name.  */
10340   len = note->namesz;
10341   name = (char *) bfd_alloc (abfd, len);
10342   if (name == NULL)
10343     return FALSE;
10344   memcpy (name, note->namedata, len);
10345   name[len - 1] = '\0';
10346
10347   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
10348   if (sect == NULL)
10349     return FALSE;
10350
10351   sect->size            = note->descsz;
10352   sect->filepos         = note->descpos;
10353   sect->alignment_power = 1;
10354
10355   return TRUE;
10356 }
10357
10358 /* Function: elfcore_write_note
10359
10360    Inputs:
10361      buffer to hold note, and current size of buffer
10362      name of note
10363      type of note
10364      data for note
10365      size of data for note
10366
10367    Writes note to end of buffer.  ELF64 notes are written exactly as
10368    for ELF32, despite the current (as of 2006) ELF gabi specifying
10369    that they ought to have 8-byte namesz and descsz field, and have
10370    8-byte alignment.  Other writers, eg. Linux kernel, do the same.
10371
10372    Return:
10373    Pointer to realloc'd buffer, *BUFSIZ updated.  */
10374
10375 char *
10376 elfcore_write_note (bfd *abfd,
10377                     char *buf,
10378                     int *bufsiz,
10379                     const char *name,
10380                     int type,
10381                     const void *input,
10382                     int size)
10383 {
10384   Elf_External_Note *xnp;
10385   size_t namesz;
10386   size_t newspace;
10387   char *dest;
10388
10389   namesz = 0;
10390   if (name != NULL)
10391     namesz = strlen (name) + 1;
10392
10393   newspace = 12 + ((namesz + 3) & -4) + ((size + 3) & -4);
10394
10395   buf = (char *) realloc (buf, *bufsiz + newspace);
10396   if (buf == NULL)
10397     return buf;
10398   dest = buf + *bufsiz;
10399   *bufsiz += newspace;
10400   xnp = (Elf_External_Note *) dest;
10401   H_PUT_32 (abfd, namesz, xnp->namesz);
10402   H_PUT_32 (abfd, size, xnp->descsz);
10403   H_PUT_32 (abfd, type, xnp->type);
10404   dest = xnp->name;
10405   if (name != NULL)
10406     {
10407       memcpy (dest, name, namesz);
10408       dest += namesz;
10409       while (namesz & 3)
10410         {
10411           *dest++ = '\0';
10412           ++namesz;
10413         }
10414     }
10415   memcpy (dest, input, size);
10416   dest += size;
10417   while (size & 3)
10418     {
10419       *dest++ = '\0';
10420       ++size;
10421     }
10422   return buf;
10423 }
10424
10425 char *
10426 elfcore_write_prpsinfo (bfd  *abfd,
10427                         char *buf,
10428                         int  *bufsiz,
10429                         const char *fname,
10430                         const char *psargs)
10431 {
10432   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10433
10434   if (bed->elf_backend_write_core_note != NULL)
10435     {
10436       char *ret;
10437       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
10438                                                  NT_PRPSINFO, fname, psargs);
10439       if (ret != NULL)
10440         return ret;
10441     }
10442
10443 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
10444 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
10445   if (bed->s->elfclass == ELFCLASS32)
10446     {
10447 #if defined (HAVE_PSINFO32_T)
10448       psinfo32_t data;
10449       int note_type = NT_PSINFO;
10450 #else
10451       prpsinfo32_t data;
10452       int note_type = NT_PRPSINFO;
10453 #endif
10454
10455       memset (&data, 0, sizeof (data));
10456       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
10457       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
10458       return elfcore_write_note (abfd, buf, bufsiz,
10459                                  "CORE", note_type, &data, sizeof (data));
10460     }
10461   else
10462 #endif
10463     {
10464 #if defined (HAVE_PSINFO_T)
10465       psinfo_t data;
10466       int note_type = NT_PSINFO;
10467 #else
10468       prpsinfo_t data;
10469       int note_type = NT_PRPSINFO;
10470 #endif
10471
10472       memset (&data, 0, sizeof (data));
10473       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
10474       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
10475       return elfcore_write_note (abfd, buf, bufsiz,
10476                                  "CORE", note_type, &data, sizeof (data));
10477     }
10478 #endif  /* PSINFO_T or PRPSINFO_T */
10479
10480   free (buf);
10481   return NULL;
10482 }
10483
10484 char *
10485 elfcore_write_linux_prpsinfo32
10486   (bfd *abfd, char *buf, int *bufsiz,
10487    const struct elf_internal_linux_prpsinfo *prpsinfo)
10488 {
10489   if (get_elf_backend_data (abfd)->linux_prpsinfo32_ugid16)
10490     {
10491       struct elf_external_linux_prpsinfo32_ugid16 data;
10492
10493       swap_linux_prpsinfo32_ugid16_out (abfd, prpsinfo, &data);
10494       return elfcore_write_note (abfd, buf, bufsiz, "CORE", NT_PRPSINFO,
10495                                  &data, sizeof (data));
10496     }
10497   else
10498     {
10499       struct elf_external_linux_prpsinfo32_ugid32 data;
10500
10501       swap_linux_prpsinfo32_ugid32_out (abfd, prpsinfo, &data);
10502       return elfcore_write_note (abfd, buf, bufsiz, "CORE", NT_PRPSINFO,
10503                                  &data, sizeof (data));
10504     }
10505 }
10506
10507 char *
10508 elfcore_write_linux_prpsinfo64
10509   (bfd *abfd, char *buf, int *bufsiz,
10510    const struct elf_internal_linux_prpsinfo *prpsinfo)
10511 {
10512   if (get_elf_backend_data (abfd)->linux_prpsinfo64_ugid16)
10513     {
10514       struct elf_external_linux_prpsinfo64_ugid16 data;
10515
10516       swap_linux_prpsinfo64_ugid16_out (abfd, prpsinfo, &data);
10517       return elfcore_write_note (abfd, buf, bufsiz,
10518                                  "CORE", NT_PRPSINFO, &data, sizeof (data));
10519     }
10520   else
10521     {
10522       struct elf_external_linux_prpsinfo64_ugid32 data;
10523
10524       swap_linux_prpsinfo64_ugid32_out (abfd, prpsinfo, &data);
10525       return elfcore_write_note (abfd, buf, bufsiz,
10526                                  "CORE", NT_PRPSINFO, &data, sizeof (data));
10527     }
10528 }
10529
10530 char *
10531 elfcore_write_prstatus (bfd *abfd,
10532                         char *buf,
10533                         int *bufsiz,
10534                         long pid,
10535                         int cursig,
10536                         const void *gregs)
10537 {
10538   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10539
10540   if (bed->elf_backend_write_core_note != NULL)
10541     {
10542       char *ret;
10543       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
10544                                                  NT_PRSTATUS,
10545                                                  pid, cursig, gregs);
10546       if (ret != NULL)
10547         return ret;
10548     }
10549
10550 #if defined (HAVE_PRSTATUS_T)
10551 #if defined (HAVE_PRSTATUS32_T)
10552   if (bed->s->elfclass == ELFCLASS32)
10553     {
10554       prstatus32_t prstat;
10555
10556       memset (&prstat, 0, sizeof (prstat));
10557       prstat.pr_pid = pid;
10558       prstat.pr_cursig = cursig;
10559       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
10560       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
10561                                  NT_PRSTATUS, &prstat, sizeof (prstat));
10562     }
10563   else
10564 #endif
10565     {
10566       prstatus_t prstat;
10567
10568       memset (&prstat, 0, sizeof (prstat));
10569       prstat.pr_pid = pid;
10570       prstat.pr_cursig = cursig;
10571       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
10572       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
10573                                  NT_PRSTATUS, &prstat, sizeof (prstat));
10574     }
10575 #endif /* HAVE_PRSTATUS_T */
10576
10577   free (buf);
10578   return NULL;
10579 }
10580
10581 #if defined (HAVE_LWPSTATUS_T)
10582 char *
10583 elfcore_write_lwpstatus (bfd *abfd,
10584                          char *buf,
10585                          int *bufsiz,
10586                          long pid,
10587                          int cursig,
10588                          const void *gregs)
10589 {
10590   lwpstatus_t lwpstat;
10591   const char *note_name = "CORE";
10592
10593   memset (&lwpstat, 0, sizeof (lwpstat));
10594   lwpstat.pr_lwpid  = pid >> 16;
10595   lwpstat.pr_cursig = cursig;
10596 #if defined (HAVE_LWPSTATUS_T_PR_REG)
10597   memcpy (&lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
10598 #elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
10599 #if !defined(gregs)
10600   memcpy (lwpstat.pr_context.uc_mcontext.gregs,
10601           gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
10602 #else
10603   memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
10604           gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
10605 #endif
10606 #endif
10607   return elfcore_write_note (abfd, buf, bufsiz, note_name,
10608                              NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
10609 }
10610 #endif /* HAVE_LWPSTATUS_T */
10611
10612 #if defined (HAVE_PSTATUS_T)
10613 char *
10614 elfcore_write_pstatus (bfd *abfd,
10615                        char *buf,
10616                        int *bufsiz,
10617                        long pid,
10618                        int cursig ATTRIBUTE_UNUSED,
10619                        const void *gregs ATTRIBUTE_UNUSED)
10620 {
10621   const char *note_name = "CORE";
10622 #if defined (HAVE_PSTATUS32_T)
10623   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10624
10625   if (bed->s->elfclass == ELFCLASS32)
10626     {
10627       pstatus32_t pstat;
10628
10629       memset (&pstat, 0, sizeof (pstat));
10630       pstat.pr_pid = pid & 0xffff;
10631       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
10632                                 NT_PSTATUS, &pstat, sizeof (pstat));
10633       return buf;
10634     }
10635   else
10636 #endif
10637     {
10638       pstatus_t pstat;
10639
10640       memset (&pstat, 0, sizeof (pstat));
10641       pstat.pr_pid = pid & 0xffff;
10642       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
10643                                 NT_PSTATUS, &pstat, sizeof (pstat));
10644       return buf;
10645     }
10646 }
10647 #endif /* HAVE_PSTATUS_T */
10648
10649 char *
10650 elfcore_write_prfpreg (bfd *abfd,
10651                        char *buf,
10652                        int *bufsiz,
10653                        const void *fpregs,
10654                        int size)
10655 {
10656   const char *note_name = "CORE";
10657   return elfcore_write_note (abfd, buf, bufsiz,
10658                              note_name, NT_FPREGSET, fpregs, size);
10659 }
10660
10661 char *
10662 elfcore_write_prxfpreg (bfd *abfd,
10663                         char *buf,
10664                         int *bufsiz,
10665                         const void *xfpregs,
10666                         int size)
10667 {
10668   char *note_name = "LINUX";
10669   return elfcore_write_note (abfd, buf, bufsiz,
10670                              note_name, NT_PRXFPREG, xfpregs, size);
10671 }
10672
10673 char *
10674 elfcore_write_xstatereg (bfd *abfd, char *buf, int *bufsiz,
10675                          const void *xfpregs, int size)
10676 {
10677   char *note_name;
10678   if (get_elf_backend_data (abfd)->elf_osabi == ELFOSABI_FREEBSD)
10679     note_name = "FreeBSD";
10680   else
10681     note_name = "LINUX";
10682   return elfcore_write_note (abfd, buf, bufsiz,
10683                              note_name, NT_X86_XSTATE, xfpregs, size);
10684 }
10685
10686 char *
10687 elfcore_write_ppc_vmx (bfd *abfd,
10688                        char *buf,
10689                        int *bufsiz,
10690                        const void *ppc_vmx,
10691                        int size)
10692 {
10693   char *note_name = "LINUX";
10694   return elfcore_write_note (abfd, buf, bufsiz,
10695                              note_name, NT_PPC_VMX, ppc_vmx, size);
10696 }
10697
10698 char *
10699 elfcore_write_ppc_vsx (bfd *abfd,
10700                        char *buf,
10701                        int *bufsiz,
10702                        const void *ppc_vsx,
10703                        int size)
10704 {
10705   char *note_name = "LINUX";
10706   return elfcore_write_note (abfd, buf, bufsiz,
10707                              note_name, NT_PPC_VSX, ppc_vsx, size);
10708 }
10709
10710 static char *
10711 elfcore_write_s390_high_gprs (bfd *abfd,
10712                               char *buf,
10713                               int *bufsiz,
10714                               const void *s390_high_gprs,
10715                               int size)
10716 {
10717   char *note_name = "LINUX";
10718   return elfcore_write_note (abfd, buf, bufsiz,
10719                              note_name, NT_S390_HIGH_GPRS,
10720                              s390_high_gprs, size);
10721 }
10722
10723 char *
10724 elfcore_write_s390_timer (bfd *abfd,
10725                           char *buf,
10726                           int *bufsiz,
10727                           const void *s390_timer,
10728                           int size)
10729 {
10730   char *note_name = "LINUX";
10731   return elfcore_write_note (abfd, buf, bufsiz,
10732                              note_name, NT_S390_TIMER, s390_timer, size);
10733 }
10734
10735 char *
10736 elfcore_write_s390_todcmp (bfd *abfd,
10737                            char *buf,
10738                            int *bufsiz,
10739                            const void *s390_todcmp,
10740                            int size)
10741 {
10742   char *note_name = "LINUX";
10743   return elfcore_write_note (abfd, buf, bufsiz,
10744                              note_name, NT_S390_TODCMP, s390_todcmp, size);
10745 }
10746
10747 char *
10748 elfcore_write_s390_todpreg (bfd *abfd,
10749                             char *buf,
10750                             int *bufsiz,
10751                             const void *s390_todpreg,
10752                             int size)
10753 {
10754   char *note_name = "LINUX";
10755   return elfcore_write_note (abfd, buf, bufsiz,
10756                              note_name, NT_S390_TODPREG, s390_todpreg, size);
10757 }
10758
10759 char *
10760 elfcore_write_s390_ctrs (bfd *abfd,
10761                          char *buf,
10762                          int *bufsiz,
10763                          const void *s390_ctrs,
10764                          int size)
10765 {
10766   char *note_name = "LINUX";
10767   return elfcore_write_note (abfd, buf, bufsiz,
10768                              note_name, NT_S390_CTRS, s390_ctrs, size);
10769 }
10770
10771 char *
10772 elfcore_write_s390_prefix (bfd *abfd,
10773                            char *buf,
10774                            int *bufsiz,
10775                            const void *s390_prefix,
10776                            int size)
10777 {
10778   char *note_name = "LINUX";
10779   return elfcore_write_note (abfd, buf, bufsiz,
10780                              note_name, NT_S390_PREFIX, s390_prefix, size);
10781 }
10782
10783 char *
10784 elfcore_write_s390_last_break (bfd *abfd,
10785                                char *buf,
10786                                int *bufsiz,
10787                                const void *s390_last_break,
10788                                int size)
10789 {
10790   char *note_name = "LINUX";
10791   return elfcore_write_note (abfd, buf, bufsiz,
10792                              note_name, NT_S390_LAST_BREAK,
10793                              s390_last_break, size);
10794 }
10795
10796 char *
10797 elfcore_write_s390_system_call (bfd *abfd,
10798                                 char *buf,
10799                                 int *bufsiz,
10800                                 const void *s390_system_call,
10801                                 int size)
10802 {
10803   char *note_name = "LINUX";
10804   return elfcore_write_note (abfd, buf, bufsiz,
10805                              note_name, NT_S390_SYSTEM_CALL,
10806                              s390_system_call, size);
10807 }
10808
10809 char *
10810 elfcore_write_s390_tdb (bfd *abfd,
10811                         char *buf,
10812                         int *bufsiz,
10813                         const void *s390_tdb,
10814                         int size)
10815 {
10816   char *note_name = "LINUX";
10817   return elfcore_write_note (abfd, buf, bufsiz,
10818                              note_name, NT_S390_TDB, s390_tdb, size);
10819 }
10820
10821 char *
10822 elfcore_write_s390_vxrs_low (bfd *abfd,
10823                              char *buf,
10824                              int *bufsiz,
10825                              const void *s390_vxrs_low,
10826                              int size)
10827 {
10828   char *note_name = "LINUX";
10829   return elfcore_write_note (abfd, buf, bufsiz,
10830                              note_name, NT_S390_VXRS_LOW, s390_vxrs_low, size);
10831 }
10832
10833 char *
10834 elfcore_write_s390_vxrs_high (bfd *abfd,
10835                              char *buf,
10836                              int *bufsiz,
10837                              const void *s390_vxrs_high,
10838                              int size)
10839 {
10840   char *note_name = "LINUX";
10841   return elfcore_write_note (abfd, buf, bufsiz,
10842                              note_name, NT_S390_VXRS_HIGH,
10843                              s390_vxrs_high, size);
10844 }
10845
10846 char *
10847 elfcore_write_s390_gs_cb (bfd *abfd,
10848                           char *buf,
10849                           int *bufsiz,
10850                           const void *s390_gs_cb,
10851                           int size)
10852 {
10853   char *note_name = "LINUX";
10854   return elfcore_write_note (abfd, buf, bufsiz,
10855                              note_name, NT_S390_GS_CB,
10856                              s390_gs_cb, size);
10857 }
10858
10859 char *
10860 elfcore_write_s390_gs_bc (bfd *abfd,
10861                           char *buf,
10862                           int *bufsiz,
10863                           const void *s390_gs_bc,
10864                           int size)
10865 {
10866   char *note_name = "LINUX";
10867   return elfcore_write_note (abfd, buf, bufsiz,
10868                              note_name, NT_S390_GS_BC,
10869                              s390_gs_bc, size);
10870 }
10871
10872 char *
10873 elfcore_write_arm_vfp (bfd *abfd,
10874                        char *buf,
10875                        int *bufsiz,
10876                        const void *arm_vfp,
10877                        int size)
10878 {
10879   char *note_name = "LINUX";
10880   return elfcore_write_note (abfd, buf, bufsiz,
10881                              note_name, NT_ARM_VFP, arm_vfp, size);
10882 }
10883
10884 char *
10885 elfcore_write_aarch_tls (bfd *abfd,
10886                        char *buf,
10887                        int *bufsiz,
10888                        const void *aarch_tls,
10889                        int size)
10890 {
10891   char *note_name = "LINUX";
10892   return elfcore_write_note (abfd, buf, bufsiz,
10893                              note_name, NT_ARM_TLS, aarch_tls, size);
10894 }
10895
10896 char *
10897 elfcore_write_aarch_hw_break (bfd *abfd,
10898                             char *buf,
10899                             int *bufsiz,
10900                             const void *aarch_hw_break,
10901                             int size)
10902 {
10903   char *note_name = "LINUX";
10904   return elfcore_write_note (abfd, buf, bufsiz,
10905                              note_name, NT_ARM_HW_BREAK, aarch_hw_break, size);
10906 }
10907
10908 char *
10909 elfcore_write_aarch_hw_watch (bfd *abfd,
10910                             char *buf,
10911                             int *bufsiz,
10912                             const void *aarch_hw_watch,
10913                             int size)
10914 {
10915   char *note_name = "LINUX";
10916   return elfcore_write_note (abfd, buf, bufsiz,
10917                              note_name, NT_ARM_HW_WATCH, aarch_hw_watch, size);
10918 }
10919
10920 char *
10921 elfcore_write_register_note (bfd *abfd,
10922                              char *buf,
10923                              int *bufsiz,
10924                              const char *section,
10925                              const void *data,
10926                              int size)
10927 {
10928   if (strcmp (section, ".reg2") == 0)
10929     return elfcore_write_prfpreg (abfd, buf, bufsiz, data, size);
10930   if (strcmp (section, ".reg-xfp") == 0)
10931     return elfcore_write_prxfpreg (abfd, buf, bufsiz, data, size);
10932   if (strcmp (section, ".reg-xstate") == 0)
10933     return elfcore_write_xstatereg (abfd, buf, bufsiz, data, size);
10934   if (strcmp (section, ".reg-ppc-vmx") == 0)
10935     return elfcore_write_ppc_vmx (abfd, buf, bufsiz, data, size);
10936   if (strcmp (section, ".reg-ppc-vsx") == 0)
10937     return elfcore_write_ppc_vsx (abfd, buf, bufsiz, data, size);
10938   if (strcmp (section, ".reg-s390-high-gprs") == 0)
10939     return elfcore_write_s390_high_gprs (abfd, buf, bufsiz, data, size);
10940   if (strcmp (section, ".reg-s390-timer") == 0)
10941     return elfcore_write_s390_timer (abfd, buf, bufsiz, data, size);
10942   if (strcmp (section, ".reg-s390-todcmp") == 0)
10943     return elfcore_write_s390_todcmp (abfd, buf, bufsiz, data, size);
10944   if (strcmp (section, ".reg-s390-todpreg") == 0)
10945     return elfcore_write_s390_todpreg (abfd, buf, bufsiz, data, size);
10946   if (strcmp (section, ".reg-s390-ctrs") == 0)
10947     return elfcore_write_s390_ctrs (abfd, buf, bufsiz, data, size);
10948   if (strcmp (section, ".reg-s390-prefix") == 0)
10949     return elfcore_write_s390_prefix (abfd, buf, bufsiz, data, size);
10950   if (strcmp (section, ".reg-s390-last-break") == 0)
10951     return elfcore_write_s390_last_break (abfd, buf, bufsiz, data, size);
10952   if (strcmp (section, ".reg-s390-system-call") == 0)
10953     return elfcore_write_s390_system_call (abfd, buf, bufsiz, data, size);
10954   if (strcmp (section, ".reg-s390-tdb") == 0)
10955     return elfcore_write_s390_tdb (abfd, buf, bufsiz, data, size);
10956   if (strcmp (section, ".reg-s390-vxrs-low") == 0)
10957     return elfcore_write_s390_vxrs_low (abfd, buf, bufsiz, data, size);
10958   if (strcmp (section, ".reg-s390-vxrs-high") == 0)
10959     return elfcore_write_s390_vxrs_high (abfd, buf, bufsiz, data, size);
10960   if (strcmp (section, ".reg-s390-gs-cb") == 0)
10961     return elfcore_write_s390_gs_cb (abfd, buf, bufsiz, data, size);
10962   if (strcmp (section, ".reg-s390-gs-bc") == 0)
10963     return elfcore_write_s390_gs_bc (abfd, buf, bufsiz, data, size);
10964   if (strcmp (section, ".reg-arm-vfp") == 0)
10965     return elfcore_write_arm_vfp (abfd, buf, bufsiz, data, size);
10966   if (strcmp (section, ".reg-aarch-tls") == 0)
10967     return elfcore_write_aarch_tls (abfd, buf, bufsiz, data, size);
10968   if (strcmp (section, ".reg-aarch-hw-break") == 0)
10969     return elfcore_write_aarch_hw_break (abfd, buf, bufsiz, data, size);
10970   if (strcmp (section, ".reg-aarch-hw-watch") == 0)
10971     return elfcore_write_aarch_hw_watch (abfd, buf, bufsiz, data, size);
10972   return NULL;
10973 }
10974
10975 static bfd_boolean
10976 elf_parse_notes (bfd *abfd, char *buf, size_t size, file_ptr offset,
10977                  size_t align)
10978 {
10979   char *p;
10980
10981   /* NB: CORE PT_NOTE segments may have p_align values of 0 or 1.
10982      gABI specifies that PT_NOTE alignment should be aligned to 4
10983      bytes for 32-bit objects and to 8 bytes for 64-bit objects.  If
10984      align is less than 4, we use 4 byte alignment.   */
10985   if (align < 4)
10986     align = 4;
10987
10988   p = buf;
10989   while (p < buf + size)
10990     {
10991       Elf_External_Note *xnp = (Elf_External_Note *) p;
10992       Elf_Internal_Note in;
10993
10994       if (offsetof (Elf_External_Note, name) > buf - p + size)
10995         return FALSE;
10996
10997       in.type = H_GET_32 (abfd, xnp->type);
10998
10999       in.namesz = H_GET_32 (abfd, xnp->namesz);
11000       in.namedata = xnp->name;
11001       if (in.namesz > buf - in.namedata + size)
11002         return FALSE;
11003
11004       in.descsz = H_GET_32 (abfd, xnp->descsz);
11005       in.descdata = p + ELF_NOTE_DESC_OFFSET (in.namesz, align);
11006       in.descpos = offset + (in.descdata - buf);
11007       if (in.descsz != 0
11008           && (in.descdata >= buf + size
11009               || in.descsz > buf - in.descdata + size))
11010         return FALSE;
11011
11012       switch (bfd_get_format (abfd))
11013         {
11014         default:
11015           return TRUE;
11016
11017         case bfd_core:
11018           {
11019 #define GROKER_ELEMENT(S,F) {S, sizeof (S) - 1, F}
11020             struct
11021             {
11022               const char * string;
11023               size_t len;
11024               bfd_boolean (* func)(bfd *, Elf_Internal_Note *);
11025             }
11026             grokers[] =
11027             {
11028               GROKER_ELEMENT ("", elfcore_grok_note),
11029               GROKER_ELEMENT ("FreeBSD", elfcore_grok_freebsd_note),
11030               GROKER_ELEMENT ("NetBSD-CORE", elfcore_grok_netbsd_note),
11031               GROKER_ELEMENT ( "OpenBSD", elfcore_grok_openbsd_note),
11032               GROKER_ELEMENT ("QNX", elfcore_grok_nto_note),
11033               GROKER_ELEMENT ("SPU/", elfcore_grok_spu_note)
11034             };
11035 #undef GROKER_ELEMENT
11036             int i;
11037
11038             for (i = ARRAY_SIZE (grokers); i--;)
11039               {
11040                 if (in.namesz >= grokers[i].len
11041                     && strncmp (in.namedata, grokers[i].string,
11042                                 grokers[i].len) == 0)
11043                   {
11044                     if (! grokers[i].func (abfd, & in))
11045                       return FALSE;
11046                     break;
11047                   }
11048               }
11049             break;
11050           }
11051
11052         case bfd_object:
11053           if (in.namesz == sizeof "GNU" && strcmp (in.namedata, "GNU") == 0)
11054             {
11055               if (! elfobj_grok_gnu_note (abfd, &in))
11056                 return FALSE;
11057             }
11058           else if (in.namesz == sizeof "stapsdt"
11059                    && strcmp (in.namedata, "stapsdt") == 0)
11060             {
11061               if (! elfobj_grok_stapsdt_note (abfd, &in))
11062                 return FALSE;
11063             }
11064           break;
11065         }
11066
11067       p += ELF_NOTE_NEXT_OFFSET (in.namesz, in.descsz, align);
11068     }
11069
11070   return TRUE;
11071 }
11072
11073 static bfd_boolean
11074 elf_read_notes (bfd *abfd, file_ptr offset, bfd_size_type size,
11075                 size_t align)
11076 {
11077   char *buf;
11078
11079   if (size == 0 || (size + 1) == 0)
11080     return TRUE;
11081
11082   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
11083     return FALSE;
11084
11085   buf = (char *) bfd_malloc (size + 1);
11086   if (buf == NULL)
11087     return FALSE;
11088
11089   /* PR 17512: file: ec08f814
11090      0-termintate the buffer so that string searches will not overflow.  */
11091   buf[size] = 0;
11092
11093   if (bfd_bread (buf, size, abfd) != size
11094       || !elf_parse_notes (abfd, buf, size, offset, align))
11095     {
11096       free (buf);
11097       return FALSE;
11098     }
11099
11100   free (buf);
11101   return TRUE;
11102 }
11103 \f
11104 /* Providing external access to the ELF program header table.  */
11105
11106 /* Return an upper bound on the number of bytes required to store a
11107    copy of ABFD's program header table entries.  Return -1 if an error
11108    occurs; bfd_get_error will return an appropriate code.  */
11109
11110 long
11111 bfd_get_elf_phdr_upper_bound (bfd *abfd)
11112 {
11113   if (abfd->xvec->flavour != bfd_target_elf_flavour)
11114     {
11115       bfd_set_error (bfd_error_wrong_format);
11116       return -1;
11117     }
11118
11119   return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
11120 }
11121
11122 /* Copy ABFD's program header table entries to *PHDRS.  The entries
11123    will be stored as an array of Elf_Internal_Phdr structures, as
11124    defined in include/elf/internal.h.  To find out how large the
11125    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
11126
11127    Return the number of program header table entries read, or -1 if an
11128    error occurs; bfd_get_error will return an appropriate code.  */
11129
11130 int
11131 bfd_get_elf_phdrs (bfd *abfd, void *phdrs)
11132 {
11133   int num_phdrs;
11134
11135   if (abfd->xvec->flavour != bfd_target_elf_flavour)
11136     {
11137       bfd_set_error (bfd_error_wrong_format);
11138       return -1;
11139     }
11140
11141   num_phdrs = elf_elfheader (abfd)->e_phnum;
11142   memcpy (phdrs, elf_tdata (abfd)->phdr,
11143           num_phdrs * sizeof (Elf_Internal_Phdr));
11144
11145   return num_phdrs;
11146 }
11147
11148 enum elf_reloc_type_class
11149 _bfd_elf_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
11150                            const asection *rel_sec ATTRIBUTE_UNUSED,
11151                            const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED)
11152 {
11153   return reloc_class_normal;
11154 }
11155
11156 /* For RELA architectures, return the relocation value for a
11157    relocation against a local symbol.  */
11158
11159 bfd_vma
11160 _bfd_elf_rela_local_sym (bfd *abfd,
11161                          Elf_Internal_Sym *sym,
11162                          asection **psec,
11163                          Elf_Internal_Rela *rel)
11164 {
11165   asection *sec = *psec;
11166   bfd_vma relocation;
11167
11168   relocation = (sec->output_section->vma
11169                 + sec->output_offset
11170                 + sym->st_value);
11171   if ((sec->flags & SEC_MERGE)
11172       && ELF_ST_TYPE (sym->st_info) == STT_SECTION
11173       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
11174     {
11175       rel->r_addend =
11176         _bfd_merged_section_offset (abfd, psec,
11177                                     elf_section_data (sec)->sec_info,
11178                                     sym->st_value + rel->r_addend);
11179       if (sec != *psec)
11180         {
11181           /* If we have changed the section, and our original section is
11182              marked with SEC_EXCLUDE, it means that the original
11183              SEC_MERGE section has been completely subsumed in some
11184              other SEC_MERGE section.  In this case, we need to leave
11185              some info around for --emit-relocs.  */
11186           if ((sec->flags & SEC_EXCLUDE) != 0)
11187             sec->kept_section = *psec;
11188           sec = *psec;
11189         }
11190       rel->r_addend -= relocation;
11191       rel->r_addend += sec->output_section->vma + sec->output_offset;
11192     }
11193   return relocation;
11194 }
11195
11196 bfd_vma
11197 _bfd_elf_rel_local_sym (bfd *abfd,
11198                         Elf_Internal_Sym *sym,
11199                         asection **psec,
11200                         bfd_vma addend)
11201 {
11202   asection *sec = *psec;
11203
11204   if (sec->sec_info_type != SEC_INFO_TYPE_MERGE)
11205     return sym->st_value + addend;
11206
11207   return _bfd_merged_section_offset (abfd, psec,
11208                                      elf_section_data (sec)->sec_info,
11209                                      sym->st_value + addend);
11210 }
11211
11212 /* Adjust an address within a section.  Given OFFSET within SEC, return
11213    the new offset within the section, based upon changes made to the
11214    section.  Returns -1 if the offset is now invalid.
11215    The offset (in abnd out) is in target sized bytes, however big a
11216    byte may be.  */
11217
11218 bfd_vma
11219 _bfd_elf_section_offset (bfd *abfd,
11220                          struct bfd_link_info *info,
11221                          asection *sec,
11222                          bfd_vma offset)
11223 {
11224   switch (sec->sec_info_type)
11225     {
11226     case SEC_INFO_TYPE_STABS:
11227       return _bfd_stab_section_offset (sec, elf_section_data (sec)->sec_info,
11228                                        offset);
11229     case SEC_INFO_TYPE_EH_FRAME:
11230       return _bfd_elf_eh_frame_section_offset (abfd, info, sec, offset);
11231
11232     default:
11233       if ((sec->flags & SEC_ELF_REVERSE_COPY) != 0)
11234         {
11235           /* Reverse the offset.  */
11236           const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11237           bfd_size_type address_size = bed->s->arch_size / 8;
11238
11239           /* address_size and sec->size are in octets.  Convert
11240              to bytes before subtracting the original offset.  */
11241           offset = (sec->size - address_size) / bfd_octets_per_byte (abfd) - offset;
11242         }
11243       return offset;
11244     }
11245 }
11246 \f
11247 /* Create a new BFD as if by bfd_openr.  Rather than opening a file,
11248    reconstruct an ELF file by reading the segments out of remote memory
11249    based on the ELF file header at EHDR_VMA and the ELF program headers it
11250    points to.  If not null, *LOADBASEP is filled in with the difference
11251    between the VMAs from which the segments were read, and the VMAs the
11252    file headers (and hence BFD's idea of each section's VMA) put them at.
11253
11254    The function TARGET_READ_MEMORY is called to copy LEN bytes from the
11255    remote memory at target address VMA into the local buffer at MYADDR; it
11256    should return zero on success or an `errno' code on failure.  TEMPL must
11257    be a BFD for an ELF target with the word size and byte order found in
11258    the remote memory.  */
11259
11260 bfd *
11261 bfd_elf_bfd_from_remote_memory
11262   (bfd *templ,
11263    bfd_vma ehdr_vma,
11264    bfd_size_type size,
11265    bfd_vma *loadbasep,
11266    int (*target_read_memory) (bfd_vma, bfd_byte *, bfd_size_type))
11267 {
11268   return (*get_elf_backend_data (templ)->elf_backend_bfd_from_remote_memory)
11269     (templ, ehdr_vma, size, loadbasep, target_read_memory);
11270 }
11271 \f
11272 long
11273 _bfd_elf_get_synthetic_symtab (bfd *abfd,
11274                                long symcount ATTRIBUTE_UNUSED,
11275                                asymbol **syms ATTRIBUTE_UNUSED,
11276                                long dynsymcount,
11277                                asymbol **dynsyms,
11278                                asymbol **ret)
11279 {
11280   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11281   asection *relplt;
11282   asymbol *s;
11283   const char *relplt_name;
11284   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
11285   arelent *p;
11286   long count, i, n;
11287   size_t size;
11288   Elf_Internal_Shdr *hdr;
11289   char *names;
11290   asection *plt;
11291
11292   *ret = NULL;
11293
11294   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0)
11295     return 0;
11296
11297   if (dynsymcount <= 0)
11298     return 0;
11299
11300   if (!bed->plt_sym_val)
11301     return 0;
11302
11303   relplt_name = bed->relplt_name;
11304   if (relplt_name == NULL)
11305     relplt_name = bed->rela_plts_and_copies_p ? ".rela.plt" : ".rel.plt";
11306   relplt = bfd_get_section_by_name (abfd, relplt_name);
11307   if (relplt == NULL)
11308     return 0;
11309
11310   hdr = &elf_section_data (relplt)->this_hdr;
11311   if (hdr->sh_link != elf_dynsymtab (abfd)
11312       || (hdr->sh_type != SHT_REL && hdr->sh_type != SHT_RELA))
11313     return 0;
11314
11315   plt = bfd_get_section_by_name (abfd, ".plt");
11316   if (plt == NULL)
11317     return 0;
11318
11319   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
11320   if (! (*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
11321     return -1;
11322
11323   count = relplt->size / hdr->sh_entsize;
11324   size = count * sizeof (asymbol);
11325   p = relplt->relocation;
11326   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
11327     {
11328       size += strlen ((*p->sym_ptr_ptr)->name) + sizeof ("@plt");
11329       if (p->addend != 0)
11330         {
11331 #ifdef BFD64
11332           size += sizeof ("+0x") - 1 + 8 + 8 * (bed->s->elfclass == ELFCLASS64);
11333 #else
11334           size += sizeof ("+0x") - 1 + 8;
11335 #endif
11336         }
11337     }
11338
11339   s = *ret = (asymbol *) bfd_malloc (size);
11340   if (s == NULL)
11341     return -1;
11342
11343   names = (char *) (s + count);
11344   p = relplt->relocation;
11345   n = 0;
11346   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
11347     {
11348       size_t len;
11349       bfd_vma addr;
11350
11351       addr = bed->plt_sym_val (i, plt, p);
11352       if (addr == (bfd_vma) -1)
11353         continue;
11354
11355       *s = **p->sym_ptr_ptr;
11356       /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
11357          we are defining a symbol, ensure one of them is set.  */
11358       if ((s->flags & BSF_LOCAL) == 0)
11359         s->flags |= BSF_GLOBAL;
11360       s->flags |= BSF_SYNTHETIC;
11361       s->section = plt;
11362       s->value = addr - plt->vma;
11363       s->name = names;
11364       s->udata.p = NULL;
11365       len = strlen ((*p->sym_ptr_ptr)->name);
11366       memcpy (names, (*p->sym_ptr_ptr)->name, len);
11367       names += len;
11368       if (p->addend != 0)
11369         {
11370           char buf[30], *a;
11371
11372           memcpy (names, "+0x", sizeof ("+0x") - 1);
11373           names += sizeof ("+0x") - 1;
11374           bfd_sprintf_vma (abfd, buf, p->addend);
11375           for (a = buf; *a == '0'; ++a)
11376             ;
11377           len = strlen (a);
11378           memcpy (names, a, len);
11379           names += len;
11380         }
11381       memcpy (names, "@plt", sizeof ("@plt"));
11382       names += sizeof ("@plt");
11383       ++s, ++n;
11384     }
11385
11386   return n;
11387 }
11388
11389 /* It is only used by x86-64 so far.
11390    ??? This repeats *COM* id of zero.  sec->id is supposed to be unique,
11391    but current usage would allow all of _bfd_std_section to be zero.  */
11392 static const asymbol lcomm_sym
11393   = GLOBAL_SYM_INIT ("LARGE_COMMON", &_bfd_elf_large_com_section);
11394 asection _bfd_elf_large_com_section
11395   = BFD_FAKE_SECTION (_bfd_elf_large_com_section, &lcomm_sym,
11396                       "LARGE_COMMON", 0, SEC_IS_COMMON);
11397
11398 void
11399 _bfd_elf_post_process_headers (bfd * abfd,
11400                                struct bfd_link_info * link_info ATTRIBUTE_UNUSED)
11401 {
11402   Elf_Internal_Ehdr * i_ehdrp;  /* ELF file header, internal form.  */
11403
11404   i_ehdrp = elf_elfheader (abfd);
11405
11406   i_ehdrp->e_ident[EI_OSABI] = get_elf_backend_data (abfd)->elf_osabi;
11407
11408   /* To make things simpler for the loader on Linux systems we set the
11409      osabi field to ELFOSABI_GNU if the binary contains symbols of
11410      the STT_GNU_IFUNC type or STB_GNU_UNIQUE binding.  */
11411   if (i_ehdrp->e_ident[EI_OSABI] == ELFOSABI_NONE
11412       && elf_tdata (abfd)->has_gnu_symbols)
11413     i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_GNU;
11414 }
11415
11416
11417 /* Return TRUE for ELF symbol types that represent functions.
11418    This is the default version of this function, which is sufficient for
11419    most targets.  It returns true if TYPE is STT_FUNC or STT_GNU_IFUNC.  */
11420
11421 bfd_boolean
11422 _bfd_elf_is_function_type (unsigned int type)
11423 {
11424   return (type == STT_FUNC
11425           || type == STT_GNU_IFUNC);
11426 }
11427
11428 /* If the ELF symbol SYM might be a function in SEC, return the
11429    function size and set *CODE_OFF to the function's entry point,
11430    otherwise return zero.  */
11431
11432 bfd_size_type
11433 _bfd_elf_maybe_function_sym (const asymbol *sym, asection *sec,
11434                              bfd_vma *code_off)
11435 {
11436   bfd_size_type size;
11437
11438   if ((sym->flags & (BSF_SECTION_SYM | BSF_FILE | BSF_OBJECT
11439                      | BSF_THREAD_LOCAL | BSF_RELC | BSF_SRELC)) != 0
11440       || sym->section != sec)
11441     return 0;
11442
11443   *code_off = sym->value;
11444   size = 0;
11445   if (!(sym->flags & BSF_SYNTHETIC))
11446     size = ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
11447   if (size == 0)
11448     size = 1;
11449   return size;
11450 }