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