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