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