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