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