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