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