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