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