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