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