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