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