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