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