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