Range of element index is too large on MIPS MSA element selection instructions.
[platform/upstream/binutils.git] / bfd / elf.c
1 /* ELF executable support for BFD.
2
3    Copyright 1993-2013 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         }
3079       if (d->rela.idx != 0)
3080         {
3081           d->rela.hdr->sh_link = elf_onesymtab (abfd);
3082           d->rela.hdr->sh_info = d->this_idx;
3083         }
3084
3085       /* We need to set up sh_link for SHF_LINK_ORDER.  */
3086       if ((d->this_hdr.sh_flags & SHF_LINK_ORDER) != 0)
3087         {
3088           s = elf_linked_to_section (sec);
3089           if (s)
3090             {
3091               /* elf_linked_to_section points to the input section.  */
3092               if (link_info != NULL)
3093                 {
3094                   /* Check discarded linkonce section.  */
3095                   if (discarded_section (s))
3096                     {
3097                       asection *kept;
3098                       (*_bfd_error_handler)
3099                         (_("%B: sh_link of section `%A' points to discarded section `%A' of `%B'"),
3100                          abfd, d->this_hdr.bfd_section,
3101                          s, s->owner);
3102                       /* Point to the kept section if it has the same
3103                          size as the discarded one.  */
3104                       kept = _bfd_elf_check_kept_section (s, link_info);
3105                       if (kept == NULL)
3106                         {
3107                           bfd_set_error (bfd_error_bad_value);
3108                           return FALSE;
3109                         }
3110                       s = kept;
3111                     }
3112
3113                   s = s->output_section;
3114                   BFD_ASSERT (s != NULL);
3115                 }
3116               else
3117                 {
3118                   /* Handle objcopy. */
3119                   if (s->output_section == NULL)
3120                     {
3121                       (*_bfd_error_handler)
3122                         (_("%B: sh_link of section `%A' points to removed section `%A' of `%B'"),
3123                          abfd, d->this_hdr.bfd_section, s, s->owner);
3124                       bfd_set_error (bfd_error_bad_value);
3125                       return FALSE;
3126                     }
3127                   s = s->output_section;
3128                 }
3129               d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3130             }
3131           else
3132             {
3133               /* PR 290:
3134                  The Intel C compiler generates SHT_IA_64_UNWIND with
3135                  SHF_LINK_ORDER.  But it doesn't set the sh_link or
3136                  sh_info fields.  Hence we could get the situation
3137                  where s is NULL.  */
3138               const struct elf_backend_data *bed
3139                 = get_elf_backend_data (abfd);
3140               if (bed->link_order_error_handler)
3141                 bed->link_order_error_handler
3142                   (_("%B: warning: sh_link not set for section `%A'"),
3143                    abfd, sec);
3144             }
3145         }
3146
3147       switch (d->this_hdr.sh_type)
3148         {
3149         case SHT_REL:
3150         case SHT_RELA:
3151           /* A reloc section which we are treating as a normal BFD
3152              section.  sh_link is the section index of the symbol
3153              table.  sh_info is the section index of the section to
3154              which the relocation entries apply.  We assume that an
3155              allocated reloc section uses the dynamic symbol table.
3156              FIXME: How can we be sure?  */
3157           s = bfd_get_section_by_name (abfd, ".dynsym");
3158           if (s != NULL)
3159             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3160
3161           /* We look up the section the relocs apply to by name.  */
3162           name = sec->name;
3163           if (d->this_hdr.sh_type == SHT_REL)
3164             name += 4;
3165           else
3166             name += 5;
3167           s = bfd_get_section_by_name (abfd, name);
3168           if (s != NULL)
3169             d->this_hdr.sh_info = elf_section_data (s)->this_idx;
3170           break;
3171
3172         case SHT_STRTAB:
3173           /* We assume that a section named .stab*str is a stabs
3174              string section.  We look for a section with the same name
3175              but without the trailing ``str'', and set its sh_link
3176              field to point to this section.  */
3177           if (CONST_STRNEQ (sec->name, ".stab")
3178               && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
3179             {
3180               size_t len;
3181               char *alc;
3182
3183               len = strlen (sec->name);
3184               alc = (char *) bfd_malloc (len - 2);
3185               if (alc == NULL)
3186                 return FALSE;
3187               memcpy (alc, sec->name, len - 3);
3188               alc[len - 3] = '\0';
3189               s = bfd_get_section_by_name (abfd, alc);
3190               free (alc);
3191               if (s != NULL)
3192                 {
3193                   elf_section_data (s)->this_hdr.sh_link = d->this_idx;
3194
3195                   /* This is a .stab section.  */
3196                   if (elf_section_data (s)->this_hdr.sh_entsize == 0)
3197                     elf_section_data (s)->this_hdr.sh_entsize
3198                       = 4 + 2 * bfd_get_arch_size (abfd) / 8;
3199                 }
3200             }
3201           break;
3202
3203         case SHT_DYNAMIC:
3204         case SHT_DYNSYM:
3205         case SHT_GNU_verneed:
3206         case SHT_GNU_verdef:
3207           /* sh_link is the section header index of the string table
3208              used for the dynamic entries, or the symbol table, or the
3209              version strings.  */
3210           s = bfd_get_section_by_name (abfd, ".dynstr");
3211           if (s != NULL)
3212             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3213           break;
3214
3215         case SHT_GNU_LIBLIST:
3216           /* sh_link is the section header index of the prelink library
3217              list used for the dynamic entries, or the symbol table, or
3218              the version strings.  */
3219           s = bfd_get_section_by_name (abfd, (sec->flags & SEC_ALLOC)
3220                                              ? ".dynstr" : ".gnu.libstr");
3221           if (s != NULL)
3222             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3223           break;
3224
3225         case SHT_HASH:
3226         case SHT_GNU_HASH:
3227         case SHT_GNU_versym:
3228           /* sh_link is the section header index of the symbol table
3229              this hash table or version table is for.  */
3230           s = bfd_get_section_by_name (abfd, ".dynsym");
3231           if (s != NULL)
3232             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
3233           break;
3234
3235         case SHT_GROUP:
3236           d->this_hdr.sh_link = elf_onesymtab (abfd);
3237         }
3238     }
3239
3240   for (secn = 1; secn < section_number; ++secn)
3241     if (i_shdrp[secn] == NULL)
3242       i_shdrp[secn] = i_shdrp[0];
3243     else
3244       i_shdrp[secn]->sh_name = _bfd_elf_strtab_offset (elf_shstrtab (abfd),
3245                                                        i_shdrp[secn]->sh_name);
3246   return TRUE;
3247 }
3248
3249 static bfd_boolean
3250 sym_is_global (bfd *abfd, asymbol *sym)
3251 {
3252   /* If the backend has a special mapping, use it.  */
3253   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3254   if (bed->elf_backend_sym_is_global)
3255     return (*bed->elf_backend_sym_is_global) (abfd, sym);
3256
3257   return ((sym->flags & (BSF_GLOBAL | BSF_WEAK | BSF_GNU_UNIQUE)) != 0
3258           || bfd_is_und_section (bfd_get_section (sym))
3259           || bfd_is_com_section (bfd_get_section (sym)));
3260 }
3261
3262 /* Don't output section symbols for sections that are not going to be
3263    output, that are duplicates or there is no BFD section.  */
3264
3265 static bfd_boolean
3266 ignore_section_sym (bfd *abfd, asymbol *sym)
3267 {
3268   elf_symbol_type *type_ptr;
3269
3270   if ((sym->flags & BSF_SECTION_SYM) == 0)
3271     return FALSE;
3272
3273   type_ptr = elf_symbol_from (abfd, sym);
3274   return ((type_ptr != NULL
3275            && type_ptr->internal_elf_sym.st_shndx != 0
3276            && bfd_is_abs_section (sym->section))
3277           || !(sym->section->owner == abfd
3278                || (sym->section->output_section->owner == abfd
3279                    && sym->section->output_offset == 0)
3280                || bfd_is_abs_section (sym->section)));
3281 }
3282
3283 /* Map symbol from it's internal number to the external number, moving
3284    all local symbols to be at the head of the list.  */
3285
3286 static bfd_boolean
3287 elf_map_symbols (bfd *abfd, unsigned int *pnum_locals)
3288 {
3289   unsigned int symcount = bfd_get_symcount (abfd);
3290   asymbol **syms = bfd_get_outsymbols (abfd);
3291   asymbol **sect_syms;
3292   unsigned int num_locals = 0;
3293   unsigned int num_globals = 0;
3294   unsigned int num_locals2 = 0;
3295   unsigned int num_globals2 = 0;
3296   int max_index = 0;
3297   unsigned int idx;
3298   asection *asect;
3299   asymbol **new_syms;
3300
3301 #ifdef DEBUG
3302   fprintf (stderr, "elf_map_symbols\n");
3303   fflush (stderr);
3304 #endif
3305
3306   for (asect = abfd->sections; asect; asect = asect->next)
3307     {
3308       if (max_index < asect->index)
3309         max_index = asect->index;
3310     }
3311
3312   max_index++;
3313   sect_syms = (asymbol **) bfd_zalloc2 (abfd, max_index, sizeof (asymbol *));
3314   if (sect_syms == NULL)
3315     return FALSE;
3316   elf_section_syms (abfd) = sect_syms;
3317   elf_num_section_syms (abfd) = max_index;
3318
3319   /* Init sect_syms entries for any section symbols we have already
3320      decided to output.  */
3321   for (idx = 0; idx < symcount; idx++)
3322     {
3323       asymbol *sym = syms[idx];
3324
3325       if ((sym->flags & BSF_SECTION_SYM) != 0
3326           && sym->value == 0
3327           && !ignore_section_sym (abfd, sym)
3328           && !bfd_is_abs_section (sym->section))
3329         {
3330           asection *sec = sym->section;
3331
3332           if (sec->owner != abfd)
3333             sec = sec->output_section;
3334
3335           sect_syms[sec->index] = syms[idx];
3336         }
3337     }
3338
3339   /* Classify all of the symbols.  */
3340   for (idx = 0; idx < symcount; idx++)
3341     {
3342       if (sym_is_global (abfd, syms[idx]))
3343         num_globals++;
3344       else if (!ignore_section_sym (abfd, syms[idx]))
3345         num_locals++;
3346     }
3347
3348   /* We will be adding a section symbol for each normal BFD section.  Most
3349      sections will already have a section symbol in outsymbols, but
3350      eg. SHT_GROUP sections will not, and we need the section symbol mapped
3351      at least in that case.  */
3352   for (asect = abfd->sections; asect; asect = asect->next)
3353     {
3354       if (sect_syms[asect->index] == NULL)
3355         {
3356           if (!sym_is_global (abfd, asect->symbol))
3357             num_locals++;
3358           else
3359             num_globals++;
3360         }
3361     }
3362
3363   /* Now sort the symbols so the local symbols are first.  */
3364   new_syms = (asymbol **) bfd_alloc2 (abfd, num_locals + num_globals,
3365                                       sizeof (asymbol *));
3366
3367   if (new_syms == NULL)
3368     return FALSE;
3369
3370   for (idx = 0; idx < symcount; idx++)
3371     {
3372       asymbol *sym = syms[idx];
3373       unsigned int i;
3374
3375       if (sym_is_global (abfd, sym))
3376         i = num_locals + num_globals2++;
3377       else if (!ignore_section_sym (abfd, sym))
3378         i = num_locals2++;
3379       else
3380         continue;
3381       new_syms[i] = sym;
3382       sym->udata.i = i + 1;
3383     }
3384   for (asect = abfd->sections; asect; asect = asect->next)
3385     {
3386       if (sect_syms[asect->index] == NULL)
3387         {
3388           asymbol *sym = asect->symbol;
3389           unsigned int i;
3390
3391           sect_syms[asect->index] = sym;
3392           if (!sym_is_global (abfd, sym))
3393             i = num_locals2++;
3394           else
3395             i = num_locals + num_globals2++;
3396           new_syms[i] = sym;
3397           sym->udata.i = i + 1;
3398         }
3399     }
3400
3401   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
3402
3403   *pnum_locals = num_locals;
3404   return TRUE;
3405 }
3406
3407 /* Align to the maximum file alignment that could be required for any
3408    ELF data structure.  */
3409
3410 static inline file_ptr
3411 align_file_position (file_ptr off, int align)
3412 {
3413   return (off + align - 1) & ~(align - 1);
3414 }
3415
3416 /* Assign a file position to a section, optionally aligning to the
3417    required section alignment.  */
3418
3419 file_ptr
3420 _bfd_elf_assign_file_position_for_section (Elf_Internal_Shdr *i_shdrp,
3421                                            file_ptr offset,
3422                                            bfd_boolean align)
3423 {
3424   if (align && i_shdrp->sh_addralign > 1)
3425     offset = BFD_ALIGN (offset, i_shdrp->sh_addralign);
3426   i_shdrp->sh_offset = offset;
3427   if (i_shdrp->bfd_section != NULL)
3428     i_shdrp->bfd_section->filepos = offset;
3429   if (i_shdrp->sh_type != SHT_NOBITS)
3430     offset += i_shdrp->sh_size;
3431   return offset;
3432 }
3433
3434 /* Compute the file positions we are going to put the sections at, and
3435    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
3436    is not NULL, this is being called by the ELF backend linker.  */
3437
3438 bfd_boolean
3439 _bfd_elf_compute_section_file_positions (bfd *abfd,
3440                                          struct bfd_link_info *link_info)
3441 {
3442   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3443   struct fake_section_arg fsargs;
3444   bfd_boolean failed;
3445   struct bfd_strtab_hash *strtab = NULL;
3446   Elf_Internal_Shdr *shstrtab_hdr;
3447   bfd_boolean need_symtab;
3448
3449   if (abfd->output_has_begun)
3450     return TRUE;
3451
3452   /* Do any elf backend specific processing first.  */
3453   if (bed->elf_backend_begin_write_processing)
3454     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
3455
3456   if (! prep_headers (abfd))
3457     return FALSE;
3458
3459   /* Post process the headers if necessary.  */
3460   if (bed->elf_backend_post_process_headers)
3461     (*bed->elf_backend_post_process_headers) (abfd, link_info);
3462
3463   fsargs.failed = FALSE;
3464   fsargs.link_info = link_info;
3465   bfd_map_over_sections (abfd, elf_fake_sections, &fsargs);
3466   if (fsargs.failed)
3467     return FALSE;
3468
3469   if (!assign_section_numbers (abfd, link_info))
3470     return FALSE;
3471
3472   /* The backend linker builds symbol table information itself.  */
3473   need_symtab = (link_info == NULL
3474                  && (bfd_get_symcount (abfd) > 0
3475                      || ((abfd->flags & (EXEC_P | DYNAMIC | HAS_RELOC))
3476                          == HAS_RELOC)));
3477   if (need_symtab)
3478     {
3479       /* Non-zero if doing a relocatable link.  */
3480       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
3481
3482       if (! swap_out_syms (abfd, &strtab, relocatable_p))
3483         return FALSE;
3484     }
3485
3486   failed = FALSE;
3487   if (link_info == NULL)
3488     {
3489       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
3490       if (failed)
3491         return FALSE;
3492     }
3493
3494   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
3495   /* sh_name was set in prep_headers.  */
3496   shstrtab_hdr->sh_type = SHT_STRTAB;
3497   shstrtab_hdr->sh_flags = 0;
3498   shstrtab_hdr->sh_addr = 0;
3499   shstrtab_hdr->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
3500   shstrtab_hdr->sh_entsize = 0;
3501   shstrtab_hdr->sh_link = 0;
3502   shstrtab_hdr->sh_info = 0;
3503   /* sh_offset is set in assign_file_positions_except_relocs.  */
3504   shstrtab_hdr->sh_addralign = 1;
3505
3506   if (!assign_file_positions_except_relocs (abfd, link_info))
3507     return FALSE;
3508
3509   if (need_symtab)
3510     {
3511       file_ptr off;
3512       Elf_Internal_Shdr *hdr;
3513
3514       off = elf_next_file_pos (abfd);
3515
3516       hdr = &elf_tdata (abfd)->symtab_hdr;
3517       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3518
3519       hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
3520       if (hdr->sh_size != 0)
3521         off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3522
3523       hdr = &elf_tdata (abfd)->strtab_hdr;
3524       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
3525
3526       elf_next_file_pos (abfd) = off;
3527
3528       /* Now that we know where the .strtab section goes, write it
3529          out.  */
3530       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
3531           || ! _bfd_stringtab_emit (abfd, strtab))
3532         return FALSE;
3533       _bfd_stringtab_free (strtab);
3534     }
3535
3536   abfd->output_has_begun = TRUE;
3537
3538   return TRUE;
3539 }
3540
3541 /* Make an initial estimate of the size of the program header.  If we
3542    get the number wrong here, we'll redo section placement.  */
3543
3544 static bfd_size_type
3545 get_program_header_size (bfd *abfd, struct bfd_link_info *info)
3546 {
3547   size_t segs;
3548   asection *s;
3549   const struct elf_backend_data *bed;
3550
3551   /* Assume we will need exactly two PT_LOAD segments: one for text
3552      and one for data.  */
3553   segs = 2;
3554
3555   s = bfd_get_section_by_name (abfd, ".interp");
3556   if (s != NULL && (s->flags & SEC_LOAD) != 0)
3557     {
3558       /* If we have a loadable interpreter section, we need a
3559          PT_INTERP segment.  In this case, assume we also need a
3560          PT_PHDR segment, although that may not be true for all
3561          targets.  */
3562       segs += 2;
3563     }
3564
3565   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
3566     {
3567       /* We need a PT_DYNAMIC segment.  */
3568       ++segs;
3569     }
3570
3571   if (info != NULL && info->relro)
3572     {
3573       /* We need a PT_GNU_RELRO segment.  */
3574       ++segs;
3575     }
3576
3577   if (elf_eh_frame_hdr (abfd))
3578     {
3579       /* We need a PT_GNU_EH_FRAME segment.  */
3580       ++segs;
3581     }
3582
3583   if (elf_stack_flags (abfd))
3584     {
3585       /* We need a PT_GNU_STACK segment.  */
3586       ++segs;
3587     }
3588
3589   for (s = abfd->sections; s != NULL; s = s->next)
3590     {
3591       if ((s->flags & SEC_LOAD) != 0
3592           && CONST_STRNEQ (s->name, ".note"))
3593         {
3594           /* We need a PT_NOTE segment.  */
3595           ++segs;
3596           /* Try to create just one PT_NOTE segment
3597              for all adjacent loadable .note* sections.
3598              gABI requires that within a PT_NOTE segment
3599              (and also inside of each SHT_NOTE section)
3600              each note is padded to a multiple of 4 size,
3601              so we check whether the sections are correctly
3602              aligned.  */
3603           if (s->alignment_power == 2)
3604             while (s->next != NULL
3605                    && s->next->alignment_power == 2
3606                    && (s->next->flags & SEC_LOAD) != 0
3607                    && CONST_STRNEQ (s->next->name, ".note"))
3608               s = s->next;
3609         }
3610     }
3611
3612   for (s = abfd->sections; s != NULL; s = s->next)
3613     {
3614       if (s->flags & SEC_THREAD_LOCAL)
3615         {
3616           /* We need a PT_TLS segment.  */
3617           ++segs;
3618           break;
3619         }
3620     }
3621
3622   /* Let the backend count up any program headers it might need.  */
3623   bed = get_elf_backend_data (abfd);
3624   if (bed->elf_backend_additional_program_headers)
3625     {
3626       int a;
3627
3628       a = (*bed->elf_backend_additional_program_headers) (abfd, info);
3629       if (a == -1)
3630         abort ();
3631       segs += a;
3632     }
3633
3634   return segs * bed->s->sizeof_phdr;
3635 }
3636
3637 /* Find the segment that contains the output_section of section.  */
3638
3639 Elf_Internal_Phdr *
3640 _bfd_elf_find_segment_containing_section (bfd * abfd, asection * section)
3641 {
3642   struct elf_segment_map *m;
3643   Elf_Internal_Phdr *p;
3644
3645   for (m = elf_seg_map (abfd), p = elf_tdata (abfd)->phdr;
3646        m != NULL;
3647        m = m->next, p++)
3648     {
3649       int i;
3650
3651       for (i = m->count - 1; i >= 0; i--)
3652         if (m->sections[i] == section)
3653           return p;
3654     }
3655
3656   return NULL;
3657 }
3658
3659 /* Create a mapping from a set of sections to a program segment.  */
3660
3661 static struct elf_segment_map *
3662 make_mapping (bfd *abfd,
3663               asection **sections,
3664               unsigned int from,
3665               unsigned int to,
3666               bfd_boolean phdr)
3667 {
3668   struct elf_segment_map *m;
3669   unsigned int i;
3670   asection **hdrpp;
3671   bfd_size_type amt;
3672
3673   amt = sizeof (struct elf_segment_map);
3674   amt += (to - from - 1) * sizeof (asection *);
3675   m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3676   if (m == NULL)
3677     return NULL;
3678   m->next = NULL;
3679   m->p_type = PT_LOAD;
3680   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
3681     m->sections[i - from] = *hdrpp;
3682   m->count = to - from;
3683
3684   if (from == 0 && phdr)
3685     {
3686       /* Include the headers in the first PT_LOAD segment.  */
3687       m->includes_filehdr = 1;
3688       m->includes_phdrs = 1;
3689     }
3690
3691   return m;
3692 }
3693
3694 /* Create the PT_DYNAMIC segment, which includes DYNSEC.  Returns NULL
3695    on failure.  */
3696
3697 struct elf_segment_map *
3698 _bfd_elf_make_dynamic_segment (bfd *abfd, asection *dynsec)
3699 {
3700   struct elf_segment_map *m;
3701
3702   m = (struct elf_segment_map *) bfd_zalloc (abfd,
3703                                              sizeof (struct elf_segment_map));
3704   if (m == NULL)
3705     return NULL;
3706   m->next = NULL;
3707   m->p_type = PT_DYNAMIC;
3708   m->count = 1;
3709   m->sections[0] = dynsec;
3710
3711   return m;
3712 }
3713
3714 /* Possibly add or remove segments from the segment map.  */
3715
3716 static bfd_boolean
3717 elf_modify_segment_map (bfd *abfd,
3718                         struct bfd_link_info *info,
3719                         bfd_boolean remove_empty_load)
3720 {
3721   struct elf_segment_map **m;
3722   const struct elf_backend_data *bed;
3723
3724   /* The placement algorithm assumes that non allocated sections are
3725      not in PT_LOAD segments.  We ensure this here by removing such
3726      sections from the segment map.  We also remove excluded
3727      sections.  Finally, any PT_LOAD segment without sections is
3728      removed.  */
3729   m = &elf_seg_map (abfd);
3730   while (*m)
3731     {
3732       unsigned int i, new_count;
3733
3734       for (new_count = 0, i = 0; i < (*m)->count; i++)
3735         {
3736           if (((*m)->sections[i]->flags & SEC_EXCLUDE) == 0
3737               && (((*m)->sections[i]->flags & SEC_ALLOC) != 0
3738                   || (*m)->p_type != PT_LOAD))
3739             {
3740               (*m)->sections[new_count] = (*m)->sections[i];
3741               new_count++;
3742             }
3743         }
3744       (*m)->count = new_count;
3745
3746       if (remove_empty_load && (*m)->p_type == PT_LOAD && (*m)->count == 0)
3747         *m = (*m)->next;
3748       else
3749         m = &(*m)->next;
3750     }
3751
3752   bed = get_elf_backend_data (abfd);
3753   if (bed->elf_backend_modify_segment_map != NULL)
3754     {
3755       if (!(*bed->elf_backend_modify_segment_map) (abfd, info))
3756         return FALSE;
3757     }
3758
3759   return TRUE;
3760 }
3761
3762 /* Set up a mapping from BFD sections to program segments.  */
3763
3764 bfd_boolean
3765 _bfd_elf_map_sections_to_segments (bfd *abfd, struct bfd_link_info *info)
3766 {
3767   unsigned int count;
3768   struct elf_segment_map *m;
3769   asection **sections = NULL;
3770   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3771   bfd_boolean no_user_phdrs;
3772
3773   no_user_phdrs = elf_seg_map (abfd) == NULL;
3774
3775   if (info != NULL)
3776     info->user_phdrs = !no_user_phdrs;
3777
3778   if (no_user_phdrs && bfd_count_sections (abfd) != 0)
3779     {
3780       asection *s;
3781       unsigned int i;
3782       struct elf_segment_map *mfirst;
3783       struct elf_segment_map **pm;
3784       asection *last_hdr;
3785       bfd_vma last_size;
3786       unsigned int phdr_index;
3787       bfd_vma maxpagesize;
3788       asection **hdrpp;
3789       bfd_boolean phdr_in_segment = TRUE;
3790       bfd_boolean writable;
3791       int tls_count = 0;
3792       asection *first_tls = NULL;
3793       asection *dynsec, *eh_frame_hdr;
3794       bfd_size_type amt;
3795       bfd_vma addr_mask, wrap_to = 0;
3796
3797       /* Select the allocated sections, and sort them.  */
3798
3799       sections = (asection **) bfd_malloc2 (bfd_count_sections (abfd),
3800                                             sizeof (asection *));
3801       if (sections == NULL)
3802         goto error_return;
3803
3804       /* Calculate top address, avoiding undefined behaviour of shift
3805          left operator when shift count is equal to size of type
3806          being shifted.  */
3807       addr_mask = ((bfd_vma) 1 << (bfd_arch_bits_per_address (abfd) - 1)) - 1;
3808       addr_mask = (addr_mask << 1) + 1;
3809
3810       i = 0;
3811       for (s = abfd->sections; s != NULL; s = s->next)
3812         {
3813           if ((s->flags & SEC_ALLOC) != 0)
3814             {
3815               sections[i] = s;
3816               ++i;
3817               /* A wrapping section potentially clashes with header.  */
3818               if (((s->lma + s->size) & addr_mask) < (s->lma & addr_mask))
3819                 wrap_to = (s->lma + s->size) & addr_mask;
3820             }
3821         }
3822       BFD_ASSERT (i <= bfd_count_sections (abfd));
3823       count = i;
3824
3825       qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
3826
3827       /* Build the mapping.  */
3828
3829       mfirst = NULL;
3830       pm = &mfirst;
3831
3832       /* If we have a .interp section, then create a PT_PHDR segment for
3833          the program headers and a PT_INTERP segment for the .interp
3834          section.  */
3835       s = bfd_get_section_by_name (abfd, ".interp");
3836       if (s != NULL && (s->flags & SEC_LOAD) != 0)
3837         {
3838           amt = sizeof (struct elf_segment_map);
3839           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3840           if (m == NULL)
3841             goto error_return;
3842           m->next = NULL;
3843           m->p_type = PT_PHDR;
3844           /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
3845           m->p_flags = PF_R | PF_X;
3846           m->p_flags_valid = 1;
3847           m->includes_phdrs = 1;
3848
3849           *pm = m;
3850           pm = &m->next;
3851
3852           amt = sizeof (struct elf_segment_map);
3853           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
3854           if (m == NULL)
3855             goto error_return;
3856           m->next = NULL;
3857           m->p_type = PT_INTERP;
3858           m->count = 1;
3859           m->sections[0] = s;
3860
3861           *pm = m;
3862           pm = &m->next;
3863         }
3864
3865       /* Look through the sections.  We put sections in the same program
3866          segment when the start of the second section can be placed within
3867          a few bytes of the end of the first section.  */
3868       last_hdr = NULL;
3869       last_size = 0;
3870       phdr_index = 0;
3871       maxpagesize = bed->maxpagesize;
3872       writable = FALSE;
3873       dynsec = bfd_get_section_by_name (abfd, ".dynamic");
3874       if (dynsec != NULL
3875           && (dynsec->flags & SEC_LOAD) == 0)
3876         dynsec = NULL;
3877
3878       /* Deal with -Ttext or something similar such that the first section
3879          is not adjacent to the program headers.  This is an
3880          approximation, since at this point we don't know exactly how many
3881          program headers we will need.  */
3882       if (count > 0)
3883         {
3884           bfd_size_type phdr_size = elf_program_header_size (abfd);
3885
3886           if (phdr_size == (bfd_size_type) -1)
3887             phdr_size = get_program_header_size (abfd, info);
3888           phdr_size += bed->s->sizeof_ehdr;
3889           if ((abfd->flags & D_PAGED) == 0
3890               || (sections[0]->lma & addr_mask) < phdr_size
3891               || ((sections[0]->lma & addr_mask) % maxpagesize
3892                   < phdr_size % maxpagesize)
3893               || (sections[0]->lma & addr_mask & -maxpagesize) < wrap_to)
3894             phdr_in_segment = FALSE;
3895         }
3896
3897       for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
3898         {
3899           asection *hdr;
3900           bfd_boolean new_segment;
3901
3902           hdr = *hdrpp;
3903
3904           /* See if this section and the last one will fit in the same
3905              segment.  */
3906
3907           if (last_hdr == NULL)
3908             {
3909               /* If we don't have a segment yet, then we don't need a new
3910                  one (we build the last one after this loop).  */
3911               new_segment = FALSE;
3912             }
3913           else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
3914             {
3915               /* If this section has a different relation between the
3916                  virtual address and the load address, then we need a new
3917                  segment.  */
3918               new_segment = TRUE;
3919             }
3920           else if (hdr->lma < last_hdr->lma + last_size
3921                    || last_hdr->lma + last_size < last_hdr->lma)
3922             {
3923               /* If this section has a load address that makes it overlap
3924                  the previous section, then we need a new segment.  */
3925               new_segment = TRUE;
3926             }
3927           /* In the next test we have to be careful when last_hdr->lma is close
3928              to the end of the address space.  If the aligned address wraps
3929              around to the start of the address space, then there are no more
3930              pages left in memory and it is OK to assume that the current
3931              section can be included in the current segment.  */
3932           else if ((BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
3933                     > last_hdr->lma)
3934                    && (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
3935                        <= hdr->lma))
3936             {
3937               /* If putting this section in this segment would force us to
3938                  skip a page in the segment, then we need a new segment.  */
3939               new_segment = TRUE;
3940             }
3941           else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
3942                    && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0)
3943             {
3944               /* We don't want to put a loadable section after a
3945                  nonloadable section in the same segment.
3946                  Consider .tbss sections as loadable for this purpose.  */
3947               new_segment = TRUE;
3948             }
3949           else if ((abfd->flags & D_PAGED) == 0)
3950             {
3951               /* If the file is not demand paged, which means that we
3952                  don't require the sections to be correctly aligned in the
3953                  file, then there is no other reason for a new segment.  */
3954               new_segment = FALSE;
3955             }
3956           else if (! writable
3957                    && (hdr->flags & SEC_READONLY) == 0
3958                    && (((last_hdr->lma + last_size - 1) & -maxpagesize)
3959                        != (hdr->lma & -maxpagesize)))
3960             {
3961               /* We don't want to put a writable section in a read only
3962                  segment, unless they are on the same page in memory
3963                  anyhow.  We already know that the last section does not
3964                  bring us past the current section on the page, so the
3965                  only case in which the new section is not on the same
3966                  page as the previous section is when the previous section
3967                  ends precisely on a page boundary.  */
3968               new_segment = TRUE;
3969             }
3970           else
3971             {
3972               /* Otherwise, we can use the same segment.  */
3973               new_segment = FALSE;
3974             }
3975
3976           /* Allow interested parties a chance to override our decision.  */
3977           if (last_hdr != NULL
3978               && info != NULL
3979               && info->callbacks->override_segment_assignment != NULL)
3980             new_segment
3981               = info->callbacks->override_segment_assignment (info, abfd, hdr,
3982                                                               last_hdr,
3983                                                               new_segment);
3984
3985           if (! new_segment)
3986             {
3987               if ((hdr->flags & SEC_READONLY) == 0)
3988                 writable = TRUE;
3989               last_hdr = hdr;
3990               /* .tbss sections effectively have zero size.  */
3991               if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
3992                   != SEC_THREAD_LOCAL)
3993                 last_size = hdr->size;
3994               else
3995                 last_size = 0;
3996               continue;
3997             }
3998
3999           /* We need a new program segment.  We must create a new program
4000              header holding all the sections from phdr_index until hdr.  */
4001
4002           m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
4003           if (m == NULL)
4004             goto error_return;
4005
4006           *pm = m;
4007           pm = &m->next;
4008
4009           if ((hdr->flags & SEC_READONLY) == 0)
4010             writable = TRUE;
4011           else
4012             writable = FALSE;
4013
4014           last_hdr = hdr;
4015           /* .tbss sections effectively have zero size.  */
4016           if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
4017             last_size = hdr->size;
4018           else
4019             last_size = 0;
4020           phdr_index = i;
4021           phdr_in_segment = FALSE;
4022         }
4023
4024       /* Create a final PT_LOAD program segment, but not if it's just
4025          for .tbss.  */
4026       if (last_hdr != NULL
4027           && (i - phdr_index != 1
4028               || ((last_hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
4029                   != SEC_THREAD_LOCAL)))
4030         {
4031           m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
4032           if (m == NULL)
4033             goto error_return;
4034
4035           *pm = m;
4036           pm = &m->next;
4037         }
4038
4039       /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
4040       if (dynsec != NULL)
4041         {
4042           m = _bfd_elf_make_dynamic_segment (abfd, dynsec);
4043           if (m == NULL)
4044             goto error_return;
4045           *pm = m;
4046           pm = &m->next;
4047         }
4048
4049       /* For each batch of consecutive loadable .note sections,
4050          add a PT_NOTE segment.  We don't use bfd_get_section_by_name,
4051          because if we link together nonloadable .note sections and
4052          loadable .note sections, we will generate two .note sections
4053          in the output file.  FIXME: Using names for section types is
4054          bogus anyhow.  */
4055       for (s = abfd->sections; s != NULL; s = s->next)
4056         {
4057           if ((s->flags & SEC_LOAD) != 0
4058               && CONST_STRNEQ (s->name, ".note"))
4059             {
4060               asection *s2;
4061
4062               count = 1;
4063               amt = sizeof (struct elf_segment_map);
4064               if (s->alignment_power == 2)
4065                 for (s2 = s; s2->next != NULL; s2 = s2->next)
4066                   {
4067                     if (s2->next->alignment_power == 2
4068                         && (s2->next->flags & SEC_LOAD) != 0
4069                         && CONST_STRNEQ (s2->next->name, ".note")
4070                         && align_power (s2->lma + s2->size, 2)
4071                            == s2->next->lma)
4072                       count++;
4073                     else
4074                       break;
4075                   }
4076               amt += (count - 1) * sizeof (asection *);
4077               m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4078               if (m == NULL)
4079                 goto error_return;
4080               m->next = NULL;
4081               m->p_type = PT_NOTE;
4082               m->count = count;
4083               while (count > 1)
4084                 {
4085                   m->sections[m->count - count--] = s;
4086                   BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
4087                   s = s->next;
4088                 }
4089               m->sections[m->count - 1] = s;
4090               BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
4091               *pm = m;
4092               pm = &m->next;
4093             }
4094           if (s->flags & SEC_THREAD_LOCAL)
4095             {
4096               if (! tls_count)
4097                 first_tls = s;
4098               tls_count++;
4099             }
4100         }
4101
4102       /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
4103       if (tls_count > 0)
4104         {
4105           amt = sizeof (struct elf_segment_map);
4106           amt += (tls_count - 1) * sizeof (asection *);
4107           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4108           if (m == NULL)
4109             goto error_return;
4110           m->next = NULL;
4111           m->p_type = PT_TLS;
4112           m->count = tls_count;
4113           /* Mandated PF_R.  */
4114           m->p_flags = PF_R;
4115           m->p_flags_valid = 1;
4116           for (i = 0; i < (unsigned int) tls_count; ++i)
4117             {
4118               BFD_ASSERT (first_tls->flags & SEC_THREAD_LOCAL);
4119               m->sections[i] = first_tls;
4120               first_tls = first_tls->next;
4121             }
4122
4123           *pm = m;
4124           pm = &m->next;
4125         }
4126
4127       /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
4128          segment.  */
4129       eh_frame_hdr = elf_eh_frame_hdr (abfd);
4130       if (eh_frame_hdr != NULL
4131           && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
4132         {
4133           amt = sizeof (struct elf_segment_map);
4134           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4135           if (m == NULL)
4136             goto error_return;
4137           m->next = NULL;
4138           m->p_type = PT_GNU_EH_FRAME;
4139           m->count = 1;
4140           m->sections[0] = eh_frame_hdr->output_section;
4141
4142           *pm = m;
4143           pm = &m->next;
4144         }
4145
4146       if (elf_stack_flags (abfd))
4147         {
4148           amt = sizeof (struct elf_segment_map);
4149           m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
4150           if (m == NULL)
4151             goto error_return;
4152           m->next = NULL;
4153           m->p_type = PT_GNU_STACK;
4154           m->p_flags = elf_stack_flags (abfd);
4155           m->p_align = bed->stack_align;
4156           m->p_flags_valid = 1;
4157           m->p_align_valid = m->p_align != 0;
4158           if (info->stacksize > 0)
4159             {
4160               m->p_size = info->stacksize;
4161               m->p_size_valid = 1;
4162             }
4163
4164           *pm = m;
4165           pm = &m->next;
4166         }
4167
4168       if (info != NULL && info->relro)
4169         {
4170           for (m = mfirst; m != NULL; m = m->next)
4171             {
4172               if (m->p_type == PT_LOAD
4173                   && m->count != 0
4174                   && m->sections[0]->vma >= info->relro_start
4175                   && m->sections[0]->vma < info->relro_end)
4176                 {
4177                   i = m->count;
4178                   while (--i != (unsigned) -1)
4179                     if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS))
4180                         == (SEC_LOAD | SEC_HAS_CONTENTS))
4181                       break;
4182
4183                   if (i == (unsigned) -1)
4184                     continue;
4185
4186                   if (m->sections[i]->vma + m->sections[i]->size
4187                       >= info->relro_end)
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   return ((vma - off) % maxpagesize);
4313 }
4314
4315 static void
4316 print_segment_map (const struct elf_segment_map *m)
4317 {
4318   unsigned int j;
4319   const char *pt = get_segment_type (m->p_type);
4320   char buf[32];
4321
4322   if (pt == NULL)
4323     {
4324       if (m->p_type >= PT_LOPROC && m->p_type <= PT_HIPROC)
4325         sprintf (buf, "LOPROC+%7.7x",
4326                  (unsigned int) (m->p_type - PT_LOPROC));
4327       else if (m->p_type >= PT_LOOS && m->p_type <= PT_HIOS)
4328         sprintf (buf, "LOOS+%7.7x",
4329                  (unsigned int) (m->p_type - PT_LOOS));
4330       else
4331         snprintf (buf, sizeof (buf), "%8.8x",
4332                   (unsigned int) m->p_type);
4333       pt = buf;
4334     }
4335   fflush (stdout);
4336   fprintf (stderr, "%s:", pt);
4337   for (j = 0; j < m->count; j++)
4338     fprintf (stderr, " %s", m->sections [j]->name);
4339   putc ('\n',stderr);
4340   fflush (stderr);
4341 }
4342
4343 static bfd_boolean
4344 write_zeros (bfd *abfd, file_ptr pos, bfd_size_type len)
4345 {
4346   void *buf;
4347   bfd_boolean ret;
4348
4349   if (bfd_seek (abfd, pos, SEEK_SET) != 0)
4350     return FALSE;
4351   buf = bfd_zmalloc (len);
4352   if (buf == NULL)
4353     return FALSE;
4354   ret = bfd_bwrite (buf, len, abfd) == len;
4355   free (buf);
4356   return ret;
4357 }
4358
4359 /* Assign file positions to the sections based on the mapping from
4360    sections to segments.  This function also sets up some fields in
4361    the file header.  */
4362
4363 static bfd_boolean
4364 assign_file_positions_for_load_sections (bfd *abfd,
4365                                          struct bfd_link_info *link_info)
4366 {
4367   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4368   struct elf_segment_map *m;
4369   Elf_Internal_Phdr *phdrs;
4370   Elf_Internal_Phdr *p;
4371   file_ptr off;
4372   bfd_size_type maxpagesize;
4373   unsigned int alloc;
4374   unsigned int i, j;
4375   bfd_vma header_pad = 0;
4376
4377   if (link_info == NULL
4378       && !_bfd_elf_map_sections_to_segments (abfd, link_info))
4379     return FALSE;
4380
4381   alloc = 0;
4382   for (m = elf_seg_map (abfd); m != NULL; m = m->next)
4383     {
4384       ++alloc;
4385       if (m->header_size)
4386         header_pad = m->header_size;
4387     }
4388
4389   if (alloc)
4390     {
4391       elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
4392       elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
4393     }
4394   else
4395     {
4396       /* PR binutils/12467.  */
4397       elf_elfheader (abfd)->e_phoff = 0;
4398       elf_elfheader (abfd)->e_phentsize = 0;
4399     }
4400
4401   elf_elfheader (abfd)->e_phnum = alloc;
4402
4403   if (elf_program_header_size (abfd) == (bfd_size_type) -1)
4404     elf_program_header_size (abfd) = alloc * bed->s->sizeof_phdr;
4405   else
4406     BFD_ASSERT (elf_program_header_size (abfd)
4407                 >= alloc * bed->s->sizeof_phdr);
4408
4409   if (alloc == 0)
4410     {
4411       elf_next_file_pos (abfd) = bed->s->sizeof_ehdr;
4412       return TRUE;
4413     }
4414
4415   /* We're writing the size in elf_program_header_size (abfd),
4416      see assign_file_positions_except_relocs, so make sure we have
4417      that amount allocated, with trailing space cleared.
4418      The variable alloc contains the computed need, while
4419      elf_program_header_size (abfd) contains the size used for the
4420      layout.
4421      See ld/emultempl/elf-generic.em:gld${EMULATION_NAME}_map_segments
4422      where the layout is forced to according to a larger size in the
4423      last iterations for the testcase ld-elf/header.  */
4424   BFD_ASSERT (elf_program_header_size (abfd) % bed->s->sizeof_phdr
4425               == 0);
4426   phdrs = (Elf_Internal_Phdr *)
4427      bfd_zalloc2 (abfd,
4428                   (elf_program_header_size (abfd) / bed->s->sizeof_phdr),
4429                   sizeof (Elf_Internal_Phdr));
4430   elf_tdata (abfd)->phdr = phdrs;
4431   if (phdrs == NULL)
4432     return FALSE;
4433
4434   maxpagesize = 1;
4435   if ((abfd->flags & D_PAGED) != 0)
4436     maxpagesize = bed->maxpagesize;
4437
4438   off = bed->s->sizeof_ehdr;
4439   off += alloc * bed->s->sizeof_phdr;
4440   if (header_pad < (bfd_vma) off)
4441     header_pad = 0;
4442   else
4443     header_pad -= off;
4444   off += header_pad;
4445
4446   for (m = elf_seg_map (abfd), p = phdrs, j = 0;
4447        m != NULL;
4448        m = m->next, p++, j++)
4449     {
4450       asection **secpp;
4451       bfd_vma off_adjust;
4452       bfd_boolean no_contents;
4453
4454       /* If elf_segment_map is not from map_sections_to_segments, the
4455          sections may not be correctly ordered.  NOTE: sorting should
4456          not be done to the PT_NOTE section of a corefile, which may
4457          contain several pseudo-sections artificially created by bfd.
4458          Sorting these pseudo-sections breaks things badly.  */
4459       if (m->count > 1
4460           && !(elf_elfheader (abfd)->e_type == ET_CORE
4461                && m->p_type == PT_NOTE))
4462         qsort (m->sections, (size_t) m->count, sizeof (asection *),
4463                elf_sort_sections);
4464
4465       /* An ELF segment (described by Elf_Internal_Phdr) may contain a
4466          number of sections with contents contributing to both p_filesz
4467          and p_memsz, followed by a number of sections with no contents
4468          that just contribute to p_memsz.  In this loop, OFF tracks next
4469          available file offset for PT_LOAD and PT_NOTE segments.  */
4470       p->p_type = m->p_type;
4471       p->p_flags = m->p_flags;
4472
4473       if (m->count == 0)
4474         p->p_vaddr = 0;
4475       else
4476         p->p_vaddr = m->sections[0]->vma - m->p_vaddr_offset;
4477
4478       if (m->p_paddr_valid)
4479         p->p_paddr = m->p_paddr;
4480       else if (m->count == 0)
4481         p->p_paddr = 0;
4482       else
4483         p->p_paddr = m->sections[0]->lma - m->p_vaddr_offset;
4484
4485       if (p->p_type == PT_LOAD
4486           && (abfd->flags & D_PAGED) != 0)
4487         {
4488           /* p_align in demand paged PT_LOAD segments effectively stores
4489              the maximum page size.  When copying an executable with
4490              objcopy, we set m->p_align from the input file.  Use this
4491              value for maxpagesize rather than bed->maxpagesize, which
4492              may be different.  Note that we use maxpagesize for PT_TLS
4493              segment alignment later in this function, so we are relying
4494              on at least one PT_LOAD segment appearing before a PT_TLS
4495              segment.  */
4496           if (m->p_align_valid)
4497             maxpagesize = m->p_align;
4498
4499           p->p_align = maxpagesize;
4500         }
4501       else if (m->p_align_valid)
4502         p->p_align = m->p_align;
4503       else if (m->count == 0)
4504         p->p_align = 1 << bed->s->log_file_align;
4505       else
4506         p->p_align = 0;
4507
4508       no_contents = FALSE;
4509       off_adjust = 0;
4510       if (p->p_type == PT_LOAD
4511           && m->count > 0)
4512         {
4513           bfd_size_type align;
4514           unsigned int align_power = 0;
4515
4516           if (m->p_align_valid)
4517             align = p->p_align;
4518           else
4519             {
4520               for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
4521                 {
4522                   unsigned int secalign;
4523
4524                   secalign = bfd_get_section_alignment (abfd, *secpp);
4525                   if (secalign > align_power)
4526                     align_power = secalign;
4527                 }
4528               align = (bfd_size_type) 1 << align_power;
4529               if (align < maxpagesize)
4530                 align = maxpagesize;
4531             }
4532
4533           for (i = 0; i < m->count; i++)
4534             if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
4535               /* If we aren't making room for this section, then
4536                  it must be SHT_NOBITS regardless of what we've
4537                  set via struct bfd_elf_special_section.  */
4538               elf_section_type (m->sections[i]) = SHT_NOBITS;
4539
4540           /* Find out whether this segment contains any loadable
4541              sections.  */
4542           no_contents = TRUE;
4543           for (i = 0; i < m->count; i++)
4544             if (elf_section_type (m->sections[i]) != SHT_NOBITS)
4545               {
4546                 no_contents = FALSE;
4547                 break;
4548               }
4549
4550           off_adjust = vma_page_aligned_bias (p->p_vaddr, off, align);
4551           off += off_adjust;
4552           if (no_contents)
4553             {
4554               /* We shouldn't need to align the segment on disk since
4555                  the segment doesn't need file space, but the gABI
4556                  arguably requires the alignment and glibc ld.so
4557                  checks it.  So to comply with the alignment
4558                  requirement but not waste file space, we adjust
4559                  p_offset for just this segment.  (OFF_ADJUST is
4560                  subtracted from OFF later.)  This may put p_offset
4561                  past the end of file, but that shouldn't matter.  */
4562             }
4563           else
4564             off_adjust = 0;
4565         }
4566       /* Make sure the .dynamic section is the first section in the
4567          PT_DYNAMIC segment.  */
4568       else if (p->p_type == PT_DYNAMIC
4569                && m->count > 1
4570                && strcmp (m->sections[0]->name, ".dynamic") != 0)
4571         {
4572           _bfd_error_handler
4573             (_("%B: The first section in the PT_DYNAMIC segment is not the .dynamic section"),
4574              abfd);
4575           bfd_set_error (bfd_error_bad_value);
4576           return FALSE;
4577         }
4578       /* Set the note section type to SHT_NOTE.  */
4579       else if (p->p_type == PT_NOTE)
4580         for (i = 0; i < m->count; i++)
4581           elf_section_type (m->sections[i]) = SHT_NOTE;
4582
4583       p->p_offset = 0;
4584       p->p_filesz = 0;
4585       p->p_memsz = 0;
4586
4587       if (m->includes_filehdr)
4588         {
4589           if (!m->p_flags_valid)
4590             p->p_flags |= PF_R;
4591           p->p_filesz = bed->s->sizeof_ehdr;
4592           p->p_memsz = bed->s->sizeof_ehdr;
4593           if (m->count > 0)
4594             {
4595               if (p->p_vaddr < (bfd_vma) off)
4596                 {
4597                   (*_bfd_error_handler)
4598                     (_("%B: Not enough room for program headers, try linking with -N"),
4599                      abfd);
4600                   bfd_set_error (bfd_error_bad_value);
4601                   return FALSE;
4602                 }
4603
4604               p->p_vaddr -= off;
4605               if (!m->p_paddr_valid)
4606                 p->p_paddr -= off;
4607             }
4608         }
4609
4610       if (m->includes_phdrs)
4611         {
4612           if (!m->p_flags_valid)
4613             p->p_flags |= PF_R;
4614
4615           if (!m->includes_filehdr)
4616             {
4617               p->p_offset = bed->s->sizeof_ehdr;
4618
4619               if (m->count > 0)
4620                 {
4621                   p->p_vaddr -= off - p->p_offset;
4622                   if (!m->p_paddr_valid)
4623                     p->p_paddr -= off - p->p_offset;
4624                 }
4625             }
4626
4627           p->p_filesz += alloc * bed->s->sizeof_phdr;
4628           p->p_memsz += alloc * bed->s->sizeof_phdr;
4629           if (m->count)
4630             {
4631               p->p_filesz += header_pad;
4632               p->p_memsz += header_pad;
4633             }
4634         }
4635
4636       if (p->p_type == PT_LOAD
4637           || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
4638         {
4639           if (!m->includes_filehdr && !m->includes_phdrs)
4640             p->p_offset = off;
4641           else
4642             {
4643               file_ptr adjust;
4644
4645               adjust = off - (p->p_offset + p->p_filesz);
4646               if (!no_contents)
4647                 p->p_filesz += adjust;
4648               p->p_memsz += adjust;
4649             }
4650         }
4651
4652       /* Set up p_filesz, p_memsz, p_align and p_flags from the section
4653          maps.  Set filepos for sections in PT_LOAD segments, and in
4654          core files, for sections in PT_NOTE segments.
4655          assign_file_positions_for_non_load_sections will set filepos
4656          for other sections and update p_filesz for other segments.  */
4657       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
4658         {
4659           asection *sec;
4660           bfd_size_type align;
4661           Elf_Internal_Shdr *this_hdr;
4662
4663           sec = *secpp;
4664           this_hdr = &elf_section_data (sec)->this_hdr;
4665           align = (bfd_size_type) 1 << bfd_get_section_alignment (abfd, sec);
4666
4667           if ((p->p_type == PT_LOAD
4668                || p->p_type == PT_TLS)
4669               && (this_hdr->sh_type != SHT_NOBITS
4670                   || ((this_hdr->sh_flags & SHF_ALLOC) != 0
4671                       && ((this_hdr->sh_flags & SHF_TLS) == 0
4672                           || p->p_type == PT_TLS))))
4673             {
4674               bfd_vma p_start = p->p_paddr;
4675               bfd_vma p_end = p_start + p->p_memsz;
4676               bfd_vma s_start = sec->lma;
4677               bfd_vma adjust = s_start - p_end;
4678
4679               if (adjust != 0
4680                   && (s_start < p_end
4681                       || p_end < p_start))
4682                 {
4683                   (*_bfd_error_handler)
4684                     (_("%B: section %A lma %#lx adjusted to %#lx"), abfd, sec,
4685                      (unsigned long) s_start, (unsigned long) p_end);
4686                   adjust = 0;
4687                   sec->lma = p_end;
4688                 }
4689               p->p_memsz += adjust;
4690
4691               if (this_hdr->sh_type != SHT_NOBITS)
4692                 {
4693                   if (p->p_filesz + adjust < p->p_memsz)
4694                     {
4695                       /* We have a PROGBITS section following NOBITS ones.
4696                          Allocate file space for the NOBITS section(s) and
4697                          zero it.  */
4698                       adjust = p->p_memsz - p->p_filesz;
4699                       if (!write_zeros (abfd, off, adjust))
4700                         return FALSE;
4701                     }
4702                   off += adjust;
4703                   p->p_filesz += adjust;
4704                 }
4705             }
4706
4707           if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
4708             {
4709               /* The section at i == 0 is the one that actually contains
4710                  everything.  */
4711               if (i == 0)
4712                 {
4713                   this_hdr->sh_offset = sec->filepos = off;
4714                   off += this_hdr->sh_size;
4715                   p->p_filesz = this_hdr->sh_size;
4716                   p->p_memsz = 0;
4717                   p->p_align = 1;
4718                 }
4719               else
4720                 {
4721                   /* The rest are fake sections that shouldn't be written.  */
4722                   sec->filepos = 0;
4723                   sec->size = 0;
4724                   sec->flags = 0;
4725                   continue;
4726                 }
4727             }
4728           else
4729             {
4730               if (p->p_type == PT_LOAD)
4731                 {
4732                   this_hdr->sh_offset = sec->filepos = off;
4733                   if (this_hdr->sh_type != SHT_NOBITS)
4734                     off += this_hdr->sh_size;
4735                 }
4736               else if (this_hdr->sh_type == SHT_NOBITS
4737                        && (this_hdr->sh_flags & SHF_TLS) != 0
4738                        && this_hdr->sh_offset == 0)
4739                 {
4740                   /* This is a .tbss section that didn't get a PT_LOAD.
4741                      (See _bfd_elf_map_sections_to_segments "Create a
4742                      final PT_LOAD".)  Set sh_offset to the value it
4743                      would have if we had created a zero p_filesz and
4744                      p_memsz PT_LOAD header for the section.  This
4745                      also makes the PT_TLS header have the same
4746                      p_offset value.  */
4747                   bfd_vma adjust = vma_page_aligned_bias (this_hdr->sh_addr,
4748                                                           off, align);
4749                   this_hdr->sh_offset = sec->filepos = off + adjust;
4750                 }
4751
4752               if (this_hdr->sh_type != SHT_NOBITS)
4753                 {
4754                   p->p_filesz += this_hdr->sh_size;
4755                   /* A load section without SHF_ALLOC is something like
4756                      a note section in a PT_NOTE segment.  These take
4757                      file space but are not loaded into memory.  */
4758                   if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
4759                     p->p_memsz += this_hdr->sh_size;
4760                 }
4761               else if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
4762                 {
4763                   if (p->p_type == PT_TLS)
4764                     p->p_memsz += this_hdr->sh_size;
4765
4766                   /* .tbss is special.  It doesn't contribute to p_memsz of
4767                      normal segments.  */
4768                   else if ((this_hdr->sh_flags & SHF_TLS) == 0)
4769                     p->p_memsz += this_hdr->sh_size;
4770                 }
4771
4772               if (align > p->p_align
4773                   && !m->p_align_valid
4774                   && (p->p_type != PT_LOAD
4775                       || (abfd->flags & D_PAGED) == 0))
4776                 p->p_align = align;
4777             }
4778
4779           if (!m->p_flags_valid)
4780             {
4781               p->p_flags |= PF_R;
4782               if ((this_hdr->sh_flags & SHF_EXECINSTR) != 0)
4783                 p->p_flags |= PF_X;
4784               if ((this_hdr->sh_flags & SHF_WRITE) != 0)
4785                 p->p_flags |= PF_W;
4786             }
4787         }
4788       off -= off_adjust;
4789
4790       /* Check that all sections are in a PT_LOAD segment.
4791          Don't check funky gdb generated core files.  */
4792       if (p->p_type == PT_LOAD && bfd_get_format (abfd) != bfd_core)
4793         {
4794           bfd_boolean check_vma = TRUE;
4795
4796           for (i = 1; i < m->count; i++)
4797             if (m->sections[i]->vma == m->sections[i - 1]->vma
4798                 && ELF_SECTION_SIZE (&(elf_section_data (m->sections[i])
4799                                        ->this_hdr), p) != 0
4800                 && ELF_SECTION_SIZE (&(elf_section_data (m->sections[i - 1])
4801                                        ->this_hdr), p) != 0)
4802               {
4803                 /* Looks like we have overlays packed into the segment.  */
4804                 check_vma = FALSE;
4805                 break;
4806               }
4807
4808           for (i = 0; i < m->count; i++)
4809             {
4810               Elf_Internal_Shdr *this_hdr;
4811               asection *sec;
4812
4813               sec = m->sections[i];
4814               this_hdr = &(elf_section_data(sec)->this_hdr);
4815               if (!ELF_SECTION_IN_SEGMENT_1 (this_hdr, p, check_vma, 0)
4816                   && !ELF_TBSS_SPECIAL (this_hdr, p))
4817                 {
4818                   (*_bfd_error_handler)
4819                     (_("%B: section `%A' can't be allocated in segment %d"),
4820                      abfd, sec, j);
4821                   print_segment_map (m);
4822                 }
4823             }
4824         }
4825     }
4826
4827   elf_next_file_pos (abfd) = off;
4828   return TRUE;
4829 }
4830
4831 /* Assign file positions for the other sections.  */
4832
4833 static bfd_boolean
4834 assign_file_positions_for_non_load_sections (bfd *abfd,
4835                                              struct bfd_link_info *link_info)
4836 {
4837   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
4838   Elf_Internal_Shdr **i_shdrpp;
4839   Elf_Internal_Shdr **hdrpp;
4840   Elf_Internal_Phdr *phdrs;
4841   Elf_Internal_Phdr *p;
4842   struct elf_segment_map *m;
4843   struct elf_segment_map *hdrs_segment;
4844   bfd_vma filehdr_vaddr, filehdr_paddr;
4845   bfd_vma phdrs_vaddr, phdrs_paddr;
4846   file_ptr off;
4847   unsigned int num_sec;
4848   unsigned int i;
4849   unsigned int count;
4850
4851   i_shdrpp = elf_elfsections (abfd);
4852   num_sec = elf_numsections (abfd);
4853   off = elf_next_file_pos (abfd);
4854   for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
4855     {
4856       Elf_Internal_Shdr *hdr;
4857
4858       hdr = *hdrpp;
4859       if (hdr->bfd_section != NULL
4860           && (hdr->bfd_section->filepos != 0
4861               || (hdr->sh_type == SHT_NOBITS
4862                   && hdr->contents == NULL)))
4863         BFD_ASSERT (hdr->sh_offset == hdr->bfd_section->filepos);
4864       else if ((hdr->sh_flags & SHF_ALLOC) != 0)
4865         {
4866           if (hdr->sh_size != 0)
4867             (*_bfd_error_handler)
4868               (_("%B: warning: allocated section `%s' not in segment"),
4869                abfd,
4870                (hdr->bfd_section == NULL
4871                 ? "*unknown*"
4872                 : hdr->bfd_section->name));
4873           /* We don't need to page align empty sections.  */
4874           if ((abfd->flags & D_PAGED) != 0 && hdr->sh_size != 0)
4875             off += vma_page_aligned_bias (hdr->sh_addr, off,
4876                                           bed->maxpagesize);
4877           else
4878             off += vma_page_aligned_bias (hdr->sh_addr, off,
4879                                           hdr->sh_addralign);
4880           off = _bfd_elf_assign_file_position_for_section (hdr, off,
4881                                                            FALSE);
4882         }
4883       else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
4884                 && hdr->bfd_section == NULL)
4885                || hdr == i_shdrpp[elf_onesymtab (abfd)]
4886                || hdr == i_shdrpp[elf_symtab_shndx (abfd)]
4887                || hdr == i_shdrpp[elf_strtab_sec (abfd)])
4888         hdr->sh_offset = -1;
4889       else
4890         off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
4891     }
4892
4893   /* Now that we have set the section file positions, we can set up
4894      the file positions for the non PT_LOAD segments.  */
4895   count = 0;
4896   filehdr_vaddr = 0;
4897   filehdr_paddr = 0;
4898   phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
4899   phdrs_paddr = 0;
4900   hdrs_segment = NULL;
4901   phdrs = elf_tdata (abfd)->phdr;
4902   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
4903     {
4904       ++count;
4905       if (p->p_type != PT_LOAD)
4906         continue;
4907
4908       if (m->includes_filehdr)
4909         {
4910           filehdr_vaddr = p->p_vaddr;
4911           filehdr_paddr = p->p_paddr;
4912         }
4913       if (m->includes_phdrs)
4914         {
4915           phdrs_vaddr = p->p_vaddr;
4916           phdrs_paddr = p->p_paddr;
4917           if (m->includes_filehdr)
4918             {
4919               hdrs_segment = m;
4920               phdrs_vaddr += bed->s->sizeof_ehdr;
4921               phdrs_paddr += bed->s->sizeof_ehdr;
4922             }
4923         }
4924     }
4925
4926   if (hdrs_segment != NULL && link_info != NULL)
4927     {
4928       /* There is a segment that contains both the file headers and the
4929          program headers, so provide a symbol __ehdr_start pointing there.
4930          A program can use this to examine itself robustly.  */
4931
4932       struct elf_link_hash_entry *hash
4933         = elf_link_hash_lookup (elf_hash_table (link_info), "__ehdr_start",
4934                                 FALSE, FALSE, TRUE);
4935       /* If the symbol was referenced and not defined, define it.  */
4936       if (hash != NULL
4937           && (hash->root.type == bfd_link_hash_new
4938               || hash->root.type == bfd_link_hash_undefined
4939               || hash->root.type == bfd_link_hash_undefweak
4940               || hash->root.type == bfd_link_hash_common))
4941         {
4942           asection *s = NULL;
4943           if (hdrs_segment->count != 0)
4944             /* The segment contains sections, so use the first one.  */
4945             s = hdrs_segment->sections[0];
4946           else
4947             /* Use the first (i.e. lowest-addressed) section in any segment.  */
4948             for (m = elf_seg_map (abfd); m != NULL; m = m->next)
4949               if (m->count != 0)
4950                 {
4951                   s = m->sections[0];
4952                   break;
4953                 }
4954
4955           if (s != NULL)
4956             {
4957               hash->root.u.def.value = filehdr_vaddr - s->vma;
4958               hash->root.u.def.section = s;
4959             }
4960           else
4961             {
4962               hash->root.u.def.value = filehdr_vaddr;
4963               hash->root.u.def.section = bfd_abs_section_ptr;
4964             }
4965
4966           hash->root.type = bfd_link_hash_defined;
4967           hash->def_regular = 1;
4968           hash->non_elf = 0;
4969         }
4970     }
4971
4972   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
4973     {
4974       if (p->p_type == PT_GNU_RELRO)
4975         {
4976           const Elf_Internal_Phdr *lp;
4977           struct elf_segment_map *lm;
4978
4979           if (link_info != NULL)
4980             {
4981               /* During linking the range of the RELRO segment is passed
4982                  in link_info.  */
4983               for (lm = elf_seg_map (abfd), lp = phdrs;
4984                    lm != NULL;
4985                    lm = lm->next, lp++)
4986                 {
4987                   if (lp->p_type == PT_LOAD
4988                       && lp->p_vaddr < link_info->relro_end
4989                       && lp->p_vaddr + lp->p_filesz >= link_info->relro_end
4990                       && lm->count != 0
4991                       && lm->sections[0]->vma >= link_info->relro_start)
4992                     break;
4993                 }
4994
4995               /* PR ld/14207.  If the RELRO segment doesn't fit in the
4996                  LOAD segment, it should be removed.  */
4997               BFD_ASSERT (lm != NULL);
4998             }
4999           else
5000             {
5001               /* Otherwise we are copying an executable or shared
5002                  library, but we need to use the same linker logic.  */
5003               for (lp = phdrs; lp < phdrs + count; ++lp)
5004                 {
5005                   if (lp->p_type == PT_LOAD
5006                       && lp->p_paddr == p->p_paddr)
5007                     break;
5008                 }
5009             }
5010
5011           if (lp < phdrs + count)
5012             {
5013               p->p_vaddr = lp->p_vaddr;
5014               p->p_paddr = lp->p_paddr;
5015               p->p_offset = lp->p_offset;
5016               if (link_info != NULL)
5017                 p->p_filesz = link_info->relro_end - lp->p_vaddr;
5018               else if (m->p_size_valid)
5019                 p->p_filesz = m->p_size;
5020               else
5021                 abort ();
5022               p->p_memsz = p->p_filesz;
5023               /* Preserve the alignment and flags if they are valid. The
5024                  gold linker generates RW/4 for the PT_GNU_RELRO section.
5025                  It is better for objcopy/strip to honor these attributes
5026                  otherwise gdb will choke when using separate debug files.
5027                */
5028               if (!m->p_align_valid)
5029                 p->p_align = 1;
5030               if (!m->p_flags_valid)
5031                 p->p_flags = (lp->p_flags & ~PF_W);
5032             }
5033           else
5034             {
5035               memset (p, 0, sizeof *p);
5036               p->p_type = PT_NULL;
5037             }
5038         }
5039       else if (p->p_type == PT_GNU_STACK)
5040         {
5041           if (m->p_size_valid)
5042             p->p_memsz = m->p_size;
5043         }
5044       else if (m->count != 0)
5045         {
5046           if (p->p_type != PT_LOAD
5047               && (p->p_type != PT_NOTE
5048                   || bfd_get_format (abfd) != bfd_core))
5049             {
5050               BFD_ASSERT (!m->includes_filehdr && !m->includes_phdrs);
5051
5052               p->p_filesz = 0;
5053               p->p_offset = m->sections[0]->filepos;
5054               for (i = m->count; i-- != 0;)
5055                 {
5056                   asection *sect = m->sections[i];
5057                   Elf_Internal_Shdr *hdr = &elf_section_data (sect)->this_hdr;
5058                   if (hdr->sh_type != SHT_NOBITS)
5059                     {
5060                       p->p_filesz = (sect->filepos - m->sections[0]->filepos
5061                                      + hdr->sh_size);
5062                       break;
5063                     }
5064                 }
5065             }
5066         }
5067       else if (m->includes_filehdr)
5068         {
5069           p->p_vaddr = filehdr_vaddr;
5070           if (! m->p_paddr_valid)
5071             p->p_paddr = filehdr_paddr;
5072         }
5073       else if (m->includes_phdrs)
5074         {
5075           p->p_vaddr = phdrs_vaddr;
5076           if (! m->p_paddr_valid)
5077             p->p_paddr = phdrs_paddr;
5078         }
5079     }
5080
5081   elf_next_file_pos (abfd) = off;
5082
5083   return TRUE;
5084 }
5085
5086 /* Work out the file positions of all the sections.  This is called by
5087    _bfd_elf_compute_section_file_positions.  All the section sizes and
5088    VMAs must be known before this is called.
5089
5090    Reloc sections come in two flavours: Those processed specially as
5091    "side-channel" data attached to a section to which they apply, and
5092    those that bfd doesn't process as relocations.  The latter sort are
5093    stored in a normal bfd section by bfd_section_from_shdr.   We don't
5094    consider the former sort here, unless they form part of the loadable
5095    image.  Reloc sections not assigned here will be handled later by
5096    assign_file_positions_for_relocs.
5097
5098    We also don't set the positions of the .symtab and .strtab here.  */
5099
5100 static bfd_boolean
5101 assign_file_positions_except_relocs (bfd *abfd,
5102                                      struct bfd_link_info *link_info)
5103 {
5104   struct elf_obj_tdata *tdata = elf_tdata (abfd);
5105   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
5106   file_ptr off;
5107   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5108
5109   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
5110       && bfd_get_format (abfd) != bfd_core)
5111     {
5112       Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
5113       unsigned int num_sec = elf_numsections (abfd);
5114       Elf_Internal_Shdr **hdrpp;
5115       unsigned int i;
5116
5117       /* Start after the ELF header.  */
5118       off = i_ehdrp->e_ehsize;
5119
5120       /* We are not creating an executable, which means that we are
5121          not creating a program header, and that the actual order of
5122          the sections in the file is unimportant.  */
5123       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
5124         {
5125           Elf_Internal_Shdr *hdr;
5126
5127           hdr = *hdrpp;
5128           if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
5129                && hdr->bfd_section == NULL)
5130               || i == elf_onesymtab (abfd)
5131               || i == elf_symtab_shndx (abfd)
5132               || i == elf_strtab_sec (abfd))
5133             {
5134               hdr->sh_offset = -1;
5135             }
5136           else
5137             off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
5138         }
5139     }
5140   else
5141     {
5142       unsigned int alloc;
5143
5144       /* Assign file positions for the loaded sections based on the
5145          assignment of sections to segments.  */
5146       if (!assign_file_positions_for_load_sections (abfd, link_info))
5147         return FALSE;
5148
5149       /* And for non-load sections.  */
5150       if (!assign_file_positions_for_non_load_sections (abfd, link_info))
5151         return FALSE;
5152
5153       if (bed->elf_backend_modify_program_headers != NULL)
5154         {
5155           if (!(*bed->elf_backend_modify_program_headers) (abfd, link_info))
5156             return FALSE;
5157         }
5158
5159       /* Set e_type in ELF header to ET_EXEC for -pie -Ttext-segment=.  */
5160       if (link_info != NULL
5161           && link_info->executable
5162           && link_info->shared)
5163         {
5164           unsigned int num_segments = elf_elfheader (abfd)->e_phnum;
5165           Elf_Internal_Phdr *segment = elf_tdata (abfd)->phdr;
5166           Elf_Internal_Phdr *end_segment = &segment[num_segments];
5167
5168           /* Find the lowest p_vaddr in PT_LOAD segments.  */
5169           bfd_vma p_vaddr = (bfd_vma) -1;
5170           for (; segment < end_segment; segment++)
5171             if (segment->p_type == PT_LOAD && p_vaddr > segment->p_vaddr)
5172               p_vaddr = segment->p_vaddr;
5173
5174           /* Set e_type to ET_EXEC if the lowest p_vaddr in PT_LOAD
5175              segments is non-zero.  */
5176           if (p_vaddr)
5177             i_ehdrp->e_type = ET_EXEC;
5178         }
5179
5180       /* Write out the program headers.  */
5181       alloc = elf_program_header_size (abfd) / bed->s->sizeof_phdr;
5182       if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
5183           || bed->s->write_out_phdrs (abfd, tdata->phdr, alloc) != 0)
5184         return FALSE;
5185
5186       off = elf_next_file_pos (abfd);
5187     }
5188
5189   /* Place the section headers.  */
5190   off = align_file_position (off, 1 << bed->s->log_file_align);
5191   i_ehdrp->e_shoff = off;
5192   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
5193
5194   elf_next_file_pos (abfd) = off;
5195
5196   return TRUE;
5197 }
5198
5199 static bfd_boolean
5200 prep_headers (bfd *abfd)
5201 {
5202   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form.  */
5203   struct elf_strtab_hash *shstrtab;
5204   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5205
5206   i_ehdrp = elf_elfheader (abfd);
5207
5208   shstrtab = _bfd_elf_strtab_init ();
5209   if (shstrtab == NULL)
5210     return FALSE;
5211
5212   elf_shstrtab (abfd) = shstrtab;
5213
5214   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
5215   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
5216   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
5217   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
5218
5219   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
5220   i_ehdrp->e_ident[EI_DATA] =
5221     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
5222   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
5223
5224   if ((abfd->flags & DYNAMIC) != 0)
5225     i_ehdrp->e_type = ET_DYN;
5226   else if ((abfd->flags & EXEC_P) != 0)
5227     i_ehdrp->e_type = ET_EXEC;
5228   else if (bfd_get_format (abfd) == bfd_core)
5229     i_ehdrp->e_type = ET_CORE;
5230   else
5231     i_ehdrp->e_type = ET_REL;
5232
5233   switch (bfd_get_arch (abfd))
5234     {
5235     case bfd_arch_unknown:
5236       i_ehdrp->e_machine = EM_NONE;
5237       break;
5238
5239       /* There used to be a long list of cases here, each one setting
5240          e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
5241          in the corresponding bfd definition.  To avoid duplication,
5242          the switch was removed.  Machines that need special handling
5243          can generally do it in elf_backend_final_write_processing(),
5244          unless they need the information earlier than the final write.
5245          Such need can generally be supplied by replacing the tests for
5246          e_machine with the conditions used to determine it.  */
5247     default:
5248       i_ehdrp->e_machine = bed->elf_machine_code;
5249     }
5250
5251   i_ehdrp->e_version = bed->s->ev_current;
5252   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
5253
5254   /* No program header, for now.  */
5255   i_ehdrp->e_phoff = 0;
5256   i_ehdrp->e_phentsize = 0;
5257   i_ehdrp->e_phnum = 0;
5258
5259   /* Each bfd section is section header entry.  */
5260   i_ehdrp->e_entry = bfd_get_start_address (abfd);
5261   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
5262
5263   /* If we're building an executable, we'll need a program header table.  */
5264   if (abfd->flags & EXEC_P)
5265     /* It all happens later.  */
5266     ;
5267   else
5268     {
5269       i_ehdrp->e_phentsize = 0;
5270       i_ehdrp->e_phoff = 0;
5271     }
5272
5273   elf_tdata (abfd)->symtab_hdr.sh_name =
5274     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", FALSE);
5275   elf_tdata (abfd)->strtab_hdr.sh_name =
5276     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", FALSE);
5277   elf_tdata (abfd)->shstrtab_hdr.sh_name =
5278     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", FALSE);
5279   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
5280       || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
5281       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
5282     return FALSE;
5283
5284   return TRUE;
5285 }
5286
5287 /* Assign file positions for all the reloc sections which are not part
5288    of the loadable file image.  */
5289
5290 void
5291 _bfd_elf_assign_file_positions_for_relocs (bfd *abfd)
5292 {
5293   file_ptr off;
5294   unsigned int i, num_sec;
5295   Elf_Internal_Shdr **shdrpp;
5296
5297   off = elf_next_file_pos (abfd);
5298
5299   num_sec = elf_numsections (abfd);
5300   for (i = 1, shdrpp = elf_elfsections (abfd) + 1; i < num_sec; i++, shdrpp++)
5301     {
5302       Elf_Internal_Shdr *shdrp;
5303
5304       shdrp = *shdrpp;
5305       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
5306           && shdrp->sh_offset == -1)
5307         off = _bfd_elf_assign_file_position_for_section (shdrp, off, TRUE);
5308     }
5309
5310   elf_next_file_pos (abfd) = off;
5311 }
5312
5313 bfd_boolean
5314 _bfd_elf_write_object_contents (bfd *abfd)
5315 {
5316   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
5317   Elf_Internal_Shdr **i_shdrp;
5318   bfd_boolean failed;
5319   unsigned int count, num_sec;
5320   struct elf_obj_tdata *t;
5321
5322   if (! abfd->output_has_begun
5323       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
5324     return FALSE;
5325
5326   i_shdrp = elf_elfsections (abfd);
5327
5328   failed = FALSE;
5329   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
5330   if (failed)
5331     return FALSE;
5332
5333   _bfd_elf_assign_file_positions_for_relocs (abfd);
5334
5335   /* After writing the headers, we need to write the sections too...  */
5336   num_sec = elf_numsections (abfd);
5337   for (count = 1; count < num_sec; count++)
5338     {
5339       if (bed->elf_backend_section_processing)
5340         (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
5341       if (i_shdrp[count]->contents)
5342         {
5343           bfd_size_type amt = i_shdrp[count]->sh_size;
5344
5345           if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
5346               || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
5347             return FALSE;
5348         }
5349     }
5350
5351   /* Write out the section header names.  */
5352   t = elf_tdata (abfd);
5353   if (elf_shstrtab (abfd) != NULL
5354       && (bfd_seek (abfd, t->shstrtab_hdr.sh_offset, SEEK_SET) != 0
5355           || !_bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd))))
5356     return FALSE;
5357
5358   if (bed->elf_backend_final_write_processing)
5359     (*bed->elf_backend_final_write_processing) (abfd, elf_linker (abfd));
5360
5361   if (!bed->s->write_shdrs_and_ehdr (abfd))
5362     return FALSE;
5363
5364   /* This is last since write_shdrs_and_ehdr can touch i_shdrp[0].  */
5365   if (t->o->build_id.after_write_object_contents != NULL)
5366     return (*t->o->build_id.after_write_object_contents) (abfd);
5367
5368   return TRUE;
5369 }
5370
5371 bfd_boolean
5372 _bfd_elf_write_corefile_contents (bfd *abfd)
5373 {
5374   /* Hopefully this can be done just like an object file.  */
5375   return _bfd_elf_write_object_contents (abfd);
5376 }
5377
5378 /* Given a section, search the header to find them.  */
5379
5380 unsigned int
5381 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
5382 {
5383   const struct elf_backend_data *bed;
5384   unsigned int sec_index;
5385
5386   if (elf_section_data (asect) != NULL
5387       && elf_section_data (asect)->this_idx != 0)
5388     return elf_section_data (asect)->this_idx;
5389
5390   if (bfd_is_abs_section (asect))
5391     sec_index = SHN_ABS;
5392   else if (bfd_is_com_section (asect))
5393     sec_index = SHN_COMMON;
5394   else if (bfd_is_und_section (asect))
5395     sec_index = SHN_UNDEF;
5396   else
5397     sec_index = SHN_BAD;
5398
5399   bed = get_elf_backend_data (abfd);
5400   if (bed->elf_backend_section_from_bfd_section)
5401     {
5402       int retval = sec_index;
5403
5404       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
5405         return retval;
5406     }
5407
5408   if (sec_index == SHN_BAD)
5409     bfd_set_error (bfd_error_nonrepresentable_section);
5410
5411   return sec_index;
5412 }
5413
5414 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
5415    on error.  */
5416
5417 int
5418 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
5419 {
5420   asymbol *asym_ptr = *asym_ptr_ptr;
5421   int idx;
5422   flagword flags = asym_ptr->flags;
5423
5424   /* When gas creates relocations against local labels, it creates its
5425      own symbol for the section, but does put the symbol into the
5426      symbol chain, so udata is 0.  When the linker is generating
5427      relocatable output, this section symbol may be for one of the
5428      input sections rather than the output section.  */
5429   if (asym_ptr->udata.i == 0
5430       && (flags & BSF_SECTION_SYM)
5431       && asym_ptr->section)
5432     {
5433       asection *sec;
5434       int indx;
5435
5436       sec = asym_ptr->section;
5437       if (sec->owner != abfd && sec->output_section != NULL)
5438         sec = sec->output_section;
5439       if (sec->owner == abfd
5440           && (indx = sec->index) < elf_num_section_syms (abfd)
5441           && elf_section_syms (abfd)[indx] != NULL)
5442         asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
5443     }
5444
5445   idx = asym_ptr->udata.i;
5446
5447   if (idx == 0)
5448     {
5449       /* This case can occur when using --strip-symbol on a symbol
5450          which is used in a relocation entry.  */
5451       (*_bfd_error_handler)
5452         (_("%B: symbol `%s' required but not present"),
5453          abfd, bfd_asymbol_name (asym_ptr));
5454       bfd_set_error (bfd_error_no_symbols);
5455       return -1;
5456     }
5457
5458 #if DEBUG & 4
5459   {
5460     fprintf (stderr,
5461              "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx\n",
5462              (long) asym_ptr, asym_ptr->name, idx, (long) flags);
5463     fflush (stderr);
5464   }
5465 #endif
5466
5467   return idx;
5468 }
5469
5470 /* Rewrite program header information.  */
5471
5472 static bfd_boolean
5473 rewrite_elf_program_header (bfd *ibfd, bfd *obfd)
5474 {
5475   Elf_Internal_Ehdr *iehdr;
5476   struct elf_segment_map *map;
5477   struct elf_segment_map *map_first;
5478   struct elf_segment_map **pointer_to_map;
5479   Elf_Internal_Phdr *segment;
5480   asection *section;
5481   unsigned int i;
5482   unsigned int num_segments;
5483   bfd_boolean phdr_included = FALSE;
5484   bfd_boolean p_paddr_valid;
5485   bfd_vma maxpagesize;
5486   struct elf_segment_map *phdr_adjust_seg = NULL;
5487   unsigned int phdr_adjust_num = 0;
5488   const struct elf_backend_data *bed;
5489
5490   bed = get_elf_backend_data (ibfd);
5491   iehdr = elf_elfheader (ibfd);
5492
5493   map_first = NULL;
5494   pointer_to_map = &map_first;
5495
5496   num_segments = elf_elfheader (ibfd)->e_phnum;
5497   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
5498
5499   /* Returns the end address of the segment + 1.  */
5500 #define SEGMENT_END(segment, start)                                     \
5501   (start + (segment->p_memsz > segment->p_filesz                        \
5502             ? segment->p_memsz : segment->p_filesz))
5503
5504 #define SECTION_SIZE(section, segment)                                  \
5505   (((section->flags & (SEC_HAS_CONTENTS | SEC_THREAD_LOCAL))            \
5506     != SEC_THREAD_LOCAL || segment->p_type == PT_TLS)                   \
5507    ? section->size : 0)
5508
5509   /* Returns TRUE if the given section is contained within
5510      the given segment.  VMA addresses are compared.  */
5511 #define IS_CONTAINED_BY_VMA(section, segment)                           \
5512   (section->vma >= segment->p_vaddr                                     \
5513    && (section->vma + SECTION_SIZE (section, segment)                   \
5514        <= (SEGMENT_END (segment, segment->p_vaddr))))
5515
5516   /* Returns TRUE if the given section is contained within
5517      the given segment.  LMA addresses are compared.  */
5518 #define IS_CONTAINED_BY_LMA(section, segment, base)                     \
5519   (section->lma >= base                                                 \
5520    && (section->lma + SECTION_SIZE (section, segment)                   \
5521        <= SEGMENT_END (segment, base)))
5522
5523   /* Handle PT_NOTE segment.  */
5524 #define IS_NOTE(p, s)                                                   \
5525   (p->p_type == PT_NOTE                                                 \
5526    && elf_section_type (s) == SHT_NOTE                                  \
5527    && (bfd_vma) s->filepos >= p->p_offset                               \
5528    && ((bfd_vma) s->filepos + s->size                                   \
5529        <= p->p_offset + p->p_filesz))
5530
5531   /* Special case: corefile "NOTE" section containing regs, prpsinfo
5532      etc.  */
5533 #define IS_COREFILE_NOTE(p, s)                                          \
5534   (IS_NOTE (p, s)                                                       \
5535    && bfd_get_format (ibfd) == bfd_core                                 \
5536    && s->vma == 0                                                       \
5537    && s->lma == 0)
5538
5539   /* The complicated case when p_vaddr is 0 is to handle the Solaris
5540      linker, which generates a PT_INTERP section with p_vaddr and
5541      p_memsz set to 0.  */
5542 #define IS_SOLARIS_PT_INTERP(p, s)                                      \
5543   (p->p_vaddr == 0                                                      \
5544    && p->p_paddr == 0                                                   \
5545    && p->p_memsz == 0                                                   \
5546    && p->p_filesz > 0                                                   \
5547    && (s->flags & SEC_HAS_CONTENTS) != 0                                \
5548    && s->size > 0                                                       \
5549    && (bfd_vma) s->filepos >= p->p_offset                               \
5550    && ((bfd_vma) s->filepos + s->size                                   \
5551        <= p->p_offset + p->p_filesz))
5552
5553   /* Decide if the given section should be included in the given segment.
5554      A section will be included if:
5555        1. It is within the address space of the segment -- we use the LMA
5556           if that is set for the segment and the VMA otherwise,
5557        2. It is an allocated section or a NOTE section in a PT_NOTE
5558           segment.
5559        3. There is an output section associated with it,
5560        4. The section has not already been allocated to a previous segment.
5561        5. PT_GNU_STACK segments do not include any sections.
5562        6. PT_TLS segment includes only SHF_TLS sections.
5563        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.
5564        8. PT_DYNAMIC should not contain empty sections at the beginning
5565           (with the possible exception of .dynamic).  */
5566 #define IS_SECTION_IN_INPUT_SEGMENT(section, segment, bed)              \
5567   ((((segment->p_paddr                                                  \
5568       ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)        \
5569       : IS_CONTAINED_BY_VMA (section, segment))                         \
5570      && (section->flags & SEC_ALLOC) != 0)                              \
5571     || IS_NOTE (segment, section))                                      \
5572    && segment->p_type != PT_GNU_STACK                                   \
5573    && (segment->p_type != PT_TLS                                        \
5574        || (section->flags & SEC_THREAD_LOCAL))                          \
5575    && (segment->p_type == PT_LOAD                                       \
5576        || segment->p_type == PT_TLS                                     \
5577        || (section->flags & SEC_THREAD_LOCAL) == 0)                     \
5578    && (segment->p_type != PT_DYNAMIC                                    \
5579        || SECTION_SIZE (section, segment) > 0                           \
5580        || (segment->p_paddr                                             \
5581            ? segment->p_paddr != section->lma                           \
5582            : segment->p_vaddr != section->vma)                          \
5583        || (strcmp (bfd_get_section_name (ibfd, section), ".dynamic")    \
5584            == 0))                                                       \
5585    && !section->segment_mark)
5586
5587 /* If the output section of a section in the input segment is NULL,
5588    it is removed from the corresponding output segment.   */
5589 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)               \
5590   (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed)          \
5591    && section->output_section != NULL)
5592
5593   /* Returns TRUE iff seg1 starts after the end of seg2.  */
5594 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)                        \
5595   (seg1->field >= SEGMENT_END (seg2, seg2->field))
5596
5597   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
5598      their VMA address ranges and their LMA address ranges overlap.
5599      It is possible to have overlapping VMA ranges without overlapping LMA
5600      ranges.  RedBoot images for example can have both .data and .bss mapped
5601      to the same VMA range, but with the .data section mapped to a different
5602      LMA.  */
5603 #define SEGMENT_OVERLAPS(seg1, seg2)                                    \
5604   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)                     \
5605         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))                 \
5606    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)                     \
5607         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
5608
5609   /* Initialise the segment mark field.  */
5610   for (section = ibfd->sections; section != NULL; section = section->next)
5611     section->segment_mark = FALSE;
5612
5613   /* The Solaris linker creates program headers in which all the
5614      p_paddr fields are zero.  When we try to objcopy or strip such a
5615      file, we get confused.  Check for this case, and if we find it
5616      don't set the p_paddr_valid fields.  */
5617   p_paddr_valid = FALSE;
5618   for (i = 0, segment = elf_tdata (ibfd)->phdr;
5619        i < num_segments;
5620        i++, segment++)
5621     if (segment->p_paddr != 0)
5622       {
5623         p_paddr_valid = TRUE;
5624         break;
5625       }
5626
5627   /* Scan through the segments specified in the program header
5628      of the input BFD.  For this first scan we look for overlaps
5629      in the loadable segments.  These can be created by weird
5630      parameters to objcopy.  Also, fix some solaris weirdness.  */
5631   for (i = 0, segment = elf_tdata (ibfd)->phdr;
5632        i < num_segments;
5633        i++, segment++)
5634     {
5635       unsigned int j;
5636       Elf_Internal_Phdr *segment2;
5637
5638       if (segment->p_type == PT_INTERP)
5639         for (section = ibfd->sections; section; section = section->next)
5640           if (IS_SOLARIS_PT_INTERP (segment, section))
5641             {
5642               /* Mininal change so that the normal section to segment
5643                  assignment code will work.  */
5644               segment->p_vaddr = section->vma;
5645               break;
5646             }
5647
5648       if (segment->p_type != PT_LOAD)
5649         {
5650           /* Remove PT_GNU_RELRO segment.  */
5651           if (segment->p_type == PT_GNU_RELRO)
5652             segment->p_type = PT_NULL;
5653           continue;
5654         }
5655
5656       /* Determine if this segment overlaps any previous segments.  */
5657       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2++)
5658         {
5659           bfd_signed_vma extra_length;
5660
5661           if (segment2->p_type != PT_LOAD
5662               || !SEGMENT_OVERLAPS (segment, segment2))
5663             continue;
5664
5665           /* Merge the two segments together.  */
5666           if (segment2->p_vaddr < segment->p_vaddr)
5667             {
5668               /* Extend SEGMENT2 to include SEGMENT and then delete
5669                  SEGMENT.  */
5670               extra_length = (SEGMENT_END (segment, segment->p_vaddr)
5671                               - SEGMENT_END (segment2, segment2->p_vaddr));
5672
5673               if (extra_length > 0)
5674                 {
5675                   segment2->p_memsz += extra_length;
5676                   segment2->p_filesz += extra_length;
5677                 }
5678
5679               segment->p_type = PT_NULL;
5680
5681               /* Since we have deleted P we must restart the outer loop.  */
5682               i = 0;
5683               segment = elf_tdata (ibfd)->phdr;
5684               break;
5685             }
5686           else
5687             {
5688               /* Extend SEGMENT to include SEGMENT2 and then delete
5689                  SEGMENT2.  */
5690               extra_length = (SEGMENT_END (segment2, segment2->p_vaddr)
5691                               - SEGMENT_END (segment, segment->p_vaddr));
5692
5693               if (extra_length > 0)
5694                 {
5695                   segment->p_memsz += extra_length;
5696                   segment->p_filesz += extra_length;
5697                 }
5698
5699               segment2->p_type = PT_NULL;
5700             }
5701         }
5702     }
5703
5704   /* The second scan attempts to assign sections to segments.  */
5705   for (i = 0, segment = elf_tdata (ibfd)->phdr;
5706        i < num_segments;
5707        i++, segment++)
5708     {
5709       unsigned int section_count;
5710       asection **sections;
5711       asection *output_section;
5712       unsigned int isec;
5713       bfd_vma matching_lma;
5714       bfd_vma suggested_lma;
5715       unsigned int j;
5716       bfd_size_type amt;
5717       asection *first_section;
5718       bfd_boolean first_matching_lma;
5719       bfd_boolean first_suggested_lma;
5720
5721       if (segment->p_type == PT_NULL)
5722         continue;
5723
5724       first_section = NULL;
5725       /* Compute how many sections might be placed into this segment.  */
5726       for (section = ibfd->sections, section_count = 0;
5727            section != NULL;
5728            section = section->next)
5729         {
5730           /* Find the first section in the input segment, which may be
5731              removed from the corresponding output segment.   */
5732           if (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed))
5733             {
5734               if (first_section == NULL)
5735                 first_section = section;
5736               if (section->output_section != NULL)
5737                 ++section_count;
5738             }
5739         }
5740
5741       /* Allocate a segment map big enough to contain
5742          all of the sections we have selected.  */
5743       amt = sizeof (struct elf_segment_map);
5744       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
5745       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
5746       if (map == NULL)
5747         return FALSE;
5748
5749       /* Initialise the fields of the segment map.  Default to
5750          using the physical address of the segment in the input BFD.  */
5751       map->next = NULL;
5752       map->p_type = segment->p_type;
5753       map->p_flags = segment->p_flags;
5754       map->p_flags_valid = 1;
5755
5756       /* If the first section in the input segment is removed, there is
5757          no need to preserve segment physical address in the corresponding
5758          output segment.  */
5759       if (!first_section || first_section->output_section != NULL)
5760         {
5761           map->p_paddr = segment->p_paddr;
5762           map->p_paddr_valid = p_paddr_valid;
5763         }
5764
5765       /* Determine if this segment contains the ELF file header
5766          and if it contains the program headers themselves.  */
5767       map->includes_filehdr = (segment->p_offset == 0
5768                                && segment->p_filesz >= iehdr->e_ehsize);
5769       map->includes_phdrs = 0;
5770
5771       if (!phdr_included || segment->p_type != PT_LOAD)
5772         {
5773           map->includes_phdrs =
5774             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
5775              && (segment->p_offset + segment->p_filesz
5776                  >= ((bfd_vma) iehdr->e_phoff
5777                      + iehdr->e_phnum * iehdr->e_phentsize)));
5778
5779           if (segment->p_type == PT_LOAD && map->includes_phdrs)
5780             phdr_included = TRUE;
5781         }
5782
5783       if (section_count == 0)
5784         {
5785           /* Special segments, such as the PT_PHDR segment, may contain
5786              no sections, but ordinary, loadable segments should contain
5787              something.  They are allowed by the ELF spec however, so only
5788              a warning is produced.  */
5789           if (segment->p_type == PT_LOAD)
5790             (*_bfd_error_handler) (_("%B: warning: Empty loadable segment"
5791                                      " detected, is this intentional ?\n"),
5792                                    ibfd);
5793
5794           map->count = 0;
5795           *pointer_to_map = map;
5796           pointer_to_map = &map->next;
5797
5798           continue;
5799         }
5800
5801       /* Now scan the sections in the input BFD again and attempt
5802          to add their corresponding output sections to the segment map.
5803          The problem here is how to handle an output section which has
5804          been moved (ie had its LMA changed).  There are four possibilities:
5805
5806          1. None of the sections have been moved.
5807             In this case we can continue to use the segment LMA from the
5808             input BFD.
5809
5810          2. All of the sections have been moved by the same amount.
5811             In this case we can change the segment's LMA to match the LMA
5812             of the first section.
5813
5814          3. Some of the sections have been moved, others have not.
5815             In this case those sections which have not been moved can be
5816             placed in the current segment which will have to have its size,
5817             and possibly its LMA changed, and a new segment or segments will
5818             have to be created to contain the other sections.
5819
5820          4. The sections have been moved, but not by the same amount.
5821             In this case we can change the segment's LMA to match the LMA
5822             of the first section and we will have to create a new segment
5823             or segments to contain the other sections.
5824
5825          In order to save time, we allocate an array to hold the section
5826          pointers that we are interested in.  As these sections get assigned
5827          to a segment, they are removed from this array.  */
5828
5829       sections = (asection **) bfd_malloc2 (section_count, sizeof (asection *));
5830       if (sections == NULL)
5831         return FALSE;
5832
5833       /* Step One: Scan for segment vs section LMA conflicts.
5834          Also add the sections to the section array allocated above.
5835          Also add the sections to the current segment.  In the common
5836          case, where the sections have not been moved, this means that
5837          we have completely filled the segment, and there is nothing
5838          more to do.  */
5839       isec = 0;
5840       matching_lma = 0;
5841       suggested_lma = 0;
5842       first_matching_lma = TRUE;
5843       first_suggested_lma = TRUE;
5844
5845       for (section = ibfd->sections;
5846            section != NULL;
5847            section = section->next)
5848         if (section == first_section)
5849           break;
5850
5851       for (j = 0; section != NULL; section = section->next)
5852         {
5853           if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
5854             {
5855               output_section = section->output_section;
5856
5857               sections[j++] = section;
5858
5859               /* The Solaris native linker always sets p_paddr to 0.
5860                  We try to catch that case here, and set it to the
5861                  correct value.  Note - some backends require that
5862                  p_paddr be left as zero.  */
5863               if (!p_paddr_valid
5864                   && segment->p_vaddr != 0
5865                   && !bed->want_p_paddr_set_to_zero
5866                   && isec == 0
5867                   && output_section->lma != 0
5868                   && output_section->vma == (segment->p_vaddr
5869                                              + (map->includes_filehdr
5870                                                 ? iehdr->e_ehsize
5871                                                 : 0)
5872                                              + (map->includes_phdrs
5873                                                 ? (iehdr->e_phnum
5874                                                    * iehdr->e_phentsize)
5875                                                 : 0)))
5876                 map->p_paddr = segment->p_vaddr;
5877
5878               /* Match up the physical address of the segment with the
5879                  LMA address of the output section.  */
5880               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
5881                   || IS_COREFILE_NOTE (segment, section)
5882                   || (bed->want_p_paddr_set_to_zero
5883                       && IS_CONTAINED_BY_VMA (output_section, segment)))
5884                 {
5885                   if (first_matching_lma || output_section->lma < matching_lma)
5886                     {
5887                       matching_lma = output_section->lma;
5888                       first_matching_lma = FALSE;
5889                     }
5890
5891                   /* We assume that if the section fits within the segment
5892                      then it does not overlap any other section within that
5893                      segment.  */
5894                   map->sections[isec++] = output_section;
5895                 }
5896               else if (first_suggested_lma)
5897                 {
5898                   suggested_lma = output_section->lma;
5899                   first_suggested_lma = FALSE;
5900                 }
5901
5902               if (j == section_count)
5903                 break;
5904             }
5905         }
5906
5907       BFD_ASSERT (j == section_count);
5908
5909       /* Step Two: Adjust the physical address of the current segment,
5910          if necessary.  */
5911       if (isec == section_count)
5912         {
5913           /* All of the sections fitted within the segment as currently
5914              specified.  This is the default case.  Add the segment to
5915              the list of built segments and carry on to process the next
5916              program header in the input BFD.  */
5917           map->count = section_count;
5918           *pointer_to_map = map;
5919           pointer_to_map = &map->next;
5920
5921           if (p_paddr_valid
5922               && !bed->want_p_paddr_set_to_zero
5923               && matching_lma != map->p_paddr
5924               && !map->includes_filehdr
5925               && !map->includes_phdrs)
5926             /* There is some padding before the first section in the
5927                segment.  So, we must account for that in the output
5928                segment's vma.  */
5929             map->p_vaddr_offset = matching_lma - map->p_paddr;
5930
5931           free (sections);
5932           continue;
5933         }
5934       else
5935         {
5936           if (!first_matching_lma)
5937             {
5938               /* At least one section fits inside the current segment.
5939                  Keep it, but modify its physical address to match the
5940                  LMA of the first section that fitted.  */
5941               map->p_paddr = matching_lma;
5942             }
5943           else
5944             {
5945               /* None of the sections fitted inside the current segment.
5946                  Change the current segment's physical address to match
5947                  the LMA of the first section.  */
5948               map->p_paddr = suggested_lma;
5949             }
5950
5951           /* Offset the segment physical address from the lma
5952              to allow for space taken up by elf headers.  */
5953           if (map->includes_filehdr)
5954             {
5955               if (map->p_paddr >= iehdr->e_ehsize)
5956                 map->p_paddr -= iehdr->e_ehsize;
5957               else
5958                 {
5959                   map->includes_filehdr = FALSE;
5960                   map->includes_phdrs = FALSE;
5961                 }
5962             }
5963
5964           if (map->includes_phdrs)
5965             {
5966               if (map->p_paddr >= iehdr->e_phnum * iehdr->e_phentsize)
5967                 {
5968                   map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
5969
5970                   /* iehdr->e_phnum is just an estimate of the number
5971                      of program headers that we will need.  Make a note
5972                      here of the number we used and the segment we chose
5973                      to hold these headers, so that we can adjust the
5974                      offset when we know the correct value.  */
5975                   phdr_adjust_num = iehdr->e_phnum;
5976                   phdr_adjust_seg = map;
5977                 }
5978               else
5979                 map->includes_phdrs = FALSE;
5980             }
5981         }
5982
5983       /* Step Three: Loop over the sections again, this time assigning
5984          those that fit to the current segment and removing them from the
5985          sections array; but making sure not to leave large gaps.  Once all
5986          possible sections have been assigned to the current segment it is
5987          added to the list of built segments and if sections still remain
5988          to be assigned, a new segment is constructed before repeating
5989          the loop.  */
5990       isec = 0;
5991       do
5992         {
5993           map->count = 0;
5994           suggested_lma = 0;
5995           first_suggested_lma = TRUE;
5996
5997           /* Fill the current segment with sections that fit.  */
5998           for (j = 0; j < section_count; j++)
5999             {
6000               section = sections[j];
6001
6002               if (section == NULL)
6003                 continue;
6004
6005               output_section = section->output_section;
6006
6007               BFD_ASSERT (output_section != NULL);
6008
6009               if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
6010                   || IS_COREFILE_NOTE (segment, section))
6011                 {
6012                   if (map->count == 0)
6013                     {
6014                       /* If the first section in a segment does not start at
6015                          the beginning of the segment, then something is
6016                          wrong.  */
6017                       if (output_section->lma
6018                           != (map->p_paddr
6019                               + (map->includes_filehdr ? iehdr->e_ehsize : 0)
6020                               + (map->includes_phdrs
6021                                  ? iehdr->e_phnum * iehdr->e_phentsize
6022                                  : 0)))
6023                         abort ();
6024                     }
6025                   else
6026                     {
6027                       asection *prev_sec;
6028
6029                       prev_sec = map->sections[map->count - 1];
6030
6031                       /* If the gap between the end of the previous section
6032                          and the start of this section is more than
6033                          maxpagesize then we need to start a new segment.  */
6034                       if ((BFD_ALIGN (prev_sec->lma + prev_sec->size,
6035                                       maxpagesize)
6036                            < BFD_ALIGN (output_section->lma, maxpagesize))
6037                           || (prev_sec->lma + prev_sec->size
6038                               > output_section->lma))
6039                         {
6040                           if (first_suggested_lma)
6041                             {
6042                               suggested_lma = output_section->lma;
6043                               first_suggested_lma = FALSE;
6044                             }
6045
6046                           continue;
6047                         }
6048                     }
6049
6050                   map->sections[map->count++] = output_section;
6051                   ++isec;
6052                   sections[j] = NULL;
6053                   section->segment_mark = TRUE;
6054                 }
6055               else if (first_suggested_lma)
6056                 {
6057                   suggested_lma = output_section->lma;
6058                   first_suggested_lma = FALSE;
6059                 }
6060             }
6061
6062           BFD_ASSERT (map->count > 0);
6063
6064           /* Add the current segment to the list of built segments.  */
6065           *pointer_to_map = map;
6066           pointer_to_map = &map->next;
6067
6068           if (isec < section_count)
6069             {
6070               /* We still have not allocated all of the sections to
6071                  segments.  Create a new segment here, initialise it
6072                  and carry on looping.  */
6073               amt = sizeof (struct elf_segment_map);
6074               amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
6075               map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
6076               if (map == NULL)
6077                 {
6078                   free (sections);
6079                   return FALSE;
6080                 }
6081
6082               /* Initialise the fields of the segment map.  Set the physical
6083                  physical address to the LMA of the first section that has
6084                  not yet been assigned.  */
6085               map->next = NULL;
6086               map->p_type = segment->p_type;
6087               map->p_flags = segment->p_flags;
6088               map->p_flags_valid = 1;
6089               map->p_paddr = suggested_lma;
6090               map->p_paddr_valid = p_paddr_valid;
6091               map->includes_filehdr = 0;
6092               map->includes_phdrs = 0;
6093             }
6094         }
6095       while (isec < section_count);
6096
6097       free (sections);
6098     }
6099
6100   elf_seg_map (obfd) = map_first;
6101
6102   /* If we had to estimate the number of program headers that were
6103      going to be needed, then check our estimate now and adjust
6104      the offset if necessary.  */
6105   if (phdr_adjust_seg != NULL)
6106     {
6107       unsigned int count;
6108
6109       for (count = 0, map = map_first; map != NULL; map = map->next)
6110         count++;
6111
6112       if (count > phdr_adjust_num)
6113         phdr_adjust_seg->p_paddr
6114           -= (count - phdr_adjust_num) * iehdr->e_phentsize;
6115     }
6116
6117 #undef SEGMENT_END
6118 #undef SECTION_SIZE
6119 #undef IS_CONTAINED_BY_VMA
6120 #undef IS_CONTAINED_BY_LMA
6121 #undef IS_NOTE
6122 #undef IS_COREFILE_NOTE
6123 #undef IS_SOLARIS_PT_INTERP
6124 #undef IS_SECTION_IN_INPUT_SEGMENT
6125 #undef INCLUDE_SECTION_IN_SEGMENT
6126 #undef SEGMENT_AFTER_SEGMENT
6127 #undef SEGMENT_OVERLAPS
6128   return TRUE;
6129 }
6130
6131 /* Copy ELF program header information.  */
6132
6133 static bfd_boolean
6134 copy_elf_program_header (bfd *ibfd, bfd *obfd)
6135 {
6136   Elf_Internal_Ehdr *iehdr;
6137   struct elf_segment_map *map;
6138   struct elf_segment_map *map_first;
6139   struct elf_segment_map **pointer_to_map;
6140   Elf_Internal_Phdr *segment;
6141   unsigned int i;
6142   unsigned int num_segments;
6143   bfd_boolean phdr_included = FALSE;
6144   bfd_boolean p_paddr_valid;
6145
6146   iehdr = elf_elfheader (ibfd);
6147
6148   map_first = NULL;
6149   pointer_to_map = &map_first;
6150
6151   /* If all the segment p_paddr fields are zero, don't set
6152      map->p_paddr_valid.  */
6153   p_paddr_valid = FALSE;
6154   num_segments = elf_elfheader (ibfd)->e_phnum;
6155   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6156        i < num_segments;
6157        i++, segment++)
6158     if (segment->p_paddr != 0)
6159       {
6160         p_paddr_valid = TRUE;
6161         break;
6162       }
6163
6164   for (i = 0, segment = elf_tdata (ibfd)->phdr;
6165        i < num_segments;
6166        i++, segment++)
6167     {
6168       asection *section;
6169       unsigned int section_count;
6170       bfd_size_type amt;
6171       Elf_Internal_Shdr *this_hdr;
6172       asection *first_section = NULL;
6173       asection *lowest_section;
6174
6175       /* Compute how many sections are in this segment.  */
6176       for (section = ibfd->sections, section_count = 0;
6177            section != NULL;
6178            section = section->next)
6179         {
6180           this_hdr = &(elf_section_data(section)->this_hdr);
6181           if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
6182             {
6183               if (first_section == NULL)
6184                 first_section = section;
6185               section_count++;
6186             }
6187         }
6188
6189       /* Allocate a segment map big enough to contain
6190          all of the sections we have selected.  */
6191       amt = sizeof (struct elf_segment_map);
6192       if (section_count != 0)
6193         amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
6194       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
6195       if (map == NULL)
6196         return FALSE;
6197
6198       /* Initialize the fields of the output segment map with the
6199          input segment.  */
6200       map->next = NULL;
6201       map->p_type = segment->p_type;
6202       map->p_flags = segment->p_flags;
6203       map->p_flags_valid = 1;
6204       map->p_paddr = segment->p_paddr;
6205       map->p_paddr_valid = p_paddr_valid;
6206       map->p_align = segment->p_align;
6207       map->p_align_valid = 1;
6208       map->p_vaddr_offset = 0;
6209
6210       if (map->p_type == PT_GNU_RELRO
6211           || map->p_type == PT_GNU_STACK)
6212         {
6213           /* The PT_GNU_RELRO segment may contain the first a few
6214              bytes in the .got.plt section even if the whole .got.plt
6215              section isn't in the PT_GNU_RELRO segment.  We won't
6216              change the size of the PT_GNU_RELRO segment.
6217              Similarly, PT_GNU_STACK size is significant on uclinux
6218              systems.    */
6219           map->p_size = segment->p_memsz;
6220           map->p_size_valid = 1;
6221         }
6222
6223       /* Determine if this segment contains the ELF file header
6224          and if it contains the program headers themselves.  */
6225       map->includes_filehdr = (segment->p_offset == 0
6226                                && segment->p_filesz >= iehdr->e_ehsize);
6227
6228       map->includes_phdrs = 0;
6229       if (! phdr_included || segment->p_type != PT_LOAD)
6230         {
6231           map->includes_phdrs =
6232             (segment->p_offset <= (bfd_vma) iehdr->e_phoff
6233              && (segment->p_offset + segment->p_filesz
6234                  >= ((bfd_vma) iehdr->e_phoff
6235                      + iehdr->e_phnum * iehdr->e_phentsize)));
6236
6237           if (segment->p_type == PT_LOAD && map->includes_phdrs)
6238             phdr_included = TRUE;
6239         }
6240
6241       lowest_section = first_section;
6242       if (section_count != 0)
6243         {
6244           unsigned int isec = 0;
6245
6246           for (section = first_section;
6247                section != NULL;
6248                section = section->next)
6249             {
6250               this_hdr = &(elf_section_data(section)->this_hdr);
6251               if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
6252                 {
6253                   map->sections[isec++] = section->output_section;
6254                   if ((section->flags & SEC_ALLOC) != 0)
6255                     {
6256                       bfd_vma seg_off;
6257
6258                       if (section->lma < lowest_section->lma)
6259                         lowest_section = section;
6260
6261                       /* Section lmas are set up from PT_LOAD header
6262                          p_paddr in _bfd_elf_make_section_from_shdr.
6263                          If this header has a p_paddr that disagrees
6264                          with the section lma, flag the p_paddr as
6265                          invalid.  */
6266                       if ((section->flags & SEC_LOAD) != 0)
6267                         seg_off = this_hdr->sh_offset - segment->p_offset;
6268                       else
6269                         seg_off = this_hdr->sh_addr - segment->p_vaddr;
6270                       if (section->lma - segment->p_paddr != seg_off)
6271                         map->p_paddr_valid = FALSE;
6272                     }
6273                   if (isec == section_count)
6274                     break;
6275                 }
6276             }
6277         }
6278
6279       if (map->includes_filehdr && lowest_section != NULL)
6280         /* We need to keep the space used by the headers fixed.  */
6281         map->header_size = lowest_section->vma - segment->p_vaddr;
6282
6283       if (!map->includes_phdrs
6284           && !map->includes_filehdr
6285           && map->p_paddr_valid)
6286         /* There is some other padding before the first section.  */
6287         map->p_vaddr_offset = ((lowest_section ? lowest_section->lma : 0)
6288                                - segment->p_paddr);
6289
6290       map->count = section_count;
6291       *pointer_to_map = map;
6292       pointer_to_map = &map->next;
6293     }
6294
6295   elf_seg_map (obfd) = map_first;
6296   return TRUE;
6297 }
6298
6299 /* Copy private BFD data.  This copies or rewrites ELF program header
6300    information.  */
6301
6302 static bfd_boolean
6303 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
6304 {
6305   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
6306       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
6307     return TRUE;
6308
6309   if (elf_tdata (ibfd)->phdr == NULL)
6310     return TRUE;
6311
6312   if (ibfd->xvec == obfd->xvec)
6313     {
6314       /* Check to see if any sections in the input BFD
6315          covered by ELF program header have changed.  */
6316       Elf_Internal_Phdr *segment;
6317       asection *section, *osec;
6318       unsigned int i, num_segments;
6319       Elf_Internal_Shdr *this_hdr;
6320       const struct elf_backend_data *bed;
6321
6322       bed = get_elf_backend_data (ibfd);
6323
6324       /* Regenerate the segment map if p_paddr is set to 0.  */
6325       if (bed->want_p_paddr_set_to_zero)
6326         goto rewrite;
6327
6328       /* Initialize the segment mark field.  */
6329       for (section = obfd->sections; section != NULL;
6330            section = section->next)
6331         section->segment_mark = FALSE;
6332
6333       num_segments = elf_elfheader (ibfd)->e_phnum;
6334       for (i = 0, segment = elf_tdata (ibfd)->phdr;
6335            i < num_segments;
6336            i++, segment++)
6337         {
6338           /* PR binutils/3535.  The Solaris linker always sets the p_paddr
6339              and p_memsz fields of special segments (DYNAMIC, INTERP) to 0
6340              which severly confuses things, so always regenerate the segment
6341              map in this case.  */
6342           if (segment->p_paddr == 0
6343               && segment->p_memsz == 0
6344               && (segment->p_type == PT_INTERP || segment->p_type == PT_DYNAMIC))
6345             goto rewrite;
6346
6347           for (section = ibfd->sections;
6348                section != NULL; section = section->next)
6349             {
6350               /* We mark the output section so that we know it comes
6351                  from the input BFD.  */
6352               osec = section->output_section;
6353               if (osec)
6354                 osec->segment_mark = TRUE;
6355
6356               /* Check if this section is covered by the segment.  */
6357               this_hdr = &(elf_section_data(section)->this_hdr);
6358               if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
6359                 {
6360                   /* FIXME: Check if its output section is changed or
6361                      removed.  What else do we need to check?  */
6362                   if (osec == NULL
6363                       || section->flags != osec->flags
6364                       || section->lma != osec->lma
6365                       || section->vma != osec->vma
6366                       || section->size != osec->size
6367                       || section->rawsize != osec->rawsize
6368                       || section->alignment_power != osec->alignment_power)
6369                     goto rewrite;
6370                 }
6371             }
6372         }
6373
6374       /* Check to see if any output section do not come from the
6375          input BFD.  */
6376       for (section = obfd->sections; section != NULL;
6377            section = section->next)
6378         {
6379           if (section->segment_mark == FALSE)
6380             goto rewrite;
6381           else
6382             section->segment_mark = FALSE;
6383         }
6384
6385       return copy_elf_program_header (ibfd, obfd);
6386     }
6387
6388 rewrite:
6389   if (ibfd->xvec == obfd->xvec)
6390     {
6391       /* When rewriting program header, set the output maxpagesize to
6392          the maximum alignment of input PT_LOAD segments.  */
6393       Elf_Internal_Phdr *segment;
6394       unsigned int i;
6395       unsigned int num_segments = elf_elfheader (ibfd)->e_phnum;
6396       bfd_vma maxpagesize = 0;
6397
6398       for (i = 0, segment = elf_tdata (ibfd)->phdr;
6399            i < num_segments;
6400            i++, segment++)
6401         if (segment->p_type == PT_LOAD
6402             && maxpagesize < segment->p_align)
6403           maxpagesize = segment->p_align;
6404
6405       if (maxpagesize != get_elf_backend_data (obfd)->maxpagesize)
6406         bfd_emul_set_maxpagesize (bfd_get_target (obfd), maxpagesize);
6407     }
6408
6409   return rewrite_elf_program_header (ibfd, obfd);
6410 }
6411
6412 /* Initialize private output section information from input section.  */
6413
6414 bfd_boolean
6415 _bfd_elf_init_private_section_data (bfd *ibfd,
6416                                     asection *isec,
6417                                     bfd *obfd,
6418                                     asection *osec,
6419                                     struct bfd_link_info *link_info)
6420
6421 {
6422   Elf_Internal_Shdr *ihdr, *ohdr;
6423   bfd_boolean final_link = link_info != NULL && !link_info->relocatable;
6424
6425   if (ibfd->xvec->flavour != bfd_target_elf_flavour
6426       || obfd->xvec->flavour != bfd_target_elf_flavour)
6427     return TRUE;
6428
6429   BFD_ASSERT (elf_section_data (osec) != NULL);
6430
6431   /* For objcopy and relocatable link, don't copy the output ELF
6432      section type from input if the output BFD section flags have been
6433      set to something different.  For a final link allow some flags
6434      that the linker clears to differ.  */
6435   if (elf_section_type (osec) == SHT_NULL
6436       && (osec->flags == isec->flags
6437           || (final_link
6438               && ((osec->flags ^ isec->flags)
6439                   & ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC)) == 0)))
6440     elf_section_type (osec) = elf_section_type (isec);
6441
6442   /* FIXME: Is this correct for all OS/PROC specific flags?  */
6443   elf_section_flags (osec) |= (elf_section_flags (isec)
6444                                & (SHF_MASKOS | SHF_MASKPROC));
6445
6446   /* Set things up for objcopy and relocatable link.  The output
6447      SHT_GROUP section will have its elf_next_in_group pointing back
6448      to the input group members.  Ignore linker created group section.
6449      See elfNN_ia64_object_p in elfxx-ia64.c.  */
6450   if (!final_link)
6451     {
6452       if (elf_sec_group (isec) == NULL
6453           || (elf_sec_group (isec)->flags & SEC_LINKER_CREATED) == 0)
6454         {
6455           if (elf_section_flags (isec) & SHF_GROUP)
6456             elf_section_flags (osec) |= SHF_GROUP;
6457           elf_next_in_group (osec) = elf_next_in_group (isec);
6458           elf_section_data (osec)->group = elf_section_data (isec)->group;
6459         }
6460     }
6461
6462   ihdr = &elf_section_data (isec)->this_hdr;
6463
6464   /* We need to handle elf_linked_to_section for SHF_LINK_ORDER. We
6465      don't use the output section of the linked-to section since it
6466      may be NULL at this point.  */
6467   if ((ihdr->sh_flags & SHF_LINK_ORDER) != 0)
6468     {
6469       ohdr = &elf_section_data (osec)->this_hdr;
6470       ohdr->sh_flags |= SHF_LINK_ORDER;
6471       elf_linked_to_section (osec) = elf_linked_to_section (isec);
6472     }
6473
6474   osec->use_rela_p = isec->use_rela_p;
6475
6476   return TRUE;
6477 }
6478
6479 /* Copy private section information.  This copies over the entsize
6480    field, and sometimes the info field.  */
6481
6482 bfd_boolean
6483 _bfd_elf_copy_private_section_data (bfd *ibfd,
6484                                     asection *isec,
6485                                     bfd *obfd,
6486                                     asection *osec)
6487 {
6488   Elf_Internal_Shdr *ihdr, *ohdr;
6489
6490   if (ibfd->xvec->flavour != bfd_target_elf_flavour
6491       || obfd->xvec->flavour != bfd_target_elf_flavour)
6492     return TRUE;
6493
6494   ihdr = &elf_section_data (isec)->this_hdr;
6495   ohdr = &elf_section_data (osec)->this_hdr;
6496
6497   ohdr->sh_entsize = ihdr->sh_entsize;
6498
6499   if (ihdr->sh_type == SHT_SYMTAB
6500       || ihdr->sh_type == SHT_DYNSYM
6501       || ihdr->sh_type == SHT_GNU_verneed
6502       || ihdr->sh_type == SHT_GNU_verdef)
6503     ohdr->sh_info = ihdr->sh_info;
6504
6505   return _bfd_elf_init_private_section_data (ibfd, isec, obfd, osec,
6506                                              NULL);
6507 }
6508
6509 /* Look at all the SHT_GROUP sections in IBFD, making any adjustments
6510    necessary if we are removing either the SHT_GROUP section or any of
6511    the group member sections.  DISCARDED is the value that a section's
6512    output_section has if the section will be discarded, NULL when this
6513    function is called from objcopy, bfd_abs_section_ptr when called
6514    from the linker.  */
6515
6516 bfd_boolean
6517 _bfd_elf_fixup_group_sections (bfd *ibfd, asection *discarded)
6518 {
6519   asection *isec;
6520
6521   for (isec = ibfd->sections; isec != NULL; isec = isec->next)
6522     if (elf_section_type (isec) == SHT_GROUP)
6523       {
6524         asection *first = elf_next_in_group (isec);
6525         asection *s = first;
6526         bfd_size_type removed = 0;
6527
6528         while (s != NULL)
6529           {
6530             /* If this member section is being output but the
6531                SHT_GROUP section is not, then clear the group info
6532                set up by _bfd_elf_copy_private_section_data.  */
6533             if (s->output_section != discarded
6534                 && isec->output_section == discarded)
6535               {
6536                 elf_section_flags (s->output_section) &= ~SHF_GROUP;
6537                 elf_group_name (s->output_section) = NULL;
6538               }
6539             /* Conversely, if the member section is not being output
6540                but the SHT_GROUP section is, then adjust its size.  */
6541             else if (s->output_section == discarded
6542                      && isec->output_section != discarded)
6543               removed += 4;
6544             s = elf_next_in_group (s);
6545             if (s == first)
6546               break;
6547           }
6548         if (removed != 0)
6549           {
6550             if (discarded != NULL)
6551               {
6552                 /* If we've been called for ld -r, then we need to
6553                    adjust the input section size.  This function may
6554                    be called multiple times, so save the original
6555                    size.  */
6556                 if (isec->rawsize == 0)
6557                   isec->rawsize = isec->size;
6558                 isec->size = isec->rawsize - removed;
6559               }
6560             else
6561               {
6562                 /* Adjust the output section size when called from
6563                    objcopy. */
6564                 isec->output_section->size -= removed;
6565               }
6566           }
6567       }
6568
6569   return TRUE;
6570 }
6571
6572 /* Copy private header information.  */
6573
6574 bfd_boolean
6575 _bfd_elf_copy_private_header_data (bfd *ibfd, bfd *obfd)
6576 {
6577   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
6578       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
6579     return TRUE;
6580
6581   /* Copy over private BFD data if it has not already been copied.
6582      This must be done here, rather than in the copy_private_bfd_data
6583      entry point, because the latter is called after the section
6584      contents have been set, which means that the program headers have
6585      already been worked out.  */
6586   if (elf_seg_map (obfd) == NULL && elf_tdata (ibfd)->phdr != NULL)
6587     {
6588       if (! copy_private_bfd_data (ibfd, obfd))
6589         return FALSE;
6590     }
6591
6592   return _bfd_elf_fixup_group_sections (ibfd, NULL);
6593 }
6594
6595 /* Copy private symbol information.  If this symbol is in a section
6596    which we did not map into a BFD section, try to map the section
6597    index correctly.  We use special macro definitions for the mapped
6598    section indices; these definitions are interpreted by the
6599    swap_out_syms function.  */
6600
6601 #define MAP_ONESYMTAB (SHN_HIOS + 1)
6602 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
6603 #define MAP_STRTAB    (SHN_HIOS + 3)
6604 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
6605 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
6606
6607 bfd_boolean
6608 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
6609                                    asymbol *isymarg,
6610                                    bfd *obfd,
6611                                    asymbol *osymarg)
6612 {
6613   elf_symbol_type *isym, *osym;
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   isym = elf_symbol_from (ibfd, isymarg);
6620   osym = elf_symbol_from (obfd, osymarg);
6621
6622   if (isym != NULL
6623       && isym->internal_elf_sym.st_shndx != 0
6624       && osym != NULL
6625       && bfd_is_abs_section (isym->symbol.section))
6626     {
6627       unsigned int shndx;
6628
6629       shndx = isym->internal_elf_sym.st_shndx;
6630       if (shndx == elf_onesymtab (ibfd))
6631         shndx = MAP_ONESYMTAB;
6632       else if (shndx == elf_dynsymtab (ibfd))
6633         shndx = MAP_DYNSYMTAB;
6634       else if (shndx == elf_strtab_sec (ibfd))
6635         shndx = MAP_STRTAB;
6636       else if (shndx == elf_shstrtab_sec (ibfd))
6637         shndx = MAP_SHSTRTAB;
6638       else if (shndx == elf_symtab_shndx (ibfd))
6639         shndx = MAP_SYM_SHNDX;
6640       osym->internal_elf_sym.st_shndx = shndx;
6641     }
6642
6643   return TRUE;
6644 }
6645
6646 /* Swap out the symbols.  */
6647
6648 static bfd_boolean
6649 swap_out_syms (bfd *abfd,
6650                struct bfd_strtab_hash **sttp,
6651                int relocatable_p)
6652 {
6653   const struct elf_backend_data *bed;
6654   int symcount;
6655   asymbol **syms;
6656   struct bfd_strtab_hash *stt;
6657   Elf_Internal_Shdr *symtab_hdr;
6658   Elf_Internal_Shdr *symtab_shndx_hdr;
6659   Elf_Internal_Shdr *symstrtab_hdr;
6660   bfd_byte *outbound_syms;
6661   bfd_byte *outbound_shndx;
6662   int idx;
6663   unsigned int num_locals;
6664   bfd_size_type amt;
6665   bfd_boolean name_local_sections;
6666
6667   if (!elf_map_symbols (abfd, &num_locals))
6668     return FALSE;
6669
6670   /* Dump out the symtabs.  */
6671   stt = _bfd_elf_stringtab_init ();
6672   if (stt == NULL)
6673     return FALSE;
6674
6675   bed = get_elf_backend_data (abfd);
6676   symcount = bfd_get_symcount (abfd);
6677   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
6678   symtab_hdr->sh_type = SHT_SYMTAB;
6679   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
6680   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
6681   symtab_hdr->sh_info = num_locals + 1;
6682   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
6683
6684   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
6685   symstrtab_hdr->sh_type = SHT_STRTAB;
6686
6687   outbound_syms = (bfd_byte *) bfd_alloc2 (abfd, 1 + symcount,
6688                                            bed->s->sizeof_sym);
6689   if (outbound_syms == NULL)
6690     {
6691       _bfd_stringtab_free (stt);
6692       return FALSE;
6693     }
6694   symtab_hdr->contents = outbound_syms;
6695
6696   outbound_shndx = NULL;
6697   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
6698   if (symtab_shndx_hdr->sh_name != 0)
6699     {
6700       amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
6701       outbound_shndx =  (bfd_byte *)
6702           bfd_zalloc2 (abfd, 1 + symcount, sizeof (Elf_External_Sym_Shndx));
6703       if (outbound_shndx == NULL)
6704         {
6705           _bfd_stringtab_free (stt);
6706           return FALSE;
6707         }
6708
6709       symtab_shndx_hdr->contents = outbound_shndx;
6710       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
6711       symtab_shndx_hdr->sh_size = amt;
6712       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
6713       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
6714     }
6715
6716   /* Now generate the data (for "contents").  */
6717   {
6718     /* Fill in zeroth symbol and swap it out.  */
6719     Elf_Internal_Sym sym;
6720     sym.st_name = 0;
6721     sym.st_value = 0;
6722     sym.st_size = 0;
6723     sym.st_info = 0;
6724     sym.st_other = 0;
6725     sym.st_shndx = SHN_UNDEF;
6726     sym.st_target_internal = 0;
6727     bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
6728     outbound_syms += bed->s->sizeof_sym;
6729     if (outbound_shndx != NULL)
6730       outbound_shndx += sizeof (Elf_External_Sym_Shndx);
6731   }
6732
6733   name_local_sections
6734     = (bed->elf_backend_name_local_section_symbols
6735        && bed->elf_backend_name_local_section_symbols (abfd));
6736
6737   syms = bfd_get_outsymbols (abfd);
6738   for (idx = 0; idx < symcount; idx++)
6739     {
6740       Elf_Internal_Sym sym;
6741       bfd_vma value = syms[idx]->value;
6742       elf_symbol_type *type_ptr;
6743       flagword flags = syms[idx]->flags;
6744       int type;
6745
6746       if (!name_local_sections
6747           && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
6748         {
6749           /* Local section symbols have no name.  */
6750           sym.st_name = 0;
6751         }
6752       else
6753         {
6754           sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
6755                                                             syms[idx]->name,
6756                                                             TRUE, FALSE);
6757           if (sym.st_name == (unsigned long) -1)
6758             {
6759               _bfd_stringtab_free (stt);
6760               return FALSE;
6761             }
6762         }
6763
6764       type_ptr = elf_symbol_from (abfd, syms[idx]);
6765
6766       if ((flags & BSF_SECTION_SYM) == 0
6767           && bfd_is_com_section (syms[idx]->section))
6768         {
6769           /* ELF common symbols put the alignment into the `value' field,
6770              and the size into the `size' field.  This is backwards from
6771              how BFD handles it, so reverse it here.  */
6772           sym.st_size = value;
6773           if (type_ptr == NULL
6774               || type_ptr->internal_elf_sym.st_value == 0)
6775             sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
6776           else
6777             sym.st_value = type_ptr->internal_elf_sym.st_value;
6778           sym.st_shndx = _bfd_elf_section_from_bfd_section
6779             (abfd, syms[idx]->section);
6780         }
6781       else
6782         {
6783           asection *sec = syms[idx]->section;
6784           unsigned int shndx;
6785
6786           if (sec->output_section)
6787             {
6788               value += sec->output_offset;
6789               sec = sec->output_section;
6790             }
6791
6792           /* Don't add in the section vma for relocatable output.  */
6793           if (! relocatable_p)
6794             value += sec->vma;
6795           sym.st_value = value;
6796           sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
6797
6798           if (bfd_is_abs_section (sec)
6799               && type_ptr != NULL
6800               && type_ptr->internal_elf_sym.st_shndx != 0)
6801             {
6802               /* This symbol is in a real ELF section which we did
6803                  not create as a BFD section.  Undo the mapping done
6804                  by copy_private_symbol_data.  */
6805               shndx = type_ptr->internal_elf_sym.st_shndx;
6806               switch (shndx)
6807                 {
6808                 case MAP_ONESYMTAB:
6809                   shndx = elf_onesymtab (abfd);
6810                   break;
6811                 case MAP_DYNSYMTAB:
6812                   shndx = elf_dynsymtab (abfd);
6813                   break;
6814                 case MAP_STRTAB:
6815                   shndx = elf_strtab_sec (abfd);
6816                   break;
6817                 case MAP_SHSTRTAB:
6818                   shndx = elf_shstrtab_sec (abfd);
6819                   break;
6820                 case MAP_SYM_SHNDX:
6821                   shndx = elf_symtab_shndx (abfd);
6822                   break;
6823                 default:
6824                   shndx = SHN_ABS;
6825                   break;
6826                 }
6827             }
6828           else
6829             {
6830               shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
6831
6832               if (shndx == SHN_BAD)
6833                 {
6834                   asection *sec2;
6835
6836                   /* Writing this would be a hell of a lot easier if
6837                      we had some decent documentation on bfd, and
6838                      knew what to expect of the library, and what to
6839                      demand of applications.  For example, it
6840                      appears that `objcopy' might not set the
6841                      section of a symbol to be a section that is
6842                      actually in the output file.  */
6843                   sec2 = bfd_get_section_by_name (abfd, sec->name);
6844                   if (sec2 == NULL)
6845                     {
6846                       _bfd_error_handler (_("\
6847 Unable to find equivalent output section for symbol '%s' from section '%s'"),
6848                                           syms[idx]->name ? syms[idx]->name : "<Local sym>",
6849                                           sec->name);
6850                       bfd_set_error (bfd_error_invalid_operation);
6851                       _bfd_stringtab_free (stt);
6852                       return FALSE;
6853                     }
6854
6855                   shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
6856                   BFD_ASSERT (shndx != SHN_BAD);
6857                 }
6858             }
6859
6860           sym.st_shndx = shndx;
6861         }
6862
6863       if ((flags & BSF_THREAD_LOCAL) != 0)
6864         type = STT_TLS;
6865       else if ((flags & BSF_GNU_INDIRECT_FUNCTION) != 0)
6866         type = STT_GNU_IFUNC;
6867       else if ((flags & BSF_FUNCTION) != 0)
6868         type = STT_FUNC;
6869       else if ((flags & BSF_OBJECT) != 0)
6870         type = STT_OBJECT;
6871       else if ((flags & BSF_RELC) != 0)
6872         type = STT_RELC;
6873       else if ((flags & BSF_SRELC) != 0)
6874         type = STT_SRELC;
6875       else
6876         type = STT_NOTYPE;
6877
6878       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
6879         type = STT_TLS;
6880
6881       /* Processor-specific types.  */
6882       if (type_ptr != NULL
6883           && bed->elf_backend_get_symbol_type)
6884         type = ((*bed->elf_backend_get_symbol_type)
6885                 (&type_ptr->internal_elf_sym, type));
6886
6887       if (flags & BSF_SECTION_SYM)
6888         {
6889           if (flags & BSF_GLOBAL)
6890             sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
6891           else
6892             sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
6893         }
6894       else if (bfd_is_com_section (syms[idx]->section))
6895         {
6896 #ifdef USE_STT_COMMON
6897           if (type == STT_OBJECT)
6898             sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_COMMON);
6899           else
6900 #endif
6901             sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
6902         }
6903       else if (bfd_is_und_section (syms[idx]->section))
6904         sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
6905                                     ? STB_WEAK
6906                                     : STB_GLOBAL),
6907                                    type);
6908       else if (flags & BSF_FILE)
6909         sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
6910       else
6911         {
6912           int bind = STB_LOCAL;
6913
6914           if (flags & BSF_LOCAL)
6915             bind = STB_LOCAL;
6916           else if (flags & BSF_GNU_UNIQUE)
6917             bind = STB_GNU_UNIQUE;
6918           else if (flags & BSF_WEAK)
6919             bind = STB_WEAK;
6920           else if (flags & BSF_GLOBAL)
6921             bind = STB_GLOBAL;
6922
6923           sym.st_info = ELF_ST_INFO (bind, type);
6924         }
6925
6926       if (type_ptr != NULL)
6927         {
6928           sym.st_other = type_ptr->internal_elf_sym.st_other;
6929           sym.st_target_internal
6930             = type_ptr->internal_elf_sym.st_target_internal;
6931         }
6932       else
6933         {
6934           sym.st_other = 0;
6935           sym.st_target_internal = 0;
6936         }
6937
6938       bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
6939       outbound_syms += bed->s->sizeof_sym;
6940       if (outbound_shndx != NULL)
6941         outbound_shndx += sizeof (Elf_External_Sym_Shndx);
6942     }
6943
6944   *sttp = stt;
6945   symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
6946   symstrtab_hdr->sh_type = SHT_STRTAB;
6947
6948   symstrtab_hdr->sh_flags = 0;
6949   symstrtab_hdr->sh_addr = 0;
6950   symstrtab_hdr->sh_entsize = 0;
6951   symstrtab_hdr->sh_link = 0;
6952   symstrtab_hdr->sh_info = 0;
6953   symstrtab_hdr->sh_addralign = 1;
6954
6955   return TRUE;
6956 }
6957
6958 /* Return the number of bytes required to hold the symtab vector.
6959
6960    Note that we base it on the count plus 1, since we will null terminate
6961    the vector allocated based on this size.  However, the ELF symbol table
6962    always has a dummy entry as symbol #0, so it ends up even.  */
6963
6964 long
6965 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
6966 {
6967   long symcount;
6968   long symtab_size;
6969   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
6970
6971   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
6972   symtab_size = (symcount + 1) * (sizeof (asymbol *));
6973   if (symcount > 0)
6974     symtab_size -= sizeof (asymbol *);
6975
6976   return symtab_size;
6977 }
6978
6979 long
6980 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
6981 {
6982   long symcount;
6983   long symtab_size;
6984   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
6985
6986   if (elf_dynsymtab (abfd) == 0)
6987     {
6988       bfd_set_error (bfd_error_invalid_operation);
6989       return -1;
6990     }
6991
6992   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
6993   symtab_size = (symcount + 1) * (sizeof (asymbol *));
6994   if (symcount > 0)
6995     symtab_size -= sizeof (asymbol *);
6996
6997   return symtab_size;
6998 }
6999
7000 long
7001 _bfd_elf_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
7002                                 sec_ptr asect)
7003 {
7004   return (asect->reloc_count + 1) * sizeof (arelent *);
7005 }
7006
7007 /* Canonicalize the relocs.  */
7008
7009 long
7010 _bfd_elf_canonicalize_reloc (bfd *abfd,
7011                              sec_ptr section,
7012                              arelent **relptr,
7013                              asymbol **symbols)
7014 {
7015   arelent *tblptr;
7016   unsigned int i;
7017   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7018
7019   if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
7020     return -1;
7021
7022   tblptr = section->relocation;
7023   for (i = 0; i < section->reloc_count; i++)
7024     *relptr++ = tblptr++;
7025
7026   *relptr = NULL;
7027
7028   return section->reloc_count;
7029 }
7030
7031 long
7032 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
7033 {
7034   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7035   long symcount = bed->s->slurp_symbol_table (abfd, allocation, FALSE);
7036
7037   if (symcount >= 0)
7038     bfd_get_symcount (abfd) = symcount;
7039   return symcount;
7040 }
7041
7042 long
7043 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
7044                                       asymbol **allocation)
7045 {
7046   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7047   long symcount = bed->s->slurp_symbol_table (abfd, allocation, TRUE);
7048
7049   if (symcount >= 0)
7050     bfd_get_dynamic_symcount (abfd) = symcount;
7051   return symcount;
7052 }
7053
7054 /* Return the size required for the dynamic reloc entries.  Any loadable
7055    section that was actually installed in the BFD, and has type SHT_REL
7056    or SHT_RELA, and uses the dynamic symbol table, is considered to be a
7057    dynamic reloc section.  */
7058
7059 long
7060 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
7061 {
7062   long ret;
7063   asection *s;
7064
7065   if (elf_dynsymtab (abfd) == 0)
7066     {
7067       bfd_set_error (bfd_error_invalid_operation);
7068       return -1;
7069     }
7070
7071   ret = sizeof (arelent *);
7072   for (s = abfd->sections; s != NULL; s = s->next)
7073     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
7074         && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
7075             || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
7076       ret += ((s->size / elf_section_data (s)->this_hdr.sh_entsize)
7077               * sizeof (arelent *));
7078
7079   return ret;
7080 }
7081
7082 /* Canonicalize the dynamic relocation entries.  Note that we return the
7083    dynamic relocations as a single block, although they are actually
7084    associated with particular sections; the interface, which was
7085    designed for SunOS style shared libraries, expects that there is only
7086    one set of dynamic relocs.  Any loadable section that was actually
7087    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses the
7088    dynamic symbol table, is considered to be a dynamic reloc section.  */
7089
7090 long
7091 _bfd_elf_canonicalize_dynamic_reloc (bfd *abfd,
7092                                      arelent **storage,
7093                                      asymbol **syms)
7094 {
7095   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
7096   asection *s;
7097   long ret;
7098
7099   if (elf_dynsymtab (abfd) == 0)
7100     {
7101       bfd_set_error (bfd_error_invalid_operation);
7102       return -1;
7103     }
7104
7105   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
7106   ret = 0;
7107   for (s = abfd->sections; s != NULL; s = s->next)
7108     {
7109       if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
7110           && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
7111               || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
7112         {
7113           arelent *p;
7114           long count, i;
7115
7116           if (! (*slurp_relocs) (abfd, s, syms, TRUE))
7117             return -1;
7118           count = s->size / elf_section_data (s)->this_hdr.sh_entsize;
7119           p = s->relocation;
7120           for (i = 0; i < count; i++)
7121             *storage++ = p++;
7122           ret += count;
7123         }
7124     }
7125
7126   *storage = NULL;
7127
7128   return ret;
7129 }
7130 \f
7131 /* Read in the version information.  */
7132
7133 bfd_boolean
7134 _bfd_elf_slurp_version_tables (bfd *abfd, bfd_boolean default_imported_symver)
7135 {
7136   bfd_byte *contents = NULL;
7137   unsigned int freeidx = 0;
7138
7139   if (elf_dynverref (abfd) != 0)
7140     {
7141       Elf_Internal_Shdr *hdr;
7142       Elf_External_Verneed *everneed;
7143       Elf_Internal_Verneed *iverneed;
7144       unsigned int i;
7145       bfd_byte *contents_end;
7146
7147       hdr = &elf_tdata (abfd)->dynverref_hdr;
7148
7149       elf_tdata (abfd)->verref = (Elf_Internal_Verneed *)
7150           bfd_zalloc2 (abfd, hdr->sh_info, sizeof (Elf_Internal_Verneed));
7151       if (elf_tdata (abfd)->verref == NULL)
7152         goto error_return;
7153
7154       elf_tdata (abfd)->cverrefs = hdr->sh_info;
7155
7156       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
7157       if (contents == NULL)
7158         {
7159 error_return_verref:
7160           elf_tdata (abfd)->verref = NULL;
7161           elf_tdata (abfd)->cverrefs = 0;
7162           goto error_return;
7163         }
7164       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
7165           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
7166         goto error_return_verref;
7167
7168       if (hdr->sh_info && hdr->sh_size < sizeof (Elf_External_Verneed))
7169         goto error_return_verref;
7170
7171       BFD_ASSERT (sizeof (Elf_External_Verneed)
7172                   == sizeof (Elf_External_Vernaux));
7173       contents_end = contents + hdr->sh_size - sizeof (Elf_External_Verneed);
7174       everneed = (Elf_External_Verneed *) contents;
7175       iverneed = elf_tdata (abfd)->verref;
7176       for (i = 0; i < hdr->sh_info; i++, iverneed++)
7177         {
7178           Elf_External_Vernaux *evernaux;
7179           Elf_Internal_Vernaux *ivernaux;
7180           unsigned int j;
7181
7182           _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
7183
7184           iverneed->vn_bfd = abfd;
7185
7186           iverneed->vn_filename =
7187             bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
7188                                              iverneed->vn_file);
7189           if (iverneed->vn_filename == NULL)
7190             goto error_return_verref;
7191
7192           if (iverneed->vn_cnt == 0)
7193             iverneed->vn_auxptr = NULL;
7194           else
7195             {
7196               iverneed->vn_auxptr = (struct elf_internal_vernaux *)
7197                   bfd_alloc2 (abfd, iverneed->vn_cnt,
7198                               sizeof (Elf_Internal_Vernaux));
7199               if (iverneed->vn_auxptr == NULL)
7200                 goto error_return_verref;
7201             }
7202
7203           if (iverneed->vn_aux
7204               > (size_t) (contents_end - (bfd_byte *) everneed))
7205             goto error_return_verref;
7206
7207           evernaux = ((Elf_External_Vernaux *)
7208                       ((bfd_byte *) everneed + iverneed->vn_aux));
7209           ivernaux = iverneed->vn_auxptr;
7210           for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
7211             {
7212               _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
7213
7214               ivernaux->vna_nodename =
7215                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
7216                                                  ivernaux->vna_name);
7217               if (ivernaux->vna_nodename == NULL)
7218                 goto error_return_verref;
7219
7220               if (j + 1 < iverneed->vn_cnt)
7221                 ivernaux->vna_nextptr = ivernaux + 1;
7222               else
7223                 ivernaux->vna_nextptr = NULL;
7224
7225               if (ivernaux->vna_next
7226                   > (size_t) (contents_end - (bfd_byte *) evernaux))
7227                 goto error_return_verref;
7228
7229               evernaux = ((Elf_External_Vernaux *)
7230                           ((bfd_byte *) evernaux + ivernaux->vna_next));
7231
7232               if (ivernaux->vna_other > freeidx)
7233                 freeidx = ivernaux->vna_other;
7234             }
7235
7236           if (i + 1 < hdr->sh_info)
7237             iverneed->vn_nextref = iverneed + 1;
7238           else
7239             iverneed->vn_nextref = NULL;
7240
7241           if (iverneed->vn_next
7242               > (size_t) (contents_end - (bfd_byte *) everneed))
7243             goto error_return_verref;
7244
7245           everneed = ((Elf_External_Verneed *)
7246                       ((bfd_byte *) everneed + iverneed->vn_next));
7247         }
7248
7249       free (contents);
7250       contents = NULL;
7251     }
7252
7253   if (elf_dynverdef (abfd) != 0)
7254     {
7255       Elf_Internal_Shdr *hdr;
7256       Elf_External_Verdef *everdef;
7257       Elf_Internal_Verdef *iverdef;
7258       Elf_Internal_Verdef *iverdefarr;
7259       Elf_Internal_Verdef iverdefmem;
7260       unsigned int i;
7261       unsigned int maxidx;
7262       bfd_byte *contents_end_def, *contents_end_aux;
7263
7264       hdr = &elf_tdata (abfd)->dynverdef_hdr;
7265
7266       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
7267       if (contents == NULL)
7268         goto error_return;
7269       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
7270           || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
7271         goto error_return;
7272
7273       if (hdr->sh_info && hdr->sh_size < sizeof (Elf_External_Verdef))
7274         goto error_return;
7275
7276       BFD_ASSERT (sizeof (Elf_External_Verdef)
7277                   >= sizeof (Elf_External_Verdaux));
7278       contents_end_def = contents + hdr->sh_size
7279                          - sizeof (Elf_External_Verdef);
7280       contents_end_aux = contents + hdr->sh_size
7281                          - sizeof (Elf_External_Verdaux);
7282
7283       /* We know the number of entries in the section but not the maximum
7284          index.  Therefore we have to run through all entries and find
7285          the maximum.  */
7286       everdef = (Elf_External_Verdef *) contents;
7287       maxidx = 0;
7288       for (i = 0; i < hdr->sh_info; ++i)
7289         {
7290           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
7291
7292           if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
7293             maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
7294
7295           if (iverdefmem.vd_next
7296               > (size_t) (contents_end_def - (bfd_byte *) everdef))
7297             goto error_return;
7298
7299           everdef = ((Elf_External_Verdef *)
7300                      ((bfd_byte *) everdef + iverdefmem.vd_next));
7301         }
7302
7303       if (default_imported_symver)
7304         {
7305           if (freeidx > maxidx)
7306             maxidx = ++freeidx;
7307           else
7308             freeidx = ++maxidx;
7309         }
7310       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *)
7311           bfd_zalloc2 (abfd, maxidx, sizeof (Elf_Internal_Verdef));
7312       if (elf_tdata (abfd)->verdef == NULL)
7313         goto error_return;
7314
7315       elf_tdata (abfd)->cverdefs = maxidx;
7316
7317       everdef = (Elf_External_Verdef *) contents;
7318       iverdefarr = elf_tdata (abfd)->verdef;
7319       for (i = 0; i < hdr->sh_info; i++)
7320         {
7321           Elf_External_Verdaux *everdaux;
7322           Elf_Internal_Verdaux *iverdaux;
7323           unsigned int j;
7324
7325           _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
7326
7327           if ((iverdefmem.vd_ndx & VERSYM_VERSION) == 0)
7328             {
7329 error_return_verdef:
7330               elf_tdata (abfd)->verdef = NULL;
7331               elf_tdata (abfd)->cverdefs = 0;
7332               goto error_return;
7333             }
7334
7335           iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
7336           memcpy (iverdef, &iverdefmem, sizeof (Elf_Internal_Verdef));
7337
7338           iverdef->vd_bfd = abfd;
7339
7340           if (iverdef->vd_cnt == 0)
7341             iverdef->vd_auxptr = NULL;
7342           else
7343             {
7344               iverdef->vd_auxptr = (struct elf_internal_verdaux *)
7345                   bfd_alloc2 (abfd, iverdef->vd_cnt,
7346                               sizeof (Elf_Internal_Verdaux));
7347               if (iverdef->vd_auxptr == NULL)
7348                 goto error_return_verdef;
7349             }
7350
7351           if (iverdef->vd_aux
7352               > (size_t) (contents_end_aux - (bfd_byte *) everdef))
7353             goto error_return_verdef;
7354
7355           everdaux = ((Elf_External_Verdaux *)
7356                       ((bfd_byte *) everdef + iverdef->vd_aux));
7357           iverdaux = iverdef->vd_auxptr;
7358           for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
7359             {
7360               _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
7361
7362               iverdaux->vda_nodename =
7363                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
7364                                                  iverdaux->vda_name);
7365               if (iverdaux->vda_nodename == NULL)
7366                 goto error_return_verdef;
7367
7368               if (j + 1 < iverdef->vd_cnt)
7369                 iverdaux->vda_nextptr = iverdaux + 1;
7370               else
7371                 iverdaux->vda_nextptr = NULL;
7372
7373               if (iverdaux->vda_next
7374                   > (size_t) (contents_end_aux - (bfd_byte *) everdaux))
7375                 goto error_return_verdef;
7376
7377               everdaux = ((Elf_External_Verdaux *)
7378                           ((bfd_byte *) everdaux + iverdaux->vda_next));
7379             }
7380
7381           if (iverdef->vd_cnt)
7382             iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
7383
7384           if ((size_t) (iverdef - iverdefarr) + 1 < maxidx)
7385             iverdef->vd_nextdef = iverdef + 1;
7386           else
7387             iverdef->vd_nextdef = NULL;
7388
7389           everdef = ((Elf_External_Verdef *)
7390                      ((bfd_byte *) everdef + iverdef->vd_next));
7391         }
7392
7393       free (contents);
7394       contents = NULL;
7395     }
7396   else if (default_imported_symver)
7397     {
7398       if (freeidx < 3)
7399         freeidx = 3;
7400       else
7401         freeidx++;
7402
7403       elf_tdata (abfd)->verdef = (Elf_Internal_Verdef *)
7404           bfd_zalloc2 (abfd, freeidx, sizeof (Elf_Internal_Verdef));
7405       if (elf_tdata (abfd)->verdef == NULL)
7406         goto error_return;
7407
7408       elf_tdata (abfd)->cverdefs = freeidx;
7409     }
7410
7411   /* Create a default version based on the soname.  */
7412   if (default_imported_symver)
7413     {
7414       Elf_Internal_Verdef *iverdef;
7415       Elf_Internal_Verdaux *iverdaux;
7416
7417       iverdef = &elf_tdata (abfd)->verdef[freeidx - 1];
7418
7419       iverdef->vd_version = VER_DEF_CURRENT;
7420       iverdef->vd_flags = 0;
7421       iverdef->vd_ndx = freeidx;
7422       iverdef->vd_cnt = 1;
7423
7424       iverdef->vd_bfd = abfd;
7425
7426       iverdef->vd_nodename = bfd_elf_get_dt_soname (abfd);
7427       if (iverdef->vd_nodename == NULL)
7428         goto error_return_verdef;
7429       iverdef->vd_nextdef = NULL;
7430       iverdef->vd_auxptr = (struct elf_internal_verdaux *)
7431           bfd_alloc (abfd, sizeof (Elf_Internal_Verdaux));
7432       if (iverdef->vd_auxptr == NULL)
7433         goto error_return_verdef;
7434
7435       iverdaux = iverdef->vd_auxptr;
7436       iverdaux->vda_nodename = iverdef->vd_nodename;
7437       iverdaux->vda_nextptr = NULL;
7438     }
7439
7440   return TRUE;
7441
7442  error_return:
7443   if (contents != NULL)
7444     free (contents);
7445   return FALSE;
7446 }
7447 \f
7448 asymbol *
7449 _bfd_elf_make_empty_symbol (bfd *abfd)
7450 {
7451   elf_symbol_type *newsym;
7452   bfd_size_type amt = sizeof (elf_symbol_type);
7453
7454   newsym = (elf_symbol_type *) bfd_zalloc (abfd, amt);
7455   if (!newsym)
7456     return NULL;
7457   else
7458     {
7459       newsym->symbol.the_bfd = abfd;
7460       return &newsym->symbol;
7461     }
7462 }
7463
7464 void
7465 _bfd_elf_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
7466                           asymbol *symbol,
7467                           symbol_info *ret)
7468 {
7469   bfd_symbol_info (symbol, ret);
7470 }
7471
7472 /* Return whether a symbol name implies a local symbol.  Most targets
7473    use this function for the is_local_label_name entry point, but some
7474    override it.  */
7475
7476 bfd_boolean
7477 _bfd_elf_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
7478                               const char *name)
7479 {
7480   /* Normal local symbols start with ``.L''.  */
7481   if (name[0] == '.' && name[1] == 'L')
7482     return TRUE;
7483
7484   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
7485      DWARF debugging symbols starting with ``..''.  */
7486   if (name[0] == '.' && name[1] == '.')
7487     return TRUE;
7488
7489   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
7490      emitting DWARF debugging output.  I suspect this is actually a
7491      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
7492      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
7493      underscore to be emitted on some ELF targets).  For ease of use,
7494      we treat such symbols as local.  */
7495   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
7496     return TRUE;
7497
7498   return FALSE;
7499 }
7500
7501 alent *
7502 _bfd_elf_get_lineno (bfd *abfd ATTRIBUTE_UNUSED,
7503                      asymbol *symbol ATTRIBUTE_UNUSED)
7504 {
7505   abort ();
7506   return NULL;
7507 }
7508
7509 bfd_boolean
7510 _bfd_elf_set_arch_mach (bfd *abfd,
7511                         enum bfd_architecture arch,
7512                         unsigned long machine)
7513 {
7514   /* If this isn't the right architecture for this backend, and this
7515      isn't the generic backend, fail.  */
7516   if (arch != get_elf_backend_data (abfd)->arch
7517       && arch != bfd_arch_unknown
7518       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
7519     return FALSE;
7520
7521   return bfd_default_set_arch_mach (abfd, arch, machine);
7522 }
7523
7524 /* Find the function to a particular section and offset,
7525    for error reporting.  */
7526
7527 static bfd_boolean
7528 elf_find_function (bfd *abfd,
7529                    asection *section,
7530                    asymbol **symbols,
7531                    bfd_vma offset,
7532                    const char **filename_ptr,
7533                    const char **functionname_ptr)
7534 {
7535   struct elf_find_function_cache
7536   {
7537     asection *last_section;
7538     asymbol *func;
7539     const char *filename;
7540     bfd_size_type func_size;
7541   } *cache;
7542
7543   if (symbols == NULL)
7544     return FALSE;
7545
7546   cache = elf_tdata (abfd)->elf_find_function_cache;
7547   if (cache == NULL)
7548     {
7549       cache = bfd_zalloc (abfd, sizeof (*cache));
7550       elf_tdata (abfd)->elf_find_function_cache = cache;
7551       if (cache == NULL)
7552         return FALSE;
7553     }
7554   if (cache->last_section != section
7555       || cache->func == NULL
7556       || offset < cache->func->value
7557       || offset >= cache->func->value + cache->func_size)
7558     {
7559       asymbol *file;
7560       bfd_vma low_func;
7561       asymbol **p;
7562       /* ??? Given multiple file symbols, it is impossible to reliably
7563          choose the right file name for global symbols.  File symbols are
7564          local symbols, and thus all file symbols must sort before any
7565          global symbols.  The ELF spec may be interpreted to say that a
7566          file symbol must sort before other local symbols, but currently
7567          ld -r doesn't do this.  So, for ld -r output, it is possible to
7568          make a better choice of file name for local symbols by ignoring
7569          file symbols appearing after a given local symbol.  */
7570       enum { nothing_seen, symbol_seen, file_after_symbol_seen } state;
7571       const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7572
7573       file = NULL;
7574       low_func = 0;
7575       state = nothing_seen;
7576       cache->filename = NULL;
7577       cache->func = NULL;
7578       cache->func_size = 0;
7579       cache->last_section = section;
7580
7581       for (p = symbols; *p != NULL; p++)
7582         {
7583           asymbol *sym = *p;
7584           bfd_vma code_off;
7585           bfd_size_type size;
7586
7587           if ((sym->flags & BSF_FILE) != 0)
7588             {
7589               file = sym;
7590               if (state == symbol_seen)
7591                 state = file_after_symbol_seen;
7592               continue;
7593             }
7594
7595           size = bed->maybe_function_sym (sym, section, &code_off);
7596           if (size != 0
7597               && code_off <= offset
7598               && (code_off > low_func
7599                   || (code_off == low_func
7600                       && size > cache->func_size)))
7601             {
7602               cache->func = sym;
7603               cache->func_size = size;
7604               cache->filename = NULL;
7605               low_func = code_off;
7606               if (file != NULL
7607                   && ((sym->flags & BSF_LOCAL) != 0
7608                       || state != file_after_symbol_seen))
7609                 cache->filename = bfd_asymbol_name (file);
7610             }
7611           if (state == nothing_seen)
7612             state = symbol_seen;
7613         }
7614     }
7615
7616   if (cache->func == NULL)
7617     return FALSE;
7618
7619   if (filename_ptr)
7620     *filename_ptr = cache->filename;
7621   if (functionname_ptr)
7622     *functionname_ptr = bfd_asymbol_name (cache->func);
7623
7624   return TRUE;
7625 }
7626
7627 /* Find the nearest line to a particular section and offset,
7628    for error reporting.  */
7629
7630 bfd_boolean
7631 _bfd_elf_find_nearest_line (bfd *abfd,
7632                             asection *section,
7633                             asymbol **symbols,
7634                             bfd_vma offset,
7635                             const char **filename_ptr,
7636                             const char **functionname_ptr,
7637                             unsigned int *line_ptr)
7638 {
7639   return _bfd_elf_find_nearest_line_discriminator (abfd, section, symbols,
7640                                                    offset, filename_ptr,
7641                                                    functionname_ptr,
7642                                                    line_ptr,
7643                                                    NULL);
7644 }
7645
7646 bfd_boolean
7647 _bfd_elf_find_nearest_line_discriminator (bfd *abfd,
7648                                           asection *section,
7649                                           asymbol **symbols,
7650                                           bfd_vma offset,
7651                                           const char **filename_ptr,
7652                                           const char **functionname_ptr,
7653                                           unsigned int *line_ptr,
7654                                           unsigned int *discriminator_ptr)
7655 {
7656   bfd_boolean found;
7657
7658   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
7659                                      filename_ptr, functionname_ptr,
7660                                      line_ptr))
7661     {
7662       if (!*functionname_ptr)
7663         elf_find_function (abfd, section, symbols, offset,
7664                            *filename_ptr ? NULL : filename_ptr,
7665                            functionname_ptr);
7666
7667       return TRUE;
7668     }
7669
7670   if (_bfd_dwarf2_find_nearest_line (abfd, dwarf_debug_sections,
7671                                      section, symbols, offset,
7672                                      filename_ptr, functionname_ptr,
7673                                      line_ptr, discriminator_ptr, 0,
7674                                      &elf_tdata (abfd)->dwarf2_find_line_info))
7675     {
7676       if (!*functionname_ptr)
7677         elf_find_function (abfd, section, symbols, offset,
7678                            *filename_ptr ? NULL : filename_ptr,
7679                            functionname_ptr);
7680
7681       return TRUE;
7682     }
7683
7684   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
7685                                              &found, filename_ptr,
7686                                              functionname_ptr, line_ptr,
7687                                              &elf_tdata (abfd)->line_info))
7688     return FALSE;
7689   if (found && (*functionname_ptr || *line_ptr))
7690     return TRUE;
7691
7692   if (symbols == NULL)
7693     return FALSE;
7694
7695   if (! elf_find_function (abfd, section, symbols, offset,
7696                            filename_ptr, functionname_ptr))
7697     return FALSE;
7698
7699   *line_ptr = 0;
7700   return TRUE;
7701 }
7702
7703 /* Find the line for a symbol.  */
7704
7705 bfd_boolean
7706 _bfd_elf_find_line (bfd *abfd, asymbol **symbols, asymbol *symbol,
7707                     const char **filename_ptr, unsigned int *line_ptr)
7708 {
7709   return _bfd_elf_find_line_discriminator (abfd, symbols, symbol,
7710                                            filename_ptr, line_ptr,
7711                                            NULL);
7712 }
7713
7714 bfd_boolean
7715 _bfd_elf_find_line_discriminator (bfd *abfd, asymbol **symbols, asymbol *symbol,
7716                                   const char **filename_ptr,
7717                                   unsigned int *line_ptr,
7718                                   unsigned int *discriminator_ptr)
7719 {
7720   return _bfd_dwarf2_find_line (abfd, symbols, symbol,
7721                                 filename_ptr, line_ptr, discriminator_ptr, 0,
7722                                 &elf_tdata (abfd)->dwarf2_find_line_info);
7723 }
7724
7725 /* After a call to bfd_find_nearest_line, successive calls to
7726    bfd_find_inliner_info can be used to get source information about
7727    each level of function inlining that terminated at the address
7728    passed to bfd_find_nearest_line.  Currently this is only supported
7729    for DWARF2 with appropriate DWARF3 extensions. */
7730
7731 bfd_boolean
7732 _bfd_elf_find_inliner_info (bfd *abfd,
7733                             const char **filename_ptr,
7734                             const char **functionname_ptr,
7735                             unsigned int *line_ptr)
7736 {
7737   bfd_boolean found;
7738   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
7739                                          functionname_ptr, line_ptr,
7740                                          & elf_tdata (abfd)->dwarf2_find_line_info);
7741   return found;
7742 }
7743
7744 int
7745 _bfd_elf_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
7746 {
7747   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7748   int ret = bed->s->sizeof_ehdr;
7749
7750   if (!info->relocatable)
7751     {
7752       bfd_size_type phdr_size = elf_program_header_size (abfd);
7753
7754       if (phdr_size == (bfd_size_type) -1)
7755         {
7756           struct elf_segment_map *m;
7757
7758           phdr_size = 0;
7759           for (m = elf_seg_map (abfd); m != NULL; m = m->next)
7760             phdr_size += bed->s->sizeof_phdr;
7761
7762           if (phdr_size == 0)
7763             phdr_size = get_program_header_size (abfd, info);
7764         }
7765
7766       elf_program_header_size (abfd) = phdr_size;
7767       ret += phdr_size;
7768     }
7769
7770   return ret;
7771 }
7772
7773 bfd_boolean
7774 _bfd_elf_set_section_contents (bfd *abfd,
7775                                sec_ptr section,
7776                                const void *location,
7777                                file_ptr offset,
7778                                bfd_size_type count)
7779 {
7780   Elf_Internal_Shdr *hdr;
7781   bfd_signed_vma pos;
7782
7783   if (! abfd->output_has_begun
7784       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
7785     return FALSE;
7786
7787   hdr = &elf_section_data (section)->this_hdr;
7788   pos = hdr->sh_offset + offset;
7789   if (bfd_seek (abfd, pos, SEEK_SET) != 0
7790       || bfd_bwrite (location, count, abfd) != count)
7791     return FALSE;
7792
7793   return TRUE;
7794 }
7795
7796 void
7797 _bfd_elf_no_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
7798                            arelent *cache_ptr ATTRIBUTE_UNUSED,
7799                            Elf_Internal_Rela *dst ATTRIBUTE_UNUSED)
7800 {
7801   abort ();
7802 }
7803
7804 /* Try to convert a non-ELF reloc into an ELF one.  */
7805
7806 bfd_boolean
7807 _bfd_elf_validate_reloc (bfd *abfd, arelent *areloc)
7808 {
7809   /* Check whether we really have an ELF howto.  */
7810
7811   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
7812     {
7813       bfd_reloc_code_real_type code;
7814       reloc_howto_type *howto;
7815
7816       /* Alien reloc: Try to determine its type to replace it with an
7817          equivalent ELF reloc.  */
7818
7819       if (areloc->howto->pc_relative)
7820         {
7821           switch (areloc->howto->bitsize)
7822             {
7823             case 8:
7824               code = BFD_RELOC_8_PCREL;
7825               break;
7826             case 12:
7827               code = BFD_RELOC_12_PCREL;
7828               break;
7829             case 16:
7830               code = BFD_RELOC_16_PCREL;
7831               break;
7832             case 24:
7833               code = BFD_RELOC_24_PCREL;
7834               break;
7835             case 32:
7836               code = BFD_RELOC_32_PCREL;
7837               break;
7838             case 64:
7839               code = BFD_RELOC_64_PCREL;
7840               break;
7841             default:
7842               goto fail;
7843             }
7844
7845           howto = bfd_reloc_type_lookup (abfd, code);
7846
7847           if (areloc->howto->pcrel_offset != howto->pcrel_offset)
7848             {
7849               if (howto->pcrel_offset)
7850                 areloc->addend += areloc->address;
7851               else
7852                 areloc->addend -= areloc->address; /* addend is unsigned!! */
7853             }
7854         }
7855       else
7856         {
7857           switch (areloc->howto->bitsize)
7858             {
7859             case 8:
7860               code = BFD_RELOC_8;
7861               break;
7862             case 14:
7863               code = BFD_RELOC_14;
7864               break;
7865             case 16:
7866               code = BFD_RELOC_16;
7867               break;
7868             case 26:
7869               code = BFD_RELOC_26;
7870               break;
7871             case 32:
7872               code = BFD_RELOC_32;
7873               break;
7874             case 64:
7875               code = BFD_RELOC_64;
7876               break;
7877             default:
7878               goto fail;
7879             }
7880
7881           howto = bfd_reloc_type_lookup (abfd, code);
7882         }
7883
7884       if (howto)
7885         areloc->howto = howto;
7886       else
7887         goto fail;
7888     }
7889
7890   return TRUE;
7891
7892  fail:
7893   (*_bfd_error_handler)
7894     (_("%B: unsupported relocation type %s"),
7895      abfd, areloc->howto->name);
7896   bfd_set_error (bfd_error_bad_value);
7897   return FALSE;
7898 }
7899
7900 bfd_boolean
7901 _bfd_elf_close_and_cleanup (bfd *abfd)
7902 {
7903   struct elf_obj_tdata *tdata = elf_tdata (abfd);
7904   if (bfd_get_format (abfd) == bfd_object && tdata != NULL)
7905     {
7906       if (elf_tdata (abfd)->o != NULL && elf_shstrtab (abfd) != NULL)
7907         _bfd_elf_strtab_free (elf_shstrtab (abfd));
7908       _bfd_dwarf2_cleanup_debug_info (abfd, &tdata->dwarf2_find_line_info);
7909     }
7910
7911   return _bfd_generic_close_and_cleanup (abfd);
7912 }
7913
7914 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
7915    in the relocation's offset.  Thus we cannot allow any sort of sanity
7916    range-checking to interfere.  There is nothing else to do in processing
7917    this reloc.  */
7918
7919 bfd_reloc_status_type
7920 _bfd_elf_rel_vtable_reloc_fn
7921   (bfd *abfd ATTRIBUTE_UNUSED, arelent *re ATTRIBUTE_UNUSED,
7922    struct bfd_symbol *symbol ATTRIBUTE_UNUSED,
7923    void *data ATTRIBUTE_UNUSED, asection *is ATTRIBUTE_UNUSED,
7924    bfd *obfd ATTRIBUTE_UNUSED, char **errmsg ATTRIBUTE_UNUSED)
7925 {
7926   return bfd_reloc_ok;
7927 }
7928 \f
7929 /* Elf core file support.  Much of this only works on native
7930    toolchains, since we rely on knowing the
7931    machine-dependent procfs structure in order to pick
7932    out details about the corefile.  */
7933
7934 #ifdef HAVE_SYS_PROCFS_H
7935 /* Needed for new procfs interface on sparc-solaris.  */
7936 # define _STRUCTURED_PROC 1
7937 # include <sys/procfs.h>
7938 #endif
7939
7940 /* Return a PID that identifies a "thread" for threaded cores, or the
7941    PID of the main process for non-threaded cores.  */
7942
7943 static int
7944 elfcore_make_pid (bfd *abfd)
7945 {
7946   int pid;
7947
7948   pid = elf_tdata (abfd)->core->lwpid;
7949   if (pid == 0)
7950     pid = elf_tdata (abfd)->core->pid;
7951
7952   return pid;
7953 }
7954
7955 /* If there isn't a section called NAME, make one, using
7956    data from SECT.  Note, this function will generate a
7957    reference to NAME, so you shouldn't deallocate or
7958    overwrite it.  */
7959
7960 static bfd_boolean
7961 elfcore_maybe_make_sect (bfd *abfd, char *name, asection *sect)
7962 {
7963   asection *sect2;
7964
7965   if (bfd_get_section_by_name (abfd, name) != NULL)
7966     return TRUE;
7967
7968   sect2 = bfd_make_section_with_flags (abfd, name, sect->flags);
7969   if (sect2 == NULL)
7970     return FALSE;
7971
7972   sect2->size = sect->size;
7973   sect2->filepos = sect->filepos;
7974   sect2->alignment_power = sect->alignment_power;
7975   return TRUE;
7976 }
7977
7978 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
7979    actually creates up to two pseudosections:
7980    - For the single-threaded case, a section named NAME, unless
7981      such a section already exists.
7982    - For the multi-threaded case, a section named "NAME/PID", where
7983      PID is elfcore_make_pid (abfd).
7984    Both pseudosections have identical contents. */
7985 bfd_boolean
7986 _bfd_elfcore_make_pseudosection (bfd *abfd,
7987                                  char *name,
7988                                  size_t size,
7989                                  ufile_ptr filepos)
7990 {
7991   char buf[100];
7992   char *threaded_name;
7993   size_t len;
7994   asection *sect;
7995
7996   /* Build the section name.  */
7997
7998   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
7999   len = strlen (buf) + 1;
8000   threaded_name = (char *) bfd_alloc (abfd, len);
8001   if (threaded_name == NULL)
8002     return FALSE;
8003   memcpy (threaded_name, buf, len);
8004
8005   sect = bfd_make_section_anyway_with_flags (abfd, threaded_name,
8006                                              SEC_HAS_CONTENTS);
8007   if (sect == NULL)
8008     return FALSE;
8009   sect->size = size;
8010   sect->filepos = filepos;
8011   sect->alignment_power = 2;
8012
8013   return elfcore_maybe_make_sect (abfd, name, sect);
8014 }
8015
8016 /* prstatus_t exists on:
8017      solaris 2.5+
8018      linux 2.[01] + glibc
8019      unixware 4.2
8020 */
8021
8022 #if defined (HAVE_PRSTATUS_T)
8023
8024 static bfd_boolean
8025 elfcore_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
8026 {
8027   size_t size;
8028   int offset;
8029
8030   if (note->descsz == sizeof (prstatus_t))
8031     {
8032       prstatus_t prstat;
8033
8034       size = sizeof (prstat.pr_reg);
8035       offset   = offsetof (prstatus_t, pr_reg);
8036       memcpy (&prstat, note->descdata, sizeof (prstat));
8037
8038       /* Do not overwrite the core signal if it
8039          has already been set by another thread.  */
8040       if (elf_tdata (abfd)->core->signal == 0)
8041         elf_tdata (abfd)->core->signal = prstat.pr_cursig;
8042       if (elf_tdata (abfd)->core->pid == 0)
8043         elf_tdata (abfd)->core->pid = prstat.pr_pid;
8044
8045       /* pr_who exists on:
8046          solaris 2.5+
8047          unixware 4.2
8048          pr_who doesn't exist on:
8049          linux 2.[01]
8050          */
8051 #if defined (HAVE_PRSTATUS_T_PR_WHO)
8052       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
8053 #else
8054       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
8055 #endif
8056     }
8057 #if defined (HAVE_PRSTATUS32_T)
8058   else if (note->descsz == sizeof (prstatus32_t))
8059     {
8060       /* 64-bit host, 32-bit corefile */
8061       prstatus32_t prstat;
8062
8063       size = sizeof (prstat.pr_reg);
8064       offset   = offsetof (prstatus32_t, pr_reg);
8065       memcpy (&prstat, note->descdata, sizeof (prstat));
8066
8067       /* Do not overwrite the core signal if it
8068          has already been set by another thread.  */
8069       if (elf_tdata (abfd)->core->signal == 0)
8070         elf_tdata (abfd)->core->signal = prstat.pr_cursig;
8071       if (elf_tdata (abfd)->core->pid == 0)
8072         elf_tdata (abfd)->core->pid = prstat.pr_pid;
8073
8074       /* pr_who exists on:
8075          solaris 2.5+
8076          unixware 4.2
8077          pr_who doesn't exist on:
8078          linux 2.[01]
8079          */
8080 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
8081       elf_tdata (abfd)->core->lwpid = prstat.pr_who;
8082 #else
8083       elf_tdata (abfd)->core->lwpid = prstat.pr_pid;
8084 #endif
8085     }
8086 #endif /* HAVE_PRSTATUS32_T */
8087   else
8088     {
8089       /* Fail - we don't know how to handle any other
8090          note size (ie. data object type).  */
8091       return TRUE;
8092     }
8093
8094   /* Make a ".reg/999" section and a ".reg" section.  */
8095   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
8096                                           size, note->descpos + offset);
8097 }
8098 #endif /* defined (HAVE_PRSTATUS_T) */
8099
8100 /* Create a pseudosection containing the exact contents of NOTE.  */
8101 static bfd_boolean
8102 elfcore_make_note_pseudosection (bfd *abfd,
8103                                  char *name,
8104                                  Elf_Internal_Note *note)
8105 {
8106   return _bfd_elfcore_make_pseudosection (abfd, name,
8107                                           note->descsz, note->descpos);
8108 }
8109
8110 /* There isn't a consistent prfpregset_t across platforms,
8111    but it doesn't matter, because we don't have to pick this
8112    data structure apart.  */
8113
8114 static bfd_boolean
8115 elfcore_grok_prfpreg (bfd *abfd, Elf_Internal_Note *note)
8116 {
8117   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
8118 }
8119
8120 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
8121    type of NT_PRXFPREG.  Just include the whole note's contents
8122    literally.  */
8123
8124 static bfd_boolean
8125 elfcore_grok_prxfpreg (bfd *abfd, Elf_Internal_Note *note)
8126 {
8127   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
8128 }
8129
8130 /* Linux dumps the Intel XSAVE extended state in a note named "LINUX"
8131    with a note type of NT_X86_XSTATE.  Just include the whole note's
8132    contents literally.  */
8133
8134 static bfd_boolean
8135 elfcore_grok_xstatereg (bfd *abfd, Elf_Internal_Note *note)
8136 {
8137   return elfcore_make_note_pseudosection (abfd, ".reg-xstate", note);
8138 }
8139
8140 static bfd_boolean
8141 elfcore_grok_ppc_vmx (bfd *abfd, Elf_Internal_Note *note)
8142 {
8143   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vmx", note);
8144 }
8145
8146 static bfd_boolean
8147 elfcore_grok_ppc_vsx (bfd *abfd, Elf_Internal_Note *note)
8148 {
8149   return elfcore_make_note_pseudosection (abfd, ".reg-ppc-vsx", note);
8150 }
8151
8152 static bfd_boolean
8153 elfcore_grok_s390_high_gprs (bfd *abfd, Elf_Internal_Note *note)
8154 {
8155   return elfcore_make_note_pseudosection (abfd, ".reg-s390-high-gprs", note);
8156 }
8157
8158 static bfd_boolean
8159 elfcore_grok_s390_timer (bfd *abfd, Elf_Internal_Note *note)
8160 {
8161   return elfcore_make_note_pseudosection (abfd, ".reg-s390-timer", note);
8162 }
8163
8164 static bfd_boolean
8165 elfcore_grok_s390_todcmp (bfd *abfd, Elf_Internal_Note *note)
8166 {
8167   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todcmp", note);
8168 }
8169
8170 static bfd_boolean
8171 elfcore_grok_s390_todpreg (bfd *abfd, Elf_Internal_Note *note)
8172 {
8173   return elfcore_make_note_pseudosection (abfd, ".reg-s390-todpreg", note);
8174 }
8175
8176 static bfd_boolean
8177 elfcore_grok_s390_ctrs (bfd *abfd, Elf_Internal_Note *note)
8178 {
8179   return elfcore_make_note_pseudosection (abfd, ".reg-s390-ctrs", note);
8180 }
8181
8182 static bfd_boolean
8183 elfcore_grok_s390_prefix (bfd *abfd, Elf_Internal_Note *note)
8184 {
8185   return elfcore_make_note_pseudosection (abfd, ".reg-s390-prefix", note);
8186 }
8187
8188 static bfd_boolean
8189 elfcore_grok_s390_last_break (bfd *abfd, Elf_Internal_Note *note)
8190 {
8191   return elfcore_make_note_pseudosection (abfd, ".reg-s390-last-break", note);
8192 }
8193
8194 static bfd_boolean
8195 elfcore_grok_s390_system_call (bfd *abfd, Elf_Internal_Note *note)
8196 {
8197   return elfcore_make_note_pseudosection (abfd, ".reg-s390-system-call", note);
8198 }
8199
8200 static bfd_boolean
8201 elfcore_grok_s390_tdb (bfd *abfd, Elf_Internal_Note *note)
8202 {
8203   return elfcore_make_note_pseudosection (abfd, ".reg-s390-tdb", note);
8204 }
8205
8206 static bfd_boolean
8207 elfcore_grok_arm_vfp (bfd *abfd, Elf_Internal_Note *note)
8208 {
8209   return elfcore_make_note_pseudosection (abfd, ".reg-arm-vfp", note);
8210 }
8211
8212 static bfd_boolean
8213 elfcore_grok_aarch_tls (bfd *abfd, Elf_Internal_Note *note)
8214 {
8215   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-tls", note);
8216 }
8217
8218 static bfd_boolean
8219 elfcore_grok_aarch_hw_break (bfd *abfd, Elf_Internal_Note *note)
8220 {
8221   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-break", note);
8222 }
8223
8224 static bfd_boolean
8225 elfcore_grok_aarch_hw_watch (bfd *abfd, Elf_Internal_Note *note)
8226 {
8227   return elfcore_make_note_pseudosection (abfd, ".reg-aarch-hw-watch", note);
8228 }
8229
8230 #if defined (HAVE_PRPSINFO_T)
8231 typedef prpsinfo_t   elfcore_psinfo_t;
8232 #if defined (HAVE_PRPSINFO32_T)         /* Sparc64 cross Sparc32 */
8233 typedef prpsinfo32_t elfcore_psinfo32_t;
8234 #endif
8235 #endif
8236
8237 #if defined (HAVE_PSINFO_T)
8238 typedef psinfo_t   elfcore_psinfo_t;
8239 #if defined (HAVE_PSINFO32_T)           /* Sparc64 cross Sparc32 */
8240 typedef psinfo32_t elfcore_psinfo32_t;
8241 #endif
8242 #endif
8243
8244 /* return a malloc'ed copy of a string at START which is at
8245    most MAX bytes long, possibly without a terminating '\0'.
8246    the copy will always have a terminating '\0'.  */
8247
8248 char *
8249 _bfd_elfcore_strndup (bfd *abfd, char *start, size_t max)
8250 {
8251   char *dups;
8252   char *end = (char *) memchr (start, '\0', max);
8253   size_t len;
8254
8255   if (end == NULL)
8256     len = max;
8257   else
8258     len = end - start;
8259
8260   dups = (char *) bfd_alloc (abfd, len + 1);
8261   if (dups == NULL)
8262     return NULL;
8263
8264   memcpy (dups, start, len);
8265   dups[len] = '\0';
8266
8267   return dups;
8268 }
8269
8270 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
8271 static bfd_boolean
8272 elfcore_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
8273 {
8274   if (note->descsz == sizeof (elfcore_psinfo_t))
8275     {
8276       elfcore_psinfo_t psinfo;
8277
8278       memcpy (&psinfo, note->descdata, sizeof (psinfo));
8279
8280 #if defined (HAVE_PSINFO_T_PR_PID) || defined (HAVE_PRPSINFO_T_PR_PID)
8281       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
8282 #endif
8283       elf_tdata (abfd)->core->program
8284         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
8285                                 sizeof (psinfo.pr_fname));
8286
8287       elf_tdata (abfd)->core->command
8288         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
8289                                 sizeof (psinfo.pr_psargs));
8290     }
8291 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
8292   else if (note->descsz == sizeof (elfcore_psinfo32_t))
8293     {
8294       /* 64-bit host, 32-bit corefile */
8295       elfcore_psinfo32_t psinfo;
8296
8297       memcpy (&psinfo, note->descdata, sizeof (psinfo));
8298
8299 #if defined (HAVE_PSINFO32_T_PR_PID) || defined (HAVE_PRPSINFO32_T_PR_PID)
8300       elf_tdata (abfd)->core->pid = psinfo.pr_pid;
8301 #endif
8302       elf_tdata (abfd)->core->program
8303         = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
8304                                 sizeof (psinfo.pr_fname));
8305
8306       elf_tdata (abfd)->core->command
8307         = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
8308                                 sizeof (psinfo.pr_psargs));
8309     }
8310 #endif
8311
8312   else
8313     {
8314       /* Fail - we don't know how to handle any other
8315          note size (ie. data object type).  */
8316       return TRUE;
8317     }
8318
8319   /* Note that for some reason, a spurious space is tacked
8320      onto the end of the args in some (at least one anyway)
8321      implementations, so strip it off if it exists.  */
8322
8323   {
8324     char *command = elf_tdata (abfd)->core->command;
8325     int n = strlen (command);
8326
8327     if (0 < n && command[n - 1] == ' ')
8328       command[n - 1] = '\0';
8329   }
8330
8331   return TRUE;
8332 }
8333 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
8334
8335 #if defined (HAVE_PSTATUS_T)
8336 static bfd_boolean
8337 elfcore_grok_pstatus (bfd *abfd, Elf_Internal_Note *note)
8338 {
8339   if (note->descsz == sizeof (pstatus_t)
8340 #if defined (HAVE_PXSTATUS_T)
8341       || note->descsz == sizeof (pxstatus_t)
8342 #endif
8343       )
8344     {
8345       pstatus_t pstat;
8346
8347       memcpy (&pstat, note->descdata, sizeof (pstat));
8348
8349       elf_tdata (abfd)->core->pid = pstat.pr_pid;
8350     }
8351 #if defined (HAVE_PSTATUS32_T)
8352   else if (note->descsz == sizeof (pstatus32_t))
8353     {
8354       /* 64-bit host, 32-bit corefile */
8355       pstatus32_t pstat;
8356
8357       memcpy (&pstat, note->descdata, sizeof (pstat));
8358
8359       elf_tdata (abfd)->core->pid = pstat.pr_pid;
8360     }
8361 #endif
8362   /* Could grab some more details from the "representative"
8363      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
8364      NT_LWPSTATUS note, presumably.  */
8365
8366   return TRUE;
8367 }
8368 #endif /* defined (HAVE_PSTATUS_T) */
8369
8370 #if defined (HAVE_LWPSTATUS_T)
8371 static bfd_boolean
8372 elfcore_grok_lwpstatus (bfd *abfd, Elf_Internal_Note *note)
8373 {
8374   lwpstatus_t lwpstat;
8375   char buf[100];
8376   char *name;
8377   size_t len;
8378   asection *sect;
8379
8380   if (note->descsz != sizeof (lwpstat)
8381 #if defined (HAVE_LWPXSTATUS_T)
8382       && note->descsz != sizeof (lwpxstatus_t)
8383 #endif
8384       )
8385     return TRUE;
8386
8387   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
8388
8389   elf_tdata (abfd)->core->lwpid = lwpstat.pr_lwpid;
8390   /* Do not overwrite the core signal if it has already been set by
8391      another thread.  */
8392   if (elf_tdata (abfd)->core->signal == 0)
8393     elf_tdata (abfd)->core->signal = lwpstat.pr_cursig;
8394
8395   /* Make a ".reg/999" section.  */
8396
8397   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
8398   len = strlen (buf) + 1;
8399   name = bfd_alloc (abfd, len);
8400   if (name == NULL)
8401     return FALSE;
8402   memcpy (name, buf, len);
8403
8404   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8405   if (sect == NULL)
8406     return FALSE;
8407
8408 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
8409   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
8410   sect->filepos = note->descpos
8411     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
8412 #endif
8413
8414 #if defined (HAVE_LWPSTATUS_T_PR_REG)
8415   sect->size = sizeof (lwpstat.pr_reg);
8416   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
8417 #endif
8418
8419   sect->alignment_power = 2;
8420
8421   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
8422     return FALSE;
8423
8424   /* Make a ".reg2/999" section */
8425
8426   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
8427   len = strlen (buf) + 1;
8428   name = bfd_alloc (abfd, len);
8429   if (name == NULL)
8430     return FALSE;
8431   memcpy (name, buf, len);
8432
8433   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8434   if (sect == NULL)
8435     return FALSE;
8436
8437 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
8438   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
8439   sect->filepos = note->descpos
8440     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
8441 #endif
8442
8443 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
8444   sect->size = sizeof (lwpstat.pr_fpreg);
8445   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
8446 #endif
8447
8448   sect->alignment_power = 2;
8449
8450   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
8451 }
8452 #endif /* defined (HAVE_LWPSTATUS_T) */
8453
8454 static bfd_boolean
8455 elfcore_grok_win32pstatus (bfd *abfd, Elf_Internal_Note *note)
8456 {
8457   char buf[30];
8458   char *name;
8459   size_t len;
8460   asection *sect;
8461   int type;
8462   int is_active_thread;
8463   bfd_vma base_addr;
8464
8465   if (note->descsz < 728)
8466     return TRUE;
8467
8468   if (! CONST_STRNEQ (note->namedata, "win32"))
8469     return TRUE;
8470
8471   type = bfd_get_32 (abfd, note->descdata);
8472
8473   switch (type)
8474     {
8475     case 1 /* NOTE_INFO_PROCESS */:
8476       /* FIXME: need to add ->core->command.  */
8477       /* process_info.pid */
8478       elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, note->descdata + 8);
8479       /* process_info.signal */
8480       elf_tdata (abfd)->core->signal = bfd_get_32 (abfd, note->descdata + 12);
8481       break;
8482
8483     case 2 /* NOTE_INFO_THREAD */:
8484       /* Make a ".reg/999" section.  */
8485       /* thread_info.tid */
8486       sprintf (buf, ".reg/%ld", (long) bfd_get_32 (abfd, note->descdata + 8));
8487
8488       len = strlen (buf) + 1;
8489       name = (char *) bfd_alloc (abfd, len);
8490       if (name == NULL)
8491         return FALSE;
8492
8493       memcpy (name, buf, len);
8494
8495       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8496       if (sect == NULL)
8497         return FALSE;
8498
8499       /* sizeof (thread_info.thread_context) */
8500       sect->size = 716;
8501       /* offsetof (thread_info.thread_context) */
8502       sect->filepos = note->descpos + 12;
8503       sect->alignment_power = 2;
8504
8505       /* thread_info.is_active_thread */
8506       is_active_thread = bfd_get_32 (abfd, note->descdata + 8);
8507
8508       if (is_active_thread)
8509         if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
8510           return FALSE;
8511       break;
8512
8513     case 3 /* NOTE_INFO_MODULE */:
8514       /* Make a ".module/xxxxxxxx" section.  */
8515       /* module_info.base_address */
8516       base_addr = bfd_get_32 (abfd, note->descdata + 4);
8517       sprintf (buf, ".module/%08lx", (unsigned long) base_addr);
8518
8519       len = strlen (buf) + 1;
8520       name = (char *) bfd_alloc (abfd, len);
8521       if (name == NULL)
8522         return FALSE;
8523
8524       memcpy (name, buf, len);
8525
8526       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8527
8528       if (sect == NULL)
8529         return FALSE;
8530
8531       sect->size = note->descsz;
8532       sect->filepos = note->descpos;
8533       sect->alignment_power = 2;
8534       break;
8535
8536     default:
8537       return TRUE;
8538     }
8539
8540   return TRUE;
8541 }
8542
8543 static bfd_boolean
8544 elfcore_grok_note (bfd *abfd, Elf_Internal_Note *note)
8545 {
8546   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8547
8548   switch (note->type)
8549     {
8550     default:
8551       return TRUE;
8552
8553     case NT_PRSTATUS:
8554       if (bed->elf_backend_grok_prstatus)
8555         if ((*bed->elf_backend_grok_prstatus) (abfd, note))
8556           return TRUE;
8557 #if defined (HAVE_PRSTATUS_T)
8558       return elfcore_grok_prstatus (abfd, note);
8559 #else
8560       return TRUE;
8561 #endif
8562
8563 #if defined (HAVE_PSTATUS_T)
8564     case NT_PSTATUS:
8565       return elfcore_grok_pstatus (abfd, note);
8566 #endif
8567
8568 #if defined (HAVE_LWPSTATUS_T)
8569     case NT_LWPSTATUS:
8570       return elfcore_grok_lwpstatus (abfd, note);
8571 #endif
8572
8573     case NT_FPREGSET:           /* FIXME: rename to NT_PRFPREG */
8574       return elfcore_grok_prfpreg (abfd, note);
8575
8576     case NT_WIN32PSTATUS:
8577       return elfcore_grok_win32pstatus (abfd, note);
8578
8579     case NT_PRXFPREG:           /* Linux SSE extension */
8580       if (note->namesz == 6
8581           && strcmp (note->namedata, "LINUX") == 0)
8582         return elfcore_grok_prxfpreg (abfd, note);
8583       else
8584         return TRUE;
8585
8586     case NT_X86_XSTATE:         /* Linux XSAVE extension */
8587       if (note->namesz == 6
8588           && strcmp (note->namedata, "LINUX") == 0)
8589         return elfcore_grok_xstatereg (abfd, note);
8590       else
8591         return TRUE;
8592
8593     case NT_PPC_VMX:
8594       if (note->namesz == 6
8595           && strcmp (note->namedata, "LINUX") == 0)
8596         return elfcore_grok_ppc_vmx (abfd, note);
8597       else
8598         return TRUE;
8599
8600     case NT_PPC_VSX:
8601       if (note->namesz == 6
8602           && strcmp (note->namedata, "LINUX") == 0)
8603         return elfcore_grok_ppc_vsx (abfd, note);
8604       else
8605         return TRUE;
8606
8607     case NT_S390_HIGH_GPRS:
8608       if (note->namesz == 6
8609           && strcmp (note->namedata, "LINUX") == 0)
8610         return elfcore_grok_s390_high_gprs (abfd, note);
8611       else
8612         return TRUE;
8613
8614     case NT_S390_TIMER:
8615       if (note->namesz == 6
8616           && strcmp (note->namedata, "LINUX") == 0)
8617         return elfcore_grok_s390_timer (abfd, note);
8618       else
8619         return TRUE;
8620
8621     case NT_S390_TODCMP:
8622       if (note->namesz == 6
8623           && strcmp (note->namedata, "LINUX") == 0)
8624         return elfcore_grok_s390_todcmp (abfd, note);
8625       else
8626         return TRUE;
8627
8628     case NT_S390_TODPREG:
8629       if (note->namesz == 6
8630           && strcmp (note->namedata, "LINUX") == 0)
8631         return elfcore_grok_s390_todpreg (abfd, note);
8632       else
8633         return TRUE;
8634
8635     case NT_S390_CTRS:
8636       if (note->namesz == 6
8637           && strcmp (note->namedata, "LINUX") == 0)
8638         return elfcore_grok_s390_ctrs (abfd, note);
8639       else
8640         return TRUE;
8641
8642     case NT_S390_PREFIX:
8643       if (note->namesz == 6
8644           && strcmp (note->namedata, "LINUX") == 0)
8645         return elfcore_grok_s390_prefix (abfd, note);
8646       else
8647         return TRUE;
8648
8649     case NT_S390_LAST_BREAK:
8650       if (note->namesz == 6
8651           && strcmp (note->namedata, "LINUX") == 0)
8652         return elfcore_grok_s390_last_break (abfd, note);
8653       else
8654         return TRUE;
8655
8656     case NT_S390_SYSTEM_CALL:
8657       if (note->namesz == 6
8658           && strcmp (note->namedata, "LINUX") == 0)
8659         return elfcore_grok_s390_system_call (abfd, note);
8660       else
8661         return TRUE;
8662
8663     case NT_S390_TDB:
8664       if (note->namesz == 6
8665           && strcmp (note->namedata, "LINUX") == 0)
8666         return elfcore_grok_s390_tdb (abfd, note);
8667       else
8668         return TRUE;
8669
8670     case NT_ARM_VFP:
8671       if (note->namesz == 6
8672           && strcmp (note->namedata, "LINUX") == 0)
8673         return elfcore_grok_arm_vfp (abfd, note);
8674       else
8675         return TRUE;
8676
8677     case NT_ARM_TLS:
8678       if (note->namesz == 6
8679           && strcmp (note->namedata, "LINUX") == 0)
8680         return elfcore_grok_aarch_tls (abfd, note);
8681       else
8682         return TRUE;
8683
8684     case NT_ARM_HW_BREAK:
8685       if (note->namesz == 6
8686           && strcmp (note->namedata, "LINUX") == 0)
8687         return elfcore_grok_aarch_hw_break (abfd, note);
8688       else
8689         return TRUE;
8690
8691     case NT_ARM_HW_WATCH:
8692       if (note->namesz == 6
8693           && strcmp (note->namedata, "LINUX") == 0)
8694         return elfcore_grok_aarch_hw_watch (abfd, note);
8695       else
8696         return TRUE;
8697
8698     case NT_PRPSINFO:
8699     case NT_PSINFO:
8700       if (bed->elf_backend_grok_psinfo)
8701         if ((*bed->elf_backend_grok_psinfo) (abfd, note))
8702           return TRUE;
8703 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
8704       return elfcore_grok_psinfo (abfd, note);
8705 #else
8706       return TRUE;
8707 #endif
8708
8709     case NT_AUXV:
8710       {
8711         asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
8712                                                              SEC_HAS_CONTENTS);
8713
8714         if (sect == NULL)
8715           return FALSE;
8716         sect->size = note->descsz;
8717         sect->filepos = note->descpos;
8718         sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
8719
8720         return TRUE;
8721       }
8722
8723     case NT_FILE:
8724       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.file",
8725                                               note);
8726
8727     case NT_SIGINFO:
8728       return elfcore_make_note_pseudosection (abfd, ".note.linuxcore.siginfo",
8729                                               note);
8730     }
8731 }
8732
8733 static bfd_boolean
8734 elfobj_grok_gnu_build_id (bfd *abfd, Elf_Internal_Note *note)
8735 {
8736   struct elf_obj_tdata *t;
8737
8738   if (note->descsz == 0)
8739     return FALSE;
8740
8741   t = elf_tdata (abfd);
8742   t->build_id = bfd_alloc (abfd, sizeof (*t->build_id) - 1 + note->descsz);
8743   if (t->build_id == NULL)
8744     return FALSE;
8745
8746   t->build_id->size = note->descsz;
8747   memcpy (t->build_id->data, note->descdata, note->descsz);
8748
8749   return TRUE;
8750 }
8751
8752 static bfd_boolean
8753 elfobj_grok_gnu_note (bfd *abfd, Elf_Internal_Note *note)
8754 {
8755   switch (note->type)
8756     {
8757     default:
8758       return TRUE;
8759
8760     case NT_GNU_BUILD_ID:
8761       return elfobj_grok_gnu_build_id (abfd, note);
8762     }
8763 }
8764
8765 static bfd_boolean
8766 elfobj_grok_stapsdt_note_1 (bfd *abfd, Elf_Internal_Note *note)
8767 {
8768   struct sdt_note *cur =
8769     (struct sdt_note *) bfd_alloc (abfd, sizeof (struct sdt_note)
8770                                    + note->descsz);
8771
8772   cur->next = (struct sdt_note *) (elf_tdata (abfd))->sdt_note_head;
8773   cur->size = (bfd_size_type) note->descsz;
8774   memcpy (cur->data, note->descdata, note->descsz);
8775
8776   elf_tdata (abfd)->sdt_note_head = cur;
8777
8778   return TRUE;
8779 }
8780
8781 static bfd_boolean
8782 elfobj_grok_stapsdt_note (bfd *abfd, Elf_Internal_Note *note)
8783 {
8784   switch (note->type)
8785     {
8786     case NT_STAPSDT:
8787       return elfobj_grok_stapsdt_note_1 (abfd, note);
8788
8789     default:
8790       return TRUE;
8791     }
8792 }
8793
8794 static bfd_boolean
8795 elfcore_netbsd_get_lwpid (Elf_Internal_Note *note, int *lwpidp)
8796 {
8797   char *cp;
8798
8799   cp = strchr (note->namedata, '@');
8800   if (cp != NULL)
8801     {
8802       *lwpidp = atoi(cp + 1);
8803       return TRUE;
8804     }
8805   return FALSE;
8806 }
8807
8808 static bfd_boolean
8809 elfcore_grok_netbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
8810 {
8811   /* Signal number at offset 0x08. */
8812   elf_tdata (abfd)->core->signal
8813     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
8814
8815   /* Process ID at offset 0x50. */
8816   elf_tdata (abfd)->core->pid
8817     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x50);
8818
8819   /* Command name at 0x7c (max 32 bytes, including nul). */
8820   elf_tdata (abfd)->core->command
8821     = _bfd_elfcore_strndup (abfd, note->descdata + 0x7c, 31);
8822
8823   return elfcore_make_note_pseudosection (abfd, ".note.netbsdcore.procinfo",
8824                                           note);
8825 }
8826
8827 static bfd_boolean
8828 elfcore_grok_netbsd_note (bfd *abfd, Elf_Internal_Note *note)
8829 {
8830   int lwp;
8831
8832   if (elfcore_netbsd_get_lwpid (note, &lwp))
8833     elf_tdata (abfd)->core->lwpid = lwp;
8834
8835   if (note->type == NT_NETBSDCORE_PROCINFO)
8836     {
8837       /* NetBSD-specific core "procinfo".  Note that we expect to
8838          find this note before any of the others, which is fine,
8839          since the kernel writes this note out first when it
8840          creates a core file.  */
8841
8842       return elfcore_grok_netbsd_procinfo (abfd, note);
8843     }
8844
8845   /* As of Jan 2002 there are no other machine-independent notes
8846      defined for NetBSD core files.  If the note type is less
8847      than the start of the machine-dependent note types, we don't
8848      understand it.  */
8849
8850   if (note->type < NT_NETBSDCORE_FIRSTMACH)
8851     return TRUE;
8852
8853
8854   switch (bfd_get_arch (abfd))
8855     {
8856       /* On the Alpha, SPARC (32-bit and 64-bit), PT_GETREGS == mach+0 and
8857          PT_GETFPREGS == mach+2.  */
8858
8859     case bfd_arch_alpha:
8860     case bfd_arch_sparc:
8861       switch (note->type)
8862         {
8863         case NT_NETBSDCORE_FIRSTMACH+0:
8864           return elfcore_make_note_pseudosection (abfd, ".reg", note);
8865
8866         case NT_NETBSDCORE_FIRSTMACH+2:
8867           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
8868
8869         default:
8870           return TRUE;
8871         }
8872
8873       /* On all other arch's, PT_GETREGS == mach+1 and
8874          PT_GETFPREGS == mach+3.  */
8875
8876     default:
8877       switch (note->type)
8878         {
8879         case NT_NETBSDCORE_FIRSTMACH+1:
8880           return elfcore_make_note_pseudosection (abfd, ".reg", note);
8881
8882         case NT_NETBSDCORE_FIRSTMACH+3:
8883           return elfcore_make_note_pseudosection (abfd, ".reg2", note);
8884
8885         default:
8886           return TRUE;
8887         }
8888     }
8889     /* NOTREACHED */
8890 }
8891
8892 static bfd_boolean
8893 elfcore_grok_openbsd_procinfo (bfd *abfd, Elf_Internal_Note *note)
8894 {
8895   /* Signal number at offset 0x08. */
8896   elf_tdata (abfd)->core->signal
8897     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x08);
8898
8899   /* Process ID at offset 0x20. */
8900   elf_tdata (abfd)->core->pid
8901     = bfd_h_get_32 (abfd, (bfd_byte *) note->descdata + 0x20);
8902
8903   /* Command name at 0x48 (max 32 bytes, including nul). */
8904   elf_tdata (abfd)->core->command
8905     = _bfd_elfcore_strndup (abfd, note->descdata + 0x48, 31);
8906
8907   return TRUE;
8908 }
8909
8910 static bfd_boolean
8911 elfcore_grok_openbsd_note (bfd *abfd, Elf_Internal_Note *note)
8912 {
8913   if (note->type == NT_OPENBSD_PROCINFO)
8914     return elfcore_grok_openbsd_procinfo (abfd, note);
8915
8916   if (note->type == NT_OPENBSD_REGS)
8917     return elfcore_make_note_pseudosection (abfd, ".reg", note);
8918
8919   if (note->type == NT_OPENBSD_FPREGS)
8920     return elfcore_make_note_pseudosection (abfd, ".reg2", note);
8921
8922   if (note->type == NT_OPENBSD_XFPREGS)
8923     return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
8924
8925   if (note->type == NT_OPENBSD_AUXV)
8926     {
8927       asection *sect = bfd_make_section_anyway_with_flags (abfd, ".auxv",
8928                                                            SEC_HAS_CONTENTS);
8929
8930       if (sect == NULL)
8931         return FALSE;
8932       sect->size = note->descsz;
8933       sect->filepos = note->descpos;
8934       sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
8935
8936       return TRUE;
8937     }
8938
8939   if (note->type == NT_OPENBSD_WCOOKIE)
8940     {
8941       asection *sect = bfd_make_section_anyway_with_flags (abfd, ".wcookie",
8942                                                            SEC_HAS_CONTENTS);
8943
8944       if (sect == NULL)
8945         return FALSE;
8946       sect->size = note->descsz;
8947       sect->filepos = note->descpos;
8948       sect->alignment_power = 1 + bfd_get_arch_size (abfd) / 32;
8949
8950       return TRUE;
8951     }
8952
8953   return TRUE;
8954 }
8955
8956 static bfd_boolean
8957 elfcore_grok_nto_status (bfd *abfd, Elf_Internal_Note *note, long *tid)
8958 {
8959   void *ddata = note->descdata;
8960   char buf[100];
8961   char *name;
8962   asection *sect;
8963   short sig;
8964   unsigned flags;
8965
8966   /* nto_procfs_status 'pid' field is at offset 0.  */
8967   elf_tdata (abfd)->core->pid = bfd_get_32 (abfd, (bfd_byte *) ddata);
8968
8969   /* nto_procfs_status 'tid' field is at offset 4.  Pass it back.  */
8970   *tid = bfd_get_32 (abfd, (bfd_byte *) ddata + 4);
8971
8972   /* nto_procfs_status 'flags' field is at offset 8.  */
8973   flags = bfd_get_32 (abfd, (bfd_byte *) ddata + 8);
8974
8975   /* nto_procfs_status 'what' field is at offset 14.  */
8976   if ((sig = bfd_get_16 (abfd, (bfd_byte *) ddata + 14)) > 0)
8977     {
8978       elf_tdata (abfd)->core->signal = sig;
8979       elf_tdata (abfd)->core->lwpid = *tid;
8980     }
8981
8982   /* _DEBUG_FLAG_CURTID (current thread) is 0x80.  Some cores
8983      do not come from signals so we make sure we set the current
8984      thread just in case.  */
8985   if (flags & 0x00000080)
8986     elf_tdata (abfd)->core->lwpid = *tid;
8987
8988   /* Make a ".qnx_core_status/%d" section.  */
8989   sprintf (buf, ".qnx_core_status/%ld", *tid);
8990
8991   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
8992   if (name == NULL)
8993     return FALSE;
8994   strcpy (name, buf);
8995
8996   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
8997   if (sect == NULL)
8998     return FALSE;
8999
9000   sect->size            = note->descsz;
9001   sect->filepos         = note->descpos;
9002   sect->alignment_power = 2;
9003
9004   return (elfcore_maybe_make_sect (abfd, ".qnx_core_status", sect));
9005 }
9006
9007 static bfd_boolean
9008 elfcore_grok_nto_regs (bfd *abfd,
9009                        Elf_Internal_Note *note,
9010                        long tid,
9011                        char *base)
9012 {
9013   char buf[100];
9014   char *name;
9015   asection *sect;
9016
9017   /* Make a "(base)/%d" section.  */
9018   sprintf (buf, "%s/%ld", base, tid);
9019
9020   name = (char *) bfd_alloc (abfd, strlen (buf) + 1);
9021   if (name == NULL)
9022     return FALSE;
9023   strcpy (name, buf);
9024
9025   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9026   if (sect == NULL)
9027     return FALSE;
9028
9029   sect->size            = note->descsz;
9030   sect->filepos         = note->descpos;
9031   sect->alignment_power = 2;
9032
9033   /* This is the current thread.  */
9034   if (elf_tdata (abfd)->core->lwpid == tid)
9035     return elfcore_maybe_make_sect (abfd, base, sect);
9036
9037   return TRUE;
9038 }
9039
9040 #define BFD_QNT_CORE_INFO       7
9041 #define BFD_QNT_CORE_STATUS     8
9042 #define BFD_QNT_CORE_GREG       9
9043 #define BFD_QNT_CORE_FPREG      10
9044
9045 static bfd_boolean
9046 elfcore_grok_nto_note (bfd *abfd, Elf_Internal_Note *note)
9047 {
9048   /* Every GREG section has a STATUS section before it.  Store the
9049      tid from the previous call to pass down to the next gregs
9050      function.  */
9051   static long tid = 1;
9052
9053   switch (note->type)
9054     {
9055     case BFD_QNT_CORE_INFO:
9056       return elfcore_make_note_pseudosection (abfd, ".qnx_core_info", note);
9057     case BFD_QNT_CORE_STATUS:
9058       return elfcore_grok_nto_status (abfd, note, &tid);
9059     case BFD_QNT_CORE_GREG:
9060       return elfcore_grok_nto_regs (abfd, note, tid, ".reg");
9061     case BFD_QNT_CORE_FPREG:
9062       return elfcore_grok_nto_regs (abfd, note, tid, ".reg2");
9063     default:
9064       return TRUE;
9065     }
9066 }
9067
9068 static bfd_boolean
9069 elfcore_grok_spu_note (bfd *abfd, Elf_Internal_Note *note)
9070 {
9071   char *name;
9072   asection *sect;
9073   size_t len;
9074
9075   /* Use note name as section name.  */
9076   len = note->namesz;
9077   name = (char *) bfd_alloc (abfd, len);
9078   if (name == NULL)
9079     return FALSE;
9080   memcpy (name, note->namedata, len);
9081   name[len - 1] = '\0';
9082
9083   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
9084   if (sect == NULL)
9085     return FALSE;
9086
9087   sect->size            = note->descsz;
9088   sect->filepos         = note->descpos;
9089   sect->alignment_power = 1;
9090
9091   return TRUE;
9092 }
9093
9094 /* Function: elfcore_write_note
9095
9096    Inputs:
9097      buffer to hold note, and current size of buffer
9098      name of note
9099      type of note
9100      data for note
9101      size of data for note
9102
9103    Writes note to end of buffer.  ELF64 notes are written exactly as
9104    for ELF32, despite the current (as of 2006) ELF gabi specifying
9105    that they ought to have 8-byte namesz and descsz field, and have
9106    8-byte alignment.  Other writers, eg. Linux kernel, do the same.
9107
9108    Return:
9109    Pointer to realloc'd buffer, *BUFSIZ updated.  */
9110
9111 char *
9112 elfcore_write_note (bfd *abfd,
9113                     char *buf,
9114                     int *bufsiz,
9115                     const char *name,
9116                     int type,
9117                     const void *input,
9118                     int size)
9119 {
9120   Elf_External_Note *xnp;
9121   size_t namesz;
9122   size_t newspace;
9123   char *dest;
9124
9125   namesz = 0;
9126   if (name != NULL)
9127     namesz = strlen (name) + 1;
9128
9129   newspace = 12 + ((namesz + 3) & -4) + ((size + 3) & -4);
9130
9131   buf = (char *) realloc (buf, *bufsiz + newspace);
9132   if (buf == NULL)
9133     return buf;
9134   dest = buf + *bufsiz;
9135   *bufsiz += newspace;
9136   xnp = (Elf_External_Note *) dest;
9137   H_PUT_32 (abfd, namesz, xnp->namesz);
9138   H_PUT_32 (abfd, size, xnp->descsz);
9139   H_PUT_32 (abfd, type, xnp->type);
9140   dest = xnp->name;
9141   if (name != NULL)
9142     {
9143       memcpy (dest, name, namesz);
9144       dest += namesz;
9145       while (namesz & 3)
9146         {
9147           *dest++ = '\0';
9148           ++namesz;
9149         }
9150     }
9151   memcpy (dest, input, size);
9152   dest += size;
9153   while (size & 3)
9154     {
9155       *dest++ = '\0';
9156       ++size;
9157     }
9158   return buf;
9159 }
9160
9161 char *
9162 elfcore_write_prpsinfo (bfd  *abfd,
9163                         char *buf,
9164                         int  *bufsiz,
9165                         const char *fname,
9166                         const char *psargs)
9167 {
9168   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9169
9170   if (bed->elf_backend_write_core_note != NULL)
9171     {
9172       char *ret;
9173       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
9174                                                  NT_PRPSINFO, fname, psargs);
9175       if (ret != NULL)
9176         return ret;
9177     }
9178
9179 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
9180 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
9181   if (bed->s->elfclass == ELFCLASS32)
9182     {
9183 #if defined (HAVE_PSINFO32_T)
9184       psinfo32_t data;
9185       int note_type = NT_PSINFO;
9186 #else
9187       prpsinfo32_t data;
9188       int note_type = NT_PRPSINFO;
9189 #endif
9190
9191       memset (&data, 0, sizeof (data));
9192       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
9193       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
9194       return elfcore_write_note (abfd, buf, bufsiz,
9195                                  "CORE", note_type, &data, sizeof (data));
9196     }
9197   else
9198 #endif
9199     {
9200 #if defined (HAVE_PSINFO_T)
9201       psinfo_t data;
9202       int note_type = NT_PSINFO;
9203 #else
9204       prpsinfo_t data;
9205       int note_type = NT_PRPSINFO;
9206 #endif
9207
9208       memset (&data, 0, sizeof (data));
9209       strncpy (data.pr_fname, fname, sizeof (data.pr_fname));
9210       strncpy (data.pr_psargs, psargs, sizeof (data.pr_psargs));
9211       return elfcore_write_note (abfd, buf, bufsiz,
9212                                  "CORE", note_type, &data, sizeof (data));
9213     }
9214 #endif  /* PSINFO_T or PRPSINFO_T */
9215
9216   free (buf);
9217   return NULL;
9218 }
9219
9220 char *
9221 elfcore_write_linux_prpsinfo32
9222   (bfd *abfd, char *buf, int *bufsiz,
9223    const struct elf_internal_linux_prpsinfo *prpsinfo)
9224 {
9225   struct elf_external_linux_prpsinfo32 data;
9226
9227   memset (&data, 0, sizeof (data));
9228   LINUX_PRPSINFO32_SWAP_FIELDS (abfd, prpsinfo, data);
9229
9230   return elfcore_write_note (abfd, buf, bufsiz, "CORE", NT_PRPSINFO,
9231                              &data, sizeof (data));
9232 }
9233
9234 char *
9235 elfcore_write_linux_prpsinfo64
9236   (bfd *abfd, char *buf, int *bufsiz,
9237    const struct elf_internal_linux_prpsinfo *prpsinfo)
9238 {
9239   struct elf_external_linux_prpsinfo64 data;
9240
9241   memset (&data, 0, sizeof (data));
9242   LINUX_PRPSINFO64_SWAP_FIELDS (abfd, prpsinfo, data);
9243
9244   return elfcore_write_note (abfd, buf, bufsiz,
9245                              "CORE", NT_PRPSINFO, &data, sizeof (data));
9246 }
9247
9248 char *
9249 elfcore_write_prstatus (bfd *abfd,
9250                         char *buf,
9251                         int *bufsiz,
9252                         long pid,
9253                         int cursig,
9254                         const void *gregs)
9255 {
9256   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9257
9258   if (bed->elf_backend_write_core_note != NULL)
9259     {
9260       char *ret;
9261       ret = (*bed->elf_backend_write_core_note) (abfd, buf, bufsiz,
9262                                                  NT_PRSTATUS,
9263                                                  pid, cursig, gregs);
9264       if (ret != NULL)
9265         return ret;
9266     }
9267
9268 #if defined (HAVE_PRSTATUS_T)
9269 #if defined (HAVE_PRSTATUS32_T)
9270   if (bed->s->elfclass == ELFCLASS32)
9271     {
9272       prstatus32_t prstat;
9273
9274       memset (&prstat, 0, sizeof (prstat));
9275       prstat.pr_pid = pid;
9276       prstat.pr_cursig = cursig;
9277       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
9278       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
9279                                  NT_PRSTATUS, &prstat, sizeof (prstat));
9280     }
9281   else
9282 #endif
9283     {
9284       prstatus_t prstat;
9285
9286       memset (&prstat, 0, sizeof (prstat));
9287       prstat.pr_pid = pid;
9288       prstat.pr_cursig = cursig;
9289       memcpy (&prstat.pr_reg, gregs, sizeof (prstat.pr_reg));
9290       return elfcore_write_note (abfd, buf, bufsiz, "CORE",
9291                                  NT_PRSTATUS, &prstat, sizeof (prstat));
9292     }
9293 #endif /* HAVE_PRSTATUS_T */
9294
9295   free (buf);
9296   return NULL;
9297 }
9298
9299 #if defined (HAVE_LWPSTATUS_T)
9300 char *
9301 elfcore_write_lwpstatus (bfd *abfd,
9302                          char *buf,
9303                          int *bufsiz,
9304                          long pid,
9305                          int cursig,
9306                          const void *gregs)
9307 {
9308   lwpstatus_t lwpstat;
9309   const char *note_name = "CORE";
9310
9311   memset (&lwpstat, 0, sizeof (lwpstat));
9312   lwpstat.pr_lwpid  = pid >> 16;
9313   lwpstat.pr_cursig = cursig;
9314 #if defined (HAVE_LWPSTATUS_T_PR_REG)
9315   memcpy (lwpstat.pr_reg, gregs, sizeof (lwpstat.pr_reg));
9316 #elif defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
9317 #if !defined(gregs)
9318   memcpy (lwpstat.pr_context.uc_mcontext.gregs,
9319           gregs, sizeof (lwpstat.pr_context.uc_mcontext.gregs));
9320 #else
9321   memcpy (lwpstat.pr_context.uc_mcontext.__gregs,
9322           gregs, sizeof (lwpstat.pr_context.uc_mcontext.__gregs));
9323 #endif
9324 #endif
9325   return elfcore_write_note (abfd, buf, bufsiz, note_name,
9326                              NT_LWPSTATUS, &lwpstat, sizeof (lwpstat));
9327 }
9328 #endif /* HAVE_LWPSTATUS_T */
9329
9330 #if defined (HAVE_PSTATUS_T)
9331 char *
9332 elfcore_write_pstatus (bfd *abfd,
9333                        char *buf,
9334                        int *bufsiz,
9335                        long pid,
9336                        int cursig ATTRIBUTE_UNUSED,
9337                        const void *gregs ATTRIBUTE_UNUSED)
9338 {
9339   const char *note_name = "CORE";
9340 #if defined (HAVE_PSTATUS32_T)
9341   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9342
9343   if (bed->s->elfclass == ELFCLASS32)
9344     {
9345       pstatus32_t pstat;
9346
9347       memset (&pstat, 0, sizeof (pstat));
9348       pstat.pr_pid = pid & 0xffff;
9349       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
9350                                 NT_PSTATUS, &pstat, sizeof (pstat));
9351       return buf;
9352     }
9353   else
9354 #endif
9355     {
9356       pstatus_t pstat;
9357
9358       memset (&pstat, 0, sizeof (pstat));
9359       pstat.pr_pid = pid & 0xffff;
9360       buf = elfcore_write_note (abfd, buf, bufsiz, note_name,
9361                                 NT_PSTATUS, &pstat, sizeof (pstat));
9362       return buf;
9363     }
9364 }
9365 #endif /* HAVE_PSTATUS_T */
9366
9367 char *
9368 elfcore_write_prfpreg (bfd *abfd,
9369                        char *buf,
9370                        int *bufsiz,
9371                        const void *fpregs,
9372                        int size)
9373 {
9374   const char *note_name = "CORE";
9375   return elfcore_write_note (abfd, buf, bufsiz,
9376                              note_name, NT_FPREGSET, fpregs, size);
9377 }
9378
9379 char *
9380 elfcore_write_prxfpreg (bfd *abfd,
9381                         char *buf,
9382                         int *bufsiz,
9383                         const void *xfpregs,
9384                         int size)
9385 {
9386   char *note_name = "LINUX";
9387   return elfcore_write_note (abfd, buf, bufsiz,
9388                              note_name, NT_PRXFPREG, xfpregs, size);
9389 }
9390
9391 char *
9392 elfcore_write_xstatereg (bfd *abfd, char *buf, int *bufsiz,
9393                          const void *xfpregs, int size)
9394 {
9395   char *note_name = "LINUX";
9396   return elfcore_write_note (abfd, buf, bufsiz,
9397                              note_name, NT_X86_XSTATE, xfpregs, size);
9398 }
9399
9400 char *
9401 elfcore_write_ppc_vmx (bfd *abfd,
9402                        char *buf,
9403                        int *bufsiz,
9404                        const void *ppc_vmx,
9405                        int size)
9406 {
9407   char *note_name = "LINUX";
9408   return elfcore_write_note (abfd, buf, bufsiz,
9409                              note_name, NT_PPC_VMX, ppc_vmx, size);
9410 }
9411
9412 char *
9413 elfcore_write_ppc_vsx (bfd *abfd,
9414                        char *buf,
9415                        int *bufsiz,
9416                        const void *ppc_vsx,
9417                        int size)
9418 {
9419   char *note_name = "LINUX";
9420   return elfcore_write_note (abfd, buf, bufsiz,
9421                              note_name, NT_PPC_VSX, ppc_vsx, size);
9422 }
9423
9424 static char *
9425 elfcore_write_s390_high_gprs (bfd *abfd,
9426                               char *buf,
9427                               int *bufsiz,
9428                               const void *s390_high_gprs,
9429                               int size)
9430 {
9431   char *note_name = "LINUX";
9432   return elfcore_write_note (abfd, buf, bufsiz,
9433                              note_name, NT_S390_HIGH_GPRS,
9434                              s390_high_gprs, size);
9435 }
9436
9437 char *
9438 elfcore_write_s390_timer (bfd *abfd,
9439                           char *buf,
9440                           int *bufsiz,
9441                           const void *s390_timer,
9442                           int size)
9443 {
9444   char *note_name = "LINUX";
9445   return elfcore_write_note (abfd, buf, bufsiz,
9446                              note_name, NT_S390_TIMER, s390_timer, size);
9447 }
9448
9449 char *
9450 elfcore_write_s390_todcmp (bfd *abfd,
9451                            char *buf,
9452                            int *bufsiz,
9453                            const void *s390_todcmp,
9454                            int size)
9455 {
9456   char *note_name = "LINUX";
9457   return elfcore_write_note (abfd, buf, bufsiz,
9458                              note_name, NT_S390_TODCMP, s390_todcmp, size);
9459 }
9460
9461 char *
9462 elfcore_write_s390_todpreg (bfd *abfd,
9463                             char *buf,
9464                             int *bufsiz,
9465                             const void *s390_todpreg,
9466                             int size)
9467 {
9468   char *note_name = "LINUX";
9469   return elfcore_write_note (abfd, buf, bufsiz,
9470                              note_name, NT_S390_TODPREG, s390_todpreg, size);
9471 }
9472
9473 char *
9474 elfcore_write_s390_ctrs (bfd *abfd,
9475                          char *buf,
9476                          int *bufsiz,
9477                          const void *s390_ctrs,
9478                          int size)
9479 {
9480   char *note_name = "LINUX";
9481   return elfcore_write_note (abfd, buf, bufsiz,
9482                              note_name, NT_S390_CTRS, s390_ctrs, size);
9483 }
9484
9485 char *
9486 elfcore_write_s390_prefix (bfd *abfd,
9487                            char *buf,
9488                            int *bufsiz,
9489                            const void *s390_prefix,
9490                            int size)
9491 {
9492   char *note_name = "LINUX";
9493   return elfcore_write_note (abfd, buf, bufsiz,
9494                              note_name, NT_S390_PREFIX, s390_prefix, size);
9495 }
9496
9497 char *
9498 elfcore_write_s390_last_break (bfd *abfd,
9499                                char *buf,
9500                                int *bufsiz,
9501                                const void *s390_last_break,
9502                                int size)
9503 {
9504   char *note_name = "LINUX";
9505   return elfcore_write_note (abfd, buf, bufsiz,
9506                              note_name, NT_S390_LAST_BREAK,
9507                              s390_last_break, size);
9508 }
9509
9510 char *
9511 elfcore_write_s390_system_call (bfd *abfd,
9512                                 char *buf,
9513                                 int *bufsiz,
9514                                 const void *s390_system_call,
9515                                 int size)
9516 {
9517   char *note_name = "LINUX";
9518   return elfcore_write_note (abfd, buf, bufsiz,
9519                              note_name, NT_S390_SYSTEM_CALL,
9520                              s390_system_call, size);
9521 }
9522
9523 char *
9524 elfcore_write_s390_tdb (bfd *abfd,
9525                         char *buf,
9526                         int *bufsiz,
9527                         const void *s390_tdb,
9528                         int size)
9529 {
9530   char *note_name = "LINUX";
9531   return elfcore_write_note (abfd, buf, bufsiz,
9532                              note_name, NT_S390_TDB, s390_tdb, size);
9533 }
9534
9535 char *
9536 elfcore_write_arm_vfp (bfd *abfd,
9537                        char *buf,
9538                        int *bufsiz,
9539                        const void *arm_vfp,
9540                        int size)
9541 {
9542   char *note_name = "LINUX";
9543   return elfcore_write_note (abfd, buf, bufsiz,
9544                              note_name, NT_ARM_VFP, arm_vfp, size);
9545 }
9546
9547 char *
9548 elfcore_write_aarch_tls (bfd *abfd,
9549                        char *buf,
9550                        int *bufsiz,
9551                        const void *aarch_tls,
9552                        int size)
9553 {
9554   char *note_name = "LINUX";
9555   return elfcore_write_note (abfd, buf, bufsiz,
9556                              note_name, NT_ARM_TLS, aarch_tls, size);
9557 }
9558
9559 char *
9560 elfcore_write_aarch_hw_break (bfd *abfd,
9561                             char *buf,
9562                             int *bufsiz,
9563                             const void *aarch_hw_break,
9564                             int size)
9565 {
9566   char *note_name = "LINUX";
9567   return elfcore_write_note (abfd, buf, bufsiz,
9568                              note_name, NT_ARM_HW_BREAK, aarch_hw_break, size);
9569 }
9570
9571 char *
9572 elfcore_write_aarch_hw_watch (bfd *abfd,
9573                             char *buf,
9574                             int *bufsiz,
9575                             const void *aarch_hw_watch,
9576                             int size)
9577 {
9578   char *note_name = "LINUX";
9579   return elfcore_write_note (abfd, buf, bufsiz,
9580                              note_name, NT_ARM_HW_WATCH, aarch_hw_watch, size);
9581 }
9582
9583 char *
9584 elfcore_write_register_note (bfd *abfd,
9585                              char *buf,
9586                              int *bufsiz,
9587                              const char *section,
9588                              const void *data,
9589                              int size)
9590 {
9591   if (strcmp (section, ".reg2") == 0)
9592     return elfcore_write_prfpreg (abfd, buf, bufsiz, data, size);
9593   if (strcmp (section, ".reg-xfp") == 0)
9594     return elfcore_write_prxfpreg (abfd, buf, bufsiz, data, size);
9595   if (strcmp (section, ".reg-xstate") == 0)
9596     return elfcore_write_xstatereg (abfd, buf, bufsiz, data, size);
9597   if (strcmp (section, ".reg-ppc-vmx") == 0)
9598     return elfcore_write_ppc_vmx (abfd, buf, bufsiz, data, size);
9599   if (strcmp (section, ".reg-ppc-vsx") == 0)
9600     return elfcore_write_ppc_vsx (abfd, buf, bufsiz, data, size);
9601   if (strcmp (section, ".reg-s390-high-gprs") == 0)
9602     return elfcore_write_s390_high_gprs (abfd, buf, bufsiz, data, size);
9603   if (strcmp (section, ".reg-s390-timer") == 0)
9604     return elfcore_write_s390_timer (abfd, buf, bufsiz, data, size);
9605   if (strcmp (section, ".reg-s390-todcmp") == 0)
9606     return elfcore_write_s390_todcmp (abfd, buf, bufsiz, data, size);
9607   if (strcmp (section, ".reg-s390-todpreg") == 0)
9608     return elfcore_write_s390_todpreg (abfd, buf, bufsiz, data, size);
9609   if (strcmp (section, ".reg-s390-ctrs") == 0)
9610     return elfcore_write_s390_ctrs (abfd, buf, bufsiz, data, size);
9611   if (strcmp (section, ".reg-s390-prefix") == 0)
9612     return elfcore_write_s390_prefix (abfd, buf, bufsiz, data, size);
9613   if (strcmp (section, ".reg-s390-last-break") == 0)
9614     return elfcore_write_s390_last_break (abfd, buf, bufsiz, data, size);
9615   if (strcmp (section, ".reg-s390-system-call") == 0)
9616     return elfcore_write_s390_system_call (abfd, buf, bufsiz, data, size);
9617   if (strcmp (section, ".reg-s390-tdb") == 0)
9618     return elfcore_write_s390_tdb (abfd, buf, bufsiz, data, size);
9619   if (strcmp (section, ".reg-arm-vfp") == 0)
9620     return elfcore_write_arm_vfp (abfd, buf, bufsiz, data, size);
9621   if (strcmp (section, ".reg-aarch-tls") == 0)
9622     return elfcore_write_aarch_tls (abfd, buf, bufsiz, data, size);
9623   if (strcmp (section, ".reg-aarch-hw-break") == 0)
9624     return elfcore_write_aarch_hw_break (abfd, buf, bufsiz, data, size);
9625   if (strcmp (section, ".reg-aarch-hw-watch") == 0)
9626     return elfcore_write_aarch_hw_watch (abfd, buf, bufsiz, data, size);
9627   return NULL;
9628 }
9629
9630 static bfd_boolean
9631 elf_parse_notes (bfd *abfd, char *buf, size_t size, file_ptr offset)
9632 {
9633   char *p;
9634
9635   p = buf;
9636   while (p < buf + size)
9637     {
9638       /* FIXME: bad alignment assumption.  */
9639       Elf_External_Note *xnp = (Elf_External_Note *) p;
9640       Elf_Internal_Note in;
9641
9642       if (offsetof (Elf_External_Note, name) > buf - p + size)
9643         return FALSE;
9644
9645       in.type = H_GET_32 (abfd, xnp->type);
9646
9647       in.namesz = H_GET_32 (abfd, xnp->namesz);
9648       in.namedata = xnp->name;
9649       if (in.namesz > buf - in.namedata + size)
9650         return FALSE;
9651
9652       in.descsz = H_GET_32 (abfd, xnp->descsz);
9653       in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
9654       in.descpos = offset + (in.descdata - buf);
9655       if (in.descsz != 0
9656           && (in.descdata >= buf + size
9657               || in.descsz > buf - in.descdata + size))
9658         return FALSE;
9659
9660       switch (bfd_get_format (abfd))
9661         {
9662         default:
9663           return TRUE;
9664
9665         case bfd_core:
9666           if (CONST_STRNEQ (in.namedata, "NetBSD-CORE"))
9667             {
9668               if (! elfcore_grok_netbsd_note (abfd, &in))
9669                 return FALSE;
9670             }
9671           else if (CONST_STRNEQ (in.namedata, "OpenBSD"))
9672             {
9673               if (! elfcore_grok_openbsd_note (abfd, &in))
9674                 return FALSE;
9675             }
9676           else if (CONST_STRNEQ (in.namedata, "QNX"))
9677             {
9678               if (! elfcore_grok_nto_note (abfd, &in))
9679                 return FALSE;
9680             }
9681           else if (CONST_STRNEQ (in.namedata, "SPU/"))
9682             {
9683               if (! elfcore_grok_spu_note (abfd, &in))
9684                 return FALSE;
9685             }
9686           else
9687             {
9688               if (! elfcore_grok_note (abfd, &in))
9689                 return FALSE;
9690             }
9691           break;
9692
9693         case bfd_object:
9694           if (in.namesz == sizeof "GNU" && strcmp (in.namedata, "GNU") == 0)
9695             {
9696               if (! elfobj_grok_gnu_note (abfd, &in))
9697                 return FALSE;
9698             }
9699           else if (in.namesz == sizeof "stapsdt"
9700                    && strcmp (in.namedata, "stapsdt") == 0)
9701             {
9702               if (! elfobj_grok_stapsdt_note (abfd, &in))
9703                 return FALSE;
9704             }
9705           break;
9706         }
9707
9708       p = in.descdata + BFD_ALIGN (in.descsz, 4);
9709     }
9710
9711   return TRUE;
9712 }
9713
9714 static bfd_boolean
9715 elf_read_notes (bfd *abfd, file_ptr offset, bfd_size_type size)
9716 {
9717   char *buf;
9718
9719   if (size <= 0)
9720     return TRUE;
9721
9722   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
9723     return FALSE;
9724
9725   buf = (char *) bfd_malloc (size);
9726   if (buf == NULL)
9727     return FALSE;
9728
9729   if (bfd_bread (buf, size, abfd) != size
9730       || !elf_parse_notes (abfd, buf, size, offset))
9731     {
9732       free (buf);
9733       return FALSE;
9734     }
9735
9736   free (buf);
9737   return TRUE;
9738 }
9739 \f
9740 /* Providing external access to the ELF program header table.  */
9741
9742 /* Return an upper bound on the number of bytes required to store a
9743    copy of ABFD's program header table entries.  Return -1 if an error
9744    occurs; bfd_get_error will return an appropriate code.  */
9745
9746 long
9747 bfd_get_elf_phdr_upper_bound (bfd *abfd)
9748 {
9749   if (abfd->xvec->flavour != bfd_target_elf_flavour)
9750     {
9751       bfd_set_error (bfd_error_wrong_format);
9752       return -1;
9753     }
9754
9755   return elf_elfheader (abfd)->e_phnum * sizeof (Elf_Internal_Phdr);
9756 }
9757
9758 /* Copy ABFD's program header table entries to *PHDRS.  The entries
9759    will be stored as an array of Elf_Internal_Phdr structures, as
9760    defined in include/elf/internal.h.  To find out how large the
9761    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
9762
9763    Return the number of program header table entries read, or -1 if an
9764    error occurs; bfd_get_error will return an appropriate code.  */
9765
9766 int
9767 bfd_get_elf_phdrs (bfd *abfd, void *phdrs)
9768 {
9769   int num_phdrs;
9770
9771   if (abfd->xvec->flavour != bfd_target_elf_flavour)
9772     {
9773       bfd_set_error (bfd_error_wrong_format);
9774       return -1;
9775     }
9776
9777   num_phdrs = elf_elfheader (abfd)->e_phnum;
9778   memcpy (phdrs, elf_tdata (abfd)->phdr,
9779           num_phdrs * sizeof (Elf_Internal_Phdr));
9780
9781   return num_phdrs;
9782 }
9783
9784 enum elf_reloc_type_class
9785 _bfd_elf_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
9786                            const asection *rel_sec ATTRIBUTE_UNUSED,
9787                            const Elf_Internal_Rela *rela ATTRIBUTE_UNUSED)
9788 {
9789   return reloc_class_normal;
9790 }
9791
9792 /* For RELA architectures, return the relocation value for a
9793    relocation against a local symbol.  */
9794
9795 bfd_vma
9796 _bfd_elf_rela_local_sym (bfd *abfd,
9797                          Elf_Internal_Sym *sym,
9798                          asection **psec,
9799                          Elf_Internal_Rela *rel)
9800 {
9801   asection *sec = *psec;
9802   bfd_vma relocation;
9803
9804   relocation = (sec->output_section->vma
9805                 + sec->output_offset
9806                 + sym->st_value);
9807   if ((sec->flags & SEC_MERGE)
9808       && ELF_ST_TYPE (sym->st_info) == STT_SECTION
9809       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
9810     {
9811       rel->r_addend =
9812         _bfd_merged_section_offset (abfd, psec,
9813                                     elf_section_data (sec)->sec_info,
9814                                     sym->st_value + rel->r_addend);
9815       if (sec != *psec)
9816         {
9817           /* If we have changed the section, and our original section is
9818              marked with SEC_EXCLUDE, it means that the original
9819              SEC_MERGE section has been completely subsumed in some
9820              other SEC_MERGE section.  In this case, we need to leave
9821              some info around for --emit-relocs.  */
9822           if ((sec->flags & SEC_EXCLUDE) != 0)
9823             sec->kept_section = *psec;
9824           sec = *psec;
9825         }
9826       rel->r_addend -= relocation;
9827       rel->r_addend += sec->output_section->vma + sec->output_offset;
9828     }
9829   return relocation;
9830 }
9831
9832 bfd_vma
9833 _bfd_elf_rel_local_sym (bfd *abfd,
9834                         Elf_Internal_Sym *sym,
9835                         asection **psec,
9836                         bfd_vma addend)
9837 {
9838   asection *sec = *psec;
9839
9840   if (sec->sec_info_type != SEC_INFO_TYPE_MERGE)
9841     return sym->st_value + addend;
9842
9843   return _bfd_merged_section_offset (abfd, psec,
9844                                      elf_section_data (sec)->sec_info,
9845                                      sym->st_value + addend);
9846 }
9847
9848 bfd_vma
9849 _bfd_elf_section_offset (bfd *abfd,
9850                          struct bfd_link_info *info,
9851                          asection *sec,
9852                          bfd_vma offset)
9853 {
9854   switch (sec->sec_info_type)
9855     {
9856     case SEC_INFO_TYPE_STABS:
9857       return _bfd_stab_section_offset (sec, elf_section_data (sec)->sec_info,
9858                                        offset);
9859     case SEC_INFO_TYPE_EH_FRAME:
9860       return _bfd_elf_eh_frame_section_offset (abfd, info, sec, offset);
9861     default:
9862       if ((sec->flags & SEC_ELF_REVERSE_COPY) != 0)
9863         {
9864           const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9865           bfd_size_type address_size = bed->s->arch_size / 8;
9866           offset = sec->size - offset - address_size;
9867         }
9868       return offset;
9869     }
9870 }
9871 \f
9872 /* Create a new BFD as if by bfd_openr.  Rather than opening a file,
9873    reconstruct an ELF file by reading the segments out of remote memory
9874    based on the ELF file header at EHDR_VMA and the ELF program headers it
9875    points to.  If not null, *LOADBASEP is filled in with the difference
9876    between the VMAs from which the segments were read, and the VMAs the
9877    file headers (and hence BFD's idea of each section's VMA) put them at.
9878
9879    The function TARGET_READ_MEMORY is called to copy LEN bytes from the
9880    remote memory at target address VMA into the local buffer at MYADDR; it
9881    should return zero on success or an `errno' code on failure.  TEMPL must
9882    be a BFD for an ELF target with the word size and byte order found in
9883    the remote memory.  */
9884
9885 bfd *
9886 bfd_elf_bfd_from_remote_memory
9887   (bfd *templ,
9888    bfd_vma ehdr_vma,
9889    bfd_vma *loadbasep,
9890    int (*target_read_memory) (bfd_vma, bfd_byte *, bfd_size_type))
9891 {
9892   return (*get_elf_backend_data (templ)->elf_backend_bfd_from_remote_memory)
9893     (templ, ehdr_vma, loadbasep, target_read_memory);
9894 }
9895 \f
9896 long
9897 _bfd_elf_get_synthetic_symtab (bfd *abfd,
9898                                long symcount ATTRIBUTE_UNUSED,
9899                                asymbol **syms ATTRIBUTE_UNUSED,
9900                                long dynsymcount,
9901                                asymbol **dynsyms,
9902                                asymbol **ret)
9903 {
9904   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9905   asection *relplt;
9906   asymbol *s;
9907   const char *relplt_name;
9908   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
9909   arelent *p;
9910   long count, i, n;
9911   size_t size;
9912   Elf_Internal_Shdr *hdr;
9913   char *names;
9914   asection *plt;
9915
9916   *ret = NULL;
9917
9918   if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0)
9919     return 0;
9920
9921   if (dynsymcount <= 0)
9922     return 0;
9923
9924   if (!bed->plt_sym_val)
9925     return 0;
9926
9927   relplt_name = bed->relplt_name;
9928   if (relplt_name == NULL)
9929     relplt_name = bed->rela_plts_and_copies_p ? ".rela.plt" : ".rel.plt";
9930   relplt = bfd_get_section_by_name (abfd, relplt_name);
9931   if (relplt == NULL)
9932     return 0;
9933
9934   hdr = &elf_section_data (relplt)->this_hdr;
9935   if (hdr->sh_link != elf_dynsymtab (abfd)
9936       || (hdr->sh_type != SHT_REL && hdr->sh_type != SHT_RELA))
9937     return 0;
9938
9939   plt = bfd_get_section_by_name (abfd, ".plt");
9940   if (plt == NULL)
9941     return 0;
9942
9943   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
9944   if (! (*slurp_relocs) (abfd, relplt, dynsyms, TRUE))
9945     return -1;
9946
9947   count = relplt->size / hdr->sh_entsize;
9948   size = count * sizeof (asymbol);
9949   p = relplt->relocation;
9950   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
9951     {
9952       size += strlen ((*p->sym_ptr_ptr)->name) + sizeof ("@plt");
9953       if (p->addend != 0)
9954         {
9955 #ifdef BFD64
9956           size += sizeof ("+0x") - 1 + 8 + 8 * (bed->s->elfclass == ELFCLASS64);
9957 #else
9958           size += sizeof ("+0x") - 1 + 8;
9959 #endif
9960         }
9961     }
9962
9963   s = *ret = (asymbol *) bfd_malloc (size);
9964   if (s == NULL)
9965     return -1;
9966
9967   names = (char *) (s + count);
9968   p = relplt->relocation;
9969   n = 0;
9970   for (i = 0; i < count; i++, p += bed->s->int_rels_per_ext_rel)
9971     {
9972       size_t len;
9973       bfd_vma addr;
9974
9975       addr = bed->plt_sym_val (i, plt, p);
9976       if (addr == (bfd_vma) -1)
9977         continue;
9978
9979       *s = **p->sym_ptr_ptr;
9980       /* Undefined syms won't have BSF_LOCAL or BSF_GLOBAL set.  Since
9981          we are defining a symbol, ensure one of them is set.  */
9982       if ((s->flags & BSF_LOCAL) == 0)
9983         s->flags |= BSF_GLOBAL;
9984       s->flags |= BSF_SYNTHETIC;
9985       s->section = plt;
9986       s->value = addr - plt->vma;
9987       s->name = names;
9988       s->udata.p = NULL;
9989       len = strlen ((*p->sym_ptr_ptr)->name);
9990       memcpy (names, (*p->sym_ptr_ptr)->name, len);
9991       names += len;
9992       if (p->addend != 0)
9993         {
9994           char buf[30], *a;
9995
9996           memcpy (names, "+0x", sizeof ("+0x") - 1);
9997           names += sizeof ("+0x") - 1;
9998           bfd_sprintf_vma (abfd, buf, p->addend);
9999           for (a = buf; *a == '0'; ++a)
10000             ;
10001           len = strlen (a);
10002           memcpy (names, a, len);
10003           names += len;
10004         }
10005       memcpy (names, "@plt", sizeof ("@plt"));
10006       names += sizeof ("@plt");
10007       ++s, ++n;
10008     }
10009
10010   return n;
10011 }
10012
10013 /* It is only used by x86-64 so far.  */
10014 asection _bfd_elf_large_com_section
10015   = BFD_FAKE_SECTION (_bfd_elf_large_com_section,
10016                       SEC_IS_COMMON, NULL, "LARGE_COMMON", 0);
10017
10018 void
10019 _bfd_elf_set_osabi (bfd * abfd,
10020                     struct bfd_link_info * link_info ATTRIBUTE_UNUSED)
10021 {
10022   Elf_Internal_Ehdr * i_ehdrp;  /* ELF file header, internal form.  */
10023
10024   i_ehdrp = elf_elfheader (abfd);
10025
10026   i_ehdrp->e_ident[EI_OSABI] = get_elf_backend_data (abfd)->elf_osabi;
10027
10028   /* To make things simpler for the loader on Linux systems we set the
10029      osabi field to ELFOSABI_GNU if the binary contains symbols of
10030      the STT_GNU_IFUNC type or STB_GNU_UNIQUE binding.  */
10031   if (i_ehdrp->e_ident[EI_OSABI] == ELFOSABI_NONE
10032       && elf_tdata (abfd)->has_gnu_symbols)
10033     i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_GNU;
10034 }
10035
10036
10037 /* Return TRUE for ELF symbol types that represent functions.
10038    This is the default version of this function, which is sufficient for
10039    most targets.  It returns true if TYPE is STT_FUNC or STT_GNU_IFUNC.  */
10040
10041 bfd_boolean
10042 _bfd_elf_is_function_type (unsigned int type)
10043 {
10044   return (type == STT_FUNC
10045           || type == STT_GNU_IFUNC);
10046 }
10047
10048 /* If the ELF symbol SYM might be a function in SEC, return the
10049    function size and set *CODE_OFF to the function's entry point,
10050    otherwise return zero.  */
10051
10052 bfd_size_type
10053 _bfd_elf_maybe_function_sym (const asymbol *sym, asection *sec,
10054                              bfd_vma *code_off)
10055 {
10056   bfd_size_type size;
10057
10058   if ((sym->flags & (BSF_SECTION_SYM | BSF_FILE | BSF_OBJECT
10059                      | BSF_THREAD_LOCAL | BSF_RELC | BSF_SRELC)) != 0
10060       || sym->section != sec)
10061     return 0;
10062
10063   *code_off = sym->value;
10064   size = 0;
10065   if (!(sym->flags & BSF_SYNTHETIC))
10066     size = ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
10067   if (size == 0)
10068     size = 1;
10069   return size;
10070 }