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