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