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