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