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