OSDN Git Service

8830ff099cc02f84b3ff01986582370d33f2f069
[pf3gnuchains/pf3gnuchains4x.git] / bfd / elf.c
1 /* ELF executable support for BFD.
2    Copyright 1993, 94, 95, 96, 97, 98, 99, 2000 Free Software Foundation, Inc.
3
4 This file is part of BFD, the Binary File Descriptor library.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /*
21
22 SECTION
23         ELF backends
24
25         BFD support for ELF formats is being worked on.
26         Currently, the best supported back ends are for sparc and i386
27         (running svr4 or Solaris 2).
28
29         Documentation of the internals of the support code still needs
30         to be written.  The code is changing quickly enough that we
31         haven't bothered yet.
32  */
33
34 #include "bfd.h"
35 #include "sysdep.h"
36 #include "bfdlink.h"
37 #include "libbfd.h"
38 #define ARCH_SIZE 0
39 #include "elf-bfd.h"
40
41 static INLINE struct elf_segment_map *make_mapping
42   PARAMS ((bfd *, asection **, unsigned int, unsigned int, boolean));
43 static boolean map_sections_to_segments PARAMS ((bfd *));
44 static int elf_sort_sections PARAMS ((const PTR, const PTR));
45 static boolean assign_file_positions_for_segments PARAMS ((bfd *));
46 static boolean assign_file_positions_except_relocs PARAMS ((bfd *));
47 static boolean prep_headers PARAMS ((bfd *));
48 static boolean swap_out_syms PARAMS ((bfd *, struct bfd_strtab_hash **, int));
49 static boolean copy_private_bfd_data PARAMS ((bfd *, bfd *));
50 static char *elf_read PARAMS ((bfd *, long, unsigned int));
51 static void elf_fake_sections PARAMS ((bfd *, asection *, PTR));
52 static boolean assign_section_numbers PARAMS ((bfd *));
53 static INLINE int sym_is_global PARAMS ((bfd *, asymbol *));
54 static boolean elf_map_symbols PARAMS ((bfd *));
55 static bfd_size_type get_program_header_size PARAMS ((bfd *));
56 static boolean elfcore_read_notes PARAMS ((bfd *, bfd_vma, bfd_vma));
57
58 /* Swap version information in and out.  The version information is
59    currently size independent.  If that ever changes, this code will
60    need to move into elfcode.h.  */
61
62 /* Swap in a Verdef structure.  */
63
64 void
65 _bfd_elf_swap_verdef_in (abfd, src, dst)
66      bfd *abfd;
67      const Elf_External_Verdef *src;
68      Elf_Internal_Verdef *dst;
69 {
70   dst->vd_version = bfd_h_get_16 (abfd, src->vd_version);
71   dst->vd_flags   = bfd_h_get_16 (abfd, src->vd_flags);
72   dst->vd_ndx     = bfd_h_get_16 (abfd, src->vd_ndx);
73   dst->vd_cnt     = bfd_h_get_16 (abfd, src->vd_cnt);
74   dst->vd_hash    = bfd_h_get_32 (abfd, src->vd_hash);
75   dst->vd_aux     = bfd_h_get_32 (abfd, src->vd_aux);
76   dst->vd_next    = bfd_h_get_32 (abfd, src->vd_next);
77 }
78
79 /* Swap out a Verdef structure.  */
80
81 void
82 _bfd_elf_swap_verdef_out (abfd, src, dst)
83      bfd *abfd;
84      const Elf_Internal_Verdef *src;
85      Elf_External_Verdef *dst;
86 {
87   bfd_h_put_16 (abfd, src->vd_version, dst->vd_version);
88   bfd_h_put_16 (abfd, src->vd_flags, dst->vd_flags);
89   bfd_h_put_16 (abfd, src->vd_ndx, dst->vd_ndx);
90   bfd_h_put_16 (abfd, src->vd_cnt, dst->vd_cnt);
91   bfd_h_put_32 (abfd, src->vd_hash, dst->vd_hash);
92   bfd_h_put_32 (abfd, src->vd_aux, dst->vd_aux);
93   bfd_h_put_32 (abfd, src->vd_next, dst->vd_next);
94 }
95
96 /* Swap in a Verdaux structure.  */
97
98 void
99 _bfd_elf_swap_verdaux_in (abfd, src, dst)
100      bfd *abfd;
101      const Elf_External_Verdaux *src;
102      Elf_Internal_Verdaux *dst;
103 {
104   dst->vda_name = bfd_h_get_32 (abfd, src->vda_name);
105   dst->vda_next = bfd_h_get_32 (abfd, src->vda_next);
106 }
107
108 /* Swap out a Verdaux structure.  */
109
110 void
111 _bfd_elf_swap_verdaux_out (abfd, src, dst)
112      bfd *abfd;
113      const Elf_Internal_Verdaux *src;
114      Elf_External_Verdaux *dst;
115 {
116   bfd_h_put_32 (abfd, src->vda_name, dst->vda_name);
117   bfd_h_put_32 (abfd, src->vda_next, dst->vda_next);
118 }
119
120 /* Swap in a Verneed structure.  */
121
122 void
123 _bfd_elf_swap_verneed_in (abfd, src, dst)
124      bfd *abfd;
125      const Elf_External_Verneed *src;
126      Elf_Internal_Verneed *dst;
127 {
128   dst->vn_version = bfd_h_get_16 (abfd, src->vn_version);
129   dst->vn_cnt     = bfd_h_get_16 (abfd, src->vn_cnt);
130   dst->vn_file    = bfd_h_get_32 (abfd, src->vn_file);
131   dst->vn_aux     = bfd_h_get_32 (abfd, src->vn_aux);
132   dst->vn_next    = bfd_h_get_32 (abfd, src->vn_next);
133 }
134
135 /* Swap out a Verneed structure.  */
136
137 void
138 _bfd_elf_swap_verneed_out (abfd, src, dst)
139      bfd *abfd;
140      const Elf_Internal_Verneed *src;
141      Elf_External_Verneed *dst;
142 {
143   bfd_h_put_16 (abfd, src->vn_version, dst->vn_version);
144   bfd_h_put_16 (abfd, src->vn_cnt, dst->vn_cnt);
145   bfd_h_put_32 (abfd, src->vn_file, dst->vn_file);
146   bfd_h_put_32 (abfd, src->vn_aux, dst->vn_aux);
147   bfd_h_put_32 (abfd, src->vn_next, dst->vn_next);
148 }
149
150 /* Swap in a Vernaux structure.  */
151
152 void
153 _bfd_elf_swap_vernaux_in (abfd, src, dst)
154      bfd *abfd;
155      const Elf_External_Vernaux *src;
156      Elf_Internal_Vernaux *dst;
157 {
158   dst->vna_hash  = bfd_h_get_32 (abfd, src->vna_hash);
159   dst->vna_flags = bfd_h_get_16 (abfd, src->vna_flags);
160   dst->vna_other = bfd_h_get_16 (abfd, src->vna_other);
161   dst->vna_name  = bfd_h_get_32 (abfd, src->vna_name);
162   dst->vna_next  = bfd_h_get_32 (abfd, src->vna_next);
163 }
164
165 /* Swap out a Vernaux structure.  */
166
167 void
168 _bfd_elf_swap_vernaux_out (abfd, src, dst)
169      bfd *abfd;
170      const Elf_Internal_Vernaux *src;
171      Elf_External_Vernaux *dst;
172 {
173   bfd_h_put_32 (abfd, src->vna_hash, dst->vna_hash);
174   bfd_h_put_16 (abfd, src->vna_flags, dst->vna_flags);
175   bfd_h_put_16 (abfd, src->vna_other, dst->vna_other);
176   bfd_h_put_32 (abfd, src->vna_name, dst->vna_name);
177   bfd_h_put_32 (abfd, src->vna_next, dst->vna_next);
178 }
179
180 /* Swap in a Versym structure.  */
181
182 void
183 _bfd_elf_swap_versym_in (abfd, src, dst)
184      bfd *abfd;
185      const Elf_External_Versym *src;
186      Elf_Internal_Versym *dst;
187 {
188   dst->vs_vers = bfd_h_get_16 (abfd, src->vs_vers);
189 }
190
191 /* Swap out a Versym structure.  */
192
193 void
194 _bfd_elf_swap_versym_out (abfd, src, dst)
195      bfd *abfd;
196      const Elf_Internal_Versym *src;
197      Elf_External_Versym *dst;
198 {
199   bfd_h_put_16 (abfd, src->vs_vers, dst->vs_vers);
200 }
201
202 /* Standard ELF hash function.  Do not change this function; you will
203    cause invalid hash tables to be generated.  */
204
205 unsigned long
206 bfd_elf_hash (namearg)
207      const char *namearg;
208 {
209   const unsigned char *name = (const unsigned char *) namearg;
210   unsigned long h = 0;
211   unsigned long g;
212   int ch;
213
214   while ((ch = *name++) != '\0')
215     {
216       h = (h << 4) + ch;
217       if ((g = (h & 0xf0000000)) != 0)
218         {
219           h ^= g >> 24;
220           /* The ELF ABI says `h &= ~g', but this is equivalent in
221              this case and on some machines one insn instead of two.  */
222           h ^= g;
223         }
224     }
225   return h;
226 }
227
228 /* Read a specified number of bytes at a specified offset in an ELF
229    file, into a newly allocated buffer, and return a pointer to the
230    buffer. */
231
232 static char *
233 elf_read (abfd, offset, size)
234      bfd * abfd;
235      long offset;
236      unsigned int size;
237 {
238   char *buf;
239
240   if ((buf = bfd_alloc (abfd, size)) == NULL)
241     return NULL;
242   if (bfd_seek (abfd, offset, SEEK_SET) == -1)
243     return NULL;
244   if (bfd_read ((PTR) buf, size, 1, abfd) != size)
245     {
246       if (bfd_get_error () != bfd_error_system_call)
247         bfd_set_error (bfd_error_file_truncated);
248       return NULL;
249     }
250   return buf;
251 }
252
253 boolean
254 bfd_elf_mkobject (abfd)
255      bfd * abfd;
256 {
257   /* this just does initialization */
258   /* coff_mkobject zalloc's space for tdata.coff_obj_data ... */
259   elf_tdata (abfd) = (struct elf_obj_tdata *)
260     bfd_zalloc (abfd, sizeof (struct elf_obj_tdata));
261   if (elf_tdata (abfd) == 0)
262     return false;
263   /* since everything is done at close time, do we need any
264      initialization? */
265
266   return true;
267 }
268
269 boolean
270 bfd_elf_mkcorefile (abfd)
271      bfd * abfd;
272 {
273   /* I think this can be done just like an object file. */
274   return bfd_elf_mkobject (abfd);
275 }
276
277 char *
278 bfd_elf_get_str_section (abfd, shindex)
279      bfd * abfd;
280      unsigned int shindex;
281 {
282   Elf_Internal_Shdr **i_shdrp;
283   char *shstrtab = NULL;
284   unsigned int offset;
285   unsigned int shstrtabsize;
286
287   i_shdrp = elf_elfsections (abfd);
288   if (i_shdrp == 0 || i_shdrp[shindex] == 0)
289     return 0;
290
291   shstrtab = (char *) i_shdrp[shindex]->contents;
292   if (shstrtab == NULL)
293     {
294       /* No cached one, attempt to read, and cache what we read. */
295       offset = i_shdrp[shindex]->sh_offset;
296       shstrtabsize = i_shdrp[shindex]->sh_size;
297       shstrtab = elf_read (abfd, offset, shstrtabsize);
298       i_shdrp[shindex]->contents = (PTR) shstrtab;
299     }
300   return shstrtab;
301 }
302
303 char *
304 bfd_elf_string_from_elf_section (abfd, shindex, strindex)
305      bfd * abfd;
306      unsigned int shindex;
307      unsigned int strindex;
308 {
309   Elf_Internal_Shdr *hdr;
310
311   if (strindex == 0)
312     return "";
313
314   hdr = elf_elfsections (abfd)[shindex];
315
316   if (hdr->contents == NULL
317       && bfd_elf_get_str_section (abfd, shindex) == NULL)
318     return NULL;
319
320   if (strindex >= hdr->sh_size)
321     {
322       (*_bfd_error_handler)
323         (_("%s: invalid string offset %u >= %lu for section `%s'"),
324          bfd_get_filename (abfd), strindex, (unsigned long) hdr->sh_size,
325          ((shindex == elf_elfheader(abfd)->e_shstrndx
326            && strindex == hdr->sh_name)
327           ? ".shstrtab"
328           : elf_string_from_elf_strtab (abfd, hdr->sh_name)));
329       return "";
330     }
331
332   return ((char *) hdr->contents) + strindex;
333 }
334
335 /* Make a BFD section from an ELF section.  We store a pointer to the
336    BFD section in the bfd_section field of the header.  */
337
338 boolean
339 _bfd_elf_make_section_from_shdr (abfd, hdr, name)
340      bfd *abfd;
341      Elf_Internal_Shdr *hdr;
342      const char *name;
343 {
344   asection *newsect;
345   flagword flags;
346
347   if (hdr->bfd_section != NULL)
348     {
349       BFD_ASSERT (strcmp (name,
350                           bfd_get_section_name (abfd, hdr->bfd_section)) == 0);
351       return true;
352     }
353
354   newsect = bfd_make_section_anyway (abfd, name);
355   if (newsect == NULL)
356     return false;
357
358   newsect->filepos = hdr->sh_offset;
359
360   if (! bfd_set_section_vma (abfd, newsect, hdr->sh_addr)
361       || ! bfd_set_section_size (abfd, newsect, hdr->sh_size)
362       || ! bfd_set_section_alignment (abfd, newsect,
363                                       bfd_log2 (hdr->sh_addralign)))
364     return false;
365
366   flags = SEC_NO_FLAGS;
367   if (hdr->sh_type != SHT_NOBITS)
368     flags |= SEC_HAS_CONTENTS;
369   if ((hdr->sh_flags & SHF_ALLOC) != 0)
370     {
371       flags |= SEC_ALLOC;
372       if (hdr->sh_type != SHT_NOBITS)
373         flags |= SEC_LOAD;
374     }
375   if ((hdr->sh_flags & SHF_WRITE) == 0)
376     flags |= SEC_READONLY;
377   if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
378     flags |= SEC_CODE;
379   else if ((flags & SEC_LOAD) != 0)
380     flags |= SEC_DATA;
381
382   /* The debugging sections appear to be recognized only by name, not
383      any sort of flag.  */
384   if (strncmp (name, ".debug", sizeof ".debug" - 1) == 0
385       || strncmp (name, ".line", sizeof ".line" - 1) == 0
386       || strncmp (name, ".stab", sizeof ".stab" - 1) == 0)
387     flags |= SEC_DEBUGGING;
388
389   /* As a GNU extension, if the name begins with .gnu.linkonce, we
390      only link a single copy of the section.  This is used to support
391      g++.  g++ will emit each template expansion in its own section.
392      The symbols will be defined as weak, so that multiple definitions
393      are permitted.  The GNU linker extension is to actually discard
394      all but one of the sections.  */
395   if (strncmp (name, ".gnu.linkonce", sizeof ".gnu.linkonce" - 1) == 0)
396     flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
397
398   if (! bfd_set_section_flags (abfd, newsect, flags))
399     return false;
400
401   if ((flags & SEC_ALLOC) != 0)
402     {
403       Elf_Internal_Phdr *phdr;
404       unsigned int i;
405
406       /* Look through the phdrs to see if we need to adjust the lma.
407          If all the p_paddr fields are zero, we ignore them, since
408          some ELF linkers produce such output.  */
409       phdr = elf_tdata (abfd)->phdr;
410       for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
411         {
412           if (phdr->p_paddr != 0)
413             break;
414         }
415       if (i < elf_elfheader (abfd)->e_phnum)
416         {
417           phdr = elf_tdata (abfd)->phdr;
418           for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
419             {
420               if (phdr->p_type == PT_LOAD
421                   && phdr->p_vaddr != phdr->p_paddr
422                   && phdr->p_vaddr <= hdr->sh_addr
423                   && (phdr->p_vaddr + phdr->p_memsz
424                       >= hdr->sh_addr + hdr->sh_size)
425                   && ((flags & SEC_LOAD) == 0
426                       || (phdr->p_offset <= (bfd_vma) hdr->sh_offset
427                           && (phdr->p_offset + phdr->p_filesz
428                               >= hdr->sh_offset + hdr->sh_size))))
429                 {
430                   newsect->lma += phdr->p_paddr - phdr->p_vaddr;
431                   break;
432                 }
433             }
434         }
435     }
436
437   hdr->bfd_section = newsect;
438   elf_section_data (newsect)->this_hdr = *hdr;
439
440   return true;
441 }
442
443 /*
444 INTERNAL_FUNCTION
445         bfd_elf_find_section
446
447 SYNOPSIS
448         struct elf_internal_shdr *bfd_elf_find_section (bfd *abfd, char *name);
449
450 DESCRIPTION
451         Helper functions for GDB to locate the string tables.
452         Since BFD hides string tables from callers, GDB needs to use an
453         internal hook to find them.  Sun's .stabstr, in particular,
454         isn't even pointed to by the .stab section, so ordinary
455         mechanisms wouldn't work to find it, even if we had some.
456 */
457
458 struct elf_internal_shdr *
459 bfd_elf_find_section (abfd, name)
460      bfd * abfd;
461      char *name;
462 {
463   Elf_Internal_Shdr **i_shdrp;
464   char *shstrtab;
465   unsigned int max;
466   unsigned int i;
467
468   i_shdrp = elf_elfsections (abfd);
469   if (i_shdrp != NULL)
470     {
471       shstrtab = bfd_elf_get_str_section
472         (abfd, elf_elfheader (abfd)->e_shstrndx);
473       if (shstrtab != NULL)
474         {
475           max = elf_elfheader (abfd)->e_shnum;
476           for (i = 1; i < max; i++)
477             if (!strcmp (&shstrtab[i_shdrp[i]->sh_name], name))
478               return i_shdrp[i];
479         }
480     }
481   return 0;
482 }
483
484 const char *const bfd_elf_section_type_names[] = {
485   "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB",
486   "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE",
487   "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM",
488 };
489
490 /* ELF relocs are against symbols.  If we are producing relocateable
491    output, and the reloc is against an external symbol, and nothing
492    has given us any additional addend, the resulting reloc will also
493    be against the same symbol.  In such a case, we don't want to
494    change anything about the way the reloc is handled, since it will
495    all be done at final link time.  Rather than put special case code
496    into bfd_perform_relocation, all the reloc types use this howto
497    function.  It just short circuits the reloc if producing
498    relocateable output against an external symbol.  */
499
500 /*ARGSUSED*/
501 bfd_reloc_status_type
502 bfd_elf_generic_reloc (abfd,
503                        reloc_entry,
504                        symbol,
505                        data,
506                        input_section,
507                        output_bfd,
508                        error_message)
509      bfd *abfd ATTRIBUTE_UNUSED;
510      arelent *reloc_entry;
511      asymbol *symbol;
512      PTR data ATTRIBUTE_UNUSED;
513      asection *input_section;
514      bfd *output_bfd;
515      char **error_message ATTRIBUTE_UNUSED;
516 {
517   if (output_bfd != (bfd *) NULL
518       && (symbol->flags & BSF_SECTION_SYM) == 0
519       && (! reloc_entry->howto->partial_inplace
520           || reloc_entry->addend == 0))
521     {
522       reloc_entry->address += input_section->output_offset;
523       return bfd_reloc_ok;
524     }
525
526   return bfd_reloc_continue;
527 }
528 \f
529 /* Print out the program headers.  */
530
531 boolean
532 _bfd_elf_print_private_bfd_data (abfd, farg)
533      bfd *abfd;
534      PTR farg;
535 {
536   FILE *f = (FILE *) farg;
537   Elf_Internal_Phdr *p;
538   asection *s;
539   bfd_byte *dynbuf = NULL;
540
541   p = elf_tdata (abfd)->phdr;
542   if (p != NULL)
543     {
544       unsigned int i, c;
545
546       fprintf (f, _("\nProgram Header:\n"));
547       c = elf_elfheader (abfd)->e_phnum;
548       for (i = 0; i < c; i++, p++)
549         {
550           const char *s;
551           char buf[20];
552
553           switch (p->p_type)
554             {
555             case PT_NULL: s = "NULL"; break;
556             case PT_LOAD: s = "LOAD"; break;
557             case PT_DYNAMIC: s = "DYNAMIC"; break;
558             case PT_INTERP: s = "INTERP"; break;
559             case PT_NOTE: s = "NOTE"; break;
560             case PT_SHLIB: s = "SHLIB"; break;
561             case PT_PHDR: s = "PHDR"; break;
562             default: sprintf (buf, "0x%lx", p->p_type); s = buf; break;
563             }
564           fprintf (f, "%8s off    0x", s);
565           fprintf_vma (f, p->p_offset);
566           fprintf (f, " vaddr 0x");
567           fprintf_vma (f, p->p_vaddr);
568           fprintf (f, " paddr 0x");
569           fprintf_vma (f, p->p_paddr);
570           fprintf (f, " align 2**%u\n", bfd_log2 (p->p_align));
571           fprintf (f, "         filesz 0x");
572           fprintf_vma (f, p->p_filesz);
573           fprintf (f, " memsz 0x");
574           fprintf_vma (f, p->p_memsz);
575           fprintf (f, " flags %c%c%c",
576                    (p->p_flags & PF_R) != 0 ? 'r' : '-',
577                    (p->p_flags & PF_W) != 0 ? 'w' : '-',
578                    (p->p_flags & PF_X) != 0 ? 'x' : '-');
579           if ((p->p_flags &~ (PF_R | PF_W | PF_X)) != 0)
580             fprintf (f, " %lx", p->p_flags &~ (PF_R | PF_W | PF_X));
581           fprintf (f, "\n");
582         }
583     }
584
585   s = bfd_get_section_by_name (abfd, ".dynamic");
586   if (s != NULL)
587     {
588       int elfsec;
589       unsigned long link;
590       bfd_byte *extdyn, *extdynend;
591       size_t extdynsize;
592       void (*swap_dyn_in) PARAMS ((bfd *, const PTR, Elf_Internal_Dyn *));
593
594       fprintf (f, _("\nDynamic Section:\n"));
595
596       dynbuf = (bfd_byte *) bfd_malloc (s->_raw_size);
597       if (dynbuf == NULL)
598         goto error_return;
599       if (! bfd_get_section_contents (abfd, s, (PTR) dynbuf, (file_ptr) 0,
600                                       s->_raw_size))
601         goto error_return;
602
603       elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
604       if (elfsec == -1)
605         goto error_return;
606       link = elf_elfsections (abfd)[elfsec]->sh_link;
607
608       extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
609       swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
610
611       extdyn = dynbuf;
612       extdynend = extdyn + s->_raw_size;
613       for (; extdyn < extdynend; extdyn += extdynsize)
614         {
615           Elf_Internal_Dyn dyn;
616           const char *name;
617           char ab[20];
618           boolean stringp;
619
620           (*swap_dyn_in) (abfd, (PTR) extdyn, &dyn);
621
622           if (dyn.d_tag == DT_NULL)
623             break;
624
625           stringp = false;
626           switch (dyn.d_tag)
627             {
628             default:
629               sprintf (ab, "0x%lx", (unsigned long) dyn.d_tag);
630               name = ab;
631               break;
632
633             case DT_NEEDED: name = "NEEDED"; stringp = true; break;
634             case DT_PLTRELSZ: name = "PLTRELSZ"; break;
635             case DT_PLTGOT: name = "PLTGOT"; break;
636             case DT_HASH: name = "HASH"; break;
637             case DT_STRTAB: name = "STRTAB"; break;
638             case DT_SYMTAB: name = "SYMTAB"; break;
639             case DT_RELA: name = "RELA"; break;
640             case DT_RELASZ: name = "RELASZ"; break;
641             case DT_RELAENT: name = "RELAENT"; break;
642             case DT_STRSZ: name = "STRSZ"; break;
643             case DT_SYMENT: name = "SYMENT"; break;
644             case DT_INIT: name = "INIT"; break;
645             case DT_FINI: name = "FINI"; break;
646             case DT_SONAME: name = "SONAME"; stringp = true; break;
647             case DT_RPATH: name = "RPATH"; stringp = true; break;
648             case DT_SYMBOLIC: name = "SYMBOLIC"; break;
649             case DT_REL: name = "REL"; break;
650             case DT_RELSZ: name = "RELSZ"; break;
651             case DT_RELENT: name = "RELENT"; break;
652             case DT_PLTREL: name = "PLTREL"; break;
653             case DT_DEBUG: name = "DEBUG"; break;
654             case DT_TEXTREL: name = "TEXTREL"; break;
655             case DT_JMPREL: name = "JMPREL"; break;
656             case DT_AUXILIARY: name = "AUXILIARY"; stringp = true; break;
657             case DT_FILTER: name = "FILTER"; stringp = true; break;
658             case DT_VERSYM: name = "VERSYM"; break;
659             case DT_VERDEF: name = "VERDEF"; break;
660             case DT_VERDEFNUM: name = "VERDEFNUM"; break;
661             case DT_VERNEED: name = "VERNEED"; break;
662             case DT_VERNEEDNUM: name = "VERNEEDNUM"; break;
663             }
664
665           fprintf (f, "  %-11s ", name);
666           if (! stringp)
667             fprintf (f, "0x%lx", (unsigned long) dyn.d_un.d_val);
668           else
669             {
670               const char *string;
671
672               string = bfd_elf_string_from_elf_section (abfd, link,
673                                                         dyn.d_un.d_val);
674               if (string == NULL)
675                 goto error_return;
676               fprintf (f, "%s", string);
677             }
678           fprintf (f, "\n");
679         }
680
681       free (dynbuf);
682       dynbuf = NULL;
683     }
684
685   if ((elf_dynverdef (abfd) != 0 && elf_tdata (abfd)->verdef == NULL)
686       || (elf_dynverref (abfd) != 0 && elf_tdata (abfd)->verref == NULL))
687     {
688       if (! _bfd_elf_slurp_version_tables (abfd))
689         return false;
690     }
691
692   if (elf_dynverdef (abfd) != 0)
693     {
694       Elf_Internal_Verdef *t;
695
696       fprintf (f, _("\nVersion definitions:\n"));
697       for (t = elf_tdata (abfd)->verdef; t != NULL; t = t->vd_nextdef)
698         {
699           fprintf (f, "%d 0x%2.2x 0x%8.8lx %s\n", t->vd_ndx,
700                    t->vd_flags, t->vd_hash, t->vd_nodename);
701           if (t->vd_auxptr->vda_nextptr != NULL)
702             {
703               Elf_Internal_Verdaux *a;
704
705               fprintf (f, "\t");
706               for (a = t->vd_auxptr->vda_nextptr;
707                    a != NULL;
708                    a = a->vda_nextptr)
709                 fprintf (f, "%s ", a->vda_nodename);
710               fprintf (f, "\n");
711             }
712         }
713     }
714
715   if (elf_dynverref (abfd) != 0)
716     {
717       Elf_Internal_Verneed *t;
718
719       fprintf (f, _("\nVersion References:\n"));
720       for (t = elf_tdata (abfd)->verref; t != NULL; t = t->vn_nextref)
721         {
722           Elf_Internal_Vernaux *a;
723
724           fprintf (f, _("  required from %s:\n"), t->vn_filename);
725           for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
726             fprintf (f, "    0x%8.8lx 0x%2.2x %2.2d %s\n", a->vna_hash,
727                      a->vna_flags, a->vna_other, a->vna_nodename);
728         }
729     }
730
731   return true;
732
733  error_return:
734   if (dynbuf != NULL)
735     free (dynbuf);
736   return false;
737 }
738
739 /* Display ELF-specific fields of a symbol.  */
740
741 void
742 bfd_elf_print_symbol (abfd, filep, symbol, how)
743      bfd *abfd;
744      PTR filep;
745      asymbol *symbol;
746      bfd_print_symbol_type how;
747 {
748   FILE *file = (FILE *) filep;
749   switch (how)
750     {
751     case bfd_print_symbol_name:
752       fprintf (file, "%s", symbol->name);
753       break;
754     case bfd_print_symbol_more:
755       fprintf (file, "elf ");
756       fprintf_vma (file, symbol->value);
757       fprintf (file, " %lx", (long) symbol->flags);
758       break;
759     case bfd_print_symbol_all:
760       {
761         CONST char *section_name;
762         CONST char *name = NULL;
763         struct elf_backend_data *bed;
764         unsigned char st_other;
765         
766         section_name = symbol->section ? symbol->section->name : "(*none*)";
767
768         bed = get_elf_backend_data (abfd);
769         if (bed->elf_backend_print_symbol_all)
770             name = (*bed->elf_backend_print_symbol_all) (abfd, filep, symbol);
771
772         if (name == NULL)
773           {
774             name = symbol->name;  
775             bfd_print_symbol_vandf ((PTR) file, symbol);
776           }
777
778         fprintf (file, " %s\t", section_name);
779         /* Print the "other" value for a symbol.  For common symbols,
780            we've already printed the size; now print the alignment.
781            For other symbols, we have no specified alignment, and
782            we've printed the address; now print the size.  */
783         fprintf_vma (file,
784                      (bfd_is_com_section (symbol->section)
785                       ? ((elf_symbol_type *) symbol)->internal_elf_sym.st_value
786                       : ((elf_symbol_type *) symbol)->internal_elf_sym.st_size));
787
788         /* If we have version information, print it.  */
789         if (elf_tdata (abfd)->dynversym_section != 0
790             && (elf_tdata (abfd)->dynverdef_section != 0
791                 || elf_tdata (abfd)->dynverref_section != 0))
792           {
793             unsigned int vernum;
794             const char *version_string;
795
796             vernum = ((elf_symbol_type *) symbol)->version & VERSYM_VERSION;
797
798             if (vernum == 0)
799               version_string = "";
800             else if (vernum == 1)
801               version_string = "Base";
802             else if (vernum <= elf_tdata (abfd)->cverdefs)
803               version_string =
804                 elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
805             else
806               {
807                 Elf_Internal_Verneed *t;
808
809                 version_string = "";
810                 for (t = elf_tdata (abfd)->verref;
811                      t != NULL;
812                      t = t->vn_nextref)
813                   {
814                     Elf_Internal_Vernaux *a;
815
816                     for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
817                       {
818                         if (a->vna_other == vernum)
819                           {
820                             version_string = a->vna_nodename;
821                             break;
822                           }
823                       }
824                   }
825               }
826
827             if ((((elf_symbol_type *) symbol)->version & VERSYM_HIDDEN) == 0)
828               fprintf (file, "  %-11s", version_string);
829             else
830               {
831                 int i;
832
833                 fprintf (file, " (%s)", version_string);
834                 for (i = 10 - strlen (version_string); i > 0; --i)
835                   putc (' ', file);
836               }
837           }
838
839         /* If the st_other field is not zero, print it.  */
840         st_other = ((elf_symbol_type *) symbol)->internal_elf_sym.st_other;
841         
842         switch (st_other)
843           {
844           case 0: break;
845           case STV_INTERNAL:  fprintf (file, " .internal");  break;
846           case STV_HIDDEN:    fprintf (file, " .hidden");    break;
847           case STV_PROTECTED: fprintf (file, " .protected"); break;
848           default:
849             /* Some other non-defined flags are also present, so print
850                everything hex.  */
851             fprintf (file, " 0x%02x", (unsigned int) st_other);
852           }
853
854         fprintf (file, " %s", name);
855       }
856       break;
857     }
858 }
859 \f
860 /* Create an entry in an ELF linker hash table.  */
861
862 struct bfd_hash_entry *
863 _bfd_elf_link_hash_newfunc (entry, table, string)
864      struct bfd_hash_entry *entry;
865      struct bfd_hash_table *table;
866      const char *string;
867 {
868   struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
869
870   /* Allocate the structure if it has not already been allocated by a
871      subclass.  */
872   if (ret == (struct elf_link_hash_entry *) NULL)
873     ret = ((struct elf_link_hash_entry *)
874            bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry)));
875   if (ret == (struct elf_link_hash_entry *) NULL)
876     return (struct bfd_hash_entry *) ret;
877
878   /* Call the allocation method of the superclass.  */
879   ret = ((struct elf_link_hash_entry *)
880          _bfd_link_hash_newfunc ((struct bfd_hash_entry *) ret,
881                                  table, string));
882   if (ret != (struct elf_link_hash_entry *) NULL)
883     {
884       /* Set local fields.  */
885       ret->indx = -1;
886       ret->size = 0;
887       ret->dynindx = -1;
888       ret->dynstr_index = 0;
889       ret->weakdef = NULL;
890       ret->got.offset = (bfd_vma) -1;
891       ret->plt.offset = (bfd_vma) -1;
892       ret->linker_section_pointer = (elf_linker_section_pointers_t *)0;
893       ret->verinfo.verdef = NULL;
894       ret->vtable_entries_used = NULL;
895       ret->vtable_entries_size = 0;
896       ret->vtable_parent = NULL;
897       ret->type = STT_NOTYPE;
898       ret->other = 0;
899       /* Assume that we have been called by a non-ELF symbol reader.
900          This flag is then reset by the code which reads an ELF input
901          file.  This ensures that a symbol created by a non-ELF symbol
902          reader will have the flag set correctly.  */
903       ret->elf_link_hash_flags = ELF_LINK_NON_ELF;
904     }
905
906   return (struct bfd_hash_entry *) ret;
907 }
908
909 /* Copy data from an indirect symbol to its direct symbol, hiding the
910    old indirect symbol.  */
911
912 void
913 _bfd_elf_link_hash_copy_indirect (dir, ind)
914      struct elf_link_hash_entry *dir, *ind;
915 {
916   /* Copy down any references that we may have already seen to the
917      symbol which just became indirect.  */
918
919   dir->elf_link_hash_flags |=
920     (ind->elf_link_hash_flags
921      & (ELF_LINK_HASH_REF_DYNAMIC
922         | ELF_LINK_HASH_REF_REGULAR
923         | ELF_LINK_HASH_REF_REGULAR_NONWEAK
924         | ELF_LINK_NON_GOT_REF));
925
926   /* Copy over the global and procedure linkage table offset entries.
927      These may have been already set up by a check_relocs routine.  */
928   if (dir->got.offset == (bfd_vma) -1)
929     {
930       dir->got.offset = ind->got.offset;
931       ind->got.offset = (bfd_vma) -1;
932     }
933   BFD_ASSERT (ind->got.offset == (bfd_vma) -1);
934
935   if (dir->plt.offset == (bfd_vma) -1)
936     {
937       dir->plt.offset = ind->plt.offset;
938       ind->plt.offset = (bfd_vma) -1;
939     }
940   BFD_ASSERT (ind->plt.offset == (bfd_vma) -1);
941
942   if (dir->dynindx == -1)
943     {
944       dir->dynindx = ind->dynindx;
945       dir->dynstr_index = ind->dynstr_index;
946       ind->dynindx = -1;
947       ind->dynstr_index = 0;
948     }
949   BFD_ASSERT (ind->dynindx == -1);
950 }
951
952 void
953 _bfd_elf_link_hash_hide_symbol(h)
954      struct elf_link_hash_entry *h;
955 {
956   h->elf_link_hash_flags &= ~ELF_LINK_HASH_NEEDS_PLT;
957   h->dynindx = -1;
958   h->plt.offset = (bfd_vma) -1;
959 }
960
961 /* Initialize an ELF linker hash table.  */
962
963 boolean
964 _bfd_elf_link_hash_table_init (table, abfd, newfunc)
965      struct elf_link_hash_table *table;
966      bfd *abfd;
967      struct bfd_hash_entry *(*newfunc) PARAMS ((struct bfd_hash_entry *,
968                                                 struct bfd_hash_table *,
969                                                 const char *));
970 {
971   table->dynamic_sections_created = false;
972   table->dynobj = NULL;
973   /* The first dynamic symbol is a dummy.  */
974   table->dynsymcount = 1;
975   table->dynstr = NULL;
976   table->bucketcount = 0;
977   table->needed = NULL;
978   table->hgot = NULL;
979   table->stab_info = NULL;
980   return _bfd_link_hash_table_init (&table->root, abfd, newfunc);
981 }
982
983 /* Create an ELF linker hash table.  */
984
985 struct bfd_link_hash_table *
986 _bfd_elf_link_hash_table_create (abfd)
987      bfd *abfd;
988 {
989   struct elf_link_hash_table *ret;
990
991   ret = ((struct elf_link_hash_table *)
992          bfd_alloc (abfd, sizeof (struct elf_link_hash_table)));
993   if (ret == (struct elf_link_hash_table *) NULL)
994     return NULL;
995
996   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc))
997     {
998       bfd_release (abfd, ret);
999       return NULL;
1000     }
1001
1002   return &ret->root;
1003 }
1004
1005 /* This is a hook for the ELF emulation code in the generic linker to
1006    tell the backend linker what file name to use for the DT_NEEDED
1007    entry for a dynamic object.  The generic linker passes name as an
1008    empty string to indicate that no DT_NEEDED entry should be made.  */
1009
1010 void
1011 bfd_elf_set_dt_needed_name (abfd, name)
1012      bfd *abfd;
1013      const char *name;
1014 {
1015   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1016       && bfd_get_format (abfd) == bfd_object)
1017     elf_dt_name (abfd) = name;
1018 }
1019
1020 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
1021    the linker ELF emulation code.  */
1022
1023 struct bfd_link_needed_list *
1024 bfd_elf_get_needed_list (abfd, info)
1025      bfd *abfd ATTRIBUTE_UNUSED;
1026      struct bfd_link_info *info;
1027 {
1028   if (info->hash->creator->flavour != bfd_target_elf_flavour)
1029     return NULL;
1030   return elf_hash_table (info)->needed;
1031 }
1032
1033 /* Get the name actually used for a dynamic object for a link.  This
1034    is the SONAME entry if there is one.  Otherwise, it is the string
1035    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
1036
1037 const char *
1038 bfd_elf_get_dt_soname (abfd)
1039      bfd *abfd;
1040 {
1041   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1042       && bfd_get_format (abfd) == bfd_object)
1043     return elf_dt_name (abfd);
1044   return NULL;
1045 }
1046
1047 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
1048    the ELF linker emulation code.  */
1049
1050 boolean
1051 bfd_elf_get_bfd_needed_list (abfd, pneeded)
1052      bfd *abfd;
1053      struct bfd_link_needed_list **pneeded;
1054 {
1055   asection *s;
1056   bfd_byte *dynbuf = NULL;
1057   int elfsec;
1058   unsigned long link;
1059   bfd_byte *extdyn, *extdynend;
1060   size_t extdynsize;
1061   void (*swap_dyn_in) PARAMS ((bfd *, const PTR, Elf_Internal_Dyn *));
1062
1063   *pneeded = NULL;
1064
1065   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
1066       || bfd_get_format (abfd) != bfd_object)
1067     return true;
1068
1069   s = bfd_get_section_by_name (abfd, ".dynamic");
1070   if (s == NULL || s->_raw_size == 0)
1071     return true;
1072
1073   dynbuf = (bfd_byte *) bfd_malloc (s->_raw_size);
1074   if (dynbuf == NULL)
1075     goto error_return;
1076
1077   if (! bfd_get_section_contents (abfd, s, (PTR) dynbuf, (file_ptr) 0,
1078                                   s->_raw_size))
1079     goto error_return;
1080
1081   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
1082   if (elfsec == -1)
1083     goto error_return;
1084
1085   link = elf_elfsections (abfd)[elfsec]->sh_link;
1086
1087   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
1088   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
1089
1090   extdyn = dynbuf;
1091   extdynend = extdyn + s->_raw_size;
1092   for (; extdyn < extdynend; extdyn += extdynsize)
1093     {
1094       Elf_Internal_Dyn dyn;
1095
1096       (*swap_dyn_in) (abfd, (PTR) extdyn, &dyn);
1097
1098       if (dyn.d_tag == DT_NULL)
1099         break;
1100
1101       if (dyn.d_tag == DT_NEEDED)
1102         {
1103           const char *string;
1104           struct bfd_link_needed_list *l;
1105
1106           string = bfd_elf_string_from_elf_section (abfd, link,
1107                                                     dyn.d_un.d_val);
1108           if (string == NULL)
1109             goto error_return;
1110
1111           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, sizeof *l);
1112           if (l == NULL)
1113             goto error_return;
1114
1115           l->by = abfd;
1116           l->name = string;
1117           l->next = *pneeded;
1118           *pneeded = l;
1119         }
1120     }
1121
1122   free (dynbuf);
1123
1124   return true;
1125
1126  error_return:
1127   if (dynbuf != NULL)
1128     free (dynbuf);
1129   return false;
1130 }
1131 \f
1132 /* Allocate an ELF string table--force the first byte to be zero.  */
1133
1134 struct bfd_strtab_hash *
1135 _bfd_elf_stringtab_init ()
1136 {
1137   struct bfd_strtab_hash *ret;
1138
1139   ret = _bfd_stringtab_init ();
1140   if (ret != NULL)
1141     {
1142       bfd_size_type loc;
1143
1144       loc = _bfd_stringtab_add (ret, "", true, false);
1145       BFD_ASSERT (loc == 0 || loc == (bfd_size_type) -1);
1146       if (loc == (bfd_size_type) -1)
1147         {
1148           _bfd_stringtab_free (ret);
1149           ret = NULL;
1150         }
1151     }
1152   return ret;
1153 }
1154 \f
1155 /* ELF .o/exec file reading */
1156
1157 /* Create a new bfd section from an ELF section header. */
1158
1159 boolean
1160 bfd_section_from_shdr (abfd, shindex)
1161      bfd *abfd;
1162      unsigned int shindex;
1163 {
1164   Elf_Internal_Shdr *hdr = elf_elfsections (abfd)[shindex];
1165   Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
1166   struct elf_backend_data *bed = get_elf_backend_data (abfd);
1167   char *name;
1168
1169   name = elf_string_from_elf_strtab (abfd, hdr->sh_name);
1170
1171   switch (hdr->sh_type)
1172     {
1173     case SHT_NULL:
1174       /* Inactive section. Throw it away.  */
1175       return true;
1176
1177     case SHT_PROGBITS:  /* Normal section with contents.  */
1178     case SHT_DYNAMIC:   /* Dynamic linking information.  */
1179     case SHT_NOBITS:    /* .bss section.  */
1180     case SHT_HASH:      /* .hash section.  */
1181     case SHT_NOTE:      /* .note section.  */
1182       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1183
1184     case SHT_SYMTAB:            /* A symbol table */
1185       if (elf_onesymtab (abfd) == shindex)
1186         return true;
1187
1188       BFD_ASSERT (hdr->sh_entsize == bed->s->sizeof_sym);
1189       BFD_ASSERT (elf_onesymtab (abfd) == 0);
1190       elf_onesymtab (abfd) = shindex;
1191       elf_tdata (abfd)->symtab_hdr = *hdr;
1192       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->symtab_hdr;
1193       abfd->flags |= HAS_SYMS;
1194
1195       /* Sometimes a shared object will map in the symbol table.  If
1196          SHF_ALLOC is set, and this is a shared object, then we also
1197          treat this section as a BFD section.  We can not base the
1198          decision purely on SHF_ALLOC, because that flag is sometimes
1199          set in a relocateable object file, which would confuse the
1200          linker.  */
1201       if ((hdr->sh_flags & SHF_ALLOC) != 0
1202           && (abfd->flags & DYNAMIC) != 0
1203           && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name))
1204         return false;
1205
1206       return true;
1207
1208     case SHT_DYNSYM:            /* A dynamic symbol table */
1209       if (elf_dynsymtab (abfd) == shindex)
1210         return true;
1211
1212       BFD_ASSERT (hdr->sh_entsize == bed->s->sizeof_sym);
1213       BFD_ASSERT (elf_dynsymtab (abfd) == 0);
1214       elf_dynsymtab (abfd) = shindex;
1215       elf_tdata (abfd)->dynsymtab_hdr = *hdr;
1216       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->dynsymtab_hdr;
1217       abfd->flags |= HAS_SYMS;
1218
1219       /* Besides being a symbol table, we also treat this as a regular
1220          section, so that objcopy can handle it.  */
1221       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1222
1223     case SHT_STRTAB:            /* A string table */
1224       if (hdr->bfd_section != NULL)
1225         return true;
1226       if (ehdr->e_shstrndx == shindex)
1227         {
1228           elf_tdata (abfd)->shstrtab_hdr = *hdr;
1229           elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
1230           return true;
1231         }
1232       {
1233         unsigned int i;
1234
1235         for (i = 1; i < ehdr->e_shnum; i++)
1236           {
1237             Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
1238             if (hdr2->sh_link == shindex)
1239               {
1240                 if (! bfd_section_from_shdr (abfd, i))
1241                   return false;
1242                 if (elf_onesymtab (abfd) == i)
1243                   {
1244                     elf_tdata (abfd)->strtab_hdr = *hdr;
1245                     elf_elfsections (abfd)[shindex] =
1246                       &elf_tdata (abfd)->strtab_hdr;
1247                     return true;
1248                   }
1249                 if (elf_dynsymtab (abfd) == i)
1250                   {
1251                     elf_tdata (abfd)->dynstrtab_hdr = *hdr;
1252                     elf_elfsections (abfd)[shindex] = hdr =
1253                       &elf_tdata (abfd)->dynstrtab_hdr;
1254                     /* We also treat this as a regular section, so
1255                        that objcopy can handle it.  */
1256                     break;
1257                   }
1258 #if 0 /* Not handling other string tables specially right now.  */
1259                 hdr2 = elf_elfsections (abfd)[i];       /* in case it moved */
1260                 /* We have a strtab for some random other section.  */
1261                 newsect = (asection *) hdr2->bfd_section;
1262                 if (!newsect)
1263                   break;
1264                 hdr->bfd_section = newsect;
1265                 hdr2 = &elf_section_data (newsect)->str_hdr;
1266                 *hdr2 = *hdr;
1267                 elf_elfsections (abfd)[shindex] = hdr2;
1268 #endif
1269               }
1270           }
1271       }
1272
1273       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1274
1275     case SHT_REL:
1276     case SHT_RELA:
1277       /* *These* do a lot of work -- but build no sections!  */
1278       {
1279         asection *target_sect;
1280         Elf_Internal_Shdr *hdr2;
1281
1282         /* Check for a bogus link to avoid crashing.  */
1283         if (hdr->sh_link >= ehdr->e_shnum)
1284           {
1285             ((*_bfd_error_handler)
1286              (_("%s: invalid link %lu for reloc section %s (index %u)"),
1287               bfd_get_filename (abfd), hdr->sh_link, name, shindex));
1288             return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1289           }
1290
1291         /* For some incomprehensible reason Oracle distributes
1292            libraries for Solaris in which some of the objects have
1293            bogus sh_link fields.  It would be nice if we could just
1294            reject them, but, unfortunately, some people need to use
1295            them.  We scan through the section headers; if we find only
1296            one suitable symbol table, we clobber the sh_link to point
1297            to it.  I hope this doesn't break anything.  */
1298         if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_SYMTAB
1299             && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_DYNSYM)
1300           {
1301             int scan;
1302             int found;
1303
1304             found = 0;
1305             for (scan = 1; scan < ehdr->e_shnum; scan++)
1306               {
1307                 if (elf_elfsections (abfd)[scan]->sh_type == SHT_SYMTAB
1308                     || elf_elfsections (abfd)[scan]->sh_type == SHT_DYNSYM)
1309                   {
1310                     if (found != 0)
1311                       {
1312                         found = 0;
1313                         break;
1314                       }
1315                     found = scan;
1316                   }
1317               }
1318             if (found != 0)
1319               hdr->sh_link = found;
1320           }
1321
1322         /* Get the symbol table.  */
1323         if (elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_SYMTAB
1324             && ! bfd_section_from_shdr (abfd, hdr->sh_link))
1325           return false;
1326
1327         /* If this reloc section does not use the main symbol table we
1328            don't treat it as a reloc section.  BFD can't adequately
1329            represent such a section, so at least for now, we don't
1330            try.  We just present it as a normal section.  */
1331         if (hdr->sh_link != elf_onesymtab (abfd))
1332           return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1333
1334         if (! bfd_section_from_shdr (abfd, hdr->sh_info))
1335           return false;
1336         target_sect = bfd_section_from_elf_index (abfd, hdr->sh_info);
1337         if (target_sect == NULL)
1338           return false;
1339
1340         if ((target_sect->flags & SEC_RELOC) == 0
1341             || target_sect->reloc_count == 0)
1342           hdr2 = &elf_section_data (target_sect)->rel_hdr;
1343         else
1344           {
1345             BFD_ASSERT (elf_section_data (target_sect)->rel_hdr2 == NULL);
1346             hdr2 = (Elf_Internal_Shdr *) bfd_alloc (abfd, sizeof (*hdr2));
1347             elf_section_data (target_sect)->rel_hdr2 = hdr2;
1348           }
1349         *hdr2 = *hdr;
1350         elf_elfsections (abfd)[shindex] = hdr2;
1351         target_sect->reloc_count += hdr->sh_size / hdr->sh_entsize;
1352         target_sect->flags |= SEC_RELOC;
1353         target_sect->relocation = NULL;
1354         target_sect->rel_filepos = hdr->sh_offset;
1355         /* In the section to which the relocations apply, mark whether
1356            its relocations are of the REL or RELA variety.  */
1357         elf_section_data (target_sect)->use_rela_p 
1358           = (hdr->sh_type == SHT_RELA);
1359         abfd->flags |= HAS_RELOC;
1360         return true;
1361       }
1362       break;
1363
1364     case SHT_GNU_verdef:
1365       elf_dynverdef (abfd) = shindex;
1366       elf_tdata (abfd)->dynverdef_hdr = *hdr;
1367       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1368       break;
1369
1370     case SHT_GNU_versym:
1371       elf_dynversym (abfd) = shindex;
1372       elf_tdata (abfd)->dynversym_hdr = *hdr;
1373       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1374       break;
1375
1376     case SHT_GNU_verneed:
1377       elf_dynverref (abfd) = shindex;
1378       elf_tdata (abfd)->dynverref_hdr = *hdr;
1379       return _bfd_elf_make_section_from_shdr (abfd, hdr, name);
1380       break;
1381
1382     case SHT_SHLIB:
1383       return true;
1384
1385     default:
1386       /* Check for any processor-specific section types.  */
1387       {
1388         if (bed->elf_backend_section_from_shdr)
1389           (*bed->elf_backend_section_from_shdr) (abfd, hdr, name);
1390       }
1391       break;
1392     }
1393
1394   return true;
1395 }
1396
1397 /* Given an ELF section number, retrieve the corresponding BFD
1398    section.  */
1399
1400 asection *
1401 bfd_section_from_elf_index (abfd, index)
1402      bfd *abfd;
1403      unsigned int index;
1404 {
1405   BFD_ASSERT (index > 0 && index < SHN_LORESERVE);
1406   if (index >= elf_elfheader (abfd)->e_shnum)
1407     return NULL;
1408   return elf_elfsections (abfd)[index]->bfd_section;
1409 }
1410
1411 boolean
1412 _bfd_elf_new_section_hook (abfd, sec)
1413      bfd *abfd;
1414      asection *sec;
1415 {
1416   struct bfd_elf_section_data *sdata;
1417
1418   sdata = (struct bfd_elf_section_data *) bfd_zalloc (abfd, sizeof (*sdata));
1419   if (!sdata)
1420     return false;
1421   sec->used_by_bfd = (PTR) sdata;
1422
1423   /* Indicate whether or not this section should use RELA relocations.  */
1424   sdata->use_rela_p 
1425     = get_elf_backend_data (abfd)->default_use_rela_p;
1426
1427   return true;
1428 }
1429
1430 /* Create a new bfd section from an ELF program header.
1431
1432    Since program segments have no names, we generate a synthetic name
1433    of the form segment<NUM>, where NUM is generally the index in the
1434    program header table.  For segments that are split (see below) we
1435    generate the names segment<NUM>a and segment<NUM>b.
1436
1437    Note that some program segments may have a file size that is different than
1438    (less than) the memory size.  All this means is that at execution the
1439    system must allocate the amount of memory specified by the memory size,
1440    but only initialize it with the first "file size" bytes read from the
1441    file.  This would occur for example, with program segments consisting
1442    of combined data+bss.
1443
1444    To handle the above situation, this routine generates TWO bfd sections
1445    for the single program segment.  The first has the length specified by
1446    the file size of the segment, and the second has the length specified
1447    by the difference between the two sizes.  In effect, the segment is split
1448    into it's initialized and uninitialized parts.
1449
1450  */
1451
1452 boolean
1453 _bfd_elf_make_section_from_phdr (abfd, hdr, index, typename)
1454      bfd *abfd;
1455      Elf_Internal_Phdr *hdr;
1456      int index;
1457      const char *typename;
1458 {
1459   asection *newsect;
1460   char *name;
1461   char namebuf[64];
1462   int split;
1463
1464   split = ((hdr->p_memsz > 0)
1465             && (hdr->p_filesz > 0)
1466             && (hdr->p_memsz > hdr->p_filesz));
1467   sprintf (namebuf, "%s%d%s", typename, index, split ? "a" : "");
1468   name = bfd_alloc (abfd, strlen (namebuf) + 1);
1469   if (!name)
1470     return false;
1471   strcpy (name, namebuf);
1472   newsect = bfd_make_section (abfd, name);
1473   if (newsect == NULL)
1474     return false;
1475   newsect->vma = hdr->p_vaddr;
1476   newsect->lma = hdr->p_paddr;
1477   newsect->_raw_size = hdr->p_filesz;
1478   newsect->filepos = hdr->p_offset;
1479   newsect->flags |= SEC_HAS_CONTENTS;
1480   if (hdr->p_type == PT_LOAD)
1481     {
1482       newsect->flags |= SEC_ALLOC;
1483       newsect->flags |= SEC_LOAD;
1484       if (hdr->p_flags & PF_X)
1485         {
1486           /* FIXME: all we known is that it has execute PERMISSION,
1487              may be data. */
1488           newsect->flags |= SEC_CODE;
1489         }
1490     }
1491   if (!(hdr->p_flags & PF_W))
1492     {
1493       newsect->flags |= SEC_READONLY;
1494     }
1495
1496   if (split)
1497     {
1498       sprintf (namebuf, "%s%db", typename, index);
1499       name = bfd_alloc (abfd, strlen (namebuf) + 1);
1500       if (!name)
1501         return false;
1502       strcpy (name, namebuf);
1503       newsect = bfd_make_section (abfd, name);
1504       if (newsect == NULL)
1505         return false;
1506       newsect->vma = hdr->p_vaddr + hdr->p_filesz;
1507       newsect->lma = hdr->p_paddr + hdr->p_filesz;
1508       newsect->_raw_size = hdr->p_memsz - hdr->p_filesz;
1509       if (hdr->p_type == PT_LOAD)
1510         {
1511           newsect->flags |= SEC_ALLOC;
1512           if (hdr->p_flags & PF_X)
1513             newsect->flags |= SEC_CODE;
1514         }
1515       if (!(hdr->p_flags & PF_W))
1516         newsect->flags |= SEC_READONLY;
1517     }
1518
1519   return true;
1520 }
1521
1522 boolean
1523 bfd_section_from_phdr (abfd, hdr, index)
1524      bfd *abfd;
1525      Elf_Internal_Phdr *hdr;
1526      int index;
1527 {
1528   struct elf_backend_data *bed;
1529
1530   switch (hdr->p_type)
1531     {
1532     case PT_NULL:
1533       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "null");
1534
1535     case PT_LOAD:
1536       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "load");
1537
1538     case PT_DYNAMIC:
1539       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "dynamic");
1540
1541     case PT_INTERP:
1542       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "interp");
1543
1544     case PT_NOTE:
1545       if (! _bfd_elf_make_section_from_phdr (abfd, hdr, index, "note"))
1546         return false;
1547       if (! elfcore_read_notes (abfd, hdr->p_offset, hdr->p_filesz))
1548         return false;
1549       return true;
1550
1551     case PT_SHLIB:
1552       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "shlib");
1553
1554     case PT_PHDR:
1555       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "phdr");
1556
1557     default:
1558       /* Check for any processor-specific program segment types.
1559          If no handler for them, default to making "segment" sections. */
1560       bed = get_elf_backend_data (abfd);
1561       if (bed->elf_backend_section_from_phdr)
1562         return (*bed->elf_backend_section_from_phdr) (abfd, hdr, index);
1563       else
1564         return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "segment");
1565     }
1566 }
1567
1568 /* Initialize REL_HDR, the section-header for new section, containing
1569    relocations against ASECT.  If USE_RELA_P is true, we use RELA
1570    relocations; otherwise, we use REL relocations.  */
1571
1572 boolean
1573 _bfd_elf_init_reloc_shdr (abfd, rel_hdr, asect, use_rela_p)
1574      bfd *abfd;
1575      Elf_Internal_Shdr *rel_hdr;
1576      asection *asect;
1577      boolean use_rela_p;
1578 {
1579   char *name;
1580   struct elf_backend_data *bed;
1581
1582   bed = get_elf_backend_data (abfd);
1583   name = bfd_alloc (abfd, sizeof ".rela" + strlen (asect->name));
1584   if (name == NULL)
1585     return false;
1586   sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", asect->name);
1587   rel_hdr->sh_name =
1588     (unsigned int) _bfd_stringtab_add (elf_shstrtab (abfd), name,
1589                                        true, false);
1590   if (rel_hdr->sh_name == (unsigned int) -1)
1591     return false;
1592   rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
1593   rel_hdr->sh_entsize = (use_rela_p
1594                          ? bed->s->sizeof_rela
1595                          : bed->s->sizeof_rel);
1596   rel_hdr->sh_addralign = bed->s->file_align;
1597   rel_hdr->sh_flags = 0;
1598   rel_hdr->sh_addr = 0;
1599   rel_hdr->sh_size = 0;
1600   rel_hdr->sh_offset = 0;
1601
1602   return true;
1603 }
1604
1605 /* Set up an ELF internal section header for a section.  */
1606
1607 /*ARGSUSED*/
1608 static void
1609 elf_fake_sections (abfd, asect, failedptrarg)
1610      bfd *abfd;
1611      asection *asect;
1612      PTR failedptrarg;
1613 {
1614   struct elf_backend_data *bed = get_elf_backend_data (abfd);
1615   boolean *failedptr = (boolean *) failedptrarg;
1616   Elf_Internal_Shdr *this_hdr;
1617
1618   if (*failedptr)
1619     {
1620       /* We already failed; just get out of the bfd_map_over_sections
1621          loop.  */
1622       return;
1623     }
1624
1625   this_hdr = &elf_section_data (asect)->this_hdr;
1626
1627   this_hdr->sh_name = (unsigned long) _bfd_stringtab_add (elf_shstrtab (abfd),
1628                                                           asect->name,
1629                                                           true, false);
1630   if (this_hdr->sh_name == (unsigned long) -1)
1631     {
1632       *failedptr = true;
1633       return;
1634     }
1635
1636   this_hdr->sh_flags = 0;
1637
1638   if ((asect->flags & SEC_ALLOC) != 0
1639       || asect->user_set_vma)
1640     this_hdr->sh_addr = asect->vma;
1641   else
1642     this_hdr->sh_addr = 0;
1643
1644   this_hdr->sh_offset = 0;
1645   this_hdr->sh_size = asect->_raw_size;
1646   this_hdr->sh_link = 0;
1647   this_hdr->sh_addralign = 1 << asect->alignment_power;
1648   /* The sh_entsize and sh_info fields may have been set already by
1649      copy_private_section_data.  */
1650
1651   this_hdr->bfd_section = asect;
1652   this_hdr->contents = NULL;
1653
1654   /* FIXME: This should not be based on section names.  */
1655   if (strcmp (asect->name, ".dynstr") == 0)
1656     this_hdr->sh_type = SHT_STRTAB;
1657   else if (strcmp (asect->name, ".hash") == 0)
1658     {
1659       this_hdr->sh_type = SHT_HASH;
1660       this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
1661     }
1662   else if (strcmp (asect->name, ".dynsym") == 0)
1663     {
1664       this_hdr->sh_type = SHT_DYNSYM;
1665       this_hdr->sh_entsize = bed->s->sizeof_sym;
1666     }
1667   else if (strcmp (asect->name, ".dynamic") == 0)
1668     {
1669       this_hdr->sh_type = SHT_DYNAMIC;
1670       this_hdr->sh_entsize = bed->s->sizeof_dyn;
1671     }
1672   else if (strncmp (asect->name, ".rela", 5) == 0
1673            && get_elf_backend_data (abfd)->may_use_rela_p)
1674     {
1675       this_hdr->sh_type = SHT_RELA;
1676       this_hdr->sh_entsize = bed->s->sizeof_rela;
1677     }
1678   else if (strncmp (asect->name, ".rel", 4) == 0
1679            && get_elf_backend_data (abfd)->may_use_rel_p)
1680     {
1681       this_hdr->sh_type = SHT_REL;
1682       this_hdr->sh_entsize = bed->s->sizeof_rel;
1683     }
1684   else if (strncmp (asect->name, ".note", 5) == 0)
1685     this_hdr->sh_type = SHT_NOTE;
1686   else if (strncmp (asect->name, ".stab", 5) == 0
1687            && strcmp (asect->name + strlen (asect->name) - 3, "str") == 0)
1688     this_hdr->sh_type = SHT_STRTAB;
1689   else if (strcmp (asect->name, ".gnu.version") == 0)
1690     {
1691       this_hdr->sh_type = SHT_GNU_versym;
1692       this_hdr->sh_entsize = sizeof (Elf_External_Versym);
1693     }
1694   else if (strcmp (asect->name, ".gnu.version_d") == 0)
1695     {
1696       this_hdr->sh_type = SHT_GNU_verdef;
1697       this_hdr->sh_entsize = 0;
1698       /* objcopy or strip will copy over sh_info, but may not set
1699          cverdefs.  The linker will set cverdefs, but sh_info will be
1700          zero.  */
1701       if (this_hdr->sh_info == 0)
1702         this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
1703       else
1704         BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
1705                     || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
1706     }
1707   else if (strcmp (asect->name, ".gnu.version_r") == 0)
1708     {
1709       this_hdr->sh_type = SHT_GNU_verneed;
1710       this_hdr->sh_entsize = 0;
1711       /* objcopy or strip will copy over sh_info, but may not set
1712          cverrefs.  The linker will set cverrefs, but sh_info will be
1713          zero.  */
1714       if (this_hdr->sh_info == 0)
1715         this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
1716       else
1717         BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
1718                     || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
1719     }
1720   else if ((asect->flags & SEC_ALLOC) != 0
1721            && (asect->flags & SEC_LOAD) != 0)
1722     this_hdr->sh_type = SHT_PROGBITS;
1723   else if ((asect->flags & SEC_ALLOC) != 0
1724            && ((asect->flags & SEC_LOAD) == 0))
1725     this_hdr->sh_type = SHT_NOBITS;
1726   else
1727     {
1728       /* Who knows?  */
1729       this_hdr->sh_type = SHT_PROGBITS;
1730     }
1731
1732   if ((asect->flags & SEC_ALLOC) != 0)
1733     this_hdr->sh_flags |= SHF_ALLOC;
1734   if ((asect->flags & SEC_READONLY) == 0)
1735     this_hdr->sh_flags |= SHF_WRITE;
1736   if ((asect->flags & SEC_CODE) != 0)
1737     this_hdr->sh_flags |= SHF_EXECINSTR;
1738
1739   /* Check for processor-specific section types.  */
1740   if (bed->elf_backend_fake_sections)
1741     (*bed->elf_backend_fake_sections) (abfd, this_hdr, asect);
1742
1743   /* If the section has relocs, set up a section header for the
1744      SHT_REL[A] section.  If two relocation sections are required for
1745      this section, it is up to the processor-specific back-end to
1746      create the other.  */ 
1747   if ((asect->flags & SEC_RELOC) != 0
1748       && !_bfd_elf_init_reloc_shdr (abfd, 
1749                                     &elf_section_data (asect)->rel_hdr,
1750                                     asect, 
1751                                     elf_section_data (asect)->use_rela_p))
1752     *failedptr = true;
1753 }
1754
1755 /* Assign all ELF section numbers.  The dummy first section is handled here
1756    too.  The link/info pointers for the standard section types are filled
1757    in here too, while we're at it.  */
1758
1759 static boolean
1760 assign_section_numbers (abfd)
1761      bfd *abfd;
1762 {
1763   struct elf_obj_tdata *t = elf_tdata (abfd);
1764   asection *sec;
1765   unsigned int section_number;
1766   Elf_Internal_Shdr **i_shdrp;
1767   struct elf_backend_data *bed = get_elf_backend_data (abfd);
1768
1769   section_number = 1;
1770
1771   for (sec = abfd->sections; sec; sec = sec->next)
1772     {
1773       struct bfd_elf_section_data *d = elf_section_data (sec);
1774
1775       d->this_idx = section_number++;
1776       if ((sec->flags & SEC_RELOC) == 0)
1777         d->rel_idx = 0;
1778       else
1779         d->rel_idx = section_number++;
1780
1781       if (d->rel_hdr2)
1782         d->rel_idx2 = section_number++;
1783       else
1784         d->rel_idx2 = 0;
1785     }
1786
1787   t->shstrtab_section = section_number++;
1788   elf_elfheader (abfd)->e_shstrndx = t->shstrtab_section;
1789   t->shstrtab_hdr.sh_size = _bfd_stringtab_size (elf_shstrtab (abfd));
1790
1791   if (bfd_get_symcount (abfd) > 0)
1792     {
1793       t->symtab_section = section_number++;
1794       t->strtab_section = section_number++;
1795     }
1796
1797   elf_elfheader (abfd)->e_shnum = section_number;
1798
1799   /* Set up the list of section header pointers, in agreement with the
1800      indices.  */
1801   i_shdrp = ((Elf_Internal_Shdr **)
1802              bfd_alloc (abfd, section_number * sizeof (Elf_Internal_Shdr *)));
1803   if (i_shdrp == NULL)
1804     return false;
1805
1806   i_shdrp[0] = ((Elf_Internal_Shdr *)
1807                 bfd_alloc (abfd, sizeof (Elf_Internal_Shdr)));
1808   if (i_shdrp[0] == NULL)
1809     {
1810       bfd_release (abfd, i_shdrp);
1811       return false;
1812     }
1813   memset (i_shdrp[0], 0, sizeof (Elf_Internal_Shdr));
1814
1815   elf_elfsections (abfd) = i_shdrp;
1816
1817   i_shdrp[t->shstrtab_section] = &t->shstrtab_hdr;
1818   if (bfd_get_symcount (abfd) > 0)
1819     {
1820       i_shdrp[t->symtab_section] = &t->symtab_hdr;
1821       i_shdrp[t->strtab_section] = &t->strtab_hdr;
1822       t->symtab_hdr.sh_link = t->strtab_section;
1823     }
1824   for (sec = abfd->sections; sec; sec = sec->next)
1825     {
1826       struct bfd_elf_section_data *d = elf_section_data (sec);
1827       asection *s;
1828       const char *name;
1829
1830       i_shdrp[d->this_idx] = &d->this_hdr;
1831       if (d->rel_idx != 0)
1832         i_shdrp[d->rel_idx] = &d->rel_hdr;
1833       if (d->rel_idx2 != 0)
1834         i_shdrp[d->rel_idx2] = d->rel_hdr2;
1835
1836       /* Fill in the sh_link and sh_info fields while we're at it.  */
1837
1838       /* sh_link of a reloc section is the section index of the symbol
1839          table.  sh_info is the section index of the section to which
1840          the relocation entries apply.  */
1841       if (d->rel_idx != 0)
1842         {
1843           d->rel_hdr.sh_link = t->symtab_section;
1844           d->rel_hdr.sh_info = d->this_idx;
1845         }
1846       if (d->rel_idx2 != 0)
1847         {
1848           d->rel_hdr2->sh_link = t->symtab_section;
1849           d->rel_hdr2->sh_info = d->this_idx;
1850         }
1851
1852       switch (d->this_hdr.sh_type)
1853         {
1854         case SHT_REL:
1855         case SHT_RELA:
1856           /* A reloc section which we are treating as a normal BFD
1857              section.  sh_link is the section index of the symbol
1858              table.  sh_info is the section index of the section to
1859              which the relocation entries apply.  We assume that an
1860              allocated reloc section uses the dynamic symbol table.
1861              FIXME: How can we be sure?  */
1862           s = bfd_get_section_by_name (abfd, ".dynsym");
1863           if (s != NULL)
1864             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1865
1866           /* We look up the section the relocs apply to by name.  */
1867           name = sec->name;
1868           if (d->this_hdr.sh_type == SHT_REL)
1869             name += 4;
1870           else
1871             name += 5;
1872           s = bfd_get_section_by_name (abfd, name);
1873           if (s != NULL)
1874             d->this_hdr.sh_info = elf_section_data (s)->this_idx;
1875           break;
1876
1877         case SHT_STRTAB:
1878           /* We assume that a section named .stab*str is a stabs
1879              string section.  We look for a section with the same name
1880              but without the trailing ``str'', and set its sh_link
1881              field to point to this section.  */
1882           if (strncmp (sec->name, ".stab", sizeof ".stab" - 1) == 0
1883               && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
1884             {
1885               size_t len;
1886               char *alc;
1887
1888               len = strlen (sec->name);
1889               alc = (char *) bfd_malloc (len - 2);
1890               if (alc == NULL)
1891                 return false;
1892               strncpy (alc, sec->name, len - 3);
1893               alc[len - 3] = '\0';
1894               s = bfd_get_section_by_name (abfd, alc);
1895               free (alc);
1896               if (s != NULL)
1897                 {
1898                   elf_section_data (s)->this_hdr.sh_link = d->this_idx;
1899
1900                   /* This is a .stab section.  */
1901                   elf_section_data (s)->this_hdr.sh_entsize =
1902                     4 + 2 * (bed->s->arch_size / 8);
1903                 }
1904             }
1905           break;
1906
1907         case SHT_DYNAMIC:
1908         case SHT_DYNSYM:
1909         case SHT_GNU_verneed:
1910         case SHT_GNU_verdef:
1911           /* sh_link is the section header index of the string table
1912              used for the dynamic entries, or the symbol table, or the
1913              version strings.  */
1914           s = bfd_get_section_by_name (abfd, ".dynstr");
1915           if (s != NULL)
1916             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1917           break;
1918
1919         case SHT_HASH:
1920         case SHT_GNU_versym:
1921           /* sh_link is the section header index of the symbol table
1922              this hash table or version table is for.  */
1923           s = bfd_get_section_by_name (abfd, ".dynsym");
1924           if (s != NULL)
1925             d->this_hdr.sh_link = elf_section_data (s)->this_idx;
1926           break;
1927         }
1928     }
1929
1930   return true;
1931 }
1932
1933 /* Map symbol from it's internal number to the external number, moving
1934    all local symbols to be at the head of the list.  */
1935
1936 static INLINE int
1937 sym_is_global (abfd, sym)
1938      bfd *abfd;
1939      asymbol *sym;
1940 {
1941   /* If the backend has a special mapping, use it.  */
1942   if (get_elf_backend_data (abfd)->elf_backend_sym_is_global)
1943     return ((*get_elf_backend_data (abfd)->elf_backend_sym_is_global)
1944             (abfd, sym));
1945
1946   return ((sym->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
1947           || bfd_is_und_section (bfd_get_section (sym))
1948           || bfd_is_com_section (bfd_get_section (sym)));
1949 }
1950
1951 static boolean
1952 elf_map_symbols (abfd)
1953      bfd *abfd;
1954 {
1955   int symcount = bfd_get_symcount (abfd);
1956   asymbol **syms = bfd_get_outsymbols (abfd);
1957   asymbol **sect_syms;
1958   int num_locals = 0;
1959   int num_globals = 0;
1960   int num_locals2 = 0;
1961   int num_globals2 = 0;
1962   int max_index = 0;
1963   int num_sections = 0;
1964   int idx;
1965   asection *asect;
1966   asymbol **new_syms;
1967   asymbol *sym;
1968
1969 #ifdef DEBUG
1970   fprintf (stderr, "elf_map_symbols\n");
1971   fflush (stderr);
1972 #endif
1973
1974   /* Add a section symbol for each BFD section.  FIXME: Is this really
1975      necessary?  */
1976   for (asect = abfd->sections; asect; asect = asect->next)
1977     {
1978       if (max_index < asect->index)
1979         max_index = asect->index;
1980     }
1981
1982   max_index++;
1983   sect_syms = (asymbol **) bfd_zalloc (abfd, max_index * sizeof (asymbol *));
1984   if (sect_syms == NULL)
1985     return false;
1986   elf_section_syms (abfd) = sect_syms;
1987
1988   for (idx = 0; idx < symcount; idx++)
1989     {
1990       sym = syms[idx];
1991       
1992       if ((sym->flags & BSF_SECTION_SYM) != 0
1993           && sym->value == 0)
1994         {
1995           asection *sec;
1996
1997           sec = sym->section;
1998
1999           if (sec->owner != NULL)
2000             {
2001               if (sec->owner != abfd)
2002                 {
2003                   if (sec->output_offset != 0)
2004                     continue;
2005                   
2006                   sec = sec->output_section;
2007
2008                   /* Empty sections in the input files may have had a section
2009                      symbol created for them.  (See the comment near the end of
2010                      _bfd_generic_link_output_symbols in linker.c).  If the linker
2011                      script discards such sections then we will reach this point.
2012                      Since we know that we cannot avoid this case, we detect it
2013                      and skip the abort and the assignment to the sect_syms array.
2014                      To reproduce this particular case try running the linker
2015                      testsuite test ld-scripts/weak.exp for an ELF port that uses
2016                      the generic linker.  */
2017                   if (sec->owner == NULL)
2018                     continue;
2019
2020                   BFD_ASSERT (sec->owner == abfd);
2021                 }
2022               sect_syms[sec->index] = syms[idx];
2023             }
2024         }
2025     }
2026
2027   for (asect = abfd->sections; asect; asect = asect->next)
2028     {
2029       if (sect_syms[asect->index] != NULL)
2030         continue;
2031
2032       sym = bfd_make_empty_symbol (abfd);
2033       if (sym == NULL)
2034         return false;
2035       sym->the_bfd = abfd;
2036       sym->name = asect->name;
2037       sym->value = 0;
2038       /* Set the flags to 0 to indicate that this one was newly added.  */
2039       sym->flags = 0;
2040       sym->section = asect;
2041       sect_syms[asect->index] = sym;
2042       num_sections++;
2043 #ifdef DEBUG
2044       fprintf (stderr,
2045  _("creating section symbol, name = %s, value = 0x%.8lx, index = %d, section = 0x%.8lx\n"),
2046                asect->name, (long) asect->vma, asect->index, (long) asect);
2047 #endif
2048     }
2049
2050   /* Classify all of the symbols.  */
2051   for (idx = 0; idx < symcount; idx++)
2052     {
2053       if (!sym_is_global (abfd, syms[idx]))
2054         num_locals++;
2055       else
2056         num_globals++;
2057     }
2058   for (asect = abfd->sections; asect; asect = asect->next)
2059     {
2060       if (sect_syms[asect->index] != NULL
2061           && sect_syms[asect->index]->flags == 0)
2062         {
2063           sect_syms[asect->index]->flags = BSF_SECTION_SYM;
2064           if (!sym_is_global (abfd, sect_syms[asect->index]))
2065             num_locals++;
2066           else
2067             num_globals++;
2068           sect_syms[asect->index]->flags = 0;
2069         }
2070     }
2071
2072   /* Now sort the symbols so the local symbols are first.  */
2073   new_syms = ((asymbol **)
2074               bfd_alloc (abfd,
2075                          (num_locals + num_globals) * sizeof (asymbol *)));
2076   if (new_syms == NULL)
2077     return false;
2078
2079   for (idx = 0; idx < symcount; idx++)
2080     {
2081       asymbol *sym = syms[idx];
2082       int i;
2083
2084       if (!sym_is_global (abfd, sym))
2085         i = num_locals2++;
2086       else
2087         i = num_locals + num_globals2++;
2088       new_syms[i] = sym;
2089       sym->udata.i = i + 1;
2090     }
2091   for (asect = abfd->sections; asect; asect = asect->next)
2092     {
2093       if (sect_syms[asect->index] != NULL
2094           && sect_syms[asect->index]->flags == 0)
2095         {
2096           asymbol *sym = sect_syms[asect->index];
2097           int i;
2098
2099           sym->flags = BSF_SECTION_SYM;
2100           if (!sym_is_global (abfd, sym))
2101             i = num_locals2++;
2102           else
2103             i = num_locals + num_globals2++;
2104           new_syms[i] = sym;
2105           sym->udata.i = i + 1;
2106         }
2107     }
2108
2109   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
2110
2111   elf_num_locals (abfd) = num_locals;
2112   elf_num_globals (abfd) = num_globals;
2113   return true;
2114 }
2115
2116 /* Align to the maximum file alignment that could be required for any
2117    ELF data structure.  */
2118
2119 static INLINE file_ptr align_file_position PARAMS ((file_ptr, int));
2120 static INLINE file_ptr
2121 align_file_position (off, align)
2122      file_ptr off;
2123      int align;
2124 {
2125   return (off + align - 1) & ~(align - 1);
2126 }
2127
2128 /* Assign a file position to a section, optionally aligning to the
2129    required section alignment.  */
2130
2131 INLINE file_ptr
2132 _bfd_elf_assign_file_position_for_section (i_shdrp, offset, align)
2133      Elf_Internal_Shdr *i_shdrp;
2134      file_ptr offset;
2135      boolean align;
2136 {
2137   if (align)
2138     {
2139       unsigned int al;
2140
2141       al = i_shdrp->sh_addralign;
2142       if (al > 1)
2143         offset = BFD_ALIGN (offset, al);
2144     }
2145   i_shdrp->sh_offset = offset;
2146   if (i_shdrp->bfd_section != NULL)
2147     i_shdrp->bfd_section->filepos = offset;
2148   if (i_shdrp->sh_type != SHT_NOBITS)
2149     offset += i_shdrp->sh_size;
2150   return offset;
2151 }
2152
2153 /* Compute the file positions we are going to put the sections at, and
2154    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
2155    is not NULL, this is being called by the ELF backend linker.  */
2156
2157 boolean
2158 _bfd_elf_compute_section_file_positions (abfd, link_info)
2159      bfd *abfd;
2160      struct bfd_link_info *link_info;
2161 {
2162   struct elf_backend_data *bed = get_elf_backend_data (abfd);
2163   boolean failed;
2164   struct bfd_strtab_hash *strtab;
2165   Elf_Internal_Shdr *shstrtab_hdr;
2166
2167   if (abfd->output_has_begun)
2168     return true;
2169
2170   /* Do any elf backend specific processing first.  */
2171   if (bed->elf_backend_begin_write_processing)
2172     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
2173
2174   if (! prep_headers (abfd))
2175     return false;
2176
2177   /* Post process the headers if necessary.  */
2178   if (bed->elf_backend_post_process_headers)
2179     (*bed->elf_backend_post_process_headers) (abfd, link_info);
2180
2181   failed = false;
2182   bfd_map_over_sections (abfd, elf_fake_sections, &failed);
2183   if (failed)
2184     return false;
2185
2186   if (!assign_section_numbers (abfd))
2187     return false;
2188
2189   /* The backend linker builds symbol table information itself.  */
2190   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
2191     {
2192       /* Non-zero if doing a relocatable link.  */
2193       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
2194
2195       if (! swap_out_syms (abfd, &strtab, relocatable_p))
2196         return false;
2197     }
2198
2199   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
2200   /* sh_name was set in prep_headers.  */
2201   shstrtab_hdr->sh_type = SHT_STRTAB;
2202   shstrtab_hdr->sh_flags = 0;
2203   shstrtab_hdr->sh_addr = 0;
2204   shstrtab_hdr->sh_size = _bfd_stringtab_size (elf_shstrtab (abfd));
2205   shstrtab_hdr->sh_entsize = 0;
2206   shstrtab_hdr->sh_link = 0;
2207   shstrtab_hdr->sh_info = 0;
2208   /* sh_offset is set in assign_file_positions_except_relocs.  */
2209   shstrtab_hdr->sh_addralign = 1;
2210
2211   if (!assign_file_positions_except_relocs (abfd))
2212     return false;
2213
2214   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
2215     {
2216       file_ptr off;
2217       Elf_Internal_Shdr *hdr;
2218
2219       off = elf_tdata (abfd)->next_file_pos;
2220
2221       hdr = &elf_tdata (abfd)->symtab_hdr;
2222       off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
2223
2224       hdr = &elf_tdata (abfd)->strtab_hdr;
2225       off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
2226
2227       elf_tdata (abfd)->next_file_pos = off;
2228
2229       /* Now that we know where the .strtab section goes, write it
2230          out.  */
2231       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
2232           || ! _bfd_stringtab_emit (abfd, strtab))
2233         return false;
2234       _bfd_stringtab_free (strtab);
2235     }
2236
2237   abfd->output_has_begun = true;
2238
2239   return true;
2240 }
2241
2242 /* Create a mapping from a set of sections to a program segment.  */
2243
2244 static INLINE struct elf_segment_map *
2245 make_mapping (abfd, sections, from, to, phdr)
2246      bfd *abfd;
2247      asection **sections;
2248      unsigned int from;
2249      unsigned int to;
2250      boolean phdr;
2251 {
2252   struct elf_segment_map *m;
2253   unsigned int i;
2254   asection **hdrpp;
2255
2256   m = ((struct elf_segment_map *)
2257        bfd_zalloc (abfd,
2258                    (sizeof (struct elf_segment_map)
2259                     + (to - from - 1) * sizeof (asection *))));
2260   if (m == NULL)
2261     return NULL;
2262   m->next = NULL;
2263   m->p_type = PT_LOAD;
2264   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
2265     m->sections[i - from] = *hdrpp;
2266   m->count = to - from;
2267
2268   if (from == 0 && phdr)
2269     {
2270       /* Include the headers in the first PT_LOAD segment.  */
2271       m->includes_filehdr = 1;
2272       m->includes_phdrs = 1;
2273     }
2274
2275   return m;
2276 }
2277
2278 /* Set up a mapping from BFD sections to program segments.  */
2279
2280 static boolean
2281 map_sections_to_segments (abfd)
2282      bfd *abfd;
2283 {
2284   asection **sections = NULL;
2285   asection *s;
2286   unsigned int i;
2287   unsigned int count;
2288   struct elf_segment_map *mfirst;
2289   struct elf_segment_map **pm;
2290   struct elf_segment_map *m;
2291   asection *last_hdr;
2292   unsigned int phdr_index;
2293   bfd_vma maxpagesize;
2294   asection **hdrpp;
2295   boolean phdr_in_segment = true;
2296   boolean writable;
2297   asection *dynsec;
2298
2299   if (elf_tdata (abfd)->segment_map != NULL)
2300     return true;
2301
2302   if (bfd_count_sections (abfd) == 0)
2303     return true;
2304
2305   /* Select the allocated sections, and sort them.  */
2306
2307   sections = (asection **) bfd_malloc (bfd_count_sections (abfd)
2308                                        * sizeof (asection *));
2309   if (sections == NULL)
2310     goto error_return;
2311
2312   i = 0;
2313   for (s = abfd->sections; s != NULL; s = s->next)
2314     {
2315       if ((s->flags & SEC_ALLOC) != 0)
2316         {
2317           sections[i] = s;
2318           ++i;
2319         }
2320     }
2321   BFD_ASSERT (i <= bfd_count_sections (abfd));
2322   count = i;
2323
2324   qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
2325
2326   /* Build the mapping.  */
2327
2328   mfirst = NULL;
2329   pm = &mfirst;
2330
2331   /* If we have a .interp section, then create a PT_PHDR segment for
2332      the program headers and a PT_INTERP segment for the .interp
2333      section.  */
2334   s = bfd_get_section_by_name (abfd, ".interp");
2335   if (s != NULL && (s->flags & SEC_LOAD) != 0)
2336     {
2337       m = ((struct elf_segment_map *)
2338            bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2339       if (m == NULL)
2340         goto error_return;
2341       m->next = NULL;
2342       m->p_type = PT_PHDR;
2343       /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
2344       m->p_flags = PF_R | PF_X;
2345       m->p_flags_valid = 1;
2346       m->includes_phdrs = 1;
2347
2348       *pm = m;
2349       pm = &m->next;
2350
2351       m = ((struct elf_segment_map *)
2352            bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2353       if (m == NULL)
2354         goto error_return;
2355       m->next = NULL;
2356       m->p_type = PT_INTERP;
2357       m->count = 1;
2358       m->sections[0] = s;
2359
2360       *pm = m;
2361       pm = &m->next;
2362     }
2363
2364   /* Look through the sections.  We put sections in the same program
2365      segment when the start of the second section can be placed within
2366      a few bytes of the end of the first section.  */
2367   last_hdr = NULL;
2368   phdr_index = 0;
2369   maxpagesize = get_elf_backend_data (abfd)->maxpagesize;
2370   writable = false;
2371   dynsec = bfd_get_section_by_name (abfd, ".dynamic");
2372   if (dynsec != NULL
2373       && (dynsec->flags & SEC_LOAD) == 0)
2374     dynsec = NULL;
2375
2376   /* Deal with -Ttext or something similar such that the first section
2377      is not adjacent to the program headers.  This is an
2378      approximation, since at this point we don't know exactly how many
2379      program headers we will need.  */
2380   if (count > 0)
2381     {
2382       bfd_size_type phdr_size;
2383
2384       phdr_size = elf_tdata (abfd)->program_header_size;
2385       if (phdr_size == 0)
2386         phdr_size = get_elf_backend_data (abfd)->s->sizeof_phdr;
2387       if ((abfd->flags & D_PAGED) == 0
2388           || sections[0]->lma < phdr_size
2389           || sections[0]->lma % maxpagesize < phdr_size % maxpagesize)
2390         phdr_in_segment = false;
2391     }
2392
2393   for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
2394     {
2395       asection *hdr;
2396       boolean new_segment;
2397
2398       hdr = *hdrpp;
2399
2400       /* See if this section and the last one will fit in the same
2401          segment.  */
2402
2403       if (last_hdr == NULL)
2404         {
2405           /* If we don't have a segment yet, then we don't need a new
2406              one (we build the last one after this loop).  */
2407           new_segment = false;
2408         }
2409       else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
2410         {
2411           /* If this section has a different relation between the
2412              virtual address and the load address, then we need a new
2413              segment.  */
2414           new_segment = true;
2415         }
2416       else if (BFD_ALIGN (last_hdr->lma + last_hdr->_raw_size, maxpagesize)
2417                < BFD_ALIGN (hdr->lma, maxpagesize))
2418         {
2419           /* If putting this section in this segment would force us to
2420              skip a page in the segment, then we need a new segment.  */
2421           new_segment = true;
2422         }
2423       else if ((last_hdr->flags & SEC_LOAD) == 0
2424                && (hdr->flags & SEC_LOAD) != 0)
2425         {
2426           /* We don't want to put a loadable section after a
2427              nonloadable section in the same segment.  */
2428           new_segment = true;
2429         }
2430       else if ((abfd->flags & D_PAGED) == 0)
2431         {
2432           /* If the file is not demand paged, which means that we
2433              don't require the sections to be correctly aligned in the
2434              file, then there is no other reason for a new segment.  */
2435           new_segment = false;
2436         }
2437       else if (! writable
2438                && (hdr->flags & SEC_READONLY) == 0
2439                && (BFD_ALIGN (last_hdr->lma + last_hdr->_raw_size, maxpagesize)
2440                    == hdr->lma))
2441         {
2442           /* We don't want to put a writable section in a read only
2443              segment, unless they are on the same page in memory
2444              anyhow.  We already know that the last section does not
2445              bring us past the current section on the page, so the
2446              only case in which the new section is not on the same
2447              page as the previous section is when the previous section
2448              ends precisely on a page boundary.  */
2449           new_segment = true;
2450         }
2451       else
2452         {
2453           /* Otherwise, we can use the same segment.  */
2454           new_segment = false;
2455         }
2456
2457       if (! new_segment)
2458         {
2459           if ((hdr->flags & SEC_READONLY) == 0)
2460             writable = true;
2461           last_hdr = hdr;
2462           continue;
2463         }
2464
2465       /* We need a new program segment.  We must create a new program
2466          header holding all the sections from phdr_index until hdr.  */
2467
2468       m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
2469       if (m == NULL)
2470         goto error_return;
2471
2472       *pm = m;
2473       pm = &m->next;
2474
2475       if ((hdr->flags & SEC_READONLY) == 0)
2476         writable = true;
2477       else
2478         writable = false;
2479
2480       last_hdr = hdr;
2481       phdr_index = i;
2482       phdr_in_segment = false;
2483     }
2484
2485   /* Create a final PT_LOAD program segment.  */
2486   if (last_hdr != NULL)
2487     {
2488       m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
2489       if (m == NULL)
2490         goto error_return;
2491
2492       *pm = m;
2493       pm = &m->next;
2494     }
2495
2496   /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
2497   if (dynsec != NULL)
2498     {
2499       m = ((struct elf_segment_map *)
2500            bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2501       if (m == NULL)
2502         goto error_return;
2503       m->next = NULL;
2504       m->p_type = PT_DYNAMIC;
2505       m->count = 1;
2506       m->sections[0] = dynsec;
2507
2508       *pm = m;
2509       pm = &m->next;
2510     }
2511
2512   /* For each loadable .note section, add a PT_NOTE segment.  We don't
2513      use bfd_get_section_by_name, because if we link together
2514      nonloadable .note sections and loadable .note sections, we will
2515      generate two .note sections in the output file.  FIXME: Using
2516      names for section types is bogus anyhow.  */
2517   for (s = abfd->sections; s != NULL; s = s->next)
2518     {
2519       if ((s->flags & SEC_LOAD) != 0
2520           && strncmp (s->name, ".note", 5) == 0)
2521         {
2522           m = ((struct elf_segment_map *)
2523                bfd_zalloc (abfd, sizeof (struct elf_segment_map)));
2524           if (m == NULL)
2525             goto error_return;
2526           m->next = NULL;
2527           m->p_type = PT_NOTE;
2528           m->count = 1;
2529           m->sections[0] = s;
2530
2531           *pm = m;
2532           pm = &m->next;
2533         }
2534     }
2535
2536   free (sections);
2537   sections = NULL;
2538
2539   elf_tdata (abfd)->segment_map = mfirst;
2540   return true;
2541
2542  error_return:
2543   if (sections != NULL)
2544     free (sections);
2545   return false;
2546 }
2547
2548 /* Sort sections by address.  */
2549
2550 static int
2551 elf_sort_sections (arg1, arg2)
2552      const PTR arg1;
2553      const PTR arg2;
2554 {
2555   const asection *sec1 = *(const asection **) arg1;
2556   const asection *sec2 = *(const asection **) arg2;
2557
2558   /* Sort by LMA first, since this is the address used to
2559      place the section into a segment.  */
2560   if (sec1->lma < sec2->lma)
2561     return -1;
2562   else if (sec1->lma > sec2->lma)
2563     return 1;
2564
2565   /* Then sort by VMA.  Normally the LMA and the VMA will be
2566      the same, and this will do nothing.  */
2567   if (sec1->vma < sec2->vma)
2568     return -1;
2569   else if (sec1->vma > sec2->vma)
2570     return 1;
2571
2572   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
2573
2574 #define TOEND(x) (((x)->flags & SEC_LOAD) == 0)
2575
2576   if (TOEND (sec1))
2577     {
2578       if (TOEND (sec2))
2579         return sec1->target_index - sec2->target_index;
2580       else
2581         return 1;
2582     }
2583
2584   if (TOEND (sec2))
2585     return -1;
2586
2587 #undef TOEND
2588
2589   /* Sort by size, to put zero sized sections before others at the
2590      same address.  */
2591
2592   if (sec1->_raw_size < sec2->_raw_size)
2593     return -1;
2594   if (sec1->_raw_size > sec2->_raw_size)
2595     return 1;
2596
2597   return sec1->target_index - sec2->target_index;
2598 }
2599
2600 /* Assign file positions to the sections based on the mapping from
2601    sections to segments.  This function also sets up some fields in
2602    the file header, and writes out the program headers.  */
2603
2604 static boolean
2605 assign_file_positions_for_segments (abfd)
2606      bfd *abfd;
2607 {
2608   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2609   unsigned int count;
2610   struct elf_segment_map *m;
2611   unsigned int alloc;
2612   Elf_Internal_Phdr *phdrs;
2613   file_ptr off, voff;
2614   bfd_vma filehdr_vaddr, filehdr_paddr;
2615   bfd_vma phdrs_vaddr, phdrs_paddr;
2616   Elf_Internal_Phdr *p;
2617
2618   if (elf_tdata (abfd)->segment_map == NULL)
2619     {
2620       if (! map_sections_to_segments (abfd))
2621         return false;
2622     }
2623
2624   if (bed->elf_backend_modify_segment_map)
2625     {
2626       if (! (*bed->elf_backend_modify_segment_map) (abfd))
2627         return false;
2628     }
2629
2630   count = 0;
2631   for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
2632     ++count;
2633
2634   elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
2635   elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
2636   elf_elfheader (abfd)->e_phnum = count;
2637
2638   if (count == 0)
2639     return true;
2640
2641   /* If we already counted the number of program segments, make sure
2642      that we allocated enough space.  This happens when SIZEOF_HEADERS
2643      is used in a linker script.  */
2644   alloc = elf_tdata (abfd)->program_header_size / bed->s->sizeof_phdr;
2645   if (alloc != 0 && count > alloc)
2646     {
2647       ((*_bfd_error_handler)
2648        (_("%s: Not enough room for program headers (allocated %u, need %u)"),
2649         bfd_get_filename (abfd), alloc, count));
2650       bfd_set_error (bfd_error_bad_value);
2651       return false;
2652     }
2653
2654   if (alloc == 0)
2655     alloc = count;
2656
2657   phdrs = ((Elf_Internal_Phdr *)
2658            bfd_alloc (abfd, alloc * sizeof (Elf_Internal_Phdr)));
2659   if (phdrs == NULL)
2660     return false;
2661
2662   off = bed->s->sizeof_ehdr;
2663   off += alloc * bed->s->sizeof_phdr;
2664
2665   filehdr_vaddr = 0;
2666   filehdr_paddr = 0;
2667   phdrs_vaddr = 0;
2668   phdrs_paddr = 0;
2669
2670   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
2671        m != NULL;
2672        m = m->next, p++)
2673     {
2674       unsigned int i;
2675       asection **secpp;
2676
2677       /* If elf_segment_map is not from map_sections_to_segments, the
2678          sections may not be correctly ordered.  */
2679       if (m->count > 0)
2680         qsort (m->sections, (size_t) m->count, sizeof (asection *),
2681                elf_sort_sections);
2682
2683       p->p_type = m->p_type;
2684       p->p_flags = m->p_flags;
2685
2686       if (p->p_type == PT_LOAD
2687           && m->count > 0
2688           && (m->sections[0]->flags & SEC_ALLOC) != 0)
2689         {
2690           if ((abfd->flags & D_PAGED) != 0)
2691             off += (m->sections[0]->vma - off) % bed->maxpagesize;
2692           else
2693             {
2694               bfd_size_type align;
2695
2696               align = 0;
2697               for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
2698                 {
2699                   bfd_size_type secalign;
2700
2701                   secalign = bfd_get_section_alignment (abfd, *secpp);
2702                   if (secalign > align)
2703                     align = secalign;
2704                 }
2705
2706               off += (m->sections[0]->vma - off) % (1 << align);
2707             }
2708         }
2709
2710       if (m->count == 0)
2711         p->p_vaddr = 0;
2712       else
2713         p->p_vaddr = m->sections[0]->vma;
2714
2715       if (m->p_paddr_valid)
2716         p->p_paddr = m->p_paddr;
2717       else if (m->count == 0)
2718         p->p_paddr = 0;
2719       else
2720         p->p_paddr = m->sections[0]->lma;
2721
2722       if (p->p_type == PT_LOAD
2723           && (abfd->flags & D_PAGED) != 0)
2724         p->p_align = bed->maxpagesize;
2725       else if (m->count == 0)
2726         p->p_align = bed->s->file_align;
2727       else
2728         p->p_align = 0;
2729
2730       p->p_offset = 0;
2731       p->p_filesz = 0;
2732       p->p_memsz = 0;
2733
2734       if (m->includes_filehdr)
2735         {
2736           if (! m->p_flags_valid)
2737             p->p_flags |= PF_R;
2738           p->p_offset = 0;
2739           p->p_filesz = bed->s->sizeof_ehdr;
2740           p->p_memsz = bed->s->sizeof_ehdr;
2741           if (m->count > 0)
2742             {
2743               BFD_ASSERT (p->p_type == PT_LOAD);
2744
2745               if (p->p_vaddr < (bfd_vma) off)
2746                 {
2747                   _bfd_error_handler (_("%s: Not enough room for program headers, try linking with -N"),
2748                                       bfd_get_filename (abfd));
2749                   bfd_set_error (bfd_error_bad_value);
2750                   return false;
2751                 }
2752
2753               p->p_vaddr -= off;
2754               if (! m->p_paddr_valid)
2755                 p->p_paddr -= off;
2756             }
2757           if (p->p_type == PT_LOAD)
2758             {
2759               filehdr_vaddr = p->p_vaddr;
2760               filehdr_paddr = p->p_paddr;
2761             }
2762         }
2763
2764       if (m->includes_phdrs)
2765         {
2766           if (! m->p_flags_valid)
2767             p->p_flags |= PF_R;
2768
2769           if (m->includes_filehdr)
2770             {
2771               if (p->p_type == PT_LOAD)
2772                 {
2773                   phdrs_vaddr = p->p_vaddr + bed->s->sizeof_ehdr;
2774                   phdrs_paddr = p->p_paddr + bed->s->sizeof_ehdr;
2775                 }
2776             }
2777           else
2778             {
2779               p->p_offset = bed->s->sizeof_ehdr;
2780
2781               if (m->count > 0)
2782                 {
2783                   BFD_ASSERT (p->p_type == PT_LOAD);
2784                   p->p_vaddr -= off - p->p_offset;
2785                   if (! m->p_paddr_valid)
2786                     p->p_paddr -= off - p->p_offset;
2787                 }
2788
2789               if (p->p_type == PT_LOAD)
2790                 {
2791                   phdrs_vaddr = p->p_vaddr;
2792                   phdrs_paddr = p->p_paddr;
2793                 }
2794               else
2795                 phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
2796             }
2797
2798           p->p_filesz += alloc * bed->s->sizeof_phdr;
2799           p->p_memsz += alloc * bed->s->sizeof_phdr;
2800         }
2801
2802       if (p->p_type == PT_LOAD
2803           || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
2804         {
2805           if (! m->includes_filehdr && ! m->includes_phdrs)
2806             p->p_offset = off;
2807           else
2808             {
2809               file_ptr adjust;
2810
2811               adjust = off - (p->p_offset + p->p_filesz);
2812               p->p_filesz += adjust;
2813               p->p_memsz += adjust;
2814             }
2815         }
2816
2817       voff = off;
2818
2819       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
2820         {
2821           asection *sec;
2822           flagword flags;
2823           bfd_size_type align;
2824
2825           sec = *secpp;
2826           flags = sec->flags;
2827           align = 1 << bfd_get_section_alignment (abfd, sec);
2828
2829           /* The section may have artificial alignment forced by a
2830              link script.  Notice this case by the gap between the
2831              cumulative phdr vma and the section's vma.  */
2832           if (p->p_vaddr + p->p_memsz < sec->vma)
2833             {
2834               bfd_vma adjust = sec->vma - (p->p_vaddr + p->p_memsz);
2835
2836               p->p_memsz += adjust;
2837               off += adjust;
2838               voff += adjust;
2839               if ((flags & SEC_LOAD) != 0)
2840                 p->p_filesz += adjust;
2841             }
2842
2843           if (p->p_type == PT_LOAD)
2844             {
2845               bfd_signed_vma adjust;
2846
2847               if ((flags & SEC_LOAD) != 0)
2848                 {
2849                   adjust = sec->lma - (p->p_paddr + p->p_memsz);
2850                   if (adjust < 0)
2851                     adjust = 0;
2852                 }
2853               else if ((flags & SEC_ALLOC) != 0)
2854                 {
2855                   /* The section VMA must equal the file position
2856                      modulo the page size.  FIXME: I'm not sure if
2857                      this adjustment is really necessary.  We used to
2858                      not have the SEC_LOAD case just above, and then
2859                      this was necessary, but now I'm not sure.  */
2860                   if ((abfd->flags & D_PAGED) != 0)
2861                     adjust = (sec->vma - voff) % bed->maxpagesize;
2862                   else
2863                     adjust = (sec->vma - voff) % align;
2864                 }
2865               else
2866                 adjust = 0;
2867
2868               if (adjust != 0)
2869                 {
2870                   if (i == 0)
2871                     {
2872                       (* _bfd_error_handler)
2873                         (_("Error: First section in segment (%s) starts at 0x%x"),
2874                          bfd_section_name (abfd, sec), sec->lma);
2875                       (* _bfd_error_handler)
2876                         (_("       whereas segment starts at 0x%x"),
2877                          p->p_paddr);
2878
2879                       return false;
2880                     }
2881                   p->p_memsz += adjust;
2882                   off += adjust;
2883                   voff += adjust;
2884                   if ((flags & SEC_LOAD) != 0)
2885                     p->p_filesz += adjust;
2886                 }
2887
2888               sec->filepos = off;
2889
2890               /* We check SEC_HAS_CONTENTS here because if NOLOAD is
2891                  used in a linker script we may have a section with
2892                  SEC_LOAD clear but which is supposed to have
2893                  contents.  */
2894               if ((flags & SEC_LOAD) != 0
2895                   || (flags & SEC_HAS_CONTENTS) != 0)
2896                 off += sec->_raw_size;
2897
2898               if ((flags & SEC_ALLOC) != 0)
2899                 voff += sec->_raw_size;
2900             }
2901
2902           if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
2903             {
2904               if (i == 0)       /* the actual "note" segment */
2905                 {               /* this one actually contains everything. */
2906                   sec->filepos = off;
2907                   p->p_filesz = sec->_raw_size;
2908                   off += sec->_raw_size;
2909                   voff = off;
2910                 }
2911               else      /* fake sections -- don't need to be written */
2912                 {
2913                   sec->filepos = 0;
2914                   sec->_raw_size = 0;
2915                   flags = sec->flags = 0;       /* no contents */
2916                 }
2917               p->p_memsz = 0;
2918               p->p_align = 1;
2919             }
2920           else
2921             {
2922               p->p_memsz += sec->_raw_size;
2923
2924               if ((flags & SEC_LOAD) != 0)
2925                 p->p_filesz += sec->_raw_size;
2926
2927               if (align > p->p_align
2928                   && (p->p_type != PT_LOAD || (abfd->flags & D_PAGED) == 0))
2929                 p->p_align = align;
2930             }
2931
2932           if (! m->p_flags_valid)
2933             {
2934               p->p_flags |= PF_R;
2935               if ((flags & SEC_CODE) != 0)
2936                 p->p_flags |= PF_X;
2937               if ((flags & SEC_READONLY) == 0)
2938                 p->p_flags |= PF_W;
2939             }
2940         }
2941     }
2942
2943   /* Now that we have set the section file positions, we can set up
2944      the file positions for the non PT_LOAD segments.  */
2945   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
2946        m != NULL;
2947        m = m->next, p++)
2948     {
2949       if (p->p_type != PT_LOAD && m->count > 0)
2950         {
2951           BFD_ASSERT (! m->includes_filehdr && ! m->includes_phdrs);
2952           p->p_offset = m->sections[0]->filepos;
2953         }
2954       if (m->count == 0)
2955         {
2956           if (m->includes_filehdr)
2957             {
2958               p->p_vaddr = filehdr_vaddr;
2959               if (! m->p_paddr_valid)
2960                 p->p_paddr = filehdr_paddr;
2961             }
2962           else if (m->includes_phdrs)
2963             {
2964               p->p_vaddr = phdrs_vaddr;
2965               if (! m->p_paddr_valid)
2966                 p->p_paddr = phdrs_paddr;
2967             }
2968         }
2969     }
2970
2971   /* Clear out any program headers we allocated but did not use.  */
2972   for (; count < alloc; count++, p++)
2973     {
2974       memset (p, 0, sizeof *p);
2975       p->p_type = PT_NULL;
2976     }
2977
2978   elf_tdata (abfd)->phdr = phdrs;
2979
2980   elf_tdata (abfd)->next_file_pos = off;
2981
2982   /* Write out the program headers.  */
2983   if (bfd_seek (abfd, bed->s->sizeof_ehdr, SEEK_SET) != 0
2984       || bed->s->write_out_phdrs (abfd, phdrs, alloc) != 0)
2985     return false;
2986
2987   return true;
2988 }
2989
2990 /* Get the size of the program header.
2991
2992    If this is called by the linker before any of the section VMA's are set, it
2993    can't calculate the correct value for a strange memory layout.  This only
2994    happens when SIZEOF_HEADERS is used in a linker script.  In this case,
2995    SORTED_HDRS is NULL and we assume the normal scenario of one text and one
2996    data segment (exclusive of .interp and .dynamic).
2997
2998    ??? User written scripts must either not use SIZEOF_HEADERS, or assume there
2999    will be two segments.  */
3000
3001 static bfd_size_type
3002 get_program_header_size (abfd)
3003      bfd *abfd;
3004 {
3005   size_t segs;
3006   asection *s;
3007   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3008
3009   /* We can't return a different result each time we're called.  */
3010   if (elf_tdata (abfd)->program_header_size != 0)
3011     return elf_tdata (abfd)->program_header_size;
3012
3013   if (elf_tdata (abfd)->segment_map != NULL)
3014     {
3015       struct elf_segment_map *m;
3016
3017       segs = 0;
3018       for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
3019         ++segs;
3020       elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
3021       return elf_tdata (abfd)->program_header_size;
3022     }
3023
3024   /* Assume we will need exactly two PT_LOAD segments: one for text
3025      and one for data.  */
3026   segs = 2;
3027
3028   s = bfd_get_section_by_name (abfd, ".interp");
3029   if (s != NULL && (s->flags & SEC_LOAD) != 0)
3030     {
3031       /* If we have a loadable interpreter section, we need a
3032          PT_INTERP segment.  In this case, assume we also need a
3033          PT_PHDR segment, although that may not be true for all
3034          targets.  */
3035       segs += 2;
3036     }
3037
3038   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
3039     {
3040       /* We need a PT_DYNAMIC segment.  */
3041       ++segs;
3042     }
3043
3044   for (s = abfd->sections; s != NULL; s = s->next)
3045     {
3046       if ((s->flags & SEC_LOAD) != 0
3047           && strncmp (s->name, ".note", 5) == 0)
3048         {
3049           /* We need a PT_NOTE segment.  */
3050           ++segs;
3051         }
3052     }
3053
3054   /* Let the backend count up any program headers it might need.  */
3055   if (bed->elf_backend_additional_program_headers)
3056     {
3057       int a;
3058
3059       a = (*bed->elf_backend_additional_program_headers) (abfd);
3060       if (a == -1)
3061         abort ();
3062       segs += a;
3063     }
3064
3065   elf_tdata (abfd)->program_header_size = segs * bed->s->sizeof_phdr;
3066   return elf_tdata (abfd)->program_header_size;
3067 }
3068
3069 /* Work out the file positions of all the sections.  This is called by
3070    _bfd_elf_compute_section_file_positions.  All the section sizes and
3071    VMAs must be known before this is called.
3072
3073    We do not consider reloc sections at this point, unless they form
3074    part of the loadable image.  Reloc sections are assigned file
3075    positions in assign_file_positions_for_relocs, which is called by
3076    write_object_contents and final_link.
3077
3078    We also don't set the positions of the .symtab and .strtab here.  */
3079
3080 static boolean
3081 assign_file_positions_except_relocs (abfd)
3082      bfd *abfd;
3083 {
3084   struct elf_obj_tdata * const tdata = elf_tdata (abfd);
3085   Elf_Internal_Ehdr * const i_ehdrp = elf_elfheader (abfd);
3086   Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
3087   file_ptr off;
3088   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3089
3090   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
3091       && bfd_get_format (abfd) != bfd_core)
3092     {
3093       Elf_Internal_Shdr **hdrpp;
3094       unsigned int i;
3095
3096       /* Start after the ELF header.  */
3097       off = i_ehdrp->e_ehsize;
3098
3099       /* We are not creating an executable, which means that we are
3100          not creating a program header, and that the actual order of
3101          the sections in the file is unimportant.  */
3102       for (i = 1, hdrpp = i_shdrpp + 1; i < i_ehdrp->e_shnum; i++, hdrpp++)
3103         {
3104           Elf_Internal_Shdr *hdr;
3105
3106           hdr = *hdrpp;
3107           if (hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
3108             {
3109               hdr->sh_offset = -1;
3110               continue;
3111             }
3112           if (i == tdata->symtab_section
3113               || i == tdata->strtab_section)
3114             {
3115               hdr->sh_offset = -1;
3116               continue;
3117             }
3118
3119           off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3120         }
3121     }
3122   else
3123     {
3124       unsigned int i;
3125       Elf_Internal_Shdr **hdrpp;
3126
3127       /* Assign file positions for the loaded sections based on the
3128          assignment of sections to segments.  */
3129       if (! assign_file_positions_for_segments (abfd))
3130         return false;
3131
3132       /* Assign file positions for the other sections.  */
3133
3134       off = elf_tdata (abfd)->next_file_pos;
3135       for (i = 1, hdrpp = i_shdrpp + 1; i < i_ehdrp->e_shnum; i++, hdrpp++)
3136         {
3137           Elf_Internal_Shdr *hdr;
3138
3139           hdr = *hdrpp;
3140           if (hdr->bfd_section != NULL
3141               && hdr->bfd_section->filepos != 0)
3142             hdr->sh_offset = hdr->bfd_section->filepos;
3143           else if ((hdr->sh_flags & SHF_ALLOC) != 0)
3144             {
3145               ((*_bfd_error_handler)
3146                (_("%s: warning: allocated section `%s' not in segment"),
3147                 bfd_get_filename (abfd),
3148                 (hdr->bfd_section == NULL
3149                  ? "*unknown*"
3150                  : hdr->bfd_section->name)));
3151               if ((abfd->flags & D_PAGED) != 0)
3152                 off += (hdr->sh_addr - off) % bed->maxpagesize;
3153               else
3154                 off += (hdr->sh_addr - off) % hdr->sh_addralign;
3155               off = _bfd_elf_assign_file_position_for_section (hdr, off,
3156                                                                false);
3157             }
3158           else if (hdr->sh_type == SHT_REL
3159                    || hdr->sh_type == SHT_RELA
3160                    || hdr == i_shdrpp[tdata->symtab_section]
3161                    || hdr == i_shdrpp[tdata->strtab_section])
3162             hdr->sh_offset = -1;
3163           else
3164             off = _bfd_elf_assign_file_position_for_section (hdr, off, true);
3165         }
3166     }
3167
3168   /* Place the section headers.  */
3169   off = align_file_position (off, bed->s->file_align);
3170   i_ehdrp->e_shoff = off;
3171   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
3172
3173   elf_tdata (abfd)->next_file_pos = off;
3174
3175   return true;
3176 }
3177
3178 static boolean
3179 prep_headers (abfd)
3180      bfd *abfd;
3181 {
3182   Elf_Internal_Ehdr *i_ehdrp;   /* Elf file header, internal form */
3183   Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
3184   Elf_Internal_Shdr **i_shdrp;  /* Section header table, internal form */
3185   int count;
3186   struct bfd_strtab_hash *shstrtab;
3187   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3188
3189   i_ehdrp = elf_elfheader (abfd);
3190   i_shdrp = elf_elfsections (abfd);
3191
3192   shstrtab = _bfd_elf_stringtab_init ();
3193   if (shstrtab == NULL)
3194     return false;
3195
3196   elf_shstrtab (abfd) = shstrtab;
3197
3198   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
3199   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
3200   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
3201   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
3202
3203   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
3204   i_ehdrp->e_ident[EI_DATA] =
3205     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
3206   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
3207
3208   i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_SYSV;
3209   i_ehdrp->e_ident[EI_ABIVERSION] = 0;
3210
3211   for (count = EI_PAD; count < EI_NIDENT; count++)
3212     i_ehdrp->e_ident[count] = 0;
3213
3214   if ((abfd->flags & DYNAMIC) != 0)
3215     i_ehdrp->e_type = ET_DYN;
3216   else if ((abfd->flags & EXEC_P) != 0)
3217     i_ehdrp->e_type = ET_EXEC;
3218   else if (bfd_get_format (abfd) == bfd_core)
3219     i_ehdrp->e_type = ET_CORE;
3220   else
3221     i_ehdrp->e_type = ET_REL;
3222
3223   switch (bfd_get_arch (abfd))
3224     {
3225     case bfd_arch_unknown:
3226       i_ehdrp->e_machine = EM_NONE;
3227       break;
3228     case bfd_arch_sparc:
3229       if (bed->s->arch_size == 64)
3230         i_ehdrp->e_machine = EM_SPARCV9;
3231       else
3232         i_ehdrp->e_machine = EM_SPARC;
3233       break;
3234     case bfd_arch_i370:
3235       i_ehdrp->e_machine = EM_S370;
3236       break;
3237     case bfd_arch_i386:
3238       i_ehdrp->e_machine = EM_386;
3239       break;
3240     case bfd_arch_m68k:
3241       i_ehdrp->e_machine = EM_68K;
3242       break;
3243     case bfd_arch_m88k:
3244       i_ehdrp->e_machine = EM_88K;
3245       break;
3246     case bfd_arch_i860:
3247       i_ehdrp->e_machine = EM_860;
3248       break;
3249     case bfd_arch_i960:
3250       i_ehdrp->e_machine = EM_960;
3251       break;
3252     case bfd_arch_mips: /* MIPS Rxxxx */
3253       i_ehdrp->e_machine = EM_MIPS;     /* only MIPS R3000 */
3254       break;
3255     case bfd_arch_hppa:
3256       i_ehdrp->e_machine = EM_PARISC;
3257       break;
3258     case bfd_arch_powerpc:
3259       i_ehdrp->e_machine = EM_PPC;
3260       break;
3261     case bfd_arch_alpha:
3262       i_ehdrp->e_machine = EM_ALPHA;
3263       break;
3264     case bfd_arch_sh:
3265       i_ehdrp->e_machine = EM_SH;
3266       break;
3267     case bfd_arch_d10v:
3268       i_ehdrp->e_machine = EM_CYGNUS_D10V;
3269       break;
3270     case bfd_arch_d30v:
3271       i_ehdrp->e_machine = EM_CYGNUS_D30V;
3272       break;
3273     case bfd_arch_fr30:
3274       i_ehdrp->e_machine = EM_CYGNUS_FR30;
3275       break;
3276     case bfd_arch_mcore:
3277       i_ehdrp->e_machine = EM_MCORE;
3278       break;
3279     case bfd_arch_avr:
3280       i_ehdrp->e_machine = EM_AVR;
3281       break;
3282     case bfd_arch_v850:
3283       switch (bfd_get_mach (abfd))
3284         {
3285         default:
3286         case 0:               i_ehdrp->e_machine = EM_CYGNUS_V850; break;
3287         }
3288       break;
3289    case bfd_arch_arc:
3290       i_ehdrp->e_machine = EM_CYGNUS_ARC;
3291       break;
3292    case bfd_arch_arm:
3293       i_ehdrp->e_machine = EM_ARM;
3294       break;
3295     case bfd_arch_m32r:
3296       i_ehdrp->e_machine = EM_CYGNUS_M32R;
3297       break;
3298     case bfd_arch_mn10200:
3299       i_ehdrp->e_machine = EM_CYGNUS_MN10200;
3300       break;
3301     case bfd_arch_mn10300:
3302       i_ehdrp->e_machine = EM_CYGNUS_MN10300;
3303       break;
3304     case bfd_arch_pj:
3305       i_ehdrp->e_machine = EM_PJ;
3306       break;
3307       /* also note that EM_M32, AT&T WE32100 is unknown to bfd */
3308     default:
3309       i_ehdrp->e_machine = EM_NONE;
3310     }
3311   i_ehdrp->e_version = bed->s->ev_current;
3312   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
3313
3314   /* no program header, for now. */
3315   i_ehdrp->e_phoff = 0;
3316   i_ehdrp->e_phentsize = 0;
3317   i_ehdrp->e_phnum = 0;
3318
3319   /* each bfd section is section header entry */
3320   i_ehdrp->e_entry = bfd_get_start_address (abfd);
3321   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
3322
3323   /* if we're building an executable, we'll need a program header table */
3324   if (abfd->flags & EXEC_P)
3325     {
3326       /* it all happens later */
3327 #if 0
3328       i_ehdrp->e_phentsize = sizeof (Elf_External_Phdr);
3329
3330       /* elf_build_phdrs() returns a (NULL-terminated) array of
3331          Elf_Internal_Phdrs */
3332       i_phdrp = elf_build_phdrs (abfd, i_ehdrp, i_shdrp, &i_ehdrp->e_phnum);
3333       i_ehdrp->e_phoff = outbase;
3334       outbase += i_ehdrp->e_phentsize * i_ehdrp->e_phnum;
3335 #endif
3336     }
3337   else
3338     {
3339       i_ehdrp->e_phentsize = 0;
3340       i_phdrp = 0;
3341       i_ehdrp->e_phoff = 0;
3342     }
3343
3344   elf_tdata (abfd)->symtab_hdr.sh_name =
3345     (unsigned int) _bfd_stringtab_add (shstrtab, ".symtab", true, false);
3346   elf_tdata (abfd)->strtab_hdr.sh_name =
3347     (unsigned int) _bfd_stringtab_add (shstrtab, ".strtab", true, false);
3348   elf_tdata (abfd)->shstrtab_hdr.sh_name =
3349     (unsigned int) _bfd_stringtab_add (shstrtab, ".shstrtab", true, false);
3350   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
3351       || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
3352       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
3353     return false;
3354
3355   return true;
3356 }
3357
3358 /* Assign file positions for all the reloc sections which are not part
3359    of the loadable file image.  */
3360
3361 void
3362 _bfd_elf_assign_file_positions_for_relocs (abfd)
3363      bfd *abfd;
3364 {
3365   file_ptr off;
3366   unsigned int i;
3367   Elf_Internal_Shdr **shdrpp;
3368
3369   off = elf_tdata (abfd)->next_file_pos;
3370
3371   for (i = 1, shdrpp = elf_elfsections (abfd) + 1;
3372        i < elf_elfheader (abfd)->e_shnum;
3373        i++, shdrpp++)
3374     {
3375       Elf_Internal_Shdr *shdrp;
3376
3377       shdrp = *shdrpp;
3378       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
3379           && shdrp->sh_offset == -1)
3380         off = _bfd_elf_assign_file_position_for_section (shdrp, off, true);
3381     }
3382
3383   elf_tdata (abfd)->next_file_pos = off;
3384 }
3385
3386 boolean
3387 _bfd_elf_write_object_contents (abfd)
3388      bfd *abfd;
3389 {
3390   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3391   Elf_Internal_Ehdr *i_ehdrp;
3392   Elf_Internal_Shdr **i_shdrp;
3393   boolean failed;
3394   unsigned int count;
3395
3396   if (! abfd->output_has_begun
3397       && ! _bfd_elf_compute_section_file_positions
3398              (abfd, (struct bfd_link_info *) NULL))
3399     return false;
3400
3401   i_shdrp = elf_elfsections (abfd);
3402   i_ehdrp = elf_elfheader (abfd);
3403
3404   failed = false;
3405   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
3406   if (failed)
3407     return false;
3408
3409   _bfd_elf_assign_file_positions_for_relocs (abfd);
3410
3411   /* After writing the headers, we need to write the sections too... */
3412   for (count = 1; count < i_ehdrp->e_shnum; count++)
3413     {
3414       if (bed->elf_backend_section_processing)
3415         (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
3416       if (i_shdrp[count]->contents)
3417         {
3418           if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
3419               || (bfd_write (i_shdrp[count]->contents, i_shdrp[count]->sh_size,
3420                              1, abfd)
3421                   != i_shdrp[count]->sh_size))
3422             return false;
3423         }
3424     }
3425
3426   /* Write out the section header names.  */
3427   if (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
3428       || ! _bfd_stringtab_emit (abfd, elf_shstrtab (abfd)))
3429     return false;
3430
3431   if (bed->elf_backend_final_write_processing)
3432     (*bed->elf_backend_final_write_processing) (abfd,
3433                                                 elf_tdata (abfd)->linker);
3434
3435   return bed->s->write_shdrs_and_ehdr (abfd);
3436 }
3437
3438 boolean
3439 _bfd_elf_write_corefile_contents (abfd)
3440      bfd *abfd;
3441 {
3442   /* Hopefully this can be done just like an object file. */
3443   return _bfd_elf_write_object_contents (abfd);
3444 }
3445 /* given a section, search the header to find them... */
3446 int
3447 _bfd_elf_section_from_bfd_section (abfd, asect)
3448      bfd *abfd;
3449      struct sec *asect;
3450 {
3451   struct elf_backend_data *bed = get_elf_backend_data (abfd);
3452   Elf_Internal_Shdr **i_shdrp = elf_elfsections (abfd);
3453   int index;
3454   Elf_Internal_Shdr *hdr;
3455   int maxindex = elf_elfheader (abfd)->e_shnum;
3456
3457   for (index = 0; index < maxindex; index++)
3458     {
3459       hdr = i_shdrp[index];
3460       if (hdr->bfd_section == asect)
3461         return index;
3462     }
3463
3464   if (bed->elf_backend_section_from_bfd_section)
3465     {
3466       for (index = 0; index < maxindex; index++)
3467         {
3468           int retval;
3469
3470           hdr = i_shdrp[index];
3471           retval = index;
3472           if ((*bed->elf_backend_section_from_bfd_section)
3473               (abfd, hdr, asect, &retval))
3474             return retval;
3475         }
3476     }
3477
3478   if (bfd_is_abs_section (asect))
3479     return SHN_ABS;
3480   if (bfd_is_com_section (asect))
3481     return SHN_COMMON;
3482   if (bfd_is_und_section (asect))
3483     return SHN_UNDEF;
3484
3485   bfd_set_error (bfd_error_nonrepresentable_section);
3486
3487   return -1;
3488 }
3489
3490 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
3491    on error.  */
3492
3493 int
3494 _bfd_elf_symbol_from_bfd_symbol (abfd, asym_ptr_ptr)
3495      bfd *abfd;
3496      asymbol **asym_ptr_ptr;
3497 {
3498   asymbol *asym_ptr = *asym_ptr_ptr;
3499   int idx;
3500   flagword flags = asym_ptr->flags;
3501
3502   /* When gas creates relocations against local labels, it creates its
3503      own symbol for the section, but does put the symbol into the
3504      symbol chain, so udata is 0.  When the linker is generating
3505      relocatable output, this section symbol may be for one of the
3506      input sections rather than the output section.  */
3507   if (asym_ptr->udata.i == 0
3508       && (flags & BSF_SECTION_SYM)
3509       && asym_ptr->section)
3510     {
3511       int indx;
3512
3513       if (asym_ptr->section->output_section != NULL)
3514         indx = asym_ptr->section->output_section->index;
3515       else
3516         indx = asym_ptr->section->index;
3517       if (elf_section_syms (abfd)[indx])
3518         asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
3519     }
3520
3521   idx = asym_ptr->udata.i;
3522
3523   if (idx == 0)
3524     {
3525       /* This case can occur when using --strip-symbol on a symbol
3526          which is used in a relocation entry.  */
3527       (*_bfd_error_handler)
3528         (_("%s: symbol `%s' required but not present"),
3529          bfd_get_filename (abfd), bfd_asymbol_name (asym_ptr));
3530       bfd_set_error (bfd_error_no_symbols);
3531       return -1;
3532     }
3533
3534 #if DEBUG & 4
3535   {
3536     fprintf (stderr,
3537              _("elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx%s\n"),
3538              (long) asym_ptr, asym_ptr->name, idx, flags,
3539              elf_symbol_flags (flags));
3540     fflush (stderr);
3541   }
3542 #endif
3543
3544   return idx;
3545 }
3546
3547 /* Copy private BFD data.  This copies any program header information.  */
3548
3549 static boolean
3550 copy_private_bfd_data (ibfd, obfd)
3551      bfd *ibfd;
3552      bfd *obfd;
3553 {
3554   Elf_Internal_Ehdr *iehdr;
3555   struct elf_segment_map *mfirst;
3556   struct elf_segment_map **pm;
3557   struct elf_segment_map *m;
3558   Elf_Internal_Phdr *p;
3559   unsigned int i;
3560   unsigned int num_segments;
3561   boolean phdr_included = false;
3562
3563   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
3564       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
3565     return true;
3566
3567   if (elf_tdata (ibfd)->phdr == NULL)
3568     return true;
3569
3570   iehdr = elf_elfheader (ibfd);
3571
3572   mfirst = NULL;
3573   pm = &mfirst;
3574
3575   num_segments = elf_elfheader (ibfd)->e_phnum;
3576
3577 #define IS_CONTAINED_BY(addr, len, bottom, phdr)                        \
3578           ((addr) >= (bottom)                                           \
3579            && (   ((addr) + (len)) <= ((bottom) + (phdr)->p_memsz)      \
3580                || ((addr) + (len)) <= ((bottom) + (phdr)->p_filesz)))
3581
3582   /* Special case: corefile "NOTE" section containing regs, prpsinfo etc. */
3583
3584 #define IS_COREFILE_NOTE(p, s)                                          \
3585             (p->p_type == PT_NOTE                                       \
3586              && bfd_get_format (ibfd) == bfd_core                       \
3587              && s->vma == 0 && s->lma == 0                              \
3588              && (bfd_vma) s->filepos >= p->p_offset                     \
3589              && (bfd_vma) s->filepos + s->_raw_size                     \
3590              <= p->p_offset + p->p_filesz)
3591
3592   /* The complicated case when p_vaddr is 0 is to handle the Solaris
3593      linker, which generates a PT_INTERP section with p_vaddr and
3594      p_memsz set to 0.  */
3595
3596 #define IS_SOLARIS_PT_INTERP(p, s)                                      \
3597             (p->p_vaddr == 0                                            \
3598              && p->p_filesz > 0                                         \
3599              && (s->flags & SEC_HAS_CONTENTS) != 0                      \
3600              && s->_raw_size > 0                                        \
3601              && (bfd_vma) s->filepos >= p->p_offset                     \
3602              && ((bfd_vma) s->filepos + s->_raw_size                    \
3603                      <= p->p_offset + p->p_filesz))
3604
3605   /* Scan through the segments specified in the program header
3606      of the input BFD.  */
3607   for (i = 0, p = elf_tdata (ibfd)->phdr; i < num_segments; i++, p++)
3608     {
3609       unsigned int csecs;
3610       asection *s;
3611       asection **sections;
3612       asection *os;
3613       unsigned int isec;
3614       bfd_vma matching_lma;
3615       bfd_vma suggested_lma;
3616       unsigned int j;
3617
3618       /* For each section in the input BFD, decide if it should be
3619          included in the current segment.  A section will be included
3620          if it is within the address space of the segment, and it is
3621          an allocated segment, and there is an output section
3622          associated with it.  */
3623       csecs = 0;
3624       for (s = ibfd->sections; s != NULL; s = s->next)
3625         if (s->output_section != NULL)
3626           {
3627             if ((IS_CONTAINED_BY (s->vma, s->_raw_size, p->p_vaddr, p)
3628                  || IS_SOLARIS_PT_INTERP (p, s))
3629                 && (s->flags & SEC_ALLOC) != 0)
3630               ++csecs;
3631             else if (IS_COREFILE_NOTE (p, s))
3632               ++csecs;
3633           }
3634
3635       /* Allocate a segment map big enough to contain all of the
3636          sections we have selected.  */
3637       m = ((struct elf_segment_map *)
3638            bfd_alloc (obfd,
3639                       (sizeof (struct elf_segment_map)
3640                        + ((size_t) csecs - 1) * sizeof (asection *))));
3641       if (m == NULL)
3642         return false;
3643
3644       /* Initialise the fields of the segment map.  Default to
3645          using the physical address of the segment in the input BFD.  */
3646       m->next          = NULL;
3647       m->p_type        = p->p_type;
3648       m->p_flags       = p->p_flags;
3649       m->p_flags_valid = 1;
3650       m->p_paddr       = p->p_paddr;
3651       m->p_paddr_valid = 1;
3652
3653       /* Determine if this segment contains the ELF file header
3654          and if it contains the program headers themselves.  */
3655       m->includes_filehdr = (p->p_offset == 0
3656                              && p->p_filesz >= iehdr->e_ehsize);
3657
3658       m->includes_phdrs = 0;
3659
3660       if (! phdr_included || p->p_type != PT_LOAD)
3661         {
3662           m->includes_phdrs =
3663             (p->p_offset <= (bfd_vma) iehdr->e_phoff
3664              && (p->p_offset + p->p_filesz
3665                  >= ((bfd_vma) iehdr->e_phoff
3666                      + iehdr->e_phnum * iehdr->e_phentsize)));
3667           if (p->p_type == PT_LOAD && m->includes_phdrs)
3668             phdr_included = true;
3669         }
3670
3671       if (csecs == 0)
3672         {
3673           /* Special segments, such as the PT_PHDR segment, may contain
3674              no sections, but ordinary, loadable segments should contain
3675              something.  */
3676
3677           if (p->p_type == PT_LOAD)
3678               _bfd_error_handler
3679                 (_("%s: warning: Empty loadable segment detected\n"),
3680                  bfd_get_filename (ibfd));
3681
3682           m->count = 0;
3683           *pm = m;
3684           pm = &m->next;
3685
3686           continue;
3687         }
3688
3689       /* Now scan the sections in the input BFD again and attempt
3690          to add their corresponding output sections to the segment map.
3691          The problem here is how to handle an output section which has
3692          been moved (ie had its LMA changed).  There are four possibilities:
3693
3694          1. None of the sections have been moved.
3695             In this case we can continue to use the segment LMA from the
3696             input BFD.
3697
3698          2. All of the sections have been moved by the same amount.
3699             In this case we can change the segment's LMA to match the LMA
3700             of the first section.
3701
3702          3. Some of the sections have been moved, others have not.
3703             In this case those sections which have not been moved can be
3704             placed in the current segment which will have to have its size,
3705             and possibly its LMA changed, and a new segment or segments will
3706             have to be created to contain the other sections.
3707
3708          4. The sections have been moved, but not be the same amount.
3709             In this case we can change the segment's LMA to match the LMA
3710             of the first section and we will have to create a new segment
3711             or segments to contain the other sections.
3712
3713          In order to save time, we allocate an array to hold the section
3714          pointers that we are interested in.  As these sections get assigned
3715          to a segment, they are removed from this array.  */
3716
3717       sections = (asection **) bfd_malloc (sizeof (asection *) * csecs);
3718       if (sections == NULL)
3719         return false;
3720
3721       /* Step One: Scan for segment vs section LMA conflicts.
3722          Also add the sections to the section array allocated above.
3723          Also add the sections to the current segment.  In the common
3724          case, where the sections have not been moved, this means that
3725          we have completely filled the segment, and there is nothing
3726          more to do.  */
3727
3728       isec = 0;
3729       matching_lma = false;
3730       suggested_lma = 0;
3731
3732       for (j = 0, s = ibfd->sections; s != NULL; s = s->next)
3733         {
3734           os = s->output_section;
3735
3736           if ((((IS_CONTAINED_BY (s->vma, s->_raw_size, p->p_vaddr, p)
3737                  || IS_SOLARIS_PT_INTERP (p, s))
3738                 && (s->flags & SEC_ALLOC) != 0)
3739                || IS_COREFILE_NOTE (p, s))
3740               && os != NULL)
3741             {
3742               sections[j++] = s;
3743
3744               /* The Solaris native linker always sets p_paddr to 0.
3745                  We try to catch that case here, and set it to the
3746                  correct value.  */
3747               if (p->p_paddr == 0
3748                   && p->p_vaddr != 0
3749                   && isec == 0
3750                   && os->lma != 0
3751                   && (os->vma == (p->p_vaddr
3752                                   + (m->includes_filehdr
3753                                      ? iehdr->e_ehsize
3754                                      : 0)
3755                                   + (m->includes_phdrs
3756                                      ? iehdr->e_phnum * iehdr->e_phentsize
3757                                      : 0))))
3758                 m->p_paddr = p->p_vaddr;
3759
3760               /* Match up the physical address of the segment with the
3761                  LMA address of the output section.  */
3762               if (IS_CONTAINED_BY (os->lma, os->_raw_size, m->p_paddr, p)
3763                   || IS_COREFILE_NOTE (p, s))
3764                 {
3765                   if (matching_lma == 0)
3766                     matching_lma = os->lma;
3767
3768                   /* We assume that if the section fits within the segment
3769                      that it does not overlap any other section within that
3770                      segment.  */
3771                   m->sections[isec++] = os;
3772                 }
3773               else if (suggested_lma == 0)
3774                 suggested_lma = os->lma;
3775             }
3776         }
3777
3778       BFD_ASSERT (j == csecs);
3779
3780       /* Step Two: Adjust the physical address of the current segment,
3781          if necessary.  */
3782       if (isec == csecs)
3783         {
3784           /* All of the sections fitted within the segment as currently
3785              specified.  This is the default case.  Add the segment to
3786              the list of built segments and carry on to process the next
3787              program header in the input BFD.  */
3788           m->count = csecs;
3789           *pm = m;
3790           pm = &m->next;
3791
3792           free (sections);
3793           continue;
3794         }
3795       else if (matching_lma != 0)
3796         {
3797           /* At least one section fits inside the current segment.
3798              Keep it, but modify its physical address to match the
3799              LMA of the first section that fitted.  */
3800
3801           m->p_paddr = matching_lma;
3802         }
3803       else
3804         {
3805           /* None of the sections fitted inside the current segment.
3806              Change the current segment's physical address to match
3807              the LMA of the first section.  */
3808
3809           m->p_paddr = suggested_lma;
3810         }
3811
3812       /* Step Three: Loop over the sections again, this time assigning
3813          those that fit to the current segment and remvoing them from the
3814          sections array; but making sure not to leave large gaps.  Once all
3815          possible sections have been assigned to the current segment it is
3816          added to the list of built segments and if sections still remain
3817          to be assigned, a new segment is constructed before repeating
3818          the loop.  */
3819       isec = 0;
3820       do
3821         {
3822           m->count = 0;
3823           suggested_lma = 0;
3824
3825           /* Fill the current segment with sections that fit.  */
3826           for (j = 0; j < csecs; j++)
3827             {
3828               s = sections[j];
3829
3830               if (s == NULL)
3831                 continue;
3832
3833               os = s->output_section;
3834
3835               if (IS_CONTAINED_BY (os->lma, os->_raw_size, m->p_paddr, p)
3836                   || IS_COREFILE_NOTE (p, s))
3837                 {
3838                   if (m->count == 0)
3839                     {
3840                       /* If the first section in a segment does not start at
3841                          the beginning of the segment, then something is wrong.  */
3842                       if (os->lma != m->p_paddr)
3843                         abort ();
3844                     }
3845                   else
3846                     {
3847                       asection * prev_sec;
3848                       bfd_vma maxpagesize;
3849
3850                       prev_sec = m->sections[m->count - 1];
3851                       maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
3852
3853                       /* If the gap between the end of the previous section
3854                          and the start of this section is more than maxpagesize
3855                          then we need to start a new segment.  */
3856                       if (BFD_ALIGN (prev_sec->lma + prev_sec->_raw_size, maxpagesize)
3857                           < BFD_ALIGN (os->lma, maxpagesize))
3858                         {
3859                           if (suggested_lma == 0)
3860                             suggested_lma = os->lma;
3861
3862                           continue;
3863                         }
3864                     }
3865
3866                   m->sections[m->count++] = os;
3867                   ++isec;
3868                   sections[j] = NULL;
3869                 }
3870               else if (suggested_lma == 0)
3871                 suggested_lma = os->lma;
3872             }
3873
3874           BFD_ASSERT (m->count > 0);
3875
3876           /* Add the current segment to the list of built segments.  */
3877           *pm = m;
3878           pm = &m->next;
3879
3880           if (isec < csecs)
3881             {
3882               /* We still have not allocated all of the sections to
3883                  segments.  Create a new segment here, initialise it
3884                  and carry on looping.  */
3885
3886               m = ((struct elf_segment_map *)
3887                    bfd_alloc (obfd,
3888                               (sizeof (struct elf_segment_map)
3889                                + ((size_t) csecs - 1) * sizeof (asection *))));
3890               if (m == NULL)
3891                 return false;
3892
3893               /* Initialise the fields of the segment map.  Set the physical
3894                  physical address to the LMA of the first section that has
3895                  not yet been assigned.  */
3896
3897               m->next             = NULL;
3898               m->p_type           = p->p_type;
3899               m->p_flags          = p->p_flags;
3900               m->p_flags_valid    = 1;
3901               m->p_paddr          = suggested_lma;
3902               m->p_paddr_valid    = 1;
3903               m->includes_filehdr = 0;
3904               m->includes_phdrs   = 0;
3905             }
3906         }
3907       while (isec < csecs);
3908
3909       free (sections);
3910     }
3911
3912   /* The Solaris linker creates program headers in which all the
3913      p_paddr fields are zero.  When we try to objcopy or strip such a
3914      file, we get confused.  Check for this case, and if we find it
3915      reset the p_paddr_valid fields.  */
3916   for (m = mfirst; m != NULL; m = m->next)
3917     if (m->p_paddr != 0)
3918       break;
3919   if (m == NULL)
3920     {
3921       for (m = mfirst; m != NULL; m = m->next)
3922         m->p_paddr_valid = 0;
3923     }
3924
3925   elf_tdata (obfd)->segment_map = mfirst;
3926
3927 #if 0
3928   /* Final Step: Sort the segments into ascending order of physical address. */
3929   if (mfirst != NULL)
3930     {
3931       struct elf_segment_map* prev;
3932
3933       prev = mfirst;
3934       for (m = mfirst->next; m != NULL; prev = m, m = m->next)
3935         {
3936           /* Yes I know - its a bubble sort....*/
3937           if (m->next != NULL && (m->next->p_paddr < m->p_paddr))
3938             {
3939               /* swap m and m->next */
3940               prev->next = m->next;
3941               m->next = m->next->next;
3942               prev->next->next = m;
3943
3944               /* restart loop. */
3945               m = mfirst;
3946             }
3947         }
3948     }
3949 #endif
3950
3951 #undef IS_CONTAINED_BY
3952 #undef IS_SOLARIS_PT_INTERP
3953 #undef IS_COREFILE_NOTE
3954   return true;
3955 }
3956
3957 /* Copy private section information.  This copies over the entsize
3958    field, and sometimes the info field.  */
3959
3960 boolean
3961 _bfd_elf_copy_private_section_data (ibfd, isec, obfd, osec)
3962      bfd *ibfd;
3963      asection *isec;
3964      bfd *obfd;
3965      asection *osec;
3966 {
3967   Elf_Internal_Shdr *ihdr, *ohdr;
3968
3969   if (ibfd->xvec->flavour != bfd_target_elf_flavour
3970       || obfd->xvec->flavour != bfd_target_elf_flavour)
3971     return true;
3972
3973   /* Copy over private BFD data if it has not already been copied.
3974      This must be done here, rather than in the copy_private_bfd_data
3975      entry point, because the latter is called after the section
3976      contents have been set, which means that the program headers have
3977      already been worked out.  */
3978   if (elf_tdata (obfd)->segment_map == NULL
3979       && elf_tdata (ibfd)->phdr != NULL)
3980     {
3981       asection *s;
3982
3983       /* Only set up the segments if there are no more SEC_ALLOC
3984          sections.  FIXME: This won't do the right thing if objcopy is
3985          used to remove the last SEC_ALLOC section, since objcopy
3986          won't call this routine in that case.  */
3987       for (s = isec->next; s != NULL; s = s->next)
3988         if ((s->flags & SEC_ALLOC) != 0)
3989           break;
3990       if (s == NULL)
3991         {
3992           if (! copy_private_bfd_data (ibfd, obfd))
3993             return false;
3994         }
3995     }
3996
3997   ihdr = &elf_section_data (isec)->this_hdr;
3998   ohdr = &elf_section_data (osec)->this_hdr;
3999
4000   ohdr->sh_entsize = ihdr->sh_entsize;
4001
4002   if (ihdr->sh_type == SHT_SYMTAB
4003       || ihdr->sh_type == SHT_DYNSYM
4004       || ihdr->sh_type == SHT_GNU_verneed
4005       || ihdr->sh_type == SHT_GNU_verdef)
4006     ohdr->sh_info = ihdr->sh_info;
4007
4008   elf_section_data (osec)->use_rela_p
4009     = elf_section_data (isec)->use_rela_p;
4010
4011   return true;
4012 }
4013
4014 /* Copy private symbol information.  If this symbol is in a section
4015    which we did not map into a BFD section, try to map the section
4016    index correctly.  We use special macro definitions for the mapped
4017    section indices; these definitions are interpreted by the
4018    swap_out_syms function.  */
4019
4020 #define MAP_ONESYMTAB (SHN_LORESERVE - 1)
4021 #define MAP_DYNSYMTAB (SHN_LORESERVE - 2)
4022 #define MAP_STRTAB (SHN_LORESERVE - 3)
4023 #define MAP_SHSTRTAB (SHN_LORESERVE - 4)
4024
4025 boolean
4026 _bfd_elf_copy_private_symbol_data (ibfd, isymarg, obfd, osymarg)
4027      bfd *ibfd;
4028      asymbol *isymarg;
4029      bfd *obfd;
4030      asymbol *osymarg;
4031 {
4032   elf_symbol_type *isym, *osym;
4033
4034   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
4035       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
4036     return true;
4037
4038   isym = elf_symbol_from (ibfd, isymarg);
4039   osym = elf_symbol_from (obfd, osymarg);
4040
4041   if (isym != NULL
4042       && osym != NULL
4043       && bfd_is_abs_section (isym->symbol.section))
4044     {
4045       unsigned int shndx;
4046
4047       shndx = isym->internal_elf_sym.st_shndx;
4048       if (shndx == elf_onesymtab (ibfd))
4049         shndx = MAP_ONESYMTAB;
4050       else if (shndx == elf_dynsymtab (ibfd))
4051         shndx = MAP_DYNSYMTAB;
4052       else if (shndx == elf_tdata (ibfd)->strtab_section)
4053         shndx = MAP_STRTAB;
4054       else if (shndx == elf_tdata (ibfd)->shstrtab_section)
4055         shndx = MAP_SHSTRTAB;
4056       osym->internal_elf_sym.st_shndx = shndx;
4057     }
4058
4059   return true;
4060 }
4061
4062 /* Swap out the symbols.  */
4063
4064 static boolean
4065 swap_out_syms (abfd, sttp, relocatable_p)
4066      bfd *abfd;
4067      struct bfd_strtab_hash **sttp;
4068      int relocatable_p;
4069 {
4070   struct elf_backend_data *bed = get_elf_backend_data (abfd);
4071
4072   if (!elf_map_symbols (abfd))
4073     return false;
4074
4075   /* Dump out the symtabs. */
4076   {
4077     int symcount = bfd_get_symcount (abfd);
4078     asymbol **syms = bfd_get_outsymbols (abfd);
4079     struct bfd_strtab_hash *stt;
4080     Elf_Internal_Shdr *symtab_hdr;
4081     Elf_Internal_Shdr *symstrtab_hdr;
4082     char *outbound_syms;
4083     int idx;
4084
4085     stt = _bfd_elf_stringtab_init ();
4086     if (stt == NULL)
4087       return false;
4088
4089     symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
4090     symtab_hdr->sh_type = SHT_SYMTAB;
4091     symtab_hdr->sh_entsize = bed->s->sizeof_sym;
4092     symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
4093     symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
4094     symtab_hdr->sh_addralign = bed->s->file_align;
4095
4096     symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
4097     symstrtab_hdr->sh_type = SHT_STRTAB;
4098
4099     outbound_syms = bfd_alloc (abfd,
4100                                (1 + symcount) * bed->s->sizeof_sym);
4101     if (outbound_syms == NULL)
4102       return false;
4103     symtab_hdr->contents = (PTR) outbound_syms;
4104
4105     /* now generate the data (for "contents") */
4106     {
4107       /* Fill in zeroth symbol and swap it out.  */
4108       Elf_Internal_Sym sym;
4109       sym.st_name = 0;
4110       sym.st_value = 0;
4111       sym.st_size = 0;
4112       sym.st_info = 0;
4113       sym.st_other = 0;
4114       sym.st_shndx = SHN_UNDEF;
4115       bed->s->swap_symbol_out (abfd, &sym, (PTR) outbound_syms);
4116       outbound_syms += bed->s->sizeof_sym;
4117     }
4118     for (idx = 0; idx < symcount; idx++)
4119       {
4120         Elf_Internal_Sym sym;
4121         bfd_vma value = syms[idx]->value;
4122         elf_symbol_type *type_ptr;
4123         flagword flags = syms[idx]->flags;
4124         int type;
4125
4126         if (flags & BSF_SECTION_SYM)
4127           /* Section symbols have no names.  */
4128           sym.st_name = 0;
4129         else
4130           {
4131             sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
4132                                                               syms[idx]->name,
4133                                                               true, false);
4134             if (sym.st_name == (unsigned long) -1)
4135               return false;
4136           }
4137
4138         type_ptr = elf_symbol_from (abfd, syms[idx]);
4139
4140         if ((flags & BSF_SECTION_SYM) == 0
4141             && bfd_is_com_section (syms[idx]->section))
4142           {
4143             /* ELF common symbols put the alignment into the `value' field,
4144                and the size into the `size' field.  This is backwards from
4145                how BFD handles it, so reverse it here.  */
4146             sym.st_size = value;
4147             if (type_ptr == NULL
4148                 || type_ptr->internal_elf_sym.st_value == 0)
4149               sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
4150             else
4151               sym.st_value = type_ptr->internal_elf_sym.st_value;
4152             sym.st_shndx = _bfd_elf_section_from_bfd_section
4153               (abfd, syms[idx]->section);
4154           }
4155         else
4156           {
4157             asection *sec = syms[idx]->section;
4158             int shndx;
4159
4160             if (sec->output_section)
4161               {
4162                 value += sec->output_offset;
4163                 sec = sec->output_section;
4164               }
4165             /* Don't add in the section vma for relocatable output.  */
4166             if (! relocatable_p)
4167               value += sec->vma;
4168             sym.st_value = value;
4169             sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
4170
4171             if (bfd_is_abs_section (sec)
4172                 && type_ptr != NULL
4173                 && type_ptr->internal_elf_sym.st_shndx != 0)
4174               {
4175                 /* This symbol is in a real ELF section which we did
4176                    not create as a BFD section.  Undo the mapping done
4177                    by copy_private_symbol_data.  */
4178                 shndx = type_ptr->internal_elf_sym.st_shndx;
4179                 switch (shndx)
4180                   {
4181                   case MAP_ONESYMTAB:
4182                     shndx = elf_onesymtab (abfd);
4183                     break;
4184                   case MAP_DYNSYMTAB:
4185                     shndx = elf_dynsymtab (abfd);
4186                     break;
4187                   case MAP_STRTAB:
4188                     shndx = elf_tdata (abfd)->strtab_section;
4189                     break;
4190                   case MAP_SHSTRTAB:
4191                     shndx = elf_tdata (abfd)->shstrtab_section;
4192                     break;
4193                   default:
4194                     break;
4195                   }
4196               }
4197             else
4198               {
4199                 shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
4200
4201                 if (shndx == -1)
4202                   {
4203                     asection *sec2;
4204
4205                     /* Writing this would be a hell of a lot easier if
4206                        we had some decent documentation on bfd, and
4207                        knew what to expect of the library, and what to
4208                        demand of applications.  For example, it
4209                        appears that `objcopy' might not set the
4210                        section of a symbol to be a section that is
4211                        actually in the output file.  */
4212                     sec2 = bfd_get_section_by_name (abfd, sec->name);
4213                     BFD_ASSERT (sec2 != 0);
4214                     shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
4215                     BFD_ASSERT (shndx != -1);
4216                   }
4217               }
4218
4219             sym.st_shndx = shndx;
4220           }
4221
4222         if ((flags & BSF_FUNCTION) != 0)
4223           type = STT_FUNC;
4224         else if ((flags & BSF_OBJECT) != 0)
4225           type = STT_OBJECT;
4226         else
4227           type = STT_NOTYPE;
4228
4229         /* Processor-specific types */
4230         if (type_ptr != NULL
4231             && bed->elf_backend_get_symbol_type)
4232           type = (*bed->elf_backend_get_symbol_type) (&type_ptr->internal_elf_sym, type);
4233
4234         if (flags & BSF_SECTION_SYM)
4235           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
4236         else if (bfd_is_com_section (syms[idx]->section))
4237           sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
4238         else if (bfd_is_und_section (syms[idx]->section))
4239           sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
4240                                       ? STB_WEAK
4241                                       : STB_GLOBAL),
4242                                      type);
4243         else if (flags & BSF_FILE)
4244           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
4245         else
4246           {
4247             int bind = STB_LOCAL;
4248
4249             if (flags & BSF_LOCAL)
4250               bind = STB_LOCAL;
4251             else if (flags & BSF_WEAK)
4252               bind = STB_WEAK;
4253             else if (flags & BSF_GLOBAL)
4254               bind = STB_GLOBAL;
4255
4256             sym.st_info = ELF_ST_INFO (bind, type);
4257           }
4258
4259         if (type_ptr != NULL)
4260           sym.st_other = type_ptr->internal_elf_sym.st_other;
4261         else
4262           sym.st_other = 0;
4263
4264         bed->s->swap_symbol_out (abfd, &sym, (PTR) outbound_syms);
4265         outbound_syms += bed->s->sizeof_sym;
4266       }
4267
4268     *sttp = stt;
4269     symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
4270     symstrtab_hdr->sh_type = SHT_STRTAB;
4271
4272     symstrtab_hdr->sh_flags = 0;
4273     symstrtab_hdr->sh_addr = 0;
4274     symstrtab_hdr->sh_entsize = 0;
4275     symstrtab_hdr->sh_link = 0;
4276     symstrtab_hdr->sh_info = 0;
4277     symstrtab_hdr->sh_addralign = 1;
4278   }
4279
4280   return true;
4281 }
4282
4283 /* Return the number of bytes required to hold the symtab vector.
4284
4285    Note that we base it on the count plus 1, since we will null terminate
4286    the vector allocated based on this size.  However, the ELF symbol table
4287    always has a dummy entry as symbol #0, so it ends up even.  */
4288
4289 long
4290 _bfd_elf_get_symtab_upper_bound (abfd)
4291      bfd *abfd;
4292 {
4293   long symcount;
4294   long symtab_size;
4295   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
4296
4297   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
4298   symtab_size = (symcount - 1 + 1) * (sizeof (asymbol *));
4299
4300   return symtab_size;
4301 }
4302
4303 long
4304 _bfd_elf_get_dynamic_symtab_upper_bound (abfd)
4305      bfd *abfd;
4306 {
4307   long symcount;
4308   long symtab_size;
4309   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4310
4311   if (elf_dynsymtab (abfd) == 0)
4312     {
4313       bfd_set_error (bfd_error_invalid_operation);
4314       return -1;
4315     }
4316
4317   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
4318   symtab_size = (symcount - 1 + 1) * (sizeof (asymbol *));
4319
4320   return symtab_size;
4321 }
4322
4323 long
4324 _bfd_elf_get_reloc_upper_bound (abfd, asect)
4325      bfd *abfd ATTRIBUTE_UNUSED;
4326      sec_ptr asect;
4327 {
4328   return (asect->reloc_count + 1) * sizeof (arelent *);
4329 }
4330
4331 /* Canonicalize the relocs.  */
4332
4333 long
4334 _bfd_elf_canonicalize_reloc (abfd, section, relptr, symbols)
4335      bfd *abfd;
4336      sec_ptr section;
4337      arelent **relptr;
4338      asymbol **symbols;
4339 {
4340   arelent *tblptr;
4341   unsigned int i;
4342
4343   if (! get_elf_backend_data (abfd)->s->slurp_reloc_table (abfd,
4344                                                            section,
4345                                                            symbols,
4346                                                            false))
4347     return -1;
4348
4349   tblptr = section->relocation;
4350   for (i = 0; i < section->reloc_count; i++)
4351     *relptr++ = tblptr++;
4352
4353   *relptr = NULL;
4354
4355   return section->reloc_count;
4356 }
4357
4358 long
4359 _bfd_elf_get_symtab (abfd, alocation)
4360      bfd *abfd;
4361      asymbol **alocation;
4362 {
4363   long symcount = get_elf_backend_data (abfd)->s->slurp_symbol_table
4364     (abfd, alocation, false);
4365
4366   if (symcount >= 0)
4367     bfd_get_symcount (abfd) = symcount;
4368   return symcount;
4369 }
4370
4371 long
4372 _bfd_elf_canonicalize_dynamic_symtab (abfd, alocation)
4373      bfd *abfd;
4374      asymbol **alocation;
4375 {
4376   return get_elf_backend_data (abfd)->s->slurp_symbol_table
4377     (abfd, alocation, true);
4378 }
4379
4380 /* Return the size required for the dynamic reloc entries.  Any
4381    section that was actually installed in the BFD, and has type
4382    SHT_REL or SHT_RELA, and uses the dynamic symbol table, is
4383    considered to be a dynamic reloc section.  */
4384
4385 long
4386 _bfd_elf_get_dynamic_reloc_upper_bound (abfd)
4387      bfd *abfd;
4388 {
4389   long ret;
4390   asection *s;
4391
4392   if (elf_dynsymtab (abfd) == 0)
4393     {
4394       bfd_set_error (bfd_error_invalid_operation);
4395       return -1;
4396     }
4397
4398   ret = sizeof (arelent *);
4399   for (s = abfd->sections; s != NULL; s = s->next)
4400     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
4401         && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
4402             || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
4403       ret += ((s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize)
4404               * sizeof (arelent *));
4405
4406   return ret;
4407 }
4408
4409 /* Canonicalize the dynamic relocation entries.  Note that we return
4410    the dynamic relocations as a single block, although they are
4411    actually associated with particular sections; the interface, which
4412    was designed for SunOS style shared libraries, expects that there
4413    is only one set of dynamic relocs.  Any section that was actually
4414    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses
4415    the dynamic symbol table, is considered to be a dynamic reloc
4416    section.  */
4417
4418 long
4419 _bfd_elf_canonicalize_dynamic_reloc (abfd, storage, syms)
4420      bfd *abfd;
4421      arelent **storage;
4422      asymbol **syms;
4423 {
4424   boolean (*slurp_relocs) PARAMS ((bfd *, asection *, asymbol **, boolean));
4425   asection *s;
4426   long ret;
4427
4428   if (elf_dynsymtab (abfd) == 0)
4429     {
4430       bfd_set_error (bfd_error_invalid_operation);
4431       return -1;
4432     }
4433
4434   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
4435   ret = 0;
4436   for (s = abfd->sections; s != NULL; s = s->next)
4437     {
4438       if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
4439           && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
4440               || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
4441         {
4442           arelent *p;
4443           long count, i;
4444
4445           if (! (*slurp_relocs) (abfd, s, syms, true))
4446             return -1;
4447           count = s->_raw_size / elf_section_data (s)->this_hdr.sh_entsize;
4448           p = s->relocation;
4449           for (i = 0; i < count; i++)
4450             *storage++ = p++;
4451           ret += count;
4452         }
4453     }
4454
4455   *storage = NULL;
4456
4457   return ret;
4458 }
4459 \f
4460 /* Read in the version information.  */
4461
4462 boolean
4463 _bfd_elf_slurp_version_tables (abfd)
4464      bfd *abfd;
4465 {
4466   bfd_byte *contents = NULL;
4467
4468   if (elf_dynverdef (abfd) != 0)
4469     {
4470       Elf_Internal_Shdr *hdr;
4471       Elf_External_Verdef *everdef;
4472       Elf_Internal_Verdef *iverdef;
4473       unsigned int i;
4474
4475       hdr = &elf_tdata (abfd)->dynverdef_hdr;
4476
4477       elf_tdata (abfd)->verdef =
4478         ((Elf_Internal_Verdef *)
4479          bfd_zalloc (abfd, hdr->sh_info * sizeof (Elf_Internal_Verdef)));
4480       if (elf_tdata (abfd)->verdef == NULL)
4481         goto error_return;
4482
4483       elf_tdata (abfd)->cverdefs = hdr->sh_info;
4484
4485       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
4486       if (contents == NULL)
4487         goto error_return;
4488       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
4489           || bfd_read ((PTR) contents, 1, hdr->sh_size, abfd) != hdr->sh_size)
4490         goto error_return;
4491
4492       everdef = (Elf_External_Verdef *) contents;
4493       iverdef = elf_tdata (abfd)->verdef;
4494       for (i = 0; i < hdr->sh_info; i++, iverdef++)
4495         {
4496           Elf_External_Verdaux *everdaux;
4497           Elf_Internal_Verdaux *iverdaux;
4498           unsigned int j;
4499
4500           _bfd_elf_swap_verdef_in (abfd, everdef, iverdef);
4501
4502           iverdef->vd_bfd = abfd;
4503
4504           iverdef->vd_auxptr = ((Elf_Internal_Verdaux *)
4505                                 bfd_alloc (abfd,
4506                                            (iverdef->vd_cnt
4507                                             * sizeof (Elf_Internal_Verdaux))));
4508           if (iverdef->vd_auxptr == NULL)
4509             goto error_return;
4510
4511           everdaux = ((Elf_External_Verdaux *)
4512                       ((bfd_byte *) everdef + iverdef->vd_aux));
4513           iverdaux = iverdef->vd_auxptr;
4514           for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
4515             {
4516               _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
4517
4518               iverdaux->vda_nodename =
4519                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4520                                                  iverdaux->vda_name);
4521               if (iverdaux->vda_nodename == NULL)
4522                 goto error_return;
4523
4524               if (j + 1 < iverdef->vd_cnt)
4525                 iverdaux->vda_nextptr = iverdaux + 1;
4526               else
4527                 iverdaux->vda_nextptr = NULL;
4528
4529               everdaux = ((Elf_External_Verdaux *)
4530                           ((bfd_byte *) everdaux + iverdaux->vda_next));
4531             }
4532
4533           iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
4534
4535           if (i + 1 < hdr->sh_info)
4536             iverdef->vd_nextdef = iverdef + 1;
4537           else
4538             iverdef->vd_nextdef = NULL;
4539
4540           everdef = ((Elf_External_Verdef *)
4541                      ((bfd_byte *) everdef + iverdef->vd_next));
4542         }
4543
4544       free (contents);
4545       contents = NULL;
4546     }
4547
4548   if (elf_dynverref (abfd) != 0)
4549     {
4550       Elf_Internal_Shdr *hdr;
4551       Elf_External_Verneed *everneed;
4552       Elf_Internal_Verneed *iverneed;
4553       unsigned int i;
4554
4555       hdr = &elf_tdata (abfd)->dynverref_hdr;
4556
4557       elf_tdata (abfd)->verref =
4558         ((Elf_Internal_Verneed *)
4559          bfd_zalloc (abfd, hdr->sh_info * sizeof (Elf_Internal_Verneed)));
4560       if (elf_tdata (abfd)->verref == NULL)
4561         goto error_return;
4562
4563       elf_tdata (abfd)->cverrefs = hdr->sh_info;
4564
4565       contents = (bfd_byte *) bfd_malloc (hdr->sh_size);
4566       if (contents == NULL)
4567         goto error_return;
4568       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
4569           || bfd_read ((PTR) contents, 1, hdr->sh_size, abfd) != hdr->sh_size)
4570         goto error_return;
4571
4572       everneed = (Elf_External_Verneed *) contents;
4573       iverneed = elf_tdata (abfd)->verref;
4574       for (i = 0; i < hdr->sh_info; i++, iverneed++)
4575         {
4576           Elf_External_Vernaux *evernaux;
4577           Elf_Internal_Vernaux *ivernaux;
4578           unsigned int j;
4579
4580           _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
4581
4582           iverneed->vn_bfd = abfd;
4583
4584           iverneed->vn_filename =
4585             bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4586                                              iverneed->vn_file);
4587           if (iverneed->vn_filename == NULL)
4588             goto error_return;
4589
4590           iverneed->vn_auxptr =
4591             ((Elf_Internal_Vernaux *)
4592              bfd_alloc (abfd,
4593                         iverneed->vn_cnt * sizeof (Elf_Internal_Vernaux)));
4594
4595           evernaux = ((Elf_External_Vernaux *)
4596                       ((bfd_byte *) everneed + iverneed->vn_aux));
4597           ivernaux = iverneed->vn_auxptr;
4598           for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
4599             {
4600               _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
4601
4602               ivernaux->vna_nodename =
4603                 bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4604                                                  ivernaux->vna_name);
4605               if (ivernaux->vna_nodename == NULL)
4606                 goto error_return;
4607
4608               if (j + 1 < iverneed->vn_cnt)
4609                 ivernaux->vna_nextptr = ivernaux + 1;
4610               else
4611                 ivernaux->vna_nextptr = NULL;
4612
4613               evernaux = ((Elf_External_Vernaux *)
4614                           ((bfd_byte *) evernaux + ivernaux->vna_next));
4615             }
4616
4617           if (i + 1 < hdr->sh_info)
4618             iverneed->vn_nextref = iverneed + 1;
4619           else
4620             iverneed->vn_nextref = NULL;
4621
4622           everneed = ((Elf_External_Verneed *)
4623                       ((bfd_byte *) everneed + iverneed->vn_next));
4624         }
4625
4626       free (contents);
4627       contents = NULL;
4628     }
4629
4630   return true;
4631
4632  error_return:
4633   if (contents == NULL)
4634     free (contents);
4635   return false;
4636 }
4637 \f
4638 asymbol *
4639 _bfd_elf_make_empty_symbol (abfd)
4640      bfd *abfd;
4641 {
4642   elf_symbol_type *newsym;
4643
4644   newsym = (elf_symbol_type *) bfd_zalloc (abfd, sizeof (elf_symbol_type));
4645   if (!newsym)
4646     return NULL;
4647   else
4648     {
4649       newsym->symbol.the_bfd = abfd;
4650       return &newsym->symbol;
4651     }
4652 }
4653
4654 void
4655 _bfd_elf_get_symbol_info (ignore_abfd, symbol, ret)
4656      bfd *ignore_abfd ATTRIBUTE_UNUSED;
4657      asymbol *symbol;
4658      symbol_info *ret;
4659 {
4660   bfd_symbol_info (symbol, ret);
4661 }
4662
4663 /* Return whether a symbol name implies a local symbol.  Most targets
4664    use this function for the is_local_label_name entry point, but some
4665    override it.  */
4666
4667 boolean
4668 _bfd_elf_is_local_label_name (abfd, name)
4669      bfd *abfd ATTRIBUTE_UNUSED;
4670      const char *name;
4671 {
4672   /* Normal local symbols start with ``.L''.  */
4673   if (name[0] == '.' && name[1] == 'L')
4674     return true;
4675
4676   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
4677      DWARF debugging symbols starting with ``..''.  */
4678   if (name[0] == '.' && name[1] == '.')
4679     return true;
4680
4681   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
4682      emitting DWARF debugging output.  I suspect this is actually a
4683      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
4684      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
4685      underscore to be emitted on some ELF targets).  For ease of use,
4686      we treat such symbols as local.  */
4687   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
4688     return true;
4689
4690   return false;
4691 }
4692
4693 alent *
4694 _bfd_elf_get_lineno (ignore_abfd, symbol)
4695      bfd *ignore_abfd ATTRIBUTE_UNUSED;
4696      asymbol *symbol ATTRIBUTE_UNUSED;
4697 {
4698   abort ();
4699   return NULL;
4700 }
4701
4702 boolean
4703 _bfd_elf_set_arch_mach (abfd, arch, machine)
4704      bfd *abfd;
4705      enum bfd_architecture arch;
4706      unsigned long machine;
4707 {
4708   /* If this isn't the right architecture for this backend, and this
4709      isn't the generic backend, fail.  */
4710   if (arch != get_elf_backend_data (abfd)->arch
4711       && arch != bfd_arch_unknown
4712       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
4713     return false;
4714
4715   return bfd_default_set_arch_mach (abfd, arch, machine);
4716 }
4717
4718 /* Find the nearest line to a particular section and offset, for error
4719    reporting.  */
4720
4721 boolean
4722 _bfd_elf_find_nearest_line (abfd,
4723                             section,
4724                             symbols,
4725                             offset,
4726                             filename_ptr,
4727                             functionname_ptr,
4728                             line_ptr)
4729      bfd *abfd;
4730      asection *section;
4731      asymbol **symbols;
4732      bfd_vma offset;
4733      CONST char **filename_ptr;
4734      CONST char **functionname_ptr;
4735      unsigned int *line_ptr;
4736 {
4737   boolean found;
4738   const char *filename;
4739   asymbol *func;
4740   bfd_vma low_func;
4741   asymbol **p;
4742
4743   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
4744                                      filename_ptr, functionname_ptr, 
4745                                      line_ptr))
4746     return true;
4747
4748   if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
4749                                      filename_ptr, functionname_ptr,
4750                                      line_ptr, 0))
4751     return true;
4752
4753   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
4754                                              &found, filename_ptr,
4755                                              functionname_ptr, line_ptr,
4756                                              &elf_tdata (abfd)->line_info))
4757     return false;
4758   if (found)
4759     return true;
4760
4761   if (symbols == NULL)
4762     return false;
4763
4764   filename = NULL;
4765   func = NULL;
4766   low_func = 0;
4767
4768   for (p = symbols; *p != NULL; p++)
4769     {
4770       elf_symbol_type *q;
4771
4772       q = (elf_symbol_type *) *p;
4773
4774       if (bfd_get_section (&q->symbol) != section)
4775         continue;
4776
4777       switch (ELF_ST_TYPE (q->internal_elf_sym.st_info))
4778         {
4779         default:
4780           break;
4781         case STT_FILE:
4782           filename = bfd_asymbol_name (&q->symbol);
4783           break;
4784         case STT_NOTYPE:
4785         case STT_FUNC:
4786           if (q->symbol.section == section
4787               && q->symbol.value >= low_func
4788               && q->symbol.value <= offset)
4789             {
4790               func = (asymbol *) q;
4791               low_func = q->symbol.value;
4792             }
4793           break;
4794         }
4795     }
4796
4797   if (func == NULL)
4798     return false;
4799
4800   *filename_ptr = filename;
4801   *functionname_ptr = bfd_asymbol_name (func);
4802   *line_ptr = 0;
4803   return true;
4804 }
4805
4806 int
4807 _bfd_elf_sizeof_headers (abfd, reloc)
4808      bfd *abfd;
4809      boolean reloc;
4810 {
4811   int ret;
4812
4813   ret = get_elf_backend_data (abfd)->s->sizeof_ehdr;
4814   if (! reloc)
4815     ret += get_program_header_size (abfd);
4816   return ret;
4817 }
4818
4819 boolean
4820 _bfd_elf_set_section_contents (abfd, section, location, offset, count)
4821      bfd *abfd;
4822      sec_ptr section;
4823      PTR location;
4824      file_ptr offset;
4825      bfd_size_type count;
4826 {
4827   Elf_Internal_Shdr *hdr;
4828
4829   if (! abfd->output_has_begun
4830       && ! _bfd_elf_compute_section_file_positions
4831       (abfd, (struct bfd_link_info *) NULL))
4832     return false;
4833
4834   hdr = &elf_section_data (section)->this_hdr;
4835
4836   if (bfd_seek (abfd, hdr->sh_offset + offset, SEEK_SET) == -1)
4837     return false;
4838   if (bfd_write (location, 1, count, abfd) != count)
4839     return false;
4840
4841   return true;
4842 }
4843
4844 void
4845 _bfd_elf_no_info_to_howto (abfd, cache_ptr, dst)
4846      bfd *abfd ATTRIBUTE_UNUSED;
4847      arelent *cache_ptr ATTRIBUTE_UNUSED;
4848      Elf_Internal_Rela *dst ATTRIBUTE_UNUSED;
4849 {
4850   abort ();
4851 }
4852
4853 #if 0
4854 void
4855 _bfd_elf_no_info_to_howto_rel (abfd, cache_ptr, dst)
4856      bfd *abfd;
4857      arelent *cache_ptr;
4858      Elf_Internal_Rel *dst;
4859 {
4860   abort ();
4861 }
4862 #endif
4863
4864 /* Try to convert a non-ELF reloc into an ELF one.  */
4865
4866 boolean
4867 _bfd_elf_validate_reloc (abfd, areloc)
4868      bfd *abfd;
4869      arelent *areloc;
4870 {
4871   /* Check whether we really have an ELF howto. */
4872
4873   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
4874     {
4875       bfd_reloc_code_real_type code;
4876       reloc_howto_type *howto;
4877
4878       /* Alien reloc: Try to determine its type to replace it with an
4879          equivalent ELF reloc. */
4880
4881       if (areloc->howto->pc_relative)
4882         {
4883           switch (areloc->howto->bitsize)
4884             {
4885             case 8:
4886               code = BFD_RELOC_8_PCREL;
4887               break;
4888             case 12:
4889               code = BFD_RELOC_12_PCREL;
4890               break;
4891             case 16:
4892               code = BFD_RELOC_16_PCREL;
4893               break;
4894             case 24:
4895               code = BFD_RELOC_24_PCREL;
4896               break;
4897             case 32:
4898               code = BFD_RELOC_32_PCREL;
4899               break;
4900             case 64:
4901               code = BFD_RELOC_64_PCREL;
4902               break;
4903             default:
4904               goto fail;
4905             }
4906
4907           howto = bfd_reloc_type_lookup (abfd, code);
4908
4909           if (areloc->howto->pcrel_offset != howto->pcrel_offset)
4910             {
4911               if (howto->pcrel_offset)
4912                 areloc->addend += areloc->address;
4913               else
4914                 areloc->addend -= areloc->address; /* addend is unsigned!! */
4915             }
4916         }
4917       else
4918         {
4919           switch (areloc->howto->bitsize)
4920             {
4921             case 8:
4922               code = BFD_RELOC_8;
4923               break;
4924             case 14:
4925               code = BFD_RELOC_14;
4926               break;
4927             case 16:
4928               code = BFD_RELOC_16;
4929               break;
4930             case 26:
4931               code = BFD_RELOC_26;
4932               break;
4933             case 32:
4934               code = BFD_RELOC_32;
4935               break;
4936             case 64:
4937               code = BFD_RELOC_64;
4938               break;
4939             default:
4940               goto fail;
4941             }
4942
4943           howto = bfd_reloc_type_lookup (abfd, code);
4944         }
4945
4946       if (howto)
4947         areloc->howto = howto;
4948       else
4949         goto fail;
4950     }
4951
4952   return true;
4953
4954  fail:
4955   (*_bfd_error_handler)
4956     (_("%s: unsupported relocation type %s"),
4957      bfd_get_filename (abfd), areloc->howto->name);
4958   bfd_set_error (bfd_error_bad_value);
4959   return false;
4960 }
4961
4962 boolean
4963 _bfd_elf_close_and_cleanup (abfd)
4964      bfd *abfd;
4965 {
4966   if (bfd_get_format (abfd) == bfd_object)
4967     {
4968       if (elf_shstrtab (abfd) != NULL)
4969         _bfd_stringtab_free (elf_shstrtab (abfd));
4970     }
4971
4972   return _bfd_generic_close_and_cleanup (abfd);
4973 }
4974
4975 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
4976    in the relocation's offset.  Thus we cannot allow any sort of sanity
4977    range-checking to interfere.  There is nothing else to do in processing
4978    this reloc.  */
4979
4980 bfd_reloc_status_type
4981 _bfd_elf_rel_vtable_reloc_fn (abfd, re, symbol, data, is, obfd, errmsg)
4982      bfd *abfd ATTRIBUTE_UNUSED;
4983      arelent *re ATTRIBUTE_UNUSED;
4984      struct symbol_cache_entry *symbol ATTRIBUTE_UNUSED;
4985      PTR data ATTRIBUTE_UNUSED;
4986      asection *is ATTRIBUTE_UNUSED;
4987      bfd *obfd ATTRIBUTE_UNUSED;
4988      char **errmsg ATTRIBUTE_UNUSED;
4989 {
4990   return bfd_reloc_ok;
4991 }
4992
4993 \f
4994 /* Elf core file support.  Much of this only works on native
4995    toolchains, since we rely on knowing the
4996    machine-dependent procfs structure in order to pick
4997    out details about the corefile. */
4998
4999 #ifdef HAVE_SYS_PROCFS_H
5000 # include <sys/procfs.h>
5001 #endif
5002
5003
5004 /* Define offsetof for those systems which lack it. */
5005
5006 #ifndef offsetof
5007 # define offsetof(TYPE, MEMBER) ((unsigned long) &((TYPE *)0)->MEMBER)
5008 #endif
5009
5010
5011 /* FIXME: this is kinda wrong, but it's what gdb wants. */
5012
5013 static int
5014 elfcore_make_pid (abfd)
5015      bfd* abfd;
5016 {
5017   return ((elf_tdata (abfd)->core_lwpid << 16)
5018           + (elf_tdata (abfd)->core_pid));
5019 }
5020
5021
5022 /* If there isn't a section called NAME, make one, using
5023    data from SECT.  Note, this function will generate a
5024    reference to NAME, so you shouldn't deallocate or
5025    overwrite it. */
5026
5027 static boolean
5028 elfcore_maybe_make_sect (abfd, name, sect)
5029      bfd* abfd;
5030      char* name;
5031      asection* sect;
5032 {
5033   asection* sect2;
5034
5035   if (bfd_get_section_by_name (abfd, name) != NULL)
5036     return true;
5037
5038   sect2 = bfd_make_section (abfd, name);
5039   if (sect2 == NULL)
5040     return false;
5041
5042   sect2->_raw_size = sect->_raw_size;
5043   sect2->filepos = sect->filepos;
5044   sect2->flags = sect->flags;
5045   sect2->alignment_power = sect->alignment_power;
5046   return true;
5047 }
5048
5049
5050 /* prstatus_t exists on:
5051      solaris 2.[567]
5052      linux 2.[01] + glibc
5053      unixware 4.2
5054 */
5055
5056 #if defined (HAVE_PRSTATUS_T)
5057 static boolean
5058 elfcore_grok_prstatus (abfd, note)
5059      bfd* abfd;
5060      Elf_Internal_Note* note;
5061 {
5062   prstatus_t prstat;
5063   char buf[100];
5064   char* name;
5065   asection* sect;
5066
5067   if (note->descsz != sizeof (prstat))
5068     return true;
5069
5070   memcpy (&prstat, note->descdata, sizeof (prstat));
5071
5072   elf_tdata (abfd)->core_signal = prstat.pr_cursig;
5073   elf_tdata (abfd)->core_pid = prstat.pr_pid;
5074
5075   /* pr_who exists on:
5076        solaris 2.[567]
5077        unixware 4.2
5078      pr_who doesn't exist on:
5079        linux 2.[01]
5080   */
5081 #if defined (HAVE_PRSTATUS_T_PR_WHO)
5082   elf_tdata (abfd)->core_lwpid = prstat.pr_who;
5083 #endif
5084
5085   /* Make a ".reg/999" section. */
5086
5087   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
5088   name = bfd_alloc (abfd, strlen (buf) + 1);
5089   if (name == NULL)
5090     return false;
5091   strcpy (name, buf);
5092
5093   sect = bfd_make_section (abfd, name);
5094   if (sect == NULL)
5095     return false;
5096   sect->_raw_size = sizeof (prstat.pr_reg);
5097   sect->filepos = note->descpos + offsetof (prstatus_t, pr_reg);
5098   sect->flags = SEC_HAS_CONTENTS;
5099   sect->alignment_power = 2;
5100
5101   if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
5102     return false;
5103
5104   return true;
5105 }
5106 #endif /* defined (HAVE_PRSTATUS_T) */
5107
5108
5109 /* Create a pseudosection containing the exact contents of NOTE.  This
5110    actually creates up to two pseudosections:
5111    - For the single-threaded case, a section named NAME, unless
5112      such a section already exists.
5113    - For the multi-threaded case, a section named "NAME/PID", where
5114      PID is elfcore_make_pid (abfd).
5115    Both pseudosections have identical contents: the contents of NOTE.  */
5116
5117 static boolean
5118 elfcore_make_note_pseudosection (abfd, name, note)
5119      bfd* abfd;
5120      char *name;
5121      Elf_Internal_Note* note;
5122 {
5123   char buf[100];
5124   char *threaded_name;
5125   asection* sect;
5126
5127   /* Build the section name.  */
5128
5129   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
5130   threaded_name = bfd_alloc (abfd, strlen (buf) + 1);
5131   if (threaded_name == NULL)
5132     return false;
5133   strcpy (threaded_name, buf);
5134
5135   sect = bfd_make_section (abfd, threaded_name);
5136   if (sect == NULL)
5137     return false;
5138   sect->_raw_size = note->descsz;
5139   sect->filepos = note->descpos;
5140   sect->flags = SEC_HAS_CONTENTS;
5141   sect->alignment_power = 2;
5142
5143   if (! elfcore_maybe_make_sect (abfd, name, sect))
5144     return false;
5145
5146   return true;
5147 }
5148
5149
5150 /* There isn't a consistent prfpregset_t across platforms,
5151    but it doesn't matter, because we don't have to pick this
5152    data structure apart. */
5153 static boolean
5154 elfcore_grok_prfpreg (abfd, note)
5155      bfd* abfd;
5156      Elf_Internal_Note* note;
5157 {
5158   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
5159 }
5160
5161
5162 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
5163    type of 5 (NT_PRXFPREG).  Just include the whole note's contents
5164    literally.  */
5165 static boolean
5166 elfcore_grok_prxfpreg (abfd, note)
5167      bfd* abfd;
5168      Elf_Internal_Note* note;
5169 {
5170   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
5171 }
5172
5173
5174 #if defined (HAVE_PRPSINFO_T)
5175 # define elfcore_psinfo_t prpsinfo_t
5176 #endif
5177
5178 #if defined (HAVE_PSINFO_T)
5179 # define elfcore_psinfo_t psinfo_t
5180 #endif
5181
5182
5183 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
5184
5185 /* return a malloc'ed copy of a string at START which is at
5186    most MAX bytes long, possibly without a terminating '\0'.
5187    the copy will always have a terminating '\0'. */
5188
5189 static char*
5190 elfcore_strndup (abfd, start, max)
5191      bfd* abfd;
5192      char* start;
5193      int max;
5194 {
5195   char* dup;
5196   char* end = memchr (start, '\0', max);
5197   int len;
5198
5199   if (end == NULL)
5200     len = max;
5201   else
5202     len = end - start;
5203
5204   dup = bfd_alloc (abfd, len + 1);
5205   if (dup == NULL)
5206     return NULL;
5207
5208   memcpy (dup, start, len);
5209   dup[len] = '\0';
5210
5211   return dup;
5212 }
5213
5214 static boolean
5215 elfcore_grok_psinfo (abfd, note)
5216      bfd* abfd;
5217      Elf_Internal_Note* note;
5218 {
5219   elfcore_psinfo_t psinfo;
5220
5221   if (note->descsz != sizeof (elfcore_psinfo_t))
5222     return true;
5223
5224   memcpy (&psinfo, note->descdata, note->descsz);
5225
5226   elf_tdata (abfd)->core_program
5227     = elfcore_strndup (abfd, psinfo.pr_fname, sizeof (psinfo.pr_fname));
5228
5229   elf_tdata (abfd)->core_command
5230     = elfcore_strndup (abfd, psinfo.pr_psargs, sizeof (psinfo.pr_psargs));
5231
5232   /* Note that for some reason, a spurious space is tacked
5233      onto the end of the args in some (at least one anyway)
5234      implementations, so strip it off if it exists. */
5235
5236   {
5237     char* command = elf_tdata (abfd)->core_command;
5238     int n = strlen (command);
5239
5240     if (0 < n && command[n - 1] == ' ')
5241       command[n - 1] = '\0';
5242   }
5243
5244   return true;
5245 }
5246 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
5247
5248
5249 #if defined (HAVE_PSTATUS_T)
5250 static boolean
5251 elfcore_grok_pstatus (abfd, note)
5252      bfd* abfd;
5253      Elf_Internal_Note* note;
5254 {
5255   pstatus_t pstat;
5256
5257   if (note->descsz != sizeof (pstat))
5258     return true;
5259
5260   memcpy (&pstat, note->descdata, sizeof (pstat));
5261
5262   elf_tdata (abfd)->core_pid = pstat.pr_pid;
5263
5264   /* Could grab some more details from the "representative"
5265      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
5266      NT_LWPSTATUS note, presumably. */
5267
5268   return true;
5269 }
5270 #endif /* defined (HAVE_PSTATUS_T) */
5271
5272
5273 #if defined (HAVE_LWPSTATUS_T)
5274 static boolean
5275 elfcore_grok_lwpstatus (abfd, note)
5276      bfd* abfd;
5277      Elf_Internal_Note* note;
5278 {
5279   lwpstatus_t lwpstat;
5280   char buf[100];
5281   char* name;
5282   asection* sect;
5283
5284   if (note->descsz != sizeof (lwpstat))
5285     return true;
5286
5287   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
5288
5289   elf_tdata (abfd)->core_lwpid = lwpstat.pr_lwpid;
5290   elf_tdata (abfd)->core_signal = lwpstat.pr_cursig;
5291
5292   /* Make a ".reg/999" section. */
5293
5294   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
5295   name = bfd_alloc (abfd, strlen (buf) + 1);
5296   if (name == NULL)
5297     return false;
5298   strcpy (name, buf);
5299
5300   sect = bfd_make_section (abfd, name);
5301   if (sect == NULL)
5302     return false;
5303
5304 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
5305   sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
5306   sect->filepos = note->descpos
5307     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
5308 #endif
5309
5310 #if defined (HAVE_LWPSTATUS_T_PR_REG)
5311   sect->_raw_size = sizeof (lwpstat.pr_reg);
5312   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
5313 #endif
5314
5315   sect->flags = SEC_HAS_CONTENTS;
5316   sect->alignment_power = 2;
5317
5318   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
5319     return false;
5320
5321   /* Make a ".reg2/999" section */
5322
5323   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
5324   name = bfd_alloc (abfd, strlen (buf) + 1);
5325   if (name == NULL)
5326     return false;
5327   strcpy (name, buf);
5328
5329   sect = bfd_make_section (abfd, name);
5330   if (sect == NULL)
5331     return false;
5332
5333 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
5334   sect->_raw_size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
5335   sect->filepos = note->descpos
5336     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
5337 #endif
5338
5339 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
5340   sect->_raw_size = sizeof (lwpstat.pr_fpreg);
5341   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
5342 #endif
5343
5344   sect->flags = SEC_HAS_CONTENTS;
5345   sect->alignment_power = 2;
5346
5347   if (!elfcore_maybe_make_sect (abfd, ".reg2", sect))
5348     return false;
5349
5350   return true;
5351 }
5352 #endif /* defined (HAVE_LWPSTATUS_T) */
5353
5354 #if defined (HAVE_WIN32_PSTATUS_T)
5355 static boolean
5356 elfcore_grok_win32pstatus (abfd, note)
5357      bfd * abfd;
5358      Elf_Internal_Note * note;
5359 {
5360   char buf[30];
5361   char * name;
5362   asection * sect;
5363   win32_pstatus_t pstatus;
5364
5365   if (note->descsz < sizeof (pstatus))
5366     return true;
5367
5368   memcpy (& pstatus, note->descdata, note->descsz);
5369   
5370   switch (pstatus.data_type) 
5371     {
5372     case NOTE_INFO_PROCESS:
5373       /* FIXME: need to add ->core_command.  */
5374       elf_tdata (abfd)->core_signal = pstatus.data.process_info.signal;
5375       elf_tdata (abfd)->core_pid = pstatus.data.process_info.pid;
5376       break ;
5377
5378     case NOTE_INFO_THREAD:
5379       /* Make a ".reg/999" section.  */
5380       sprintf (buf, ".reg/%d", pstatus.data.thread_info.tid);
5381       
5382       name = bfd_alloc (abfd, strlen (buf) + 1);
5383       if (name == NULL)
5384         return false;
5385       
5386       strcpy (name, buf);
5387
5388       sect = bfd_make_section (abfd, name);
5389       if (sect == NULL)
5390         return false;
5391       
5392       sect->_raw_size = sizeof (pstatus.data.thread_info.thread_context);
5393       sect->filepos = note->descpos + offsetof (struct win32_pstatus,
5394                                                 data.thread_info.thread_context);
5395       sect->flags = SEC_HAS_CONTENTS;
5396       sect->alignment_power = 2;
5397
5398       if (pstatus.data.thread_info.is_active_thread)
5399         if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
5400           return false;
5401       break;
5402
5403     case NOTE_INFO_MODULE:
5404       /* Make a ".module/xxxxxxxx" section.  */
5405       sprintf (buf, ".module/%08x" , pstatus.data.module_info.base_address);
5406       
5407       name = bfd_alloc (abfd, strlen (buf) + 1);
5408       if (name == NULL)
5409         return false;
5410       
5411       strcpy (name, buf);
5412
5413       sect = bfd_make_section (abfd, name);
5414       
5415       if (sect == NULL)
5416         return false;
5417       
5418       sect->_raw_size = note->descsz;
5419       sect->filepos = note->descpos;
5420       sect->flags = SEC_HAS_CONTENTS;
5421       sect->alignment_power = 2;
5422       break;
5423
5424     default:
5425       return true;
5426     }
5427
5428   return true;
5429 }
5430 #endif /* HAVE_WIN32_PSTATUS_T */
5431
5432 static boolean
5433 elfcore_grok_note (abfd, note)
5434      bfd* abfd;
5435      Elf_Internal_Note* note;
5436 {
5437   switch (note->type)
5438     {
5439     default:
5440       return true;
5441
5442 #if defined (HAVE_PRSTATUS_T)
5443     case NT_PRSTATUS:
5444       return elfcore_grok_prstatus (abfd, note);
5445 #endif
5446
5447 #if defined (HAVE_PSTATUS_T)
5448     case NT_PSTATUS:
5449       return elfcore_grok_pstatus (abfd, note);
5450 #endif
5451
5452 #if defined (HAVE_LWPSTATUS_T)
5453     case NT_LWPSTATUS:
5454       return elfcore_grok_lwpstatus (abfd, note);
5455 #endif
5456
5457     case NT_FPREGSET:           /* FIXME: rename to NT_PRFPREG */
5458       return elfcore_grok_prfpreg (abfd, note);
5459
5460 #if defined (HAVE_WIN32_PSTATUS_T)
5461     case NT_WIN32PSTATUS:       
5462       return elfcore_grok_win32pstatus (abfd, note);
5463 #endif
5464
5465   case NT_PRXFPREG:             /* Linux SSE extension */
5466       if (note->namesz == 5
5467           && ! strcmp (note->namedata, "LINUX"))
5468         return elfcore_grok_prxfpreg (abfd, note);
5469       else
5470         return true;
5471
5472 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
5473     case NT_PRPSINFO:
5474     case NT_PSINFO:
5475       return elfcore_grok_psinfo (abfd, note);
5476 #endif
5477     }
5478 }
5479
5480
5481 static boolean
5482 elfcore_read_notes (abfd, offset, size)
5483      bfd* abfd;
5484      bfd_vma offset;
5485      bfd_vma size;
5486 {
5487   char* buf;
5488   char* p;
5489
5490   if (size <= 0)
5491     return true;
5492
5493   if (bfd_seek (abfd, offset, SEEK_SET) == -1)
5494     return false;
5495
5496   buf = bfd_malloc ((size_t) size);
5497   if (buf == NULL)
5498     return false;
5499
5500   if (bfd_read (buf, size, 1, abfd) != size)
5501     {
5502     error:
5503       free (buf);
5504       return false;
5505     }
5506
5507   p = buf;
5508   while (p < buf + size)
5509     {
5510       /* FIXME: bad alignment assumption. */
5511       Elf_External_Note* xnp = (Elf_External_Note*) p;
5512       Elf_Internal_Note in;
5513
5514       in.type = bfd_h_get_32 (abfd, (bfd_byte *) xnp->type);
5515
5516       in.namesz = bfd_h_get_32 (abfd, (bfd_byte *) xnp->namesz);
5517       in.namedata = xnp->name;
5518
5519       in.descsz = bfd_h_get_32 (abfd, (bfd_byte *) xnp->descsz);
5520       in.descdata = in.namedata + BFD_ALIGN (in.namesz, 4);
5521       in.descpos = offset + (in.descdata - buf);
5522
5523       if (! elfcore_grok_note (abfd, &in))
5524         goto error;
5525
5526       p = in.descdata + BFD_ALIGN (in.descsz, 4);
5527     }
5528
5529   free (buf);
5530   return true;
5531 }
5532
5533
5534 /* FIXME: This function is now unnecessary.  Callers can just call
5535    bfd_section_from_phdr directly.  */
5536
5537 boolean
5538 _bfd_elfcore_section_from_phdr (abfd, phdr, sec_num)
5539      bfd* abfd;
5540      Elf_Internal_Phdr* phdr;
5541      int sec_num;
5542 {
5543   if (! bfd_section_from_phdr (abfd, phdr, sec_num))
5544     return false;
5545
5546   return true;
5547 }
5548
5549
5550 \f
5551 /* Providing external access to the ELF program header table.  */
5552
5553 /* Return an upper bound on the number of bytes required to store a
5554    copy of ABFD's program header table entries.  Return -1 if an error
5555    occurs; bfd_get_error will return an appropriate code.  */
5556 long
5557 bfd_get_elf_phdr_upper_bound (abfd)
5558      bfd *abfd;
5559 {
5560   if (abfd->xvec->flavour != bfd_target_elf_flavour)
5561     {
5562       bfd_set_error (bfd_error_wrong_format);
5563       return -1;
5564     }
5565
5566   return (elf_elfheader (abfd)->e_phnum
5567           * sizeof (Elf_Internal_Phdr));
5568 }
5569
5570
5571 /* Copy ABFD's program header table entries to *PHDRS.  The entries
5572    will be stored as an array of Elf_Internal_Phdr structures, as
5573    defined in include/elf/internal.h.  To find out how large the
5574    buffer needs to be, call bfd_get_elf_phdr_upper_bound.
5575
5576    Return the number of program header table entries read, or -1 if an
5577    error occurs; bfd_get_error will return an appropriate code.  */
5578 int
5579 bfd_get_elf_phdrs (abfd, phdrs)
5580      bfd *abfd;
5581      void *phdrs;
5582 {
5583   int num_phdrs;
5584
5585   if (abfd->xvec->flavour != bfd_target_elf_flavour)
5586     {
5587       bfd_set_error (bfd_error_wrong_format);
5588       return -1;
5589     }
5590
5591   num_phdrs = elf_elfheader (abfd)->e_phnum;
5592   memcpy (phdrs, elf_tdata (abfd)->phdr, 
5593           num_phdrs * sizeof (Elf_Internal_Phdr));
5594
5595   return num_phdrs;
5596 }