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